JumpThreading.cpp revision fddcf47a249fe3a1102257deddc996ee327a85cb
1//===- JumpThreading.cpp - Thread control through conditional blocks ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Jump Threading pass. 11// 12//===----------------------------------------------------------------------===// 13 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" 32using namespace llvm; 33 34STATISTIC(NumThreads, "Number of jumps threaded"); 35STATISTIC(NumFolds, "Number of terminators folded"); 36STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); 37 38static cl::opt<unsigned> 39Threshold("jump-threading-threshold", 40 cl::desc("Max block size to duplicate for jump threading"), 41 cl::init(6), cl::Hidden); 42 43namespace { 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. 49 /// 50 /// An example of when this can occur is code like this: 51 /// 52 /// if () { ... 53 /// X = 4; 54 /// } 55 /// if (X < 3) { 56 /// 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. 59 /// 60 class JumpThreading : public FunctionPass { 61 TargetData *TD; 62#ifdef NDEBUG 63 SmallPtrSet<BasicBlock*, 16> LoopHeaders; 64#else 65 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders; 66#endif 67 public: 68 static char ID; // Pass identification 69 JumpThreading() : FunctionPass(&ID) {} 70 71 bool runOnFunction(Function &F); 72 void FindLoopHeaders(Function &F); 73 74 bool ProcessBlock(BasicBlock *BB); 75 bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs, 76 BasicBlock *SuccBB); 77 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, 78 BasicBlock *PredBB); 79 80 typedef SmallVectorImpl<std::pair<ConstantInt*, 81 BasicBlock*> > PredValueInfo; 82 83 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, 84 PredValueInfo &Result); 85 bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB); 86 87 88 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); 89 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); 90 91 bool ProcessJumpOnPHI(PHINode *PN); 92 93 bool SimplifyPartiallyRedundantLoad(LoadInst *LI); 94 }; 95} 96 97char JumpThreading::ID = 0; 98static RegisterPass<JumpThreading> 99X("jump-threading", "Jump Threading"); 100 101// Public interface to the Jump Threading pass 102FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); } 103 104/// runOnFunction - Top level algorithm. 105/// 106bool JumpThreading::runOnFunction(Function &F) { 107 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n"); 108 TD = getAnalysisIfAvailable<TargetData>(); 109 110 FindLoopHeaders(F); 111 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;) { 117 BasicBlock *BB = I; 118 while (ProcessBlock(BB)) 119 Changed = true; 120 121 ++I; 122 123 // If the block is trivially dead, zap it. This eliminates the successor 124 // edges which simplifies the CFG. 125 if (pred_begin(BB) == pred_end(BB) && 126 BB != &BB->getParent()->getEntryBlock()) { 127 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName() 128 << "' with terminator: " << *BB->getTerminator() << '\n'); 129 LoopHeaders.erase(BB); 130 DeleteDeadBlock(BB); 131 Changed = true; 132 } 133 } 134 AnotherIteration = Changed; 135 EverChanged |= Changed; 136 } 137 138 LoopHeaders.clear(); 139 return EverChanged; 140} 141 142/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to 143/// thread across it. 144static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) { 145 /// Ignore PHI nodes, these will be flattened when duplication happens. 146 BasicBlock::const_iterator I = BB->getFirstNonPHI(); 147 148 // Sum up the cost of each instruction until we get to the terminator. Don't 149 // include the terminator because the copy won't include it. 150 unsigned Size = 0; 151 for (; !isa<TerminatorInst>(I); ++I) { 152 // Debugger intrinsics don't incur code size. 153 if (isa<DbgInfoIntrinsic>(I)) continue; 154 155 // If this is a pointer->pointer bitcast, it is free. 156 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType())) 157 continue; 158 159 // All other instructions count for at least one unit. 160 ++Size; 161 162 // Calls are more expensive. If they are non-intrinsic calls, we model them 163 // as having cost of 4. If they are a non-vector intrinsic, we model them 164 // as having cost of 2 total, and if they are a vector intrinsic, we model 165 // them as having cost 1. 166 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 167 if (!isa<IntrinsicInst>(CI)) 168 Size += 3; 169 else if (!isa<VectorType>(CI->getType())) 170 Size += 1; 171 } 172 } 173 174 // Threading through a switch statement is particularly profitable. If this 175 // block ends in a switch, decrease its cost to make it more likely to happen. 176 if (isa<SwitchInst>(I)) 177 Size = Size > 6 ? Size-6 : 0; 178 179 return Size; 180} 181 182 183//===----------------------------------------------------------------------===// 184 185/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then 186/// delete the From instruction. In addition to a basic RAUW, this does a 187/// recursive simplification of the newly formed instructions. This catches 188/// things where one simplification exposes other opportunities. This only 189/// simplifies and deletes scalar operations, it does not change the CFG. 190/// 191static void ReplaceAndSimplifyAllUses(Instruction *From, Value *To, 192 const TargetData *TD) { 193 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!"); 194 195 // FromHandle - This keeps a weakvh on the from value so that we can know if 196 // it gets deleted out from under us in a recursive simplification. 197 WeakVH FromHandle(From); 198 199 while (!From->use_empty()) { 200 // Update the instruction to use the new value. 201 Use &U = From->use_begin().getUse(); 202 Instruction *User = cast<Instruction>(U.getUser()); 203 U = To; 204 205 // See if we can simplify it. 206 if (Value *V = SimplifyInstruction(User, TD)) { 207 // Recursively simplify this. 208 ReplaceAndSimplifyAllUses(User, V, TD); 209 210 // If the recursive simplification ended up revisiting and deleting 'From' 211 // then we're done. 212 if (FromHandle == 0) 213 return; 214 } 215 } 216 From->eraseFromParent(); 217} 218 219 220/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this 221/// method is called when we're about to delete Pred as a predecessor of BB. If 222/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred. 223/// 224/// Unlike the removePredecessor method, this attempts to simplify uses of PHI 225/// nodes that collapse into identity values. For example, if we have: 226/// x = phi(1, 0, 0, 0) 227/// y = and x, z 228/// 229/// .. and delete the predecessor corresponding to the '1', this will attempt to 230/// recursively fold the and to 0. 231static void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred, 232 TargetData *TD) { 233 // This only adjusts blocks with PHI nodes. 234 if (!isa<PHINode>(BB->begin())) 235 return; 236 237 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify 238 // them down. This will leave us with single entry phi nodes and other phis 239 // that can be removed. 240 BB->removePredecessor(Pred, true); 241 242 WeakVH PhiIt = &BB->front(); 243 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) { 244 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt)); 245 246 Value *PNV = PN->hasConstantValue(); 247 if (PNV == 0) continue; 248 249 // If we're able to simplify the phi to a single value, substitute the new 250 // value into all of its uses. 251 assert(PNV != PN && "hasConstantValue broken"); 252 253 ReplaceAndSimplifyAllUses(PN, PNV, TD); 254 255 // If recursive simplification ended up deleting the next PHI node we would 256 // iterate to, then our iterator is invalid, restart scanning from the top 257 // of the block. 258 if (PhiIt == 0) PhiIt = &BB->front(); 259 } 260} 261 262//===----------------------------------------------------------------------===// 263 264 265/// FindLoopHeaders - We do not want jump threading to turn proper loop 266/// structures into irreducible loops. Doing this breaks up the loop nesting 267/// hierarchy and pessimizes later transformations. To prevent this from 268/// happening, we first have to find the loop headers. Here we approximate this 269/// by finding targets of backedges in the CFG. 270/// 271/// Note that there definitely are cases when we want to allow threading of 272/// edges across a loop header. For example, threading a jump from outside the 273/// loop (the preheader) to an exit block of the loop is definitely profitable. 274/// It is also almost always profitable to thread backedges from within the loop 275/// to exit blocks, and is often profitable to thread backedges to other blocks 276/// within the loop (forming a nested loop). This simple analysis is not rich 277/// enough to track all of these properties and keep it up-to-date as the CFG 278/// mutates, so we don't allow any of these transformations. 279/// 280void JumpThreading::FindLoopHeaders(Function &F) { 281 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 282 FindFunctionBackedges(F, Edges); 283 284 for (unsigned i = 0, e = Edges.size(); i != e; ++i) 285 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second)); 286} 287 288/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see 289/// if we can infer that the value is a known ConstantInt in any of our 290/// predecessors. If so, return the known list of value and pred BB in the 291/// result vector. If a value is known to be undef, it is returned as null. 292/// 293/// The BB basic block is known to start with a PHI node. 294/// 295/// This returns true if there were any known values. 296/// 297/// 298/// TODO: Per PR2563, we could infer value range information about a predecessor 299/// based on its terminator. 300bool JumpThreading:: 301ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){ 302 PHINode *TheFirstPHI = cast<PHINode>(BB->begin()); 303 304 // If V is a constantint, then it is known in all predecessors. 305 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) { 306 ConstantInt *CI = dyn_cast<ConstantInt>(V); 307 Result.resize(TheFirstPHI->getNumIncomingValues()); 308 for (unsigned i = 0, e = Result.size(); i != e; ++i) 309 Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i)); 310 return true; 311 } 312 313 // If V is a non-instruction value, or an instruction in a different block, 314 // then it can't be derived from a PHI. 315 Instruction *I = dyn_cast<Instruction>(V); 316 if (I == 0 || I->getParent() != BB) 317 return false; 318 319 /// If I is a PHI node, then we know the incoming values for any constants. 320 if (PHINode *PN = dyn_cast<PHINode>(I)) { 321 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 322 Value *InVal = PN->getIncomingValue(i); 323 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) { 324 ConstantInt *CI = dyn_cast<ConstantInt>(InVal); 325 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i))); 326 } 327 } 328 return !Result.empty(); 329 } 330 331 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals; 332 333 // Handle some boolean conditions. 334 if (I->getType()->getPrimitiveSizeInBits() == 1) { 335 // X | true -> true 336 // X & false -> false 337 if (I->getOpcode() == Instruction::Or || 338 I->getOpcode() == Instruction::And) { 339 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals); 340 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals); 341 342 if (LHSVals.empty() && RHSVals.empty()) 343 return false; 344 345 ConstantInt *InterestingVal; 346 if (I->getOpcode() == Instruction::Or) 347 InterestingVal = ConstantInt::getTrue(I->getContext()); 348 else 349 InterestingVal = ConstantInt::getFalse(I->getContext()); 350 351 // Scan for the sentinel. 352 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) 353 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0) 354 Result.push_back(LHSVals[i]); 355 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i) 356 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0) 357 Result.push_back(RHSVals[i]); 358 return !Result.empty(); 359 } 360 361 // TODO: Should handle the NOT form of XOR. 362 363 } 364 365 // Handle compare with phi operand, where the PHI is defined in this block. 366 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 367 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0)); 368 if (PN && PN->getParent() == BB) { 369 // We can do this simplification if any comparisons fold to true or false. 370 // See if any do. 371 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 372 BasicBlock *PredBB = PN->getIncomingBlock(i); 373 Value *LHS = PN->getIncomingValue(i); 374 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB); 375 376 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS); 377 if (Res == 0) continue; 378 379 if (isa<UndefValue>(Res)) 380 Result.push_back(std::make_pair((ConstantInt*)0, PredBB)); 381 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res)) 382 Result.push_back(std::make_pair(CI, PredBB)); 383 } 384 385 return !Result.empty(); 386 } 387 388 // TODO: We could also recurse to see if we can determine constants another 389 // way. 390 } 391 return false; 392} 393 394 395 396/// GetBestDestForBranchOnUndef - If we determine that the specified block ends 397/// in an undefined jump, decide which block is best to revector to. 398/// 399/// Since we can pick an arbitrary destination, we pick the successor with the 400/// fewest predecessors. This should reduce the in-degree of the others. 401/// 402static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) { 403 TerminatorInst *BBTerm = BB->getTerminator(); 404 unsigned MinSucc = 0; 405 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 406 // Compute the successor with the minimum number of predecessors. 407 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 408 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 409 TestBB = BBTerm->getSuccessor(i); 410 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 411 if (NumPreds < MinNumPreds) 412 MinSucc = i; 413 } 414 415 return MinSucc; 416} 417 418/// ProcessBlock - If there are any predecessors whose control can be threaded 419/// through to a successor, transform them now. 420bool JumpThreading::ProcessBlock(BasicBlock *BB) { 421 // If this block has a single predecessor, and if that pred has a single 422 // successor, merge the blocks. This encourages recursive jump threading 423 // because now the condition in this block can be threaded through 424 // predecessors of our predecessor block. 425 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) { 426 if (SinglePred->getTerminator()->getNumSuccessors() == 1 && 427 SinglePred != BB) { 428 // If SinglePred was a loop header, BB becomes one. 429 if (LoopHeaders.erase(SinglePred)) 430 LoopHeaders.insert(BB); 431 432 // Remember if SinglePred was the entry block of the function. If so, we 433 // will need to move BB back to the entry position. 434 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); 435 MergeBasicBlockIntoOnlyPred(BB); 436 437 if (isEntry && BB != &BB->getParent()->getEntryBlock()) 438 BB->moveBefore(&BB->getParent()->getEntryBlock()); 439 return true; 440 } 441 } 442 443 // Look to see if the terminator is a branch of switch, if not we can't thread 444 // it. 445 Value *Condition; 446 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 447 // Can't thread an unconditional jump. 448 if (BI->isUnconditional()) return false; 449 Condition = BI->getCondition(); 450 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) 451 Condition = SI->getCondition(); 452 else 453 return false; // Must be an invoke. 454 455 // If the terminator of this block is branching on a constant, simplify the 456 // terminator to an unconditional branch. This can occur due to threading in 457 // other blocks. 458 if (isa<ConstantInt>(Condition)) { 459 DEBUG(errs() << " In block '" << BB->getName() 460 << "' folding terminator: " << *BB->getTerminator() << '\n'); 461 ++NumFolds; 462 ConstantFoldTerminator(BB); 463 return true; 464 } 465 466 // If the terminator is branching on an undef, we can pick any of the 467 // successors to branch to. Let GetBestDestForJumpOnUndef decide. 468 if (isa<UndefValue>(Condition)) { 469 unsigned BestSucc = GetBestDestForJumpOnUndef(BB); 470 471 // Fold the branch/switch. 472 TerminatorInst *BBTerm = BB->getTerminator(); 473 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 474 if (i == BestSucc) continue; 475 RemovePredecessorAndSimplify(BBTerm->getSuccessor(i), BB, TD); 476 } 477 478 DEBUG(errs() << " In block '" << BB->getName() 479 << "' folding undef terminator: " << *BBTerm << '\n'); 480 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); 481 BBTerm->eraseFromParent(); 482 return true; 483 } 484 485 Instruction *CondInst = dyn_cast<Instruction>(Condition); 486 487 // If the condition is an instruction defined in another block, see if a 488 // predecessor has the same condition: 489 // br COND, BBX, BBY 490 // BBX: 491 // br COND, BBZ, BBW 492 if (!Condition->hasOneUse() && // Multiple uses. 493 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition. 494 pred_iterator PI = pred_begin(BB), E = pred_end(BB); 495 if (isa<BranchInst>(BB->getTerminator())) { 496 for (; PI != E; ++PI) 497 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 498 if (PBI->isConditional() && PBI->getCondition() == Condition && 499 ProcessBranchOnDuplicateCond(*PI, BB)) 500 return true; 501 } else { 502 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator"); 503 for (; PI != E; ++PI) 504 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator())) 505 if (PSI->getCondition() == Condition && 506 ProcessSwitchOnDuplicateCond(*PI, BB)) 507 return true; 508 } 509 } 510 511 // All the rest of our checks depend on the condition being an instruction. 512 if (CondInst == 0) 513 return false; 514 515 // See if this is a phi node in the current block. 516 if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 517 if (PN->getParent() == BB) 518 return ProcessJumpOnPHI(PN); 519 520 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { 521 if (!isa<PHINode>(CondCmp->getOperand(0)) || 522 cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) { 523 // If we have a comparison, loop over the predecessors to see if there is 524 // a condition with a lexically identical value. 525 pred_iterator PI = pred_begin(BB), E = pred_end(BB); 526 for (; PI != E; ++PI) 527 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 528 if (PBI->isConditional() && *PI != BB) { 529 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) { 530 if (CI->getOperand(0) == CondCmp->getOperand(0) && 531 CI->getOperand(1) == CondCmp->getOperand(1) && 532 CI->getPredicate() == CondCmp->getPredicate()) { 533 // TODO: Could handle things like (x != 4) --> (x == 17) 534 if (ProcessBranchOnDuplicateCond(*PI, BB)) 535 return true; 536 } 537 } 538 } 539 } 540 } 541 542 // Check for some cases that are worth simplifying. Right now we want to look 543 // for loads that are used by a switch or by the condition for the branch. If 544 // we see one, check to see if it's partially redundant. If so, insert a PHI 545 // which can then be used to thread the values. 546 // 547 // This is particularly important because reg2mem inserts loads and stores all 548 // over the place, and this blocks jump threading if we don't zap them. 549 Value *SimplifyValue = CondInst; 550 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 551 if (isa<Constant>(CondCmp->getOperand(1))) 552 SimplifyValue = CondCmp->getOperand(0); 553 554 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue)) 555 if (SimplifyPartiallyRedundantLoad(LI)) 556 return true; 557 558 559 // Handle a variety of cases where we are branching on something derived from 560 // a PHI node in the current block. If we can prove that any predecessors 561 // compute a predictable value based on a PHI node, thread those predecessors. 562 // 563 // We only bother doing this if the current block has a PHI node and if the 564 // conditional instruction lives in the current block. If either condition 565 // fails, this won't be a computable value anyway. 566 if (CondInst->getParent() == BB && isa<PHINode>(BB->front())) 567 if (ProcessThreadableEdges(CondInst, BB)) 568 return true; 569 570 571 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know 572 // "(X == 4)" thread through this block. 573 574 return false; 575} 576 577/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that 578/// block that jump on exactly the same condition. This means that we almost 579/// always know the direction of the edge in the DESTBB: 580/// PREDBB: 581/// br COND, DESTBB, BBY 582/// DESTBB: 583/// br COND, BBZ, BBW 584/// 585/// If DESTBB has multiple predecessors, we can't just constant fold the branch 586/// in DESTBB, we have to thread over it. 587bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB, 588 BasicBlock *BB) { 589 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator()); 590 591 // If both successors of PredBB go to DESTBB, we don't know anything. We can 592 // fold the branch to an unconditional one, which allows other recursive 593 // simplifications. 594 bool BranchDir; 595 if (PredBI->getSuccessor(1) != BB) 596 BranchDir = true; 597 else if (PredBI->getSuccessor(0) != BB) 598 BranchDir = false; 599 else { 600 DEBUG(errs() << " In block '" << PredBB->getName() 601 << "' folding terminator: " << *PredBB->getTerminator() << '\n'); 602 ++NumFolds; 603 ConstantFoldTerminator(PredBB); 604 return true; 605 } 606 607 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator()); 608 609 // If the dest block has one predecessor, just fix the branch condition to a 610 // constant and fold it. 611 if (BB->getSinglePredecessor()) { 612 DEBUG(errs() << " In block '" << BB->getName() 613 << "' folding condition to '" << BranchDir << "': " 614 << *BB->getTerminator() << '\n'); 615 ++NumFolds; 616 Value *OldCond = DestBI->getCondition(); 617 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 618 BranchDir)); 619 ConstantFoldTerminator(BB); 620 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 621 return true; 622 } 623 624 625 // Next, figure out which successor we are threading to. 626 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir); 627 628 SmallVector<BasicBlock*, 2> Preds; 629 Preds.push_back(PredBB); 630 631 // Ok, try to thread it! 632 return ThreadEdge(BB, Preds, SuccBB); 633} 634 635/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that 636/// block that switch on exactly the same condition. This means that we almost 637/// always know the direction of the edge in the DESTBB: 638/// PREDBB: 639/// switch COND [... DESTBB, BBY ... ] 640/// DESTBB: 641/// switch COND [... BBZ, BBW ] 642/// 643/// Optimizing switches like this is very important, because simplifycfg builds 644/// switches out of repeated 'if' conditions. 645bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, 646 BasicBlock *DestBB) { 647 // Can't thread edge to self. 648 if (PredBB == DestBB) 649 return false; 650 651 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator()); 652 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator()); 653 654 // There are a variety of optimizations that we can potentially do on these 655 // blocks: we order them from most to least preferable. 656 657 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB 658 // directly to their destination. This does not introduce *any* code size 659 // growth. Skip debug info first. 660 BasicBlock::iterator BBI = DestBB->begin(); 661 while (isa<DbgInfoIntrinsic>(BBI)) 662 BBI++; 663 664 // FIXME: Thread if it just contains a PHI. 665 if (isa<SwitchInst>(BBI)) { 666 bool MadeChange = false; 667 // Ignore the default edge for now. 668 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) { 669 ConstantInt *DestVal = DestSI->getCaseValue(i); 670 BasicBlock *DestSucc = DestSI->getSuccessor(i); 671 672 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if 673 // PredSI has an explicit case for it. If so, forward. If it is covered 674 // by the default case, we can't update PredSI. 675 unsigned PredCase = PredSI->findCaseValue(DestVal); 676 if (PredCase == 0) continue; 677 678 // If PredSI doesn't go to DestBB on this value, then it won't reach the 679 // case on this condition. 680 if (PredSI->getSuccessor(PredCase) != DestBB && 681 DestSI->getSuccessor(i) != DestBB) 682 continue; 683 684 // Otherwise, we're safe to make the change. Make sure that the edge from 685 // DestSI to DestSucc is not critical and has no PHI nodes. 686 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI); 687 DEBUG(errs() << "THROUGH: " << *DestSI); 688 689 // If the destination has PHI nodes, just split the edge for updating 690 // simplicity. 691 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){ 692 SplitCriticalEdge(DestSI, i, this); 693 DestSucc = DestSI->getSuccessor(i); 694 } 695 FoldSingleEntryPHINodes(DestSucc); 696 PredSI->setSuccessor(PredCase, DestSucc); 697 MadeChange = true; 698 } 699 700 if (MadeChange) 701 return true; 702 } 703 704 return false; 705} 706 707 708/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant 709/// load instruction, eliminate it by replacing it with a PHI node. This is an 710/// important optimization that encourages jump threading, and needs to be run 711/// interlaced with other jump threading tasks. 712bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) { 713 // Don't hack volatile loads. 714 if (LI->isVolatile()) return false; 715 716 // If the load is defined in a block with exactly one predecessor, it can't be 717 // partially redundant. 718 BasicBlock *LoadBB = LI->getParent(); 719 if (LoadBB->getSinglePredecessor()) 720 return false; 721 722 Value *LoadedPtr = LI->getOperand(0); 723 724 // If the loaded operand is defined in the LoadBB, it can't be available. 725 // FIXME: Could do PHI translation, that would be fun :) 726 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr)) 727 if (PtrOp->getParent() == LoadBB) 728 return false; 729 730 // Scan a few instructions up from the load, to see if it is obviously live at 731 // the entry to its block. 732 BasicBlock::iterator BBIt = LI; 733 734 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, 735 BBIt, 6)) { 736 // If the value if the load is locally available within the block, just use 737 // it. This frequently occurs for reg2mem'd allocas. 738 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n"; 739 740 // If the returned value is the load itself, replace with an undef. This can 741 // only happen in dead loops. 742 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType()); 743 LI->replaceAllUsesWith(AvailableVal); 744 LI->eraseFromParent(); 745 return true; 746 } 747 748 // Otherwise, if we scanned the whole block and got to the top of the block, 749 // we know the block is locally transparent to the load. If not, something 750 // might clobber its value. 751 if (BBIt != LoadBB->begin()) 752 return false; 753 754 755 SmallPtrSet<BasicBlock*, 8> PredsScanned; 756 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy; 757 AvailablePredsTy AvailablePreds; 758 BasicBlock *OneUnavailablePred = 0; 759 760 // If we got here, the loaded value is transparent through to the start of the 761 // block. Check to see if it is available in any of the predecessor blocks. 762 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); 763 PI != PE; ++PI) { 764 BasicBlock *PredBB = *PI; 765 766 // If we already scanned this predecessor, skip it. 767 if (!PredsScanned.insert(PredBB)) 768 continue; 769 770 // Scan the predecessor to see if the value is available in the pred. 771 BBIt = PredBB->end(); 772 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6); 773 if (!PredAvailable) { 774 OneUnavailablePred = PredBB; 775 continue; 776 } 777 778 // If so, this load is partially redundant. Remember this info so that we 779 // can create a PHI node. 780 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable)); 781 } 782 783 // If the loaded value isn't available in any predecessor, it isn't partially 784 // redundant. 785 if (AvailablePreds.empty()) return false; 786 787 // Okay, the loaded value is available in at least one (and maybe all!) 788 // predecessors. If the value is unavailable in more than one unique 789 // predecessor, we want to insert a merge block for those common predecessors. 790 // This ensures that we only have to insert one reload, thus not increasing 791 // code size. 792 BasicBlock *UnavailablePred = 0; 793 794 // If there is exactly one predecessor where the value is unavailable, the 795 // already computed 'OneUnavailablePred' block is it. If it ends in an 796 // unconditional branch, we know that it isn't a critical edge. 797 if (PredsScanned.size() == AvailablePreds.size()+1 && 798 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 799 UnavailablePred = OneUnavailablePred; 800 } else if (PredsScanned.size() != AvailablePreds.size()) { 801 // Otherwise, we had multiple unavailable predecessors or we had a critical 802 // edge from the one. 803 SmallVector<BasicBlock*, 8> PredsToSplit; 804 SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 805 806 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i) 807 AvailablePredSet.insert(AvailablePreds[i].first); 808 809 // Add all the unavailable predecessors to the PredsToSplit list. 810 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); 811 PI != PE; ++PI) 812 if (!AvailablePredSet.count(*PI)) 813 PredsToSplit.push_back(*PI); 814 815 // Split them out to their own block. 816 UnavailablePred = 817 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(), 818 "thread-split", this); 819 } 820 821 // If the value isn't available in all predecessors, then there will be 822 // exactly one where it isn't available. Insert a load on that edge and add 823 // it to the AvailablePreds list. 824 if (UnavailablePred) { 825 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 826 "Can't handle critical edge here!"); 827 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", 828 UnavailablePred->getTerminator()); 829 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal)); 830 } 831 832 // Now we know that each predecessor of this block has a value in 833 // AvailablePreds, sort them for efficient access as we're walking the preds. 834 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 835 836 // Create a PHI node at the start of the block for the PRE'd load value. 837 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin()); 838 PN->takeName(LI); 839 840 // Insert new entries into the PHI for each predecessor. A single block may 841 // have multiple entries here. 842 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E; 843 ++PI) { 844 AvailablePredsTy::iterator I = 845 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(), 846 std::make_pair(*PI, (Value*)0)); 847 848 assert(I != AvailablePreds.end() && I->first == *PI && 849 "Didn't find entry for predecessor!"); 850 851 PN->addIncoming(I->second, I->first); 852 } 853 854 //cerr << "PRE: " << *LI << *PN << "\n"; 855 856 LI->replaceAllUsesWith(PN); 857 LI->eraseFromParent(); 858 859 return true; 860} 861 862/// FindMostPopularDest - The specified list contains multiple possible 863/// threadable destinations. Pick the one that occurs the most frequently in 864/// the list. 865static BasicBlock * 866FindMostPopularDest(BasicBlock *BB, 867 const SmallVectorImpl<std::pair<BasicBlock*, 868 BasicBlock*> > &PredToDestList) { 869 assert(!PredToDestList.empty()); 870 871 // Determine popularity. If there are multiple possible destinations, we 872 // explicitly choose to ignore 'undef' destinations. We prefer to thread 873 // blocks with known and real destinations to threading undef. We'll handle 874 // them later if interesting. 875 DenseMap<BasicBlock*, unsigned> DestPopularity; 876 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i) 877 if (PredToDestList[i].second) 878 DestPopularity[PredToDestList[i].second]++; 879 880 // Find the most popular dest. 881 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin(); 882 BasicBlock *MostPopularDest = DPI->first; 883 unsigned Popularity = DPI->second; 884 SmallVector<BasicBlock*, 4> SamePopularity; 885 886 for (++DPI; DPI != DestPopularity.end(); ++DPI) { 887 // If the popularity of this entry isn't higher than the popularity we've 888 // seen so far, ignore it. 889 if (DPI->second < Popularity) 890 ; // ignore. 891 else if (DPI->second == Popularity) { 892 // If it is the same as what we've seen so far, keep track of it. 893 SamePopularity.push_back(DPI->first); 894 } else { 895 // If it is more popular, remember it. 896 SamePopularity.clear(); 897 MostPopularDest = DPI->first; 898 Popularity = DPI->second; 899 } 900 } 901 902 // Okay, now we know the most popular destination. If there is more than 903 // destination, we need to determine one. This is arbitrary, but we need 904 // to make a deterministic decision. Pick the first one that appears in the 905 // successor list. 906 if (!SamePopularity.empty()) { 907 SamePopularity.push_back(MostPopularDest); 908 TerminatorInst *TI = BB->getTerminator(); 909 for (unsigned i = 0; ; ++i) { 910 assert(i != TI->getNumSuccessors() && "Didn't find any successor!"); 911 912 if (std::find(SamePopularity.begin(), SamePopularity.end(), 913 TI->getSuccessor(i)) == SamePopularity.end()) 914 continue; 915 916 MostPopularDest = TI->getSuccessor(i); 917 break; 918 } 919 } 920 921 // Okay, we have finally picked the most popular destination. 922 return MostPopularDest; 923} 924 925bool JumpThreading::ProcessThreadableEdges(Instruction *CondInst, 926 BasicBlock *BB) { 927 // If threading this would thread across a loop header, don't even try to 928 // thread the edge. 929 if (LoopHeaders.count(BB)) 930 return false; 931 932 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues; 933 if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues)) 934 return false; 935 assert(!PredValues.empty() && 936 "ComputeValueKnownInPredecessors returned true with no values"); 937 938 DEBUG(errs() << "IN BB: " << *BB; 939 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) { 940 errs() << " BB '" << BB->getName() << "': FOUND condition = "; 941 if (PredValues[i].first) 942 errs() << *PredValues[i].first; 943 else 944 errs() << "UNDEF"; 945 errs() << " for pred '" << PredValues[i].second->getName() 946 << "'.\n"; 947 }); 948 949 // Decide what we want to thread through. Convert our list of known values to 950 // a list of known destinations for each pred. This also discards duplicate 951 // predecessors and keeps track of the undefined inputs (which are represented 952 // as a null dest in the PredToDestList). 953 SmallPtrSet<BasicBlock*, 16> SeenPreds; 954 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList; 955 956 BasicBlock *OnlyDest = 0; 957 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL; 958 959 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) { 960 BasicBlock *Pred = PredValues[i].second; 961 if (!SeenPreds.insert(Pred)) 962 continue; // Duplicate predecessor entry. 963 964 // If the predecessor ends with an indirect goto, we can't change its 965 // destination. 966 if (isa<IndirectBrInst>(Pred->getTerminator())) 967 continue; 968 969 ConstantInt *Val = PredValues[i].first; 970 971 BasicBlock *DestBB; 972 if (Val == 0) // Undef. 973 DestBB = 0; 974 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) 975 DestBB = BI->getSuccessor(Val->isZero()); 976 else { 977 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator()); 978 DestBB = SI->getSuccessor(SI->findCaseValue(Val)); 979 } 980 981 // If we have exactly one destination, remember it for efficiency below. 982 if (i == 0) 983 OnlyDest = DestBB; 984 else if (OnlyDest != DestBB) 985 OnlyDest = MultipleDestSentinel; 986 987 PredToDestList.push_back(std::make_pair(Pred, DestBB)); 988 } 989 990 // If all edges were unthreadable, we fail. 991 if (PredToDestList.empty()) 992 return false; 993 994 // Determine which is the most common successor. If we have many inputs and 995 // this block is a switch, we want to start by threading the batch that goes 996 // to the most popular destination first. If we only know about one 997 // threadable destination (the common case) we can avoid this. 998 BasicBlock *MostPopularDest = OnlyDest; 999 1000 if (MostPopularDest == MultipleDestSentinel) 1001 MostPopularDest = FindMostPopularDest(BB, PredToDestList); 1002 1003 // Now that we know what the most popular destination is, factor all 1004 // predecessors that will jump to it into a single predecessor. 1005 SmallVector<BasicBlock*, 16> PredsToFactor; 1006 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i) 1007 if (PredToDestList[i].second == MostPopularDest) { 1008 BasicBlock *Pred = PredToDestList[i].first; 1009 1010 // This predecessor may be a switch or something else that has multiple 1011 // edges to the block. Factor each of these edges by listing them 1012 // according to # occurrences in PredsToFactor. 1013 TerminatorInst *PredTI = Pred->getTerminator(); 1014 for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i) 1015 if (PredTI->getSuccessor(i) == BB) 1016 PredsToFactor.push_back(Pred); 1017 } 1018 1019 // If the threadable edges are branching on an undefined value, we get to pick 1020 // the destination that these predecessors should get to. 1021 if (MostPopularDest == 0) 1022 MostPopularDest = BB->getTerminator()-> 1023 getSuccessor(GetBestDestForJumpOnUndef(BB)); 1024 1025 // Ok, try to thread it! 1026 return ThreadEdge(BB, PredsToFactor, MostPopularDest); 1027} 1028 1029/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in 1030/// the current block. See if there are any simplifications we can do based on 1031/// inputs to the phi node. 1032/// 1033bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) { 1034 BasicBlock *BB = PN->getParent(); 1035 1036 // If any of the predecessor blocks end in an unconditional branch, we can 1037 // *duplicate* the jump into that block in order to further encourage jump 1038 // threading and to eliminate cases where we have branch on a phi of an icmp 1039 // (branch on icmp is much better). 1040 1041 // We don't want to do this tranformation for switches, because we don't 1042 // really want to duplicate a switch. 1043 if (isa<SwitchInst>(BB->getTerminator())) 1044 return false; 1045 1046 // Look for unconditional branch predecessors. 1047 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1048 BasicBlock *PredBB = PN->getIncomingBlock(i); 1049 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) 1050 if (PredBr->isUnconditional() && 1051 // Try to duplicate BB into PredBB. 1052 DuplicateCondBranchOnPHIIntoPred(BB, PredBB)) 1053 return true; 1054 } 1055 1056 return false; 1057} 1058 1059 1060/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new 1061/// predecessor to the PHIBB block. If it has PHI nodes, add entries for 1062/// NewPred using the entries from OldPred (suitably mapped). 1063static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, 1064 BasicBlock *OldPred, 1065 BasicBlock *NewPred, 1066 DenseMap<Instruction*, Value*> &ValueMap) { 1067 for (BasicBlock::iterator PNI = PHIBB->begin(); 1068 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) { 1069 // Ok, we have a PHI node. Figure out what the incoming value was for the 1070 // DestBlock. 1071 Value *IV = PN->getIncomingValueForBlock(OldPred); 1072 1073 // Remap the value if necessary. 1074 if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 1075 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst); 1076 if (I != ValueMap.end()) 1077 IV = I->second; 1078 } 1079 1080 PN->addIncoming(IV, NewPred); 1081 } 1082} 1083 1084/// ThreadEdge - We have decided that it is safe and profitable to factor the 1085/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB 1086/// across BB. Transform the IR to reflect this change. 1087bool JumpThreading::ThreadEdge(BasicBlock *BB, 1088 const SmallVectorImpl<BasicBlock*> &PredBBs, 1089 BasicBlock *SuccBB) { 1090 // If threading to the same block as we come from, we would infinite loop. 1091 if (SuccBB == BB) { 1092 DEBUG(errs() << " Not threading across BB '" << BB->getName() 1093 << "' - would thread to self!\n"); 1094 return false; 1095 } 1096 1097 // If threading this would thread across a loop header, don't thread the edge. 1098 // See the comments above FindLoopHeaders for justifications and caveats. 1099 if (LoopHeaders.count(BB)) { 1100 DEBUG(errs() << " Not threading across loop header BB '" << BB->getName() 1101 << "' to dest BB '" << SuccBB->getName() 1102 << "' - it might create an irreducible loop!\n"); 1103 return false; 1104 } 1105 1106 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB); 1107 if (JumpThreadCost > Threshold) { 1108 DEBUG(errs() << " Not threading BB '" << BB->getName() 1109 << "' - Cost is too high: " << JumpThreadCost << "\n"); 1110 return false; 1111 } 1112 1113 // And finally, do it! Start by factoring the predecessors is needed. 1114 BasicBlock *PredBB; 1115 if (PredBBs.size() == 1) 1116 PredBB = PredBBs[0]; 1117 else { 1118 DEBUG(errs() << " Factoring out " << PredBBs.size() 1119 << " common predecessors.\n"); 1120 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(), 1121 ".thr_comm", this); 1122 } 1123 1124 // And finally, do it! 1125 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '" 1126 << SuccBB->getName() << "' with cost: " << JumpThreadCost 1127 << ", across block:\n " 1128 << *BB << "\n"); 1129 1130 // We are going to have to map operands from the original BB block to the new 1131 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 1132 // account for entry from PredBB. 1133 DenseMap<Instruction*, Value*> ValueMapping; 1134 1135 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 1136 BB->getName()+".thread", 1137 BB->getParent(), BB); 1138 NewBB->moveAfter(PredBB); 1139 1140 BasicBlock::iterator BI = BB->begin(); 1141 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1142 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1143 1144 // Clone the non-phi instructions of BB into NewBB, keeping track of the 1145 // mapping and using it to remap operands in the cloned instructions. 1146 for (; !isa<TerminatorInst>(BI); ++BI) { 1147 Instruction *New = BI->clone(); 1148 New->setName(BI->getName()); 1149 NewBB->getInstList().push_back(New); 1150 ValueMapping[BI] = New; 1151 1152 // Remap operands to patch up intra-block references. 1153 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1154 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1155 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1156 if (I != ValueMapping.end()) 1157 New->setOperand(i, I->second); 1158 } 1159 } 1160 1161 // We didn't copy the terminator from BB over to NewBB, because there is now 1162 // an unconditional jump to SuccBB. Insert the unconditional jump. 1163 BranchInst::Create(SuccBB, NewBB); 1164 1165 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 1166 // PHI nodes for NewBB now. 1167 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); 1168 1169 // If there were values defined in BB that are used outside the block, then we 1170 // now have to update all uses of the value to use either the original value, 1171 // the cloned value, or some PHI derived value. This can require arbitrary 1172 // PHI insertion, of which we are prepared to do, clean these up now. 1173 SSAUpdater SSAUpdate; 1174 SmallVector<Use*, 16> UsesToRename; 1175 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { 1176 // Scan all uses of this instruction to see if it is used outside of its 1177 // block, and if so, record them in UsesToRename. 1178 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 1179 ++UI) { 1180 Instruction *User = cast<Instruction>(*UI); 1181 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1182 if (UserPN->getIncomingBlock(UI) == BB) 1183 continue; 1184 } else if (User->getParent() == BB) 1185 continue; 1186 1187 UsesToRename.push_back(&UI.getUse()); 1188 } 1189 1190 // If there are no uses outside the block, we're done with this instruction. 1191 if (UsesToRename.empty()) 1192 continue; 1193 1194 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n"); 1195 1196 // We found a use of I outside of BB. Rename all uses of I that are outside 1197 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1198 // with the two values we know. 1199 SSAUpdate.Initialize(I); 1200 SSAUpdate.AddAvailableValue(BB, I); 1201 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]); 1202 1203 while (!UsesToRename.empty()) 1204 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1205 DEBUG(errs() << "\n"); 1206 } 1207 1208 1209 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to 1210 // NewBB instead of BB. This eliminates predecessors from BB, which requires 1211 // us to simplify any PHI nodes in BB. 1212 TerminatorInst *PredTerm = PredBB->getTerminator(); 1213 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 1214 if (PredTerm->getSuccessor(i) == BB) { 1215 RemovePredecessorAndSimplify(BB, PredBB, TD); 1216 PredTerm->setSuccessor(i, NewBB); 1217 } 1218 1219 // At this point, the IR is fully up to date and consistent. Do a quick scan 1220 // over the new instructions and zap any that are constants or dead. This 1221 // frequently happens because of phi translation. 1222 BI = NewBB->begin(); 1223 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) { 1224 Instruction *Inst = BI++; 1225 1226 if (Value *V = SimplifyInstruction(Inst, TD)) { 1227 WeakVH BIHandle(BI); 1228 ReplaceAndSimplifyAllUses(Inst, V, TD); 1229 if (BIHandle == 0) 1230 BI = NewBB->begin(); 1231 continue; 1232 } 1233 1234 RecursivelyDeleteTriviallyDeadInstructions(Inst); 1235 } 1236 1237 // Threaded an edge! 1238 ++NumThreads; 1239 return true; 1240} 1241 1242/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch 1243/// to BB which contains an i1 PHI node and a conditional branch on that PHI. 1244/// If we can duplicate the contents of BB up into PredBB do so now, this 1245/// improves the odds that the branch will be on an analyzable instruction like 1246/// a compare. 1247bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, 1248 BasicBlock *PredBB) { 1249 // If BB is a loop header, then duplicating this block outside the loop would 1250 // cause us to transform this into an irreducible loop, don't do this. 1251 // See the comments above FindLoopHeaders for justifications and caveats. 1252 if (LoopHeaders.count(BB)) { 1253 DEBUG(errs() << " Not duplicating loop header '" << BB->getName() 1254 << "' into predecessor block '" << PredBB->getName() 1255 << "' - it might create an irreducible loop!\n"); 1256 return false; 1257 } 1258 1259 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB); 1260 if (DuplicationCost > Threshold) { 1261 DEBUG(errs() << " Not duplicating BB '" << BB->getName() 1262 << "' - Cost is too high: " << DuplicationCost << "\n"); 1263 return false; 1264 } 1265 1266 // Okay, we decided to do this! Clone all the instructions in BB onto the end 1267 // of PredBB. 1268 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '" 1269 << PredBB->getName() << "' to eliminate branch on phi. Cost: " 1270 << DuplicationCost << " block is:" << *BB << "\n"); 1271 1272 // We are going to have to map operands from the original BB block into the 1273 // PredBB block. Evaluate PHI nodes in BB. 1274 DenseMap<Instruction*, Value*> ValueMapping; 1275 1276 BasicBlock::iterator BI = BB->begin(); 1277 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1278 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1279 1280 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); 1281 1282 // Clone the non-phi instructions of BB into PredBB, keeping track of the 1283 // mapping and using it to remap operands in the cloned instructions. 1284 for (; BI != BB->end(); ++BI) { 1285 Instruction *New = BI->clone(); 1286 New->setName(BI->getName()); 1287 PredBB->getInstList().insert(OldPredBranch, New); 1288 ValueMapping[BI] = New; 1289 1290 // Remap operands to patch up intra-block references. 1291 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1292 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1293 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1294 if (I != ValueMapping.end()) 1295 New->setOperand(i, I->second); 1296 } 1297 } 1298 1299 // Check to see if the targets of the branch had PHI nodes. If so, we need to 1300 // add entries to the PHI nodes for branch from PredBB now. 1301 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); 1302 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, 1303 ValueMapping); 1304 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, 1305 ValueMapping); 1306 1307 // If there were values defined in BB that are used outside the block, then we 1308 // now have to update all uses of the value to use either the original value, 1309 // the cloned value, or some PHI derived value. This can require arbitrary 1310 // PHI insertion, of which we are prepared to do, clean these up now. 1311 SSAUpdater SSAUpdate; 1312 SmallVector<Use*, 16> UsesToRename; 1313 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { 1314 // Scan all uses of this instruction to see if it is used outside of its 1315 // block, and if so, record them in UsesToRename. 1316 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 1317 ++UI) { 1318 Instruction *User = cast<Instruction>(*UI); 1319 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1320 if (UserPN->getIncomingBlock(UI) == BB) 1321 continue; 1322 } else if (User->getParent() == BB) 1323 continue; 1324 1325 UsesToRename.push_back(&UI.getUse()); 1326 } 1327 1328 // If there are no uses outside the block, we're done with this instruction. 1329 if (UsesToRename.empty()) 1330 continue; 1331 1332 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n"); 1333 1334 // We found a use of I outside of BB. Rename all uses of I that are outside 1335 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1336 // with the two values we know. 1337 SSAUpdate.Initialize(I); 1338 SSAUpdate.AddAvailableValue(BB, I); 1339 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]); 1340 1341 while (!UsesToRename.empty()) 1342 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1343 DEBUG(errs() << "\n"); 1344 } 1345 1346 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge 1347 // that we nuked. 1348 RemovePredecessorAndSimplify(BB, PredBB, TD); 1349 1350 // Remove the unconditional branch at the end of the PredBB block. 1351 OldPredBranch->eraseFromParent(); 1352 1353 ++NumDupes; 1354 return true; 1355} 1356 1357 1358