1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/LLVMContext.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Transforms/Utils/SSAUpdater.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
34 STATISTIC(NumThreads, "Number of jumps threaded");
35 STATISTIC(NumFolds, "Number of terminators folded");
36 STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
38 static cl::opt<unsigned>
39 Threshold("jump-threading-threshold",
40 cl::desc("Max block size to duplicate for jump threading"),
41 cl::init(6), cl::Hidden);
44 /// This pass performs 'jump threading', which looks at blocks that have
45 /// multiple predecessors and multiple successors. If one or more of the
46 /// predecessors of the block can be proven to always jump to one of the
47 /// successors, we forward the edge from the predecessor to the successor by
48 /// duplicating the contents of this block.
50 /// An example of when this can occur is code like this:
57 /// In this case, the unconditional branch at the end of the first if can be
58 /// revectored to the false side of the second if.
60 class JumpThreading : public FunctionPass {
63 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
65 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
68 static char ID; // Pass identification
69 JumpThreading() : FunctionPass(&ID) {}
71 bool runOnFunction(Function &F);
72 void FindLoopHeaders(Function &F);
74 bool ProcessBlock(BasicBlock *BB);
75 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
76 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
79 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val);
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.
100 bool JumpThreading::runOnFunction(Function &F) {
101 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
102 TD = getAnalysisIfAvailable<TargetData>();
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;) {
112 while (ProcessBlock(BB))
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 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
122 << "' with terminator: " << *BB->getTerminator() << '\n');
123 LoopHeaders.erase(BB);
128 AnotherIteration = Changed;
129 EverChanged |= Changed;
136 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
137 /// thread across it.
138 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
139 /// Ignore PHI nodes, these will be flattened when duplication happens.
140 BasicBlock::const_iterator I = BB->getFirstNonPHI();
142 // Sum up the cost of each instruction until we get to the terminator. Don't
143 // include the terminator because the copy won't include it.
145 for (; !isa<TerminatorInst>(I); ++I) {
146 // Debugger intrinsics don't incur code size.
147 if (isa<DbgInfoIntrinsic>(I)) continue;
149 // If this is a pointer->pointer bitcast, it is free.
150 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
153 // All other instructions count for at least one unit.
156 // Calls are more expensive. If they are non-intrinsic calls, we model them
157 // as having cost of 4. If they are a non-vector intrinsic, we model them
158 // as having cost of 2 total, and if they are a vector intrinsic, we model
159 // them as having cost 1.
160 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
161 if (!isa<IntrinsicInst>(CI))
163 else if (!isa<VectorType>(CI->getType()))
168 // Threading through a switch statement is particularly profitable. If this
169 // block ends in a switch, decrease its cost to make it more likely to happen.
170 if (isa<SwitchInst>(I))
171 Size = Size > 6 ? Size-6 : 0;
178 /// FindLoopHeaders - We do not want jump threading to turn proper loop
179 /// structures into irreducible loops. Doing this breaks up the loop nesting
180 /// hierarchy and pessimizes later transformations. To prevent this from
181 /// happening, we first have to find the loop headers. Here we approximate this
182 /// by finding targets of backedges in the CFG.
184 /// Note that there definitely are cases when we want to allow threading of
185 /// edges across a loop header. For example, threading a jump from outside the
186 /// loop (the preheader) to an exit block of the loop is definitely profitable.
187 /// It is also almost always profitable to thread backedges from within the loop
188 /// to exit blocks, and is often profitable to thread backedges to other blocks
189 /// within the loop (forming a nested loop). This simple analysis is not rich
190 /// enough to track all of these properties and keep it up-to-date as the CFG
191 /// mutates, so we don't allow any of these transformations.
193 void JumpThreading::FindLoopHeaders(Function &F) {
194 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
195 FindFunctionBackedges(F, Edges);
197 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
198 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
202 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
203 /// value for the PHI, factor them together so we get one block to thread for
205 /// This is important for things like "phi i1 [true, true, false, true, x]"
206 /// where we only need to clone the block for the true blocks once.
208 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
209 SmallVector<BasicBlock*, 16> CommonPreds;
210 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
211 if (PN->getIncomingValue(i) == Val)
212 CommonPreds.push_back(PN->getIncomingBlock(i));
214 if (CommonPreds.size() == 1)
215 return CommonPreds[0];
217 DEBUG(errs() << " Factoring out " << CommonPreds.size()
218 << " common predecessors.\n");
219 return SplitBlockPredecessors(PN->getParent(),
220 &CommonPreds[0], CommonPreds.size(),
225 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
226 /// in an undefined jump, decide which block is best to revector to.
228 /// Since we can pick an arbitrary destination, we pick the successor with the
229 /// fewest predecessors. This should reduce the in-degree of the others.
231 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
232 TerminatorInst *BBTerm = BB->getTerminator();
233 unsigned MinSucc = 0;
234 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
235 // Compute the successor with the minimum number of predecessors.
236 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
237 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
238 TestBB = BBTerm->getSuccessor(i);
239 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
240 if (NumPreds < MinNumPreds)
247 /// ProcessBlock - If there are any predecessors whose control can be threaded
248 /// through to a successor, transform them now.
249 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
250 // If this block has a single predecessor, and if that pred has a single
251 // successor, merge the blocks. This encourages recursive jump threading
252 // because now the condition in this block can be threaded through
253 // predecessors of our predecessor block.
254 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
255 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
257 // If SinglePred was a loop header, BB becomes one.
258 if (LoopHeaders.erase(SinglePred))
259 LoopHeaders.insert(BB);
261 // Remember if SinglePred was the entry block of the function. If so, we
262 // will need to move BB back to the entry position.
263 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
264 MergeBasicBlockIntoOnlyPred(BB);
266 if (isEntry && BB != &BB->getParent()->getEntryBlock())
267 BB->moveBefore(&BB->getParent()->getEntryBlock());
271 // See if this block ends with a branch or switch. If so, see if the
272 // condition is a phi node. If so, and if an entry of the phi node is a
273 // constant, we can thread the block.
275 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
276 // Can't thread an unconditional jump.
277 if (BI->isUnconditional()) return false;
278 Condition = BI->getCondition();
279 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
280 Condition = SI->getCondition();
282 return false; // Must be an invoke.
284 // If the terminator of this block is branching on a constant, simplify the
285 // terminator to an unconditional branch. This can occur due to threading in
287 if (isa<ConstantInt>(Condition)) {
288 DEBUG(errs() << " In block '" << BB->getName()
289 << "' folding terminator: " << *BB->getTerminator() << '\n');
291 ConstantFoldTerminator(BB);
295 // If the terminator is branching on an undef, we can pick any of the
296 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
297 if (isa<UndefValue>(Condition)) {
298 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
300 // Fold the branch/switch.
301 TerminatorInst *BBTerm = BB->getTerminator();
302 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
303 if (i == BestSucc) continue;
304 BBTerm->getSuccessor(i)->removePredecessor(BB);
307 DEBUG(errs() << " In block '" << BB->getName()
308 << "' folding undef terminator: " << *BBTerm << '\n');
309 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
310 BBTerm->eraseFromParent();
314 Instruction *CondInst = dyn_cast<Instruction>(Condition);
316 // If the condition is an instruction defined in another block, see if a
317 // predecessor has the same condition:
321 if (!Condition->hasOneUse() && // Multiple uses.
322 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
323 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
324 if (isa<BranchInst>(BB->getTerminator())) {
325 for (; PI != E; ++PI)
326 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
327 if (PBI->isConditional() && PBI->getCondition() == Condition &&
328 ProcessBranchOnDuplicateCond(*PI, BB))
331 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
332 for (; PI != E; ++PI)
333 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
334 if (PSI->getCondition() == Condition &&
335 ProcessSwitchOnDuplicateCond(*PI, BB))
340 // All the rest of our checks depend on the condition being an instruction.
344 // See if this is a phi node in the current block.
345 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
346 if (PN->getParent() == BB)
347 return ProcessJumpOnPHI(PN);
349 // If this is a conditional branch whose condition is and/or of a phi, try to
351 if ((CondInst->getOpcode() == Instruction::And ||
352 CondInst->getOpcode() == Instruction::Or) &&
353 isa<BranchInst>(BB->getTerminator()) &&
354 ProcessBranchOnLogical(CondInst, BB,
355 CondInst->getOpcode() == Instruction::And))
358 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
359 if (isa<PHINode>(CondCmp->getOperand(0))) {
360 // If we have "br (phi != 42)" and the phi node has any constant values
361 // as operands, we can thread through this block.
363 // If we have "br (cmp phi, x)" and the phi node contains x such that the
364 // comparison uniquely identifies the branch target, we can thread
365 // through this block.
367 if (ProcessBranchOnCompare(CondCmp, BB))
371 // If we have a comparison, loop over the predecessors to see if there is
372 // a condition with the same value.
373 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
374 for (; PI != E; ++PI)
375 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
376 if (PBI->isConditional() && *PI != BB) {
377 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
378 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
379 CI->getOperand(1) == CondCmp->getOperand(1) &&
380 CI->getPredicate() == CondCmp->getPredicate()) {
381 // TODO: Could handle things like (x != 4) --> (x == 17)
382 if (ProcessBranchOnDuplicateCond(*PI, BB))
389 // Check for some cases that are worth simplifying. Right now we want to look
390 // for loads that are used by a switch or by the condition for the branch. If
391 // we see one, check to see if it's partially redundant. If so, insert a PHI
392 // which can then be used to thread the values.
394 // This is particularly important because reg2mem inserts loads and stores all
395 // over the place, and this blocks jump threading if we don't zap them.
396 Value *SimplifyValue = CondInst;
397 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
398 if (isa<Constant>(CondCmp->getOperand(1)))
399 SimplifyValue = CondCmp->getOperand(0);
401 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
402 if (SimplifyPartiallyRedundantLoad(LI))
405 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
406 // "(X == 4)" thread through this block.
411 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
412 /// block that jump on exactly the same condition. This means that we almost
413 /// always know the direction of the edge in the DESTBB:
415 /// br COND, DESTBB, BBY
417 /// br COND, BBZ, BBW
419 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
420 /// in DESTBB, we have to thread over it.
421 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
423 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
425 // If both successors of PredBB go to DESTBB, we don't know anything. We can
426 // fold the branch to an unconditional one, which allows other recursive
429 if (PredBI->getSuccessor(1) != BB)
431 else if (PredBI->getSuccessor(0) != BB)
434 DEBUG(errs() << " In block '" << PredBB->getName()
435 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
437 ConstantFoldTerminator(PredBB);
441 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
443 // If the dest block has one predecessor, just fix the branch condition to a
444 // constant and fold it.
445 if (BB->getSinglePredecessor()) {
446 DEBUG(errs() << " In block '" << BB->getName()
447 << "' folding condition to '" << BranchDir << "': "
448 << *BB->getTerminator() << '\n');
450 Value *OldCond = DestBI->getCondition();
451 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
453 ConstantFoldTerminator(BB);
454 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
459 // Next, figure out which successor we are threading to.
460 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
462 // Ok, try to thread it!
463 return ThreadEdge(BB, PredBB, SuccBB);
466 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
467 /// block that switch on exactly the same condition. This means that we almost
468 /// always know the direction of the edge in the DESTBB:
470 /// switch COND [... DESTBB, BBY ... ]
472 /// switch COND [... BBZ, BBW ]
474 /// Optimizing switches like this is very important, because simplifycfg builds
475 /// switches out of repeated 'if' conditions.
476 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
477 BasicBlock *DestBB) {
478 // Can't thread edge to self.
479 if (PredBB == DestBB)
482 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
483 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
485 // There are a variety of optimizations that we can potentially do on these
486 // blocks: we order them from most to least preferable.
488 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
489 // directly to their destination. This does not introduce *any* code size
490 // growth. Skip debug info first.
491 BasicBlock::iterator BBI = DestBB->begin();
492 while (isa<DbgInfoIntrinsic>(BBI))
495 // FIXME: Thread if it just contains a PHI.
496 if (isa<SwitchInst>(BBI)) {
497 bool MadeChange = false;
498 // Ignore the default edge for now.
499 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
500 ConstantInt *DestVal = DestSI->getCaseValue(i);
501 BasicBlock *DestSucc = DestSI->getSuccessor(i);
503 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
504 // PredSI has an explicit case for it. If so, forward. If it is covered
505 // by the default case, we can't update PredSI.
506 unsigned PredCase = PredSI->findCaseValue(DestVal);
507 if (PredCase == 0) continue;
509 // If PredSI doesn't go to DestBB on this value, then it won't reach the
510 // case on this condition.
511 if (PredSI->getSuccessor(PredCase) != DestBB &&
512 DestSI->getSuccessor(i) != DestBB)
515 // Otherwise, we're safe to make the change. Make sure that the edge from
516 // DestSI to DestSucc is not critical and has no PHI nodes.
517 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
518 DEBUG(errs() << "THROUGH: " << *DestSI);
520 // If the destination has PHI nodes, just split the edge for updating
522 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
523 SplitCriticalEdge(DestSI, i, this);
524 DestSucc = DestSI->getSuccessor(i);
526 FoldSingleEntryPHINodes(DestSucc);
527 PredSI->setSuccessor(PredCase, DestSucc);
539 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
540 /// load instruction, eliminate it by replacing it with a PHI node. This is an
541 /// important optimization that encourages jump threading, and needs to be run
542 /// interlaced with other jump threading tasks.
543 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
544 // Don't hack volatile loads.
545 if (LI->isVolatile()) return false;
547 // If the load is defined in a block with exactly one predecessor, it can't be
548 // partially redundant.
549 BasicBlock *LoadBB = LI->getParent();
550 if (LoadBB->getSinglePredecessor())
553 Value *LoadedPtr = LI->getOperand(0);
555 // If the loaded operand is defined in the LoadBB, it can't be available.
556 // FIXME: Could do PHI translation, that would be fun :)
557 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
558 if (PtrOp->getParent() == LoadBB)
561 // Scan a few instructions up from the load, to see if it is obviously live at
562 // the entry to its block.
563 BasicBlock::iterator BBIt = LI;
565 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
567 // If the value if the load is locally available within the block, just use
568 // it. This frequently occurs for reg2mem'd allocas.
569 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
571 // If the returned value is the load itself, replace with an undef. This can
572 // only happen in dead loops.
573 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
574 LI->replaceAllUsesWith(AvailableVal);
575 LI->eraseFromParent();
579 // Otherwise, if we scanned the whole block and got to the top of the block,
580 // we know the block is locally transparent to the load. If not, something
581 // might clobber its value.
582 if (BBIt != LoadBB->begin())
586 SmallPtrSet<BasicBlock*, 8> PredsScanned;
587 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
588 AvailablePredsTy AvailablePreds;
589 BasicBlock *OneUnavailablePred = 0;
591 // If we got here, the loaded value is transparent through to the start of the
592 // block. Check to see if it is available in any of the predecessor blocks.
593 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
595 BasicBlock *PredBB = *PI;
597 // If we already scanned this predecessor, skip it.
598 if (!PredsScanned.insert(PredBB))
601 // Scan the predecessor to see if the value is available in the pred.
602 BBIt = PredBB->end();
603 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
604 if (!PredAvailable) {
605 OneUnavailablePred = PredBB;
609 // If so, this load is partially redundant. Remember this info so that we
610 // can create a PHI node.
611 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
614 // If the loaded value isn't available in any predecessor, it isn't partially
616 if (AvailablePreds.empty()) return false;
618 // Okay, the loaded value is available in at least one (and maybe all!)
619 // predecessors. If the value is unavailable in more than one unique
620 // predecessor, we want to insert a merge block for those common predecessors.
621 // This ensures that we only have to insert one reload, thus not increasing
623 BasicBlock *UnavailablePred = 0;
625 // If there is exactly one predecessor where the value is unavailable, the
626 // already computed 'OneUnavailablePred' block is it. If it ends in an
627 // unconditional branch, we know that it isn't a critical edge.
628 if (PredsScanned.size() == AvailablePreds.size()+1 &&
629 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
630 UnavailablePred = OneUnavailablePred;
631 } else if (PredsScanned.size() != AvailablePreds.size()) {
632 // Otherwise, we had multiple unavailable predecessors or we had a critical
633 // edge from the one.
634 SmallVector<BasicBlock*, 8> PredsToSplit;
635 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
637 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
638 AvailablePredSet.insert(AvailablePreds[i].first);
640 // Add all the unavailable predecessors to the PredsToSplit list.
641 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
643 if (!AvailablePredSet.count(*PI))
644 PredsToSplit.push_back(*PI);
646 // Split them out to their own block.
648 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
649 "thread-split", this);
652 // If the value isn't available in all predecessors, then there will be
653 // exactly one where it isn't available. Insert a load on that edge and add
654 // it to the AvailablePreds list.
655 if (UnavailablePred) {
656 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
657 "Can't handle critical edge here!");
658 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
659 UnavailablePred->getTerminator());
660 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
663 // Now we know that each predecessor of this block has a value in
664 // AvailablePreds, sort them for efficient access as we're walking the preds.
665 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
667 // Create a PHI node at the start of the block for the PRE'd load value.
668 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
671 // Insert new entries into the PHI for each predecessor. A single block may
672 // have multiple entries here.
673 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
675 AvailablePredsTy::iterator I =
676 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
677 std::make_pair(*PI, (Value*)0));
679 assert(I != AvailablePreds.end() && I->first == *PI &&
680 "Didn't find entry for predecessor!");
682 PN->addIncoming(I->second, I->first);
685 //cerr << "PRE: " << *LI << *PN << "\n";
687 LI->replaceAllUsesWith(PN);
688 LI->eraseFromParent();
694 /// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
695 /// the current block. See if there are any simplifications we can do based on
696 /// inputs to the phi node.
698 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
699 BasicBlock *BB = PN->getParent();
701 // See if the phi node has any constant integer or undef values. If so, we
702 // can determine where the corresponding predecessor will branch.
703 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
704 Value *PredVal = PN->getIncomingValue(i);
706 // Check to see if this input is a constant integer. If so, the direction
707 // of the branch is predictable.
708 if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) {
709 // Merge any common predecessors that will act the same.
710 BasicBlock *PredBB = FactorCommonPHIPreds(PN, CI);
713 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
714 SuccBB = BI->getSuccessor(CI->isZero());
716 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
717 SuccBB = SI->getSuccessor(SI->findCaseValue(CI));
720 // Ok, try to thread it!
721 return ThreadEdge(BB, PredBB, SuccBB);
724 // If the input is an undef, then it doesn't matter which way it will go.
725 // Pick an arbitrary dest and thread the edge.
726 if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) {
727 // Merge any common predecessors that will act the same.
728 BasicBlock *PredBB = FactorCommonPHIPreds(PN, UV);
730 BB->getTerminator()->getSuccessor(GetBestDestForJumpOnUndef(BB));
732 // Ok, try to thread it!
733 return ThreadEdge(BB, PredBB, SuccBB);
737 // If the incoming values are all variables, we don't know the destination of
738 // any predecessors. However, if any of the predecessor blocks end in an
739 // unconditional branch, we can *duplicate* the jump into that block in order
740 // to further encourage jump threading and to eliminate cases where we have
741 // branch on a phi of an icmp (branch on icmp is much better).
743 // We don't want to do this tranformation for switches, because we don't
744 // really want to duplicate a switch.
745 if (isa<SwitchInst>(BB->getTerminator()))
748 // Look for unconditional branch predecessors.
749 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
750 BasicBlock *PredBB = PN->getIncomingBlock(i);
751 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
752 if (PredBr->isUnconditional() &&
753 // Try to duplicate BB into PredBB.
754 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
762 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
763 /// whose condition is an AND/OR where one side is PN. If PN has constant
764 /// operands that permit us to evaluate the condition for some operand, thread
765 /// through the block. For example with:
766 /// br (and X, phi(Y, Z, false))
767 /// the predecessor corresponding to the 'false' will always jump to the false
768 /// destination of the branch.
770 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
772 // If this is a binary operator tree of the same AND/OR opcode, check the
774 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
775 if ((isAnd && BO->getOpcode() == Instruction::And) ||
776 (!isAnd && BO->getOpcode() == Instruction::Or)) {
777 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
779 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
783 // If this isn't a PHI node, we can't handle it.
784 PHINode *PN = dyn_cast<PHINode>(V);
785 if (!PN || PN->getParent() != BB) return false;
787 // We can only do the simplification for phi nodes of 'false' with AND or
788 // 'true' with OR. See if we have any entries in the phi for this.
789 unsigned PredNo = ~0U;
790 ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()),
792 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
793 if (PN->getIncomingValue(i) == PredCst) {
799 // If no match, bail out.
803 // If so, we can actually do this threading. Merge any common predecessors
804 // that will act the same.
805 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
807 // Next, figure out which successor we are threading to. If this was an AND,
808 // the constant must be FALSE, and we must be targeting the 'false' block.
809 // If this is an OR, the constant must be TRUE, and we must be targeting the
811 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
813 // Ok, try to thread it!
814 return ThreadEdge(BB, PredBB, SuccBB);
817 /// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
818 /// hand sides of the compare instruction, try to determine the result. If the
819 /// result can not be determined, a null pointer is returned.
820 static Constant *GetResultOfComparison(CmpInst::Predicate pred,
821 Value *LHS, Value *RHS,
822 LLVMContext &Context) {
823 if (Constant *CLHS = dyn_cast<Constant>(LHS))
824 if (Constant *CRHS = dyn_cast<Constant>(RHS))
825 return ConstantExpr::getCompare(pred, CLHS, CRHS);
828 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
829 return ICmpInst::isTrueWhenEqual(pred) ?
830 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context);
835 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
836 /// node and a value. If we can identify when the comparison is true between
837 /// the phi inputs and the value, we can fold the compare for that edge and
838 /// thread through it.
839 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
840 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
841 Value *RHS = Cmp->getOperand(1);
843 // If the phi isn't in the current block, an incoming edge to this block
844 // doesn't control the destination.
845 if (PN->getParent() != BB)
848 // We can do this simplification if any comparisons fold to true or false.
851 bool TrueDirection = false;
852 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
853 PredVal = PN->getIncomingValue(i);
855 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal,
856 RHS, Cmp->getContext());
862 // If this folded to a constant expr, we can't do anything.
863 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
864 TrueDirection = ResC->getZExtValue();
867 // If this folded to undef, just go the false way.
868 if (isa<UndefValue>(Res)) {
869 TrueDirection = false;
873 // Otherwise, we can't fold this input.
877 // If no match, bail out.
881 // If so, we can actually do this threading. Merge any common predecessors
882 // that will act the same.
883 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
885 // Next, get our successor.
886 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
888 // Ok, try to thread it!
889 return ThreadEdge(BB, PredBB, SuccBB);
893 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
894 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
895 /// NewPred using the entries from OldPred (suitably mapped).
896 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
899 DenseMap<Instruction*, Value*> &ValueMap) {
900 for (BasicBlock::iterator PNI = PHIBB->begin();
901 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
902 // Ok, we have a PHI node. Figure out what the incoming value was for the
904 Value *IV = PN->getIncomingValueForBlock(OldPred);
906 // Remap the value if necessary.
907 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
908 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
909 if (I != ValueMap.end())
913 PN->addIncoming(IV, NewPred);
917 /// ThreadEdge - We have decided that it is safe and profitable to thread an
918 /// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
920 bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
921 BasicBlock *SuccBB) {
922 // If threading to the same block as we come from, we would infinite loop.
924 DEBUG(errs() << " Not threading across BB '" << BB->getName()
925 << "' - would thread to self!\n");
929 // If threading this would thread across a loop header, don't thread the edge.
930 // See the comments above FindLoopHeaders for justifications and caveats.
931 if (LoopHeaders.count(BB)) {
932 DEBUG(errs() << " Not threading from '" << PredBB->getName()
933 << "' across loop header BB '" << BB->getName()
934 << "' to dest BB '" << SuccBB->getName()
935 << "' - it might create an irreducible loop!\n");
939 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
940 if (JumpThreadCost > Threshold) {
941 DEBUG(errs() << " Not threading BB '" << BB->getName()
942 << "' - Cost is too high: " << JumpThreadCost << "\n");
946 // And finally, do it!
947 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
948 << SuccBB->getName() << "' with cost: " << JumpThreadCost
949 << ", across block:\n "
952 // We are going to have to map operands from the original BB block to the new
953 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
954 // account for entry from PredBB.
955 DenseMap<Instruction*, Value*> ValueMapping;
957 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
958 BB->getName()+".thread",
959 BB->getParent(), BB);
960 NewBB->moveAfter(PredBB);
962 BasicBlock::iterator BI = BB->begin();
963 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
964 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
966 // Clone the non-phi instructions of BB into NewBB, keeping track of the
967 // mapping and using it to remap operands in the cloned instructions.
968 for (; !isa<TerminatorInst>(BI); ++BI) {
969 Instruction *New = BI->clone();
970 New->setName(BI->getName());
971 NewBB->getInstList().push_back(New);
972 ValueMapping[BI] = New;
974 // Remap operands to patch up intra-block references.
975 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
976 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
977 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
978 if (I != ValueMapping.end())
979 New->setOperand(i, I->second);
983 // We didn't copy the terminator from BB over to NewBB, because there is now
984 // an unconditional jump to SuccBB. Insert the unconditional jump.
985 BranchInst::Create(SuccBB, NewBB);
987 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
988 // PHI nodes for NewBB now.
989 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
991 // If there were values defined in BB that are used outside the block, then we
992 // now have to update all uses of the value to use either the original value,
993 // the cloned value, or some PHI derived value. This can require arbitrary
994 // PHI insertion, of which we are prepared to do, clean these up now.
995 SSAUpdater SSAUpdate;
996 SmallVector<Use*, 16> UsesToRename;
997 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
998 // Scan all uses of this instruction to see if it is used outside of its
999 // block, and if so, record them in UsesToRename.
1000 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1002 Instruction *User = cast<Instruction>(*UI);
1003 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1004 if (UserPN->getIncomingBlock(UI) == BB)
1006 } else if (User->getParent() == BB)
1009 UsesToRename.push_back(&UI.getUse());
1012 // If there are no uses outside the block, we're done with this instruction.
1013 if (UsesToRename.empty())
1016 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1018 // We found a use of I outside of BB. Rename all uses of I that are outside
1019 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1020 // with the two values we know.
1021 SSAUpdate.Initialize(I);
1022 SSAUpdate.AddAvailableValue(BB, I);
1023 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1025 while (!UsesToRename.empty())
1026 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1027 DEBUG(errs() << "\n");
1031 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
1032 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1033 // us to simplify any PHI nodes in BB.
1034 TerminatorInst *PredTerm = PredBB->getTerminator();
1035 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1036 if (PredTerm->getSuccessor(i) == BB) {
1037 BB->removePredecessor(PredBB);
1038 PredTerm->setSuccessor(i, NewBB);
1041 // At this point, the IR is fully up to date and consistent. Do a quick scan
1042 // over the new instructions and zap any that are constants or dead. This
1043 // frequently happens because of phi translation.
1044 BI = NewBB->begin();
1045 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1046 Instruction *Inst = BI++;
1047 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
1048 Inst->replaceAllUsesWith(C);
1049 Inst->eraseFromParent();
1053 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1056 // Threaded an edge!
1061 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1062 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1063 /// If we can duplicate the contents of BB up into PredBB do so now, this
1064 /// improves the odds that the branch will be on an analyzable instruction like
1066 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1067 BasicBlock *PredBB) {
1068 // If BB is a loop header, then duplicating this block outside the loop would
1069 // cause us to transform this into an irreducible loop, don't do this.
1070 // See the comments above FindLoopHeaders for justifications and caveats.
1071 if (LoopHeaders.count(BB)) {
1072 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1073 << "' into predecessor block '" << PredBB->getName()
1074 << "' - it might create an irreducible loop!\n");
1078 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1079 if (DuplicationCost > Threshold) {
1080 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1081 << "' - Cost is too high: " << DuplicationCost << "\n");
1085 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1087 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1088 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1089 << DuplicationCost << " block is:" << *BB << "\n");
1091 // We are going to have to map operands from the original BB block into the
1092 // PredBB block. Evaluate PHI nodes in BB.
1093 DenseMap<Instruction*, Value*> ValueMapping;
1095 BasicBlock::iterator BI = BB->begin();
1096 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1097 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1099 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1101 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1102 // mapping and using it to remap operands in the cloned instructions.
1103 for (; BI != BB->end(); ++BI) {
1104 Instruction *New = BI->clone();
1105 New->setName(BI->getName());
1106 PredBB->getInstList().insert(OldPredBranch, New);
1107 ValueMapping[BI] = New;
1109 // Remap operands to patch up intra-block references.
1110 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1111 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1112 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1113 if (I != ValueMapping.end())
1114 New->setOperand(i, I->second);
1118 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1119 // add entries to the PHI nodes for branch from PredBB now.
1120 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1121 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1123 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1126 // If there were values defined in BB that are used outside the block, then we
1127 // now have to update all uses of the value to use either the original value,
1128 // the cloned value, or some PHI derived value. This can require arbitrary
1129 // PHI insertion, of which we are prepared to do, clean these up now.
1130 SSAUpdater SSAUpdate;
1131 SmallVector<Use*, 16> UsesToRename;
1132 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1133 // Scan all uses of this instruction to see if it is used outside of its
1134 // block, and if so, record them in UsesToRename.
1135 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1137 Instruction *User = cast<Instruction>(*UI);
1138 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1139 if (UserPN->getIncomingBlock(UI) == BB)
1141 } else if (User->getParent() == BB)
1144 UsesToRename.push_back(&UI.getUse());
1147 // If there are no uses outside the block, we're done with this instruction.
1148 if (UsesToRename.empty())
1151 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1153 // We found a use of I outside of BB. Rename all uses of I that are outside
1154 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1155 // with the two values we know.
1156 SSAUpdate.Initialize(I);
1157 SSAUpdate.AddAvailableValue(BB, I);
1158 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1160 while (!UsesToRename.empty())
1161 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1162 DEBUG(errs() << "\n");
1165 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1167 BB->removePredecessor(PredBB);
1169 // Remove the unconditional branch at the end of the PredBB block.
1170 OldPredBranch->eraseFromParent();