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/InstructionSimplify.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, const SmallVectorImpl<BasicBlock*> &PredBBs,
77 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
80 typedef SmallVectorImpl<std::pair<ConstantInt*,
81 BasicBlock*> > PredValueInfo;
83 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
84 PredValueInfo &Result);
85 bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB);
88 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
89 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
91 bool ProcessJumpOnPHI(PHINode *PN);
93 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
97 char JumpThreading::ID = 0;
98 static RegisterPass<JumpThreading>
99 X("jump-threading", "Jump Threading");
101 // Public interface to the Jump Threading pass
102 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
104 /// runOnFunction - Top level algorithm.
106 bool JumpThreading::runOnFunction(Function &F) {
107 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
108 TD = getAnalysisIfAvailable<TargetData>();
112 bool AnotherIteration = true, EverChanged = false;
113 while (AnotherIteration) {
114 AnotherIteration = false;
115 bool Changed = false;
116 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
118 // Thread all of the branches we can over this block.
119 while (ProcessBlock(BB))
124 // If the block is trivially dead, zap it. This eliminates the successor
125 // edges which simplifies the CFG.
126 if (pred_begin(BB) == pred_end(BB) &&
127 BB != &BB->getParent()->getEntryBlock()) {
128 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
129 << "' with terminator: " << *BB->getTerminator() << '\n');
130 LoopHeaders.erase(BB);
133 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
134 // Can't thread an unconditional jump, but if the block is "almost
135 // empty", we can replace uses of it with uses of the successor and make
137 if (BI->isUnconditional() &&
138 BB != &BB->getParent()->getEntryBlock()) {
139 BasicBlock::iterator BBI = BB->getFirstNonPHI();
140 // Ignore dbg intrinsics.
141 while (isa<DbgInfoIntrinsic>(BBI))
143 // If the terminator is the only non-phi instruction, try to nuke it.
144 if (BBI->isTerminator()) {
145 // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
146 // block, we have to make sure it isn't in the LoopHeaders set. We
147 // reinsert afterward in the rare case when the block isn't deleted.
148 bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
150 if (TryToSimplifyUncondBranchFromEmptyBlock(BB))
152 else if (ErasedFromLoopHeaders)
153 LoopHeaders.insert(BB);
158 AnotherIteration = Changed;
159 EverChanged |= Changed;
166 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
167 /// thread across it.
168 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
169 /// Ignore PHI nodes, these will be flattened when duplication happens.
170 BasicBlock::const_iterator I = BB->getFirstNonPHI();
172 // Sum up the cost of each instruction until we get to the terminator. Don't
173 // include the terminator because the copy won't include it.
175 for (; !isa<TerminatorInst>(I); ++I) {
176 // Debugger intrinsics don't incur code size.
177 if (isa<DbgInfoIntrinsic>(I)) continue;
179 // If this is a pointer->pointer bitcast, it is free.
180 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
183 // All other instructions count for at least one unit.
186 // Calls are more expensive. If they are non-intrinsic calls, we model them
187 // as having cost of 4. If they are a non-vector intrinsic, we model them
188 // as having cost of 2 total, and if they are a vector intrinsic, we model
189 // them as having cost 1.
190 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
191 if (!isa<IntrinsicInst>(CI))
193 else if (!isa<VectorType>(CI->getType()))
198 // Threading through a switch statement is particularly profitable. If this
199 // block ends in a switch, decrease its cost to make it more likely to happen.
200 if (isa<SwitchInst>(I))
201 Size = Size > 6 ? Size-6 : 0;
207 //===----------------------------------------------------------------------===//
209 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
210 /// delete the From instruction. In addition to a basic RAUW, this does a
211 /// recursive simplification of the newly formed instructions. This catches
212 /// things where one simplification exposes other opportunities. This only
213 /// simplifies and deletes scalar operations, it does not change the CFG.
215 static void ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
216 const TargetData *TD) {
217 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
219 // FromHandle - This keeps a weakvh on the from value so that we can know if
220 // it gets deleted out from under us in a recursive simplification.
221 WeakVH FromHandle(From);
223 while (!From->use_empty()) {
224 // Update the instruction to use the new value.
225 Use &U = From->use_begin().getUse();
226 Instruction *User = cast<Instruction>(U.getUser());
229 // See if we can simplify it.
230 if (Value *V = SimplifyInstruction(User, TD)) {
231 // Recursively simplify this.
232 ReplaceAndSimplifyAllUses(User, V, TD);
234 // If the recursive simplification ended up revisiting and deleting 'From'
240 From->eraseFromParent();
244 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
245 /// method is called when we're about to delete Pred as a predecessor of BB. If
246 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
248 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
249 /// nodes that collapse into identity values. For example, if we have:
250 /// x = phi(1, 0, 0, 0)
253 /// .. and delete the predecessor corresponding to the '1', this will attempt to
254 /// recursively fold the and to 0.
255 static void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
257 // This only adjusts blocks with PHI nodes.
258 if (!isa<PHINode>(BB->begin()))
261 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
262 // them down. This will leave us with single entry phi nodes and other phis
263 // that can be removed.
264 BB->removePredecessor(Pred, true);
266 WeakVH PhiIt = &BB->front();
267 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
268 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
270 Value *PNV = PN->hasConstantValue();
271 if (PNV == 0) continue;
273 // If we're able to simplify the phi to a single value, substitute the new
274 // value into all of its uses.
275 assert(PNV != PN && "hasConstantValue broken");
277 ReplaceAndSimplifyAllUses(PN, PNV, TD);
279 // If recursive simplification ended up deleting the next PHI node we would
280 // iterate to, then our iterator is invalid, restart scanning from the top
282 if (PhiIt == 0) PhiIt = &BB->front();
286 //===----------------------------------------------------------------------===//
289 /// FindLoopHeaders - We do not want jump threading to turn proper loop
290 /// structures into irreducible loops. Doing this breaks up the loop nesting
291 /// hierarchy and pessimizes later transformations. To prevent this from
292 /// happening, we first have to find the loop headers. Here we approximate this
293 /// by finding targets of backedges in the CFG.
295 /// Note that there definitely are cases when we want to allow threading of
296 /// edges across a loop header. For example, threading a jump from outside the
297 /// loop (the preheader) to an exit block of the loop is definitely profitable.
298 /// It is also almost always profitable to thread backedges from within the loop
299 /// to exit blocks, and is often profitable to thread backedges to other blocks
300 /// within the loop (forming a nested loop). This simple analysis is not rich
301 /// enough to track all of these properties and keep it up-to-date as the CFG
302 /// mutates, so we don't allow any of these transformations.
304 void JumpThreading::FindLoopHeaders(Function &F) {
305 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
306 FindFunctionBackedges(F, Edges);
308 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
309 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
312 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
313 /// if we can infer that the value is a known ConstantInt in any of our
314 /// predecessors. If so, return the known list of value and pred BB in the
315 /// result vector. If a value is known to be undef, it is returned as null.
317 /// The BB basic block is known to start with a PHI node.
319 /// This returns true if there were any known values.
322 /// TODO: Per PR2563, we could infer value range information about a predecessor
323 /// based on its terminator.
325 ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
326 PHINode *TheFirstPHI = cast<PHINode>(BB->begin());
328 // If V is a constantint, then it is known in all predecessors.
329 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
330 ConstantInt *CI = dyn_cast<ConstantInt>(V);
331 Result.resize(TheFirstPHI->getNumIncomingValues());
332 for (unsigned i = 0, e = Result.size(); i != e; ++i)
333 Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i));
337 // If V is a non-instruction value, or an instruction in a different block,
338 // then it can't be derived from a PHI.
339 Instruction *I = dyn_cast<Instruction>(V);
340 if (I == 0 || I->getParent() != BB)
343 /// If I is a PHI node, then we know the incoming values for any constants.
344 if (PHINode *PN = dyn_cast<PHINode>(I)) {
345 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
346 Value *InVal = PN->getIncomingValue(i);
347 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
348 ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
349 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
352 return !Result.empty();
355 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
357 // Handle some boolean conditions.
358 if (I->getType()->getPrimitiveSizeInBits() == 1) {
360 // X & false -> false
361 if (I->getOpcode() == Instruction::Or ||
362 I->getOpcode() == Instruction::And) {
363 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
364 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
366 if (LHSVals.empty() && RHSVals.empty())
369 ConstantInt *InterestingVal;
370 if (I->getOpcode() == Instruction::Or)
371 InterestingVal = ConstantInt::getTrue(I->getContext());
373 InterestingVal = ConstantInt::getFalse(I->getContext());
375 // Scan for the sentinel.
376 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
377 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
378 Result.push_back(LHSVals[i]);
379 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
380 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
381 Result.push_back(RHSVals[i]);
382 return !Result.empty();
385 // TODO: Should handle the NOT form of XOR.
389 // Handle compare with phi operand, where the PHI is defined in this block.
390 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
391 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
392 if (PN && PN->getParent() == BB) {
393 // We can do this simplification if any comparisons fold to true or false.
395 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
396 BasicBlock *PredBB = PN->getIncomingBlock(i);
397 Value *LHS = PN->getIncomingValue(i);
398 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
400 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS);
401 if (Res == 0) continue;
403 if (isa<UndefValue>(Res))
404 Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
405 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
406 Result.push_back(std::make_pair(CI, PredBB));
409 return !Result.empty();
412 // TODO: We could also recurse to see if we can determine constants another
420 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
421 /// in an undefined jump, decide which block is best to revector to.
423 /// Since we can pick an arbitrary destination, we pick the successor with the
424 /// fewest predecessors. This should reduce the in-degree of the others.
426 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
427 TerminatorInst *BBTerm = BB->getTerminator();
428 unsigned MinSucc = 0;
429 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
430 // Compute the successor with the minimum number of predecessors.
431 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
432 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
433 TestBB = BBTerm->getSuccessor(i);
434 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
435 if (NumPreds < MinNumPreds)
442 /// ProcessBlock - If there are any predecessors whose control can be threaded
443 /// through to a successor, transform them now.
444 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
445 // If this block has a single predecessor, and if that pred has a single
446 // successor, merge the blocks. This encourages recursive jump threading
447 // because now the condition in this block can be threaded through
448 // predecessors of our predecessor block.
449 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
450 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
452 // If SinglePred was a loop header, BB becomes one.
453 if (LoopHeaders.erase(SinglePred))
454 LoopHeaders.insert(BB);
456 // Remember if SinglePred was the entry block of the function. If so, we
457 // will need to move BB back to the entry position.
458 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
459 MergeBasicBlockIntoOnlyPred(BB);
461 if (isEntry && BB != &BB->getParent()->getEntryBlock())
462 BB->moveBefore(&BB->getParent()->getEntryBlock());
467 // Look to see if the terminator is a branch of switch, if not we can't thread
470 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
471 // Can't thread an unconditional jump.
472 if (BI->isUnconditional()) return false;
473 Condition = BI->getCondition();
474 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
475 Condition = SI->getCondition();
477 return false; // Must be an invoke.
479 // If the terminator of this block is branching on a constant, simplify the
480 // terminator to an unconditional branch. This can occur due to threading in
482 if (isa<ConstantInt>(Condition)) {
483 DEBUG(errs() << " In block '" << BB->getName()
484 << "' folding terminator: " << *BB->getTerminator() << '\n');
486 ConstantFoldTerminator(BB);
490 // If the terminator is branching on an undef, we can pick any of the
491 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
492 if (isa<UndefValue>(Condition)) {
493 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
495 // Fold the branch/switch.
496 TerminatorInst *BBTerm = BB->getTerminator();
497 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
498 if (i == BestSucc) continue;
499 RemovePredecessorAndSimplify(BBTerm->getSuccessor(i), BB, TD);
502 DEBUG(errs() << " In block '" << BB->getName()
503 << "' folding undef terminator: " << *BBTerm << '\n');
504 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
505 BBTerm->eraseFromParent();
509 Instruction *CondInst = dyn_cast<Instruction>(Condition);
511 // If the condition is an instruction defined in another block, see if a
512 // predecessor has the same condition:
516 if (!Condition->hasOneUse() && // Multiple uses.
517 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
518 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
519 if (isa<BranchInst>(BB->getTerminator())) {
520 for (; PI != E; ++PI)
521 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
522 if (PBI->isConditional() && PBI->getCondition() == Condition &&
523 ProcessBranchOnDuplicateCond(*PI, BB))
526 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
527 for (; PI != E; ++PI)
528 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
529 if (PSI->getCondition() == Condition &&
530 ProcessSwitchOnDuplicateCond(*PI, BB))
535 // All the rest of our checks depend on the condition being an instruction.
539 // See if this is a phi node in the current block.
540 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
541 if (PN->getParent() == BB)
542 return ProcessJumpOnPHI(PN);
544 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
545 if (!isa<PHINode>(CondCmp->getOperand(0)) ||
546 cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
547 // If we have a comparison, loop over the predecessors to see if there is
548 // a condition with a lexically identical value.
549 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
550 for (; PI != E; ++PI)
551 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
552 if (PBI->isConditional() && *PI != BB) {
553 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
554 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
555 CI->getOperand(1) == CondCmp->getOperand(1) &&
556 CI->getPredicate() == CondCmp->getPredicate()) {
557 // TODO: Could handle things like (x != 4) --> (x == 17)
558 if (ProcessBranchOnDuplicateCond(*PI, BB))
566 // Check for some cases that are worth simplifying. Right now we want to look
567 // for loads that are used by a switch or by the condition for the branch. If
568 // we see one, check to see if it's partially redundant. If so, insert a PHI
569 // which can then be used to thread the values.
571 // This is particularly important because reg2mem inserts loads and stores all
572 // over the place, and this blocks jump threading if we don't zap them.
573 Value *SimplifyValue = CondInst;
574 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
575 if (isa<Constant>(CondCmp->getOperand(1)))
576 SimplifyValue = CondCmp->getOperand(0);
578 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
579 if (SimplifyPartiallyRedundantLoad(LI))
583 // Handle a variety of cases where we are branching on something derived from
584 // a PHI node in the current block. If we can prove that any predecessors
585 // compute a predictable value based on a PHI node, thread those predecessors.
587 // We only bother doing this if the current block has a PHI node and if the
588 // conditional instruction lives in the current block. If either condition
589 // fails, this won't be a computable value anyway.
590 if (CondInst->getParent() == BB && isa<PHINode>(BB->front()))
591 if (ProcessThreadableEdges(CondInst, BB))
595 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
596 // "(X == 4)" thread through this block.
601 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
602 /// block that jump on exactly the same condition. This means that we almost
603 /// always know the direction of the edge in the DESTBB:
605 /// br COND, DESTBB, BBY
607 /// br COND, BBZ, BBW
609 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
610 /// in DESTBB, we have to thread over it.
611 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
613 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
615 // If both successors of PredBB go to DESTBB, we don't know anything. We can
616 // fold the branch to an unconditional one, which allows other recursive
619 if (PredBI->getSuccessor(1) != BB)
621 else if (PredBI->getSuccessor(0) != BB)
624 DEBUG(errs() << " In block '" << PredBB->getName()
625 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
627 ConstantFoldTerminator(PredBB);
631 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
633 // If the dest block has one predecessor, just fix the branch condition to a
634 // constant and fold it.
635 if (BB->getSinglePredecessor()) {
636 DEBUG(errs() << " In block '" << BB->getName()
637 << "' folding condition to '" << BranchDir << "': "
638 << *BB->getTerminator() << '\n');
640 Value *OldCond = DestBI->getCondition();
641 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
643 ConstantFoldTerminator(BB);
644 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
649 // Next, figure out which successor we are threading to.
650 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
652 SmallVector<BasicBlock*, 2> Preds;
653 Preds.push_back(PredBB);
655 // Ok, try to thread it!
656 return ThreadEdge(BB, Preds, SuccBB);
659 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
660 /// block that switch on exactly the same condition. This means that we almost
661 /// always know the direction of the edge in the DESTBB:
663 /// switch COND [... DESTBB, BBY ... ]
665 /// switch COND [... BBZ, BBW ]
667 /// Optimizing switches like this is very important, because simplifycfg builds
668 /// switches out of repeated 'if' conditions.
669 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
670 BasicBlock *DestBB) {
671 // Can't thread edge to self.
672 if (PredBB == DestBB)
675 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
676 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
678 // There are a variety of optimizations that we can potentially do on these
679 // blocks: we order them from most to least preferable.
681 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
682 // directly to their destination. This does not introduce *any* code size
683 // growth. Skip debug info first.
684 BasicBlock::iterator BBI = DestBB->begin();
685 while (isa<DbgInfoIntrinsic>(BBI))
688 // FIXME: Thread if it just contains a PHI.
689 if (isa<SwitchInst>(BBI)) {
690 bool MadeChange = false;
691 // Ignore the default edge for now.
692 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
693 ConstantInt *DestVal = DestSI->getCaseValue(i);
694 BasicBlock *DestSucc = DestSI->getSuccessor(i);
696 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
697 // PredSI has an explicit case for it. If so, forward. If it is covered
698 // by the default case, we can't update PredSI.
699 unsigned PredCase = PredSI->findCaseValue(DestVal);
700 if (PredCase == 0) continue;
702 // If PredSI doesn't go to DestBB on this value, then it won't reach the
703 // case on this condition.
704 if (PredSI->getSuccessor(PredCase) != DestBB &&
705 DestSI->getSuccessor(i) != DestBB)
708 // Otherwise, we're safe to make the change. Make sure that the edge from
709 // DestSI to DestSucc is not critical and has no PHI nodes.
710 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
711 DEBUG(errs() << "THROUGH: " << *DestSI);
713 // If the destination has PHI nodes, just split the edge for updating
715 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
716 SplitCriticalEdge(DestSI, i, this);
717 DestSucc = DestSI->getSuccessor(i);
719 FoldSingleEntryPHINodes(DestSucc);
720 PredSI->setSuccessor(PredCase, DestSucc);
732 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
733 /// load instruction, eliminate it by replacing it with a PHI node. This is an
734 /// important optimization that encourages jump threading, and needs to be run
735 /// interlaced with other jump threading tasks.
736 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
737 // Don't hack volatile loads.
738 if (LI->isVolatile()) return false;
740 // If the load is defined in a block with exactly one predecessor, it can't be
741 // partially redundant.
742 BasicBlock *LoadBB = LI->getParent();
743 if (LoadBB->getSinglePredecessor())
746 Value *LoadedPtr = LI->getOperand(0);
748 // If the loaded operand is defined in the LoadBB, it can't be available.
749 // FIXME: Could do PHI translation, that would be fun :)
750 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
751 if (PtrOp->getParent() == LoadBB)
754 // Scan a few instructions up from the load, to see if it is obviously live at
755 // the entry to its block.
756 BasicBlock::iterator BBIt = LI;
758 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
760 // If the value if the load is locally available within the block, just use
761 // it. This frequently occurs for reg2mem'd allocas.
762 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
764 // If the returned value is the load itself, replace with an undef. This can
765 // only happen in dead loops.
766 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
767 LI->replaceAllUsesWith(AvailableVal);
768 LI->eraseFromParent();
772 // Otherwise, if we scanned the whole block and got to the top of the block,
773 // we know the block is locally transparent to the load. If not, something
774 // might clobber its value.
775 if (BBIt != LoadBB->begin())
779 SmallPtrSet<BasicBlock*, 8> PredsScanned;
780 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
781 AvailablePredsTy AvailablePreds;
782 BasicBlock *OneUnavailablePred = 0;
784 // If we got here, the loaded value is transparent through to the start of the
785 // block. Check to see if it is available in any of the predecessor blocks.
786 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
788 BasicBlock *PredBB = *PI;
790 // If we already scanned this predecessor, skip it.
791 if (!PredsScanned.insert(PredBB))
794 // Scan the predecessor to see if the value is available in the pred.
795 BBIt = PredBB->end();
796 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
797 if (!PredAvailable) {
798 OneUnavailablePred = PredBB;
802 // If so, this load is partially redundant. Remember this info so that we
803 // can create a PHI node.
804 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
807 // If the loaded value isn't available in any predecessor, it isn't partially
809 if (AvailablePreds.empty()) return false;
811 // Okay, the loaded value is available in at least one (and maybe all!)
812 // predecessors. If the value is unavailable in more than one unique
813 // predecessor, we want to insert a merge block for those common predecessors.
814 // This ensures that we only have to insert one reload, thus not increasing
816 BasicBlock *UnavailablePred = 0;
818 // If there is exactly one predecessor where the value is unavailable, the
819 // already computed 'OneUnavailablePred' block is it. If it ends in an
820 // unconditional branch, we know that it isn't a critical edge.
821 if (PredsScanned.size() == AvailablePreds.size()+1 &&
822 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
823 UnavailablePred = OneUnavailablePred;
824 } else if (PredsScanned.size() != AvailablePreds.size()) {
825 // Otherwise, we had multiple unavailable predecessors or we had a critical
826 // edge from the one.
827 SmallVector<BasicBlock*, 8> PredsToSplit;
828 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
830 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
831 AvailablePredSet.insert(AvailablePreds[i].first);
833 // Add all the unavailable predecessors to the PredsToSplit list.
834 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
836 if (!AvailablePredSet.count(*PI))
837 PredsToSplit.push_back(*PI);
839 // Split them out to their own block.
841 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
842 "thread-split", this);
845 // If the value isn't available in all predecessors, then there will be
846 // exactly one where it isn't available. Insert a load on that edge and add
847 // it to the AvailablePreds list.
848 if (UnavailablePred) {
849 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
850 "Can't handle critical edge here!");
851 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
852 UnavailablePred->getTerminator());
853 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
856 // Now we know that each predecessor of this block has a value in
857 // AvailablePreds, sort them for efficient access as we're walking the preds.
858 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
860 // Create a PHI node at the start of the block for the PRE'd load value.
861 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
864 // Insert new entries into the PHI for each predecessor. A single block may
865 // have multiple entries here.
866 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
868 AvailablePredsTy::iterator I =
869 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
870 std::make_pair(*PI, (Value*)0));
872 assert(I != AvailablePreds.end() && I->first == *PI &&
873 "Didn't find entry for predecessor!");
875 PN->addIncoming(I->second, I->first);
878 //cerr << "PRE: " << *LI << *PN << "\n";
880 LI->replaceAllUsesWith(PN);
881 LI->eraseFromParent();
886 /// FindMostPopularDest - The specified list contains multiple possible
887 /// threadable destinations. Pick the one that occurs the most frequently in
890 FindMostPopularDest(BasicBlock *BB,
891 const SmallVectorImpl<std::pair<BasicBlock*,
892 BasicBlock*> > &PredToDestList) {
893 assert(!PredToDestList.empty());
895 // Determine popularity. If there are multiple possible destinations, we
896 // explicitly choose to ignore 'undef' destinations. We prefer to thread
897 // blocks with known and real destinations to threading undef. We'll handle
898 // them later if interesting.
899 DenseMap<BasicBlock*, unsigned> DestPopularity;
900 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
901 if (PredToDestList[i].second)
902 DestPopularity[PredToDestList[i].second]++;
904 // Find the most popular dest.
905 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
906 BasicBlock *MostPopularDest = DPI->first;
907 unsigned Popularity = DPI->second;
908 SmallVector<BasicBlock*, 4> SamePopularity;
910 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
911 // If the popularity of this entry isn't higher than the popularity we've
912 // seen so far, ignore it.
913 if (DPI->second < Popularity)
915 else if (DPI->second == Popularity) {
916 // If it is the same as what we've seen so far, keep track of it.
917 SamePopularity.push_back(DPI->first);
919 // If it is more popular, remember it.
920 SamePopularity.clear();
921 MostPopularDest = DPI->first;
922 Popularity = DPI->second;
926 // Okay, now we know the most popular destination. If there is more than
927 // destination, we need to determine one. This is arbitrary, but we need
928 // to make a deterministic decision. Pick the first one that appears in the
930 if (!SamePopularity.empty()) {
931 SamePopularity.push_back(MostPopularDest);
932 TerminatorInst *TI = BB->getTerminator();
933 for (unsigned i = 0; ; ++i) {
934 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
936 if (std::find(SamePopularity.begin(), SamePopularity.end(),
937 TI->getSuccessor(i)) == SamePopularity.end())
940 MostPopularDest = TI->getSuccessor(i);
945 // Okay, we have finally picked the most popular destination.
946 return MostPopularDest;
949 bool JumpThreading::ProcessThreadableEdges(Instruction *CondInst,
951 // If threading this would thread across a loop header, don't even try to
953 if (LoopHeaders.count(BB))
956 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
957 if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues))
959 assert(!PredValues.empty() &&
960 "ComputeValueKnownInPredecessors returned true with no values");
962 DEBUG(errs() << "IN BB: " << *BB;
963 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
964 errs() << " BB '" << BB->getName() << "': FOUND condition = ";
965 if (PredValues[i].first)
966 errs() << *PredValues[i].first;
969 errs() << " for pred '" << PredValues[i].second->getName()
973 // Decide what we want to thread through. Convert our list of known values to
974 // a list of known destinations for each pred. This also discards duplicate
975 // predecessors and keeps track of the undefined inputs (which are represented
976 // as a null dest in the PredToDestList).
977 SmallPtrSet<BasicBlock*, 16> SeenPreds;
978 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
980 BasicBlock *OnlyDest = 0;
981 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
983 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
984 BasicBlock *Pred = PredValues[i].second;
985 if (!SeenPreds.insert(Pred))
986 continue; // Duplicate predecessor entry.
988 // If the predecessor ends with an indirect goto, we can't change its
990 if (isa<IndirectBrInst>(Pred->getTerminator()))
993 ConstantInt *Val = PredValues[i].first;
996 if (Val == 0) // Undef.
998 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
999 DestBB = BI->getSuccessor(Val->isZero());
1001 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
1002 DestBB = SI->getSuccessor(SI->findCaseValue(Val));
1005 // If we have exactly one destination, remember it for efficiency below.
1008 else if (OnlyDest != DestBB)
1009 OnlyDest = MultipleDestSentinel;
1011 PredToDestList.push_back(std::make_pair(Pred, DestBB));
1014 // If all edges were unthreadable, we fail.
1015 if (PredToDestList.empty())
1018 // Determine which is the most common successor. If we have many inputs and
1019 // this block is a switch, we want to start by threading the batch that goes
1020 // to the most popular destination first. If we only know about one
1021 // threadable destination (the common case) we can avoid this.
1022 BasicBlock *MostPopularDest = OnlyDest;
1024 if (MostPopularDest == MultipleDestSentinel)
1025 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1027 // Now that we know what the most popular destination is, factor all
1028 // predecessors that will jump to it into a single predecessor.
1029 SmallVector<BasicBlock*, 16> PredsToFactor;
1030 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1031 if (PredToDestList[i].second == MostPopularDest) {
1032 BasicBlock *Pred = PredToDestList[i].first;
1034 // This predecessor may be a switch or something else that has multiple
1035 // edges to the block. Factor each of these edges by listing them
1036 // according to # occurrences in PredsToFactor.
1037 TerminatorInst *PredTI = Pred->getTerminator();
1038 for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
1039 if (PredTI->getSuccessor(i) == BB)
1040 PredsToFactor.push_back(Pred);
1043 // If the threadable edges are branching on an undefined value, we get to pick
1044 // the destination that these predecessors should get to.
1045 if (MostPopularDest == 0)
1046 MostPopularDest = BB->getTerminator()->
1047 getSuccessor(GetBestDestForJumpOnUndef(BB));
1049 // Ok, try to thread it!
1050 return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1053 /// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
1054 /// the current block. See if there are any simplifications we can do based on
1055 /// inputs to the phi node.
1057 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
1058 BasicBlock *BB = PN->getParent();
1060 // If any of the predecessor blocks end in an unconditional branch, we can
1061 // *duplicate* the jump into that block in order to further encourage jump
1062 // threading and to eliminate cases where we have branch on a phi of an icmp
1063 // (branch on icmp is much better).
1065 // We don't want to do this tranformation for switches, because we don't
1066 // really want to duplicate a switch.
1067 if (isa<SwitchInst>(BB->getTerminator()))
1070 // Look for unconditional branch predecessors.
1071 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1072 BasicBlock *PredBB = PN->getIncomingBlock(i);
1073 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1074 if (PredBr->isUnconditional() &&
1075 // Try to duplicate BB into PredBB.
1076 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
1084 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1085 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1086 /// NewPred using the entries from OldPred (suitably mapped).
1087 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1088 BasicBlock *OldPred,
1089 BasicBlock *NewPred,
1090 DenseMap<Instruction*, Value*> &ValueMap) {
1091 for (BasicBlock::iterator PNI = PHIBB->begin();
1092 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1093 // Ok, we have a PHI node. Figure out what the incoming value was for the
1095 Value *IV = PN->getIncomingValueForBlock(OldPred);
1097 // Remap the value if necessary.
1098 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1099 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1100 if (I != ValueMap.end())
1104 PN->addIncoming(IV, NewPred);
1108 /// ThreadEdge - We have decided that it is safe and profitable to factor the
1109 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1110 /// across BB. Transform the IR to reflect this change.
1111 bool JumpThreading::ThreadEdge(BasicBlock *BB,
1112 const SmallVectorImpl<BasicBlock*> &PredBBs,
1113 BasicBlock *SuccBB) {
1114 // If threading to the same block as we come from, we would infinite loop.
1116 DEBUG(errs() << " Not threading across BB '" << BB->getName()
1117 << "' - would thread to self!\n");
1121 // If threading this would thread across a loop header, don't thread the edge.
1122 // See the comments above FindLoopHeaders for justifications and caveats.
1123 if (LoopHeaders.count(BB)) {
1124 DEBUG(errs() << " Not threading across loop header BB '" << BB->getName()
1125 << "' to dest BB '" << SuccBB->getName()
1126 << "' - it might create an irreducible loop!\n");
1130 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1131 if (JumpThreadCost > Threshold) {
1132 DEBUG(errs() << " Not threading BB '" << BB->getName()
1133 << "' - Cost is too high: " << JumpThreadCost << "\n");
1137 // And finally, do it! Start by factoring the predecessors is needed.
1139 if (PredBBs.size() == 1)
1140 PredBB = PredBBs[0];
1142 DEBUG(errs() << " Factoring out " << PredBBs.size()
1143 << " common predecessors.\n");
1144 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1148 // And finally, do it!
1149 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
1150 << SuccBB->getName() << "' with cost: " << JumpThreadCost
1151 << ", across block:\n "
1154 // We are going to have to map operands from the original BB block to the new
1155 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1156 // account for entry from PredBB.
1157 DenseMap<Instruction*, Value*> ValueMapping;
1159 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1160 BB->getName()+".thread",
1161 BB->getParent(), BB);
1162 NewBB->moveAfter(PredBB);
1164 BasicBlock::iterator BI = BB->begin();
1165 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1166 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1168 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1169 // mapping and using it to remap operands in the cloned instructions.
1170 for (; !isa<TerminatorInst>(BI); ++BI) {
1171 Instruction *New = BI->clone();
1172 New->setName(BI->getName());
1173 NewBB->getInstList().push_back(New);
1174 ValueMapping[BI] = New;
1176 // Remap operands to patch up intra-block references.
1177 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1178 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1179 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1180 if (I != ValueMapping.end())
1181 New->setOperand(i, I->second);
1185 // We didn't copy the terminator from BB over to NewBB, because there is now
1186 // an unconditional jump to SuccBB. Insert the unconditional jump.
1187 BranchInst::Create(SuccBB, NewBB);
1189 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1190 // PHI nodes for NewBB now.
1191 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1193 // If there were values defined in BB that are used outside the block, then we
1194 // now have to update all uses of the value to use either the original value,
1195 // the cloned value, or some PHI derived value. This can require arbitrary
1196 // PHI insertion, of which we are prepared to do, clean these up now.
1197 SSAUpdater SSAUpdate;
1198 SmallVector<Use*, 16> UsesToRename;
1199 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1200 // Scan all uses of this instruction to see if it is used outside of its
1201 // block, and if so, record them in UsesToRename.
1202 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1204 Instruction *User = cast<Instruction>(*UI);
1205 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1206 if (UserPN->getIncomingBlock(UI) == BB)
1208 } else if (User->getParent() == BB)
1211 UsesToRename.push_back(&UI.getUse());
1214 // If there are no uses outside the block, we're done with this instruction.
1215 if (UsesToRename.empty())
1218 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1220 // We found a use of I outside of BB. Rename all uses of I that are outside
1221 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1222 // with the two values we know.
1223 SSAUpdate.Initialize(I);
1224 SSAUpdate.AddAvailableValue(BB, I);
1225 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1227 while (!UsesToRename.empty())
1228 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1229 DEBUG(errs() << "\n");
1233 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
1234 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1235 // us to simplify any PHI nodes in BB.
1236 TerminatorInst *PredTerm = PredBB->getTerminator();
1237 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1238 if (PredTerm->getSuccessor(i) == BB) {
1239 RemovePredecessorAndSimplify(BB, PredBB, TD);
1240 PredTerm->setSuccessor(i, NewBB);
1243 // At this point, the IR is fully up to date and consistent. Do a quick scan
1244 // over the new instructions and zap any that are constants or dead. This
1245 // frequently happens because of phi translation.
1246 BI = NewBB->begin();
1247 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1248 Instruction *Inst = BI++;
1250 if (Value *V = SimplifyInstruction(Inst, TD)) {
1251 WeakVH BIHandle(BI);
1252 ReplaceAndSimplifyAllUses(Inst, V, TD);
1254 BI = NewBB->begin();
1258 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1261 // Threaded an edge!
1266 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1267 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1268 /// If we can duplicate the contents of BB up into PredBB do so now, this
1269 /// improves the odds that the branch will be on an analyzable instruction like
1271 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1272 BasicBlock *PredBB) {
1273 // If BB is a loop header, then duplicating this block outside the loop would
1274 // cause us to transform this into an irreducible loop, don't do this.
1275 // See the comments above FindLoopHeaders for justifications and caveats.
1276 if (LoopHeaders.count(BB)) {
1277 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1278 << "' into predecessor block '" << PredBB->getName()
1279 << "' - it might create an irreducible loop!\n");
1283 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1284 if (DuplicationCost > Threshold) {
1285 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1286 << "' - Cost is too high: " << DuplicationCost << "\n");
1290 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1292 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1293 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1294 << DuplicationCost << " block is:" << *BB << "\n");
1296 // We are going to have to map operands from the original BB block into the
1297 // PredBB block. Evaluate PHI nodes in BB.
1298 DenseMap<Instruction*, Value*> ValueMapping;
1300 BasicBlock::iterator BI = BB->begin();
1301 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1302 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1304 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1306 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1307 // mapping and using it to remap operands in the cloned instructions.
1308 for (; BI != BB->end(); ++BI) {
1309 Instruction *New = BI->clone();
1310 New->setName(BI->getName());
1311 PredBB->getInstList().insert(OldPredBranch, New);
1312 ValueMapping[BI] = New;
1314 // Remap operands to patch up intra-block references.
1315 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1316 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1317 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1318 if (I != ValueMapping.end())
1319 New->setOperand(i, I->second);
1323 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1324 // add entries to the PHI nodes for branch from PredBB now.
1325 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1326 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1328 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1331 // If there were values defined in BB that are used outside the block, then we
1332 // now have to update all uses of the value to use either the original value,
1333 // the cloned value, or some PHI derived value. This can require arbitrary
1334 // PHI insertion, of which we are prepared to do, clean these up now.
1335 SSAUpdater SSAUpdate;
1336 SmallVector<Use*, 16> UsesToRename;
1337 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1338 // Scan all uses of this instruction to see if it is used outside of its
1339 // block, and if so, record them in UsesToRename.
1340 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1342 Instruction *User = cast<Instruction>(*UI);
1343 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1344 if (UserPN->getIncomingBlock(UI) == BB)
1346 } else if (User->getParent() == BB)
1349 UsesToRename.push_back(&UI.getUse());
1352 // If there are no uses outside the block, we're done with this instruction.
1353 if (UsesToRename.empty())
1356 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1358 // We found a use of I outside of BB. Rename all uses of I that are outside
1359 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1360 // with the two values we know.
1361 SSAUpdate.Initialize(I);
1362 SSAUpdate.AddAvailableValue(BB, I);
1363 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1365 while (!UsesToRename.empty())
1366 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1367 DEBUG(errs() << "\n");
1370 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1372 RemovePredecessorAndSimplify(BB, PredBB, TD);
1374 // Remove the unconditional branch at the end of the PredBB block.
1375 OldPredBranch->eraseFromParent();