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");
37 static cl::opt<unsigned>
38 Threshold("jump-threading-threshold",
39 cl::desc("Max block size to duplicate for jump threading"),
40 cl::init(6), cl::Hidden);
43 /// This pass performs 'jump threading', which looks at blocks that have
44 /// multiple predecessors and multiple successors. If one or more of the
45 /// predecessors of the block can be proven to always jump to one of the
46 /// successors, we forward the edge from the predecessor to the successor by
47 /// duplicating the contents of this block.
49 /// An example of when this can occur is code like this:
56 /// In this case, the unconditional branch at the end of the first if can be
57 /// revectored to the false side of the second if.
59 class JumpThreading : public FunctionPass {
62 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
64 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
67 static char ID; // Pass identification
68 JumpThreading() : FunctionPass(&ID) {}
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 bool runOnFunction(Function &F);
74 void FindLoopHeaders(Function &F);
76 bool ProcessBlock(BasicBlock *BB);
77 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB,
78 unsigned JumpThreadCost);
79 BasicBlock *FactorCommonPHIPreds(PHINode *PN, 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());
123 LoopHeaders.erase(BB);
128 AnotherIteration = Changed;
129 EverChanged |= Changed;
136 /// FindLoopHeaders - We do not want jump threading to turn proper loop
137 /// structures into irreducible loops. Doing this breaks up the loop nesting
138 /// hierarchy and pessimizes later transformations. To prevent this from
139 /// happening, we first have to find the loop headers. Here we approximate this
140 /// by finding targets of backedges in the CFG.
142 /// Note that there definitely are cases when we want to allow threading of
143 /// edges across a loop header. For example, threading a jump from outside the
144 /// loop (the preheader) to an exit block of the loop is definitely profitable.
145 /// It is also almost always profitable to thread backedges from within the loop
146 /// to exit blocks, and is often profitable to thread backedges to other blocks
147 /// within the loop (forming a nested loop). This simple analysis is not rich
148 /// enough to track all of these properties and keep it up-to-date as the CFG
149 /// mutates, so we don't allow any of these transformations.
151 void JumpThreading::FindLoopHeaders(Function &F) {
152 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
153 FindFunctionBackedges(F, Edges);
155 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
156 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
160 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
161 /// value for the PHI, factor them together so we get one block to thread for
163 /// This is important for things like "phi i1 [true, true, false, true, x]"
164 /// where we only need to clone the block for the true blocks once.
166 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
167 SmallVector<BasicBlock*, 16> CommonPreds;
168 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
169 if (PN->getIncomingValue(i) == Val)
170 CommonPreds.push_back(PN->getIncomingBlock(i));
172 if (CommonPreds.size() == 1)
173 return CommonPreds[0];
175 DEBUG(errs() << " Factoring out " << CommonPreds.size()
176 << " common predecessors.\n");
177 return SplitBlockPredecessors(PN->getParent(),
178 &CommonPreds[0], CommonPreds.size(),
183 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
184 /// thread across it.
185 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
186 /// Ignore PHI nodes, these will be flattened when duplication happens.
187 BasicBlock::const_iterator I = BB->getFirstNonPHI();
189 // Sum up the cost of each instruction until we get to the terminator. Don't
190 // include the terminator because the copy won't include it.
192 for (; !isa<TerminatorInst>(I); ++I) {
193 // Debugger intrinsics don't incur code size.
194 if (isa<DbgInfoIntrinsic>(I)) continue;
196 // If this is a pointer->pointer bitcast, it is free.
197 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
200 // All other instructions count for at least one unit.
203 // Calls are more expensive. If they are non-intrinsic calls, we model them
204 // as having cost of 4. If they are a non-vector intrinsic, we model them
205 // as having cost of 2 total, and if they are a vector intrinsic, we model
206 // them as having cost 1.
207 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
208 if (!isa<IntrinsicInst>(CI))
210 else if (!isa<VectorType>(CI->getType()))
215 // Threading through a switch statement is particularly profitable. If this
216 // block ends in a switch, decrease its cost to make it more likely to happen.
217 if (isa<SwitchInst>(I))
218 Size = Size > 6 ? Size-6 : 0;
223 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
224 /// in an undefined jump, decide which block is best to revector to.
226 /// Since we can pick an arbitrary destination, we pick the successor with the
227 /// fewest predecessors. This should reduce the in-degree of the others.
229 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
230 TerminatorInst *BBTerm = BB->getTerminator();
231 unsigned MinSucc = 0;
232 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
233 // Compute the successor with the minimum number of predecessors.
234 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
235 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
236 TestBB = BBTerm->getSuccessor(i);
237 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
238 if (NumPreds < MinNumPreds)
245 /// ProcessBlock - If there are any predecessors whose control can be threaded
246 /// through to a successor, transform them now.
247 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
248 // If this block has a single predecessor, and if that pred has a single
249 // successor, merge the blocks. This encourages recursive jump threading
250 // because now the condition in this block can be threaded through
251 // predecessors of our predecessor block.
252 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
253 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
255 // If SinglePred was a loop header, BB becomes one.
256 if (LoopHeaders.erase(SinglePred))
257 LoopHeaders.insert(BB);
259 // Remember if SinglePred was the entry block of the function. If so, we
260 // will need to move BB back to the entry position.
261 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
262 MergeBasicBlockIntoOnlyPred(BB);
264 if (isEntry && BB != &BB->getParent()->getEntryBlock())
265 BB->moveBefore(&BB->getParent()->getEntryBlock());
269 // See if this block ends with a branch or switch. If so, see if the
270 // condition is a phi node. If so, and if an entry of the phi node is a
271 // constant, we can thread the block.
273 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
274 // Can't thread an unconditional jump.
275 if (BI->isUnconditional()) return false;
276 Condition = BI->getCondition();
277 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
278 Condition = SI->getCondition();
280 return false; // Must be an invoke.
282 // If the terminator of this block is branching on a constant, simplify the
283 // terminator to an unconditional branch. This can occur due to threading in
285 if (isa<ConstantInt>(Condition)) {
286 DEBUG(errs() << " In block '" << BB->getName()
287 << "' folding terminator: " << *BB->getTerminator());
289 ConstantFoldTerminator(BB);
293 // If the terminator is branching on an undef, we can pick any of the
294 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
295 if (isa<UndefValue>(Condition)) {
296 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
298 // Fold the branch/switch.
299 TerminatorInst *BBTerm = BB->getTerminator();
300 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
301 if (i == BestSucc) continue;
302 BBTerm->getSuccessor(i)->removePredecessor(BB);
305 DEBUG(errs() << " In block '" << BB->getName()
306 << "' folding undef terminator: " << *BBTerm);
307 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
308 BBTerm->eraseFromParent();
312 Instruction *CondInst = dyn_cast<Instruction>(Condition);
314 // If the condition is an instruction defined in another block, see if a
315 // predecessor has the same condition:
319 if (!Condition->hasOneUse() && // Multiple uses.
320 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
321 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
322 if (isa<BranchInst>(BB->getTerminator())) {
323 for (; PI != E; ++PI)
324 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
325 if (PBI->isConditional() && PBI->getCondition() == Condition &&
326 ProcessBranchOnDuplicateCond(*PI, BB))
329 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
330 for (; PI != E; ++PI)
331 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
332 if (PSI->getCondition() == Condition &&
333 ProcessSwitchOnDuplicateCond(*PI, BB))
338 // All the rest of our checks depend on the condition being an instruction.
342 // See if this is a phi node in the current block.
343 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
344 if (PN->getParent() == BB)
345 return ProcessJumpOnPHI(PN);
347 // If this is a conditional branch whose condition is and/or of a phi, try to
349 if ((CondInst->getOpcode() == Instruction::And ||
350 CondInst->getOpcode() == Instruction::Or) &&
351 isa<BranchInst>(BB->getTerminator()) &&
352 ProcessBranchOnLogical(CondInst, BB,
353 CondInst->getOpcode() == Instruction::And))
356 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
357 if (isa<PHINode>(CondCmp->getOperand(0))) {
358 // If we have "br (phi != 42)" and the phi node has any constant values
359 // as operands, we can thread through this block.
361 // If we have "br (cmp phi, x)" and the phi node contains x such that the
362 // comparison uniquely identifies the branch target, we can thread
363 // through this block.
365 if (ProcessBranchOnCompare(CondCmp, BB))
369 // If we have a comparison, loop over the predecessors to see if there is
370 // a condition with the same value.
371 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
372 for (; PI != E; ++PI)
373 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
374 if (PBI->isConditional() && *PI != BB) {
375 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
376 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
377 CI->getOperand(1) == CondCmp->getOperand(1) &&
378 CI->getPredicate() == CondCmp->getPredicate()) {
379 // TODO: Could handle things like (x != 4) --> (x == 17)
380 if (ProcessBranchOnDuplicateCond(*PI, BB))
387 // Check for some cases that are worth simplifying. Right now we want to look
388 // for loads that are used by a switch or by the condition for the branch. If
389 // we see one, check to see if it's partially redundant. If so, insert a PHI
390 // which can then be used to thread the values.
392 // This is particularly important because reg2mem inserts loads and stores all
393 // over the place, and this blocks jump threading if we don't zap them.
394 Value *SimplifyValue = CondInst;
395 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
396 if (isa<Constant>(CondCmp->getOperand(1)))
397 SimplifyValue = CondCmp->getOperand(0);
399 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
400 if (SimplifyPartiallyRedundantLoad(LI))
403 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
404 // "(X == 4)" thread through this block.
409 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
410 /// block that jump on exactly the same condition. This means that we almost
411 /// always know the direction of the edge in the DESTBB:
413 /// br COND, DESTBB, BBY
415 /// br COND, BBZ, BBW
417 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
418 /// in DESTBB, we have to thread over it.
419 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
421 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
423 // If both successors of PredBB go to DESTBB, we don't know anything. We can
424 // fold the branch to an unconditional one, which allows other recursive
427 if (PredBI->getSuccessor(1) != BB)
429 else if (PredBI->getSuccessor(0) != BB)
432 DEBUG(errs() << " In block '" << PredBB->getName()
433 << "' folding terminator: " << *PredBB->getTerminator());
435 ConstantFoldTerminator(PredBB);
439 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
441 // If the dest block has one predecessor, just fix the branch condition to a
442 // constant and fold it.
443 if (BB->getSinglePredecessor()) {
444 DEBUG(errs() << " In block '" << BB->getName()
445 << "' folding condition to '" << BranchDir << "': "
446 << *BB->getTerminator());
448 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
450 ConstantFoldTerminator(BB);
454 // Otherwise we need to thread from PredBB to DestBB's successor which
455 // involves code duplication. Check to see if it is worth it.
456 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
457 if (JumpThreadCost > Threshold) {
458 DEBUG(errs() << " Not threading BB '" << BB->getName()
459 << "' - Cost is too high: " << JumpThreadCost << "\n");
463 // Next, figure out which successor we are threading to.
464 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
466 // Ok, try to thread it!
467 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
470 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
471 /// block that switch on exactly the same condition. This means that we almost
472 /// always know the direction of the edge in the DESTBB:
474 /// switch COND [... DESTBB, BBY ... ]
476 /// switch COND [... BBZ, BBW ]
478 /// Optimizing switches like this is very important, because simplifycfg builds
479 /// switches out of repeated 'if' conditions.
480 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
481 BasicBlock *DestBB) {
482 // Can't thread edge to self.
483 if (PredBB == DestBB)
486 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
487 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
489 // There are a variety of optimizations that we can potentially do on these
490 // blocks: we order them from most to least preferable.
492 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
493 // directly to their destination. This does not introduce *any* code size
494 // growth. Skip debug info first.
495 BasicBlock::iterator BBI = DestBB->begin();
496 while (isa<DbgInfoIntrinsic>(BBI))
499 // FIXME: Thread if it just contains a PHI.
500 if (isa<SwitchInst>(BBI)) {
501 bool MadeChange = false;
502 // Ignore the default edge for now.
503 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
504 ConstantInt *DestVal = DestSI->getCaseValue(i);
505 BasicBlock *DestSucc = DestSI->getSuccessor(i);
507 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
508 // PredSI has an explicit case for it. If so, forward. If it is covered
509 // by the default case, we can't update PredSI.
510 unsigned PredCase = PredSI->findCaseValue(DestVal);
511 if (PredCase == 0) continue;
513 // If PredSI doesn't go to DestBB on this value, then it won't reach the
514 // case on this condition.
515 if (PredSI->getSuccessor(PredCase) != DestBB &&
516 DestSI->getSuccessor(i) != DestBB)
519 // Otherwise, we're safe to make the change. Make sure that the edge from
520 // DestSI to DestSucc is not critical and has no PHI nodes.
521 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
522 DEBUG(errs() << "THROUGH: " << *DestSI);
524 // If the destination has PHI nodes, just split the edge for updating
526 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
527 SplitCriticalEdge(DestSI, i, this);
528 DestSucc = DestSI->getSuccessor(i);
530 FoldSingleEntryPHINodes(DestSucc);
531 PredSI->setSuccessor(PredCase, DestSucc);
543 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
544 /// load instruction, eliminate it by replacing it with a PHI node. This is an
545 /// important optimization that encourages jump threading, and needs to be run
546 /// interlaced with other jump threading tasks.
547 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
548 // Don't hack volatile loads.
549 if (LI->isVolatile()) return false;
551 // If the load is defined in a block with exactly one predecessor, it can't be
552 // partially redundant.
553 BasicBlock *LoadBB = LI->getParent();
554 if (LoadBB->getSinglePredecessor())
557 Value *LoadedPtr = LI->getOperand(0);
559 // If the loaded operand is defined in the LoadBB, it can't be available.
560 // FIXME: Could do PHI translation, that would be fun :)
561 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
562 if (PtrOp->getParent() == LoadBB)
565 // Scan a few instructions up from the load, to see if it is obviously live at
566 // the entry to its block.
567 BasicBlock::iterator BBIt = LI;
569 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
571 // If the value if the load is locally available within the block, just use
572 // it. This frequently occurs for reg2mem'd allocas.
573 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
575 // If the returned value is the load itself, replace with an undef. This can
576 // only happen in dead loops.
577 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
578 LI->replaceAllUsesWith(AvailableVal);
579 LI->eraseFromParent();
583 // Otherwise, if we scanned the whole block and got to the top of the block,
584 // we know the block is locally transparent to the load. If not, something
585 // might clobber its value.
586 if (BBIt != LoadBB->begin())
590 SmallPtrSet<BasicBlock*, 8> PredsScanned;
591 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
592 AvailablePredsTy AvailablePreds;
593 BasicBlock *OneUnavailablePred = 0;
595 // If we got here, the loaded value is transparent through to the start of the
596 // block. Check to see if it is available in any of the predecessor blocks.
597 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
599 BasicBlock *PredBB = *PI;
601 // If we already scanned this predecessor, skip it.
602 if (!PredsScanned.insert(PredBB))
605 // Scan the predecessor to see if the value is available in the pred.
606 BBIt = PredBB->end();
607 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
608 if (!PredAvailable) {
609 OneUnavailablePred = PredBB;
613 // If so, this load is partially redundant. Remember this info so that we
614 // can create a PHI node.
615 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
618 // If the loaded value isn't available in any predecessor, it isn't partially
620 if (AvailablePreds.empty()) return false;
622 // Okay, the loaded value is available in at least one (and maybe all!)
623 // predecessors. If the value is unavailable in more than one unique
624 // predecessor, we want to insert a merge block for those common predecessors.
625 // This ensures that we only have to insert one reload, thus not increasing
627 BasicBlock *UnavailablePred = 0;
629 // If there is exactly one predecessor where the value is unavailable, the
630 // already computed 'OneUnavailablePred' block is it. If it ends in an
631 // unconditional branch, we know that it isn't a critical edge.
632 if (PredsScanned.size() == AvailablePreds.size()+1 &&
633 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
634 UnavailablePred = OneUnavailablePred;
635 } else if (PredsScanned.size() != AvailablePreds.size()) {
636 // Otherwise, we had multiple unavailable predecessors or we had a critical
637 // edge from the one.
638 SmallVector<BasicBlock*, 8> PredsToSplit;
639 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
641 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
642 AvailablePredSet.insert(AvailablePreds[i].first);
644 // Add all the unavailable predecessors to the PredsToSplit list.
645 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
647 if (!AvailablePredSet.count(*PI))
648 PredsToSplit.push_back(*PI);
650 // Split them out to their own block.
652 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
653 "thread-split", this);
656 // If the value isn't available in all predecessors, then there will be
657 // exactly one where it isn't available. Insert a load on that edge and add
658 // it to the AvailablePreds list.
659 if (UnavailablePred) {
660 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
661 "Can't handle critical edge here!");
662 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
663 UnavailablePred->getTerminator());
664 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
667 // Now we know that each predecessor of this block has a value in
668 // AvailablePreds, sort them for efficient access as we're walking the preds.
669 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
671 // Create a PHI node at the start of the block for the PRE'd load value.
672 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
675 // Insert new entries into the PHI for each predecessor. A single block may
676 // have multiple entries here.
677 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
679 AvailablePredsTy::iterator I =
680 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
681 std::make_pair(*PI, (Value*)0));
683 assert(I != AvailablePreds.end() && I->first == *PI &&
684 "Didn't find entry for predecessor!");
686 PN->addIncoming(I->second, I->first);
689 //cerr << "PRE: " << *LI << *PN << "\n";
691 LI->replaceAllUsesWith(PN);
692 LI->eraseFromParent();
698 /// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
699 /// the current block. See if there are any simplifications we can do based on
700 /// inputs to the phi node.
702 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
703 // See if the phi node has any constant integer or undef values. If so, we
704 // can determine where the corresponding predecessor will branch.
705 Constant *PredCst = 0;
706 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
707 Value *PredVal = PN->getIncomingValue(i);
708 if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) {
713 if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) {
719 // If no incoming value has a constant, we don't know the destination of any
725 // See if the cost of duplicating this block is low enough.
726 BasicBlock *BB = PN->getParent();
727 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
728 if (JumpThreadCost > Threshold) {
729 DEBUG(errs() << " Not threading BB '" << BB->getName()
730 << "' - Cost is too high: " << JumpThreadCost << "\n");
734 // If so, we can actually do this threading. Merge any common predecessors
735 // that will act the same.
736 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
739 TerminatorInst *BBTerm = BB->getTerminator();
741 // Next, figure out which successor we are threading to.
743 if (isa<UndefValue>(PredCst)) {
744 // If the branch was going off an undef from PredBB, pick an arbitrary dest.
745 SuccBB = BBTerm->getSuccessor(GetBestDestForJumpOnUndef(BB));
746 } else if (BranchInst *BI = dyn_cast<BranchInst>(BBTerm))
747 SuccBB = BI->getSuccessor(cast<ConstantInt>(PredCst)->isZero());
749 SwitchInst *SI = cast<SwitchInst>(BBTerm);
750 SuccBB = SI->getSuccessor(SI->findCaseValue(cast<ConstantInt>(PredCst)));
753 // Ok, try to thread it!
754 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
757 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
758 /// whose condition is an AND/OR where one side is PN. If PN has constant
759 /// operands that permit us to evaluate the condition for some operand, thread
760 /// through the block. For example with:
761 /// br (and X, phi(Y, Z, false))
762 /// the predecessor corresponding to the 'false' will always jump to the false
763 /// destination of the branch.
765 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
767 // If this is a binary operator tree of the same AND/OR opcode, check the
769 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
770 if ((isAnd && BO->getOpcode() == Instruction::And) ||
771 (!isAnd && BO->getOpcode() == Instruction::Or)) {
772 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
774 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
778 // If this isn't a PHI node, we can't handle it.
779 PHINode *PN = dyn_cast<PHINode>(V);
780 if (!PN || PN->getParent() != BB) return false;
782 // We can only do the simplification for phi nodes of 'false' with AND or
783 // 'true' with OR. See if we have any entries in the phi for this.
784 unsigned PredNo = ~0U;
785 ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()),
787 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
788 if (PN->getIncomingValue(i) == PredCst) {
794 // If no match, bail out.
798 // See if the cost of duplicating this block is low enough.
799 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
800 if (JumpThreadCost > Threshold) {
801 DEBUG(errs() << " Not threading BB '" << BB->getName()
802 << "' - Cost is too high: " << JumpThreadCost << "\n");
806 // If so, we can actually do this threading. Merge any common predecessors
807 // that will act the same.
808 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
810 // Next, figure out which successor we are threading to. If this was an AND,
811 // the constant must be FALSE, and we must be targeting the 'false' block.
812 // If this is an OR, the constant must be TRUE, and we must be targeting the
814 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
816 // Ok, try to thread it!
817 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
820 /// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
821 /// hand sides of the compare instruction, try to determine the result. If the
822 /// result can not be determined, a null pointer is returned.
823 static Constant *GetResultOfComparison(CmpInst::Predicate pred,
824 Value *LHS, Value *RHS,
825 LLVMContext &Context) {
826 if (Constant *CLHS = dyn_cast<Constant>(LHS))
827 if (Constant *CRHS = dyn_cast<Constant>(RHS))
828 return ConstantExpr::getCompare(pred, CLHS, CRHS);
831 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
832 return ICmpInst::isTrueWhenEqual(pred) ?
833 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context);
838 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
839 /// node and a value. If we can identify when the comparison is true between
840 /// the phi inputs and the value, we can fold the compare for that edge and
841 /// thread through it.
842 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
843 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
844 Value *RHS = Cmp->getOperand(1);
846 // If the phi isn't in the current block, an incoming edge to this block
847 // doesn't control the destination.
848 if (PN->getParent() != BB)
851 // We can do this simplification if any comparisons fold to true or false.
854 bool TrueDirection = false;
855 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
856 PredVal = PN->getIncomingValue(i);
858 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal,
859 RHS, Cmp->getContext());
865 // If this folded to a constant expr, we can't do anything.
866 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
867 TrueDirection = ResC->getZExtValue();
870 // If this folded to undef, just go the false way.
871 if (isa<UndefValue>(Res)) {
872 TrueDirection = false;
876 // Otherwise, we can't fold this input.
880 // If no match, bail out.
884 // See if the cost of duplicating this block is low enough.
885 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
886 if (JumpThreadCost > Threshold) {
887 DEBUG(errs() << " Not threading BB '" << BB->getName()
888 << "' - Cost is too high: " << JumpThreadCost << "\n");
892 // If so, we can actually do this threading. Merge any common predecessors
893 // that will act the same.
894 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
896 // Next, get our successor.
897 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
899 // Ok, try to thread it!
900 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
904 /// ThreadEdge - We have decided that it is safe and profitable to thread an
905 /// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
907 bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
908 BasicBlock *SuccBB, unsigned JumpThreadCost) {
910 // If threading to the same block as we come from, we would infinite loop.
912 DEBUG(errs() << " Not threading across BB '" << BB->getName()
913 << "' - would thread to self!\n");
917 // If threading this would thread across a loop header, don't thread the edge.
918 // See the comments above FindLoopHeaders for justifications and caveats.
919 if (LoopHeaders.count(BB)) {
920 DEBUG(errs() << " Not threading from '" << PredBB->getName()
921 << "' across loop header BB '" << BB->getName()
922 << "' to dest BB '" << SuccBB->getName()
923 << "' - it might create an irreducible loop!\n");
927 // And finally, do it!
928 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
929 << SuccBB->getName() << "' with cost: " << JumpThreadCost
930 << ", across block:\n "
933 // We are going to have to map operands from the original BB block to the new
934 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
935 // account for entry from PredBB.
936 DenseMap<Instruction*, Value*> ValueMapping;
938 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
939 BB->getName()+".thread",
940 BB->getParent(), BB);
941 NewBB->moveAfter(PredBB);
943 BasicBlock::iterator BI = BB->begin();
944 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
945 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
947 // Clone the non-phi instructions of BB into NewBB, keeping track of the
948 // mapping and using it to remap operands in the cloned instructions.
949 for (; !isa<TerminatorInst>(BI); ++BI) {
950 Instruction *New = BI->clone();
951 New->setName(BI->getName());
952 NewBB->getInstList().push_back(New);
953 ValueMapping[BI] = New;
955 // Remap operands to patch up intra-block references.
956 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
957 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
958 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
959 if (I != ValueMapping.end())
960 New->setOperand(i, I->second);
964 // We didn't copy the terminator from BB over to NewBB, because there is now
965 // an unconditional jump to SuccBB. Insert the unconditional jump.
966 BranchInst::Create(SuccBB, NewBB);
968 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
969 // PHI nodes for NewBB now.
970 for (BasicBlock::iterator PNI = SuccBB->begin();
971 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
972 // Ok, we have a PHI node. Figure out what the incoming value was for the
974 Value *IV = PN->getIncomingValueForBlock(BB);
976 // Remap the value if necessary.
977 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
978 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
979 if (I != ValueMapping.end())
982 PN->addIncoming(IV, NewBB);
985 // If there were values defined in BB that are used outside the block, then we
986 // now have to update all uses of the value to use either the original value,
987 // the cloned value, or some PHI derived value. This can require arbitrary
988 // PHI insertion, of which we are prepared to do, clean these up now.
989 SSAUpdater SSAUpdate;
990 SmallVector<Use*, 16> UsesToRename;
991 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
992 // Scan all uses of this instruction to see if it is used outside of its
993 // block, and if so, record them in UsesToRename.
994 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
996 Instruction *User = cast<Instruction>(*UI);
997 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
998 if (UserPN->getIncomingBlock(UI) == BB)
1000 } else if (User->getParent() == BB)
1003 UsesToRename.push_back(&UI.getUse());
1006 // If there are no uses outside the block, we're done with this instruction.
1007 if (UsesToRename.empty())
1010 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1012 // We found a use of I outside of BB. Rename all uses of I that are outside
1013 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1014 // with the two values we know.
1015 SSAUpdate.Initialize(I);
1016 SSAUpdate.AddAvailableValue(BB, I);
1017 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1019 while (!UsesToRename.empty())
1020 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1021 DEBUG(errs() << "\n");
1025 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
1026 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1027 // us to simplify any PHI nodes in BB.
1028 TerminatorInst *PredTerm = PredBB->getTerminator();
1029 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1030 if (PredTerm->getSuccessor(i) == BB) {
1031 BB->removePredecessor(PredBB);
1032 PredTerm->setSuccessor(i, NewBB);
1035 // At this point, the IR is fully up to date and consistent. Do a quick scan
1036 // over the new instructions and zap any that are constants or dead. This
1037 // frequently happens because of phi translation.
1038 BI = NewBB->begin();
1039 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1040 Instruction *Inst = BI++;
1041 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
1042 Inst->replaceAllUsesWith(C);
1043 Inst->eraseFromParent();
1047 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1050 // Threaded an edge!