JumpThreading.cpp revision bdbf1a177de085927c375efa986c52af2057fb7a
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/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" 32using namespace llvm; 33 34STATISTIC(NumThreads, "Number of jumps threaded"); 35STATISTIC(NumFolds, "Number of terminators folded"); 36 37static cl::opt<unsigned> 38Threshold("jump-threading-threshold", 39 cl::desc("Max block size to duplicate for jump threading"), 40 cl::init(6), cl::Hidden); 41 42namespace { 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. 48 /// 49 /// An example of when this can occur is code like this: 50 /// 51 /// if () { ... 52 /// X = 4; 53 /// } 54 /// if (X < 3) { 55 /// 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. 58 /// 59 class JumpThreading : public FunctionPass { 60 TargetData *TD; 61#ifdef NDEBUG 62 SmallPtrSet<BasicBlock*, 16> LoopHeaders; 63#else 64 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders; 65#endif 66 public: 67 static char ID; // Pass identification 68 JumpThreading() : FunctionPass(&ID) {} 69 70 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 71 } 72 73 bool runOnFunction(Function &F); 74 void FindLoopHeaders(Function &F); 75 76 bool ProcessBlock(BasicBlock *BB); 77 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB); 78 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val); 79 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); 80 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); 81 82 bool ProcessJumpOnPHI(PHINode *PN); 83 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd); 84 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB); 85 86 bool SimplifyPartiallyRedundantLoad(LoadInst *LI); 87 }; 88} 89 90char JumpThreading::ID = 0; 91static RegisterPass<JumpThreading> 92X("jump-threading", "Jump Threading"); 93 94// Public interface to the Jump Threading pass 95FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); } 96 97/// runOnFunction - Top level algorithm. 98/// 99bool JumpThreading::runOnFunction(Function &F) { 100 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n"); 101 TD = getAnalysisIfAvailable<TargetData>(); 102 103 FindLoopHeaders(F); 104 105 bool AnotherIteration = true, EverChanged = false; 106 while (AnotherIteration) { 107 AnotherIteration = false; 108 bool Changed = false; 109 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 110 BasicBlock *BB = I; 111 while (ProcessBlock(BB)) 112 Changed = true; 113 114 ++I; 115 116 // If the block is trivially dead, zap it. This eliminates the successor 117 // edges which simplifies the CFG. 118 if (pred_begin(BB) == pred_end(BB) && 119 BB != &BB->getParent()->getEntryBlock()) { 120 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName() 121 << "' with terminator: " << *BB->getTerminator()); 122 LoopHeaders.erase(BB); 123 DeleteDeadBlock(BB); 124 Changed = true; 125 } 126 } 127 AnotherIteration = Changed; 128 EverChanged |= Changed; 129 } 130 131 LoopHeaders.clear(); 132 return EverChanged; 133} 134 135/// FindLoopHeaders - We do not want jump threading to turn proper loop 136/// structures into irreducible loops. Doing this breaks up the loop nesting 137/// hierarchy and pessimizes later transformations. To prevent this from 138/// happening, we first have to find the loop headers. Here we approximate this 139/// by finding targets of backedges in the CFG. 140/// 141/// Note that there definitely are cases when we want to allow threading of 142/// edges across a loop header. For example, threading a jump from outside the 143/// loop (the preheader) to an exit block of the loop is definitely profitable. 144/// It is also almost always profitable to thread backedges from within the loop 145/// to exit blocks, and is often profitable to thread backedges to other blocks 146/// within the loop (forming a nested loop). This simple analysis is not rich 147/// enough to track all of these properties and keep it up-to-date as the CFG 148/// mutates, so we don't allow any of these transformations. 149/// 150void JumpThreading::FindLoopHeaders(Function &F) { 151 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 152 FindFunctionBackedges(F, Edges); 153 154 for (unsigned i = 0, e = Edges.size(); i != e; ++i) 155 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second)); 156} 157 158 159/// FactorCommonPHIPreds - If there are multiple preds with the same incoming 160/// value for the PHI, factor them together so we get one block to thread for 161/// the whole group. 162/// This is important for things like "phi i1 [true, true, false, true, x]" 163/// where we only need to clone the block for the true blocks once. 164/// 165BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) { 166 SmallVector<BasicBlock*, 16> CommonPreds; 167 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 168 if (PN->getIncomingValue(i) == Val) 169 CommonPreds.push_back(PN->getIncomingBlock(i)); 170 171 if (CommonPreds.size() == 1) 172 return CommonPreds[0]; 173 174 DEBUG(errs() << " Factoring out " << CommonPreds.size() 175 << " common predecessors.\n"); 176 return SplitBlockPredecessors(PN->getParent(), 177 &CommonPreds[0], CommonPreds.size(), 178 ".thr_comm", this); 179} 180 181 182/// GetBestDestForBranchOnUndef - If we determine that the specified block ends 183/// in an undefined jump, decide which block is best to revector to. 184/// 185/// Since we can pick an arbitrary destination, we pick the successor with the 186/// fewest predecessors. This should reduce the in-degree of the others. 187/// 188static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) { 189 TerminatorInst *BBTerm = BB->getTerminator(); 190 unsigned MinSucc = 0; 191 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 192 // Compute the successor with the minimum number of predecessors. 193 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 194 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 195 TestBB = BBTerm->getSuccessor(i); 196 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 197 if (NumPreds < MinNumPreds) 198 MinSucc = i; 199 } 200 201 return MinSucc; 202} 203 204/// ProcessBlock - If there are any predecessors whose control can be threaded 205/// through to a successor, transform them now. 206bool JumpThreading::ProcessBlock(BasicBlock *BB) { 207 // If this block has a single predecessor, and if that pred has a single 208 // successor, merge the blocks. This encourages recursive jump threading 209 // because now the condition in this block can be threaded through 210 // predecessors of our predecessor block. 211 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) 212 if (SinglePred->getTerminator()->getNumSuccessors() == 1 && 213 SinglePred != BB) { 214 // If SinglePred was a loop header, BB becomes one. 215 if (LoopHeaders.erase(SinglePred)) 216 LoopHeaders.insert(BB); 217 218 // Remember if SinglePred was the entry block of the function. If so, we 219 // will need to move BB back to the entry position. 220 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); 221 MergeBasicBlockIntoOnlyPred(BB); 222 223 if (isEntry && BB != &BB->getParent()->getEntryBlock()) 224 BB->moveBefore(&BB->getParent()->getEntryBlock()); 225 return true; 226 } 227 228 // See if this block ends with a branch or switch. If so, see if the 229 // condition is a phi node. If so, and if an entry of the phi node is a 230 // constant, we can thread the block. 231 Value *Condition; 232 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 233 // Can't thread an unconditional jump. 234 if (BI->isUnconditional()) return false; 235 Condition = BI->getCondition(); 236 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) 237 Condition = SI->getCondition(); 238 else 239 return false; // Must be an invoke. 240 241 // If the terminator of this block is branching on a constant, simplify the 242 // terminator to an unconditional branch. This can occur due to threading in 243 // other blocks. 244 if (isa<ConstantInt>(Condition)) { 245 DEBUG(errs() << " In block '" << BB->getName() 246 << "' folding terminator: " << *BB->getTerminator()); 247 ++NumFolds; 248 ConstantFoldTerminator(BB); 249 return true; 250 } 251 252 // If the terminator is branching on an undef, we can pick any of the 253 // successors to branch to. Let GetBestDestForJumpOnUndef decide. 254 if (isa<UndefValue>(Condition)) { 255 unsigned BestSucc = GetBestDestForJumpOnUndef(BB); 256 257 // Fold the branch/switch. 258 TerminatorInst *BBTerm = BB->getTerminator(); 259 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 260 if (i == BestSucc) continue; 261 BBTerm->getSuccessor(i)->removePredecessor(BB); 262 } 263 264 DEBUG(errs() << " In block '" << BB->getName() 265 << "' folding undef terminator: " << *BBTerm); 266 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); 267 BBTerm->eraseFromParent(); 268 return true; 269 } 270 271 Instruction *CondInst = dyn_cast<Instruction>(Condition); 272 273 // If the condition is an instruction defined in another block, see if a 274 // predecessor has the same condition: 275 // br COND, BBX, BBY 276 // BBX: 277 // br COND, BBZ, BBW 278 if (!Condition->hasOneUse() && // Multiple uses. 279 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition. 280 pred_iterator PI = pred_begin(BB), E = pred_end(BB); 281 if (isa<BranchInst>(BB->getTerminator())) { 282 for (; PI != E; ++PI) 283 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 284 if (PBI->isConditional() && PBI->getCondition() == Condition && 285 ProcessBranchOnDuplicateCond(*PI, BB)) 286 return true; 287 } else { 288 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator"); 289 for (; PI != E; ++PI) 290 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator())) 291 if (PSI->getCondition() == Condition && 292 ProcessSwitchOnDuplicateCond(*PI, BB)) 293 return true; 294 } 295 } 296 297 // All the rest of our checks depend on the condition being an instruction. 298 if (CondInst == 0) 299 return false; 300 301 // See if this is a phi node in the current block. 302 if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 303 if (PN->getParent() == BB) 304 return ProcessJumpOnPHI(PN); 305 306 // If this is a conditional branch whose condition is and/or of a phi, try to 307 // simplify it. 308 if ((CondInst->getOpcode() == Instruction::And || 309 CondInst->getOpcode() == Instruction::Or) && 310 isa<BranchInst>(BB->getTerminator()) && 311 ProcessBranchOnLogical(CondInst, BB, 312 CondInst->getOpcode() == Instruction::And)) 313 return true; 314 315 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { 316 if (isa<PHINode>(CondCmp->getOperand(0))) { 317 // If we have "br (phi != 42)" and the phi node has any constant values 318 // as operands, we can thread through this block. 319 // 320 // If we have "br (cmp phi, x)" and the phi node contains x such that the 321 // comparison uniquely identifies the branch target, we can thread 322 // through this block. 323 324 if (ProcessBranchOnCompare(CondCmp, BB)) 325 return true; 326 } 327 328 // If we have a comparison, loop over the predecessors to see if there is 329 // a condition with the same value. 330 pred_iterator PI = pred_begin(BB), E = pred_end(BB); 331 for (; PI != E; ++PI) 332 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 333 if (PBI->isConditional() && *PI != BB) { 334 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) { 335 if (CI->getOperand(0) == CondCmp->getOperand(0) && 336 CI->getOperand(1) == CondCmp->getOperand(1) && 337 CI->getPredicate() == CondCmp->getPredicate()) { 338 // TODO: Could handle things like (x != 4) --> (x == 17) 339 if (ProcessBranchOnDuplicateCond(*PI, BB)) 340 return true; 341 } 342 } 343 } 344 } 345 346 // Check for some cases that are worth simplifying. Right now we want to look 347 // for loads that are used by a switch or by the condition for the branch. If 348 // we see one, check to see if it's partially redundant. If so, insert a PHI 349 // which can then be used to thread the values. 350 // 351 // This is particularly important because reg2mem inserts loads and stores all 352 // over the place, and this blocks jump threading if we don't zap them. 353 Value *SimplifyValue = CondInst; 354 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 355 if (isa<Constant>(CondCmp->getOperand(1))) 356 SimplifyValue = CondCmp->getOperand(0); 357 358 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue)) 359 if (SimplifyPartiallyRedundantLoad(LI)) 360 return true; 361 362 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know 363 // "(X == 4)" thread through this block. 364 365 return false; 366} 367 368/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that 369/// block that jump on exactly the same condition. This means that we almost 370/// always know the direction of the edge in the DESTBB: 371/// PREDBB: 372/// br COND, DESTBB, BBY 373/// DESTBB: 374/// br COND, BBZ, BBW 375/// 376/// If DESTBB has multiple predecessors, we can't just constant fold the branch 377/// in DESTBB, we have to thread over it. 378bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB, 379 BasicBlock *BB) { 380 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator()); 381 382 // If both successors of PredBB go to DESTBB, we don't know anything. We can 383 // fold the branch to an unconditional one, which allows other recursive 384 // simplifications. 385 bool BranchDir; 386 if (PredBI->getSuccessor(1) != BB) 387 BranchDir = true; 388 else if (PredBI->getSuccessor(0) != BB) 389 BranchDir = false; 390 else { 391 DEBUG(errs() << " In block '" << PredBB->getName() 392 << "' folding terminator: " << *PredBB->getTerminator()); 393 ++NumFolds; 394 ConstantFoldTerminator(PredBB); 395 return true; 396 } 397 398 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator()); 399 400 // If the dest block has one predecessor, just fix the branch condition to a 401 // constant and fold it. 402 if (BB->getSinglePredecessor()) { 403 DEBUG(errs() << " In block '" << BB->getName() 404 << "' folding condition to '" << BranchDir << "': " 405 << *BB->getTerminator()); 406 ++NumFolds; 407 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 408 BranchDir)); 409 ConstantFoldTerminator(BB); 410 return true; 411 } 412 413 414 // Next, figure out which successor we are threading to. 415 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir); 416 417 // Ok, try to thread it! 418 return ThreadEdge(BB, PredBB, SuccBB); 419} 420 421/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that 422/// block that switch on exactly the same condition. This means that we almost 423/// always know the direction of the edge in the DESTBB: 424/// PREDBB: 425/// switch COND [... DESTBB, BBY ... ] 426/// DESTBB: 427/// switch COND [... BBZ, BBW ] 428/// 429/// Optimizing switches like this is very important, because simplifycfg builds 430/// switches out of repeated 'if' conditions. 431bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, 432 BasicBlock *DestBB) { 433 // Can't thread edge to self. 434 if (PredBB == DestBB) 435 return false; 436 437 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator()); 438 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator()); 439 440 // There are a variety of optimizations that we can potentially do on these 441 // blocks: we order them from most to least preferable. 442 443 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB 444 // directly to their destination. This does not introduce *any* code size 445 // growth. Skip debug info first. 446 BasicBlock::iterator BBI = DestBB->begin(); 447 while (isa<DbgInfoIntrinsic>(BBI)) 448 BBI++; 449 450 // FIXME: Thread if it just contains a PHI. 451 if (isa<SwitchInst>(BBI)) { 452 bool MadeChange = false; 453 // Ignore the default edge for now. 454 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) { 455 ConstantInt *DestVal = DestSI->getCaseValue(i); 456 BasicBlock *DestSucc = DestSI->getSuccessor(i); 457 458 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if 459 // PredSI has an explicit case for it. If so, forward. If it is covered 460 // by the default case, we can't update PredSI. 461 unsigned PredCase = PredSI->findCaseValue(DestVal); 462 if (PredCase == 0) continue; 463 464 // If PredSI doesn't go to DestBB on this value, then it won't reach the 465 // case on this condition. 466 if (PredSI->getSuccessor(PredCase) != DestBB && 467 DestSI->getSuccessor(i) != DestBB) 468 continue; 469 470 // Otherwise, we're safe to make the change. Make sure that the edge from 471 // DestSI to DestSucc is not critical and has no PHI nodes. 472 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI); 473 DEBUG(errs() << "THROUGH: " << *DestSI); 474 475 // If the destination has PHI nodes, just split the edge for updating 476 // simplicity. 477 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){ 478 SplitCriticalEdge(DestSI, i, this); 479 DestSucc = DestSI->getSuccessor(i); 480 } 481 FoldSingleEntryPHINodes(DestSucc); 482 PredSI->setSuccessor(PredCase, DestSucc); 483 MadeChange = true; 484 } 485 486 if (MadeChange) 487 return true; 488 } 489 490 return false; 491} 492 493 494/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant 495/// load instruction, eliminate it by replacing it with a PHI node. This is an 496/// important optimization that encourages jump threading, and needs to be run 497/// interlaced with other jump threading tasks. 498bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) { 499 // Don't hack volatile loads. 500 if (LI->isVolatile()) return false; 501 502 // If the load is defined in a block with exactly one predecessor, it can't be 503 // partially redundant. 504 BasicBlock *LoadBB = LI->getParent(); 505 if (LoadBB->getSinglePredecessor()) 506 return false; 507 508 Value *LoadedPtr = LI->getOperand(0); 509 510 // If the loaded operand is defined in the LoadBB, it can't be available. 511 // FIXME: Could do PHI translation, that would be fun :) 512 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr)) 513 if (PtrOp->getParent() == LoadBB) 514 return false; 515 516 // Scan a few instructions up from the load, to see if it is obviously live at 517 // the entry to its block. 518 BasicBlock::iterator BBIt = LI; 519 520 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, 521 BBIt, 6)) { 522 // If the value if the load is locally available within the block, just use 523 // it. This frequently occurs for reg2mem'd allocas. 524 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n"; 525 526 // If the returned value is the load itself, replace with an undef. This can 527 // only happen in dead loops. 528 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType()); 529 LI->replaceAllUsesWith(AvailableVal); 530 LI->eraseFromParent(); 531 return true; 532 } 533 534 // Otherwise, if we scanned the whole block and got to the top of the block, 535 // we know the block is locally transparent to the load. If not, something 536 // might clobber its value. 537 if (BBIt != LoadBB->begin()) 538 return false; 539 540 541 SmallPtrSet<BasicBlock*, 8> PredsScanned; 542 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy; 543 AvailablePredsTy AvailablePreds; 544 BasicBlock *OneUnavailablePred = 0; 545 546 // If we got here, the loaded value is transparent through to the start of the 547 // block. Check to see if it is available in any of the predecessor blocks. 548 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); 549 PI != PE; ++PI) { 550 BasicBlock *PredBB = *PI; 551 552 // If we already scanned this predecessor, skip it. 553 if (!PredsScanned.insert(PredBB)) 554 continue; 555 556 // Scan the predecessor to see if the value is available in the pred. 557 BBIt = PredBB->end(); 558 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6); 559 if (!PredAvailable) { 560 OneUnavailablePred = PredBB; 561 continue; 562 } 563 564 // If so, this load is partially redundant. Remember this info so that we 565 // can create a PHI node. 566 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable)); 567 } 568 569 // If the loaded value isn't available in any predecessor, it isn't partially 570 // redundant. 571 if (AvailablePreds.empty()) return false; 572 573 // Okay, the loaded value is available in at least one (and maybe all!) 574 // predecessors. If the value is unavailable in more than one unique 575 // predecessor, we want to insert a merge block for those common predecessors. 576 // This ensures that we only have to insert one reload, thus not increasing 577 // code size. 578 BasicBlock *UnavailablePred = 0; 579 580 // If there is exactly one predecessor where the value is unavailable, the 581 // already computed 'OneUnavailablePred' block is it. If it ends in an 582 // unconditional branch, we know that it isn't a critical edge. 583 if (PredsScanned.size() == AvailablePreds.size()+1 && 584 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 585 UnavailablePred = OneUnavailablePred; 586 } else if (PredsScanned.size() != AvailablePreds.size()) { 587 // Otherwise, we had multiple unavailable predecessors or we had a critical 588 // edge from the one. 589 SmallVector<BasicBlock*, 8> PredsToSplit; 590 SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 591 592 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i) 593 AvailablePredSet.insert(AvailablePreds[i].first); 594 595 // Add all the unavailable predecessors to the PredsToSplit list. 596 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); 597 PI != PE; ++PI) 598 if (!AvailablePredSet.count(*PI)) 599 PredsToSplit.push_back(*PI); 600 601 // Split them out to their own block. 602 UnavailablePred = 603 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(), 604 "thread-split", this); 605 } 606 607 // If the value isn't available in all predecessors, then there will be 608 // exactly one where it isn't available. Insert a load on that edge and add 609 // it to the AvailablePreds list. 610 if (UnavailablePred) { 611 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 612 "Can't handle critical edge here!"); 613 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", 614 UnavailablePred->getTerminator()); 615 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal)); 616 } 617 618 // Now we know that each predecessor of this block has a value in 619 // AvailablePreds, sort them for efficient access as we're walking the preds. 620 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 621 622 // Create a PHI node at the start of the block for the PRE'd load value. 623 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin()); 624 PN->takeName(LI); 625 626 // Insert new entries into the PHI for each predecessor. A single block may 627 // have multiple entries here. 628 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E; 629 ++PI) { 630 AvailablePredsTy::iterator I = 631 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(), 632 std::make_pair(*PI, (Value*)0)); 633 634 assert(I != AvailablePreds.end() && I->first == *PI && 635 "Didn't find entry for predecessor!"); 636 637 PN->addIncoming(I->second, I->first); 638 } 639 640 //cerr << "PRE: " << *LI << *PN << "\n"; 641 642 LI->replaceAllUsesWith(PN); 643 LI->eraseFromParent(); 644 645 return true; 646} 647 648 649/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in 650/// the current block. See if there are any simplifications we can do based on 651/// inputs to the phi node. 652/// 653bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) { 654 // See if the phi node has any constant integer or undef values. If so, we 655 // can determine where the corresponding predecessor will branch. 656 Constant *PredCst = 0; 657 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 658 Value *PredVal = PN->getIncomingValue(i); 659 if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) { 660 PredCst = CI; 661 break; 662 } 663 664 if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) { 665 PredCst = UV; 666 break; 667 } 668 } 669 670 // If no incoming value has a constant, we don't know the destination of any 671 // predecessors. 672 if (PredCst == 0) { 673 return false; 674 } 675 676 // See if the cost of duplicating this block is low enough. 677 BasicBlock *BB = PN->getParent(); 678 679 // If so, we can actually do this threading. Merge any common predecessors 680 // that will act the same. 681 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst); 682 683 TerminatorInst *BBTerm = BB->getTerminator(); 684 685 // Next, figure out which successor we are threading to. 686 BasicBlock *SuccBB; 687 if (isa<UndefValue>(PredCst)) { 688 // If the branch was going off an undef from PredBB, pick an arbitrary dest. 689 SuccBB = BBTerm->getSuccessor(GetBestDestForJumpOnUndef(BB)); 690 } else if (BranchInst *BI = dyn_cast<BranchInst>(BBTerm)) 691 SuccBB = BI->getSuccessor(cast<ConstantInt>(PredCst)->isZero()); 692 else { 693 SwitchInst *SI = cast<SwitchInst>(BBTerm); 694 SuccBB = SI->getSuccessor(SI->findCaseValue(cast<ConstantInt>(PredCst))); 695 } 696 697 // Ok, try to thread it! 698 return ThreadEdge(BB, PredBB, SuccBB); 699} 700 701/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch 702/// whose condition is an AND/OR where one side is PN. If PN has constant 703/// operands that permit us to evaluate the condition for some operand, thread 704/// through the block. For example with: 705/// br (and X, phi(Y, Z, false)) 706/// the predecessor corresponding to the 'false' will always jump to the false 707/// destination of the branch. 708/// 709bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB, 710 bool isAnd) { 711 // If this is a binary operator tree of the same AND/OR opcode, check the 712 // LHS/RHS. 713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) 714 if ((isAnd && BO->getOpcode() == Instruction::And) || 715 (!isAnd && BO->getOpcode() == Instruction::Or)) { 716 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd)) 717 return true; 718 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd)) 719 return true; 720 } 721 722 // If this isn't a PHI node, we can't handle it. 723 PHINode *PN = dyn_cast<PHINode>(V); 724 if (!PN || PN->getParent() != BB) return false; 725 726 // We can only do the simplification for phi nodes of 'false' with AND or 727 // 'true' with OR. See if we have any entries in the phi for this. 728 unsigned PredNo = ~0U; 729 ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()), 730 !isAnd); 731 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 732 if (PN->getIncomingValue(i) == PredCst) { 733 PredNo = i; 734 break; 735 } 736 } 737 738 // If no match, bail out. 739 if (PredNo == ~0U) 740 return false; 741 742 // If so, we can actually do this threading. Merge any common predecessors 743 // that will act the same. 744 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst); 745 746 // Next, figure out which successor we are threading to. If this was an AND, 747 // the constant must be FALSE, and we must be targeting the 'false' block. 748 // If this is an OR, the constant must be TRUE, and we must be targeting the 749 // 'true' block. 750 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd); 751 752 // Ok, try to thread it! 753 return ThreadEdge(BB, PredBB, SuccBB); 754} 755 756/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right 757/// hand sides of the compare instruction, try to determine the result. If the 758/// result can not be determined, a null pointer is returned. 759static Constant *GetResultOfComparison(CmpInst::Predicate pred, 760 Value *LHS, Value *RHS, 761 LLVMContext &Context) { 762 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 763 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 764 return ConstantExpr::getCompare(pred, CLHS, CRHS); 765 766 if (LHS == RHS) 767 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType())) 768 return ICmpInst::isTrueWhenEqual(pred) ? 769 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context); 770 771 return 0; 772} 773 774/// ProcessBranchOnCompare - We found a branch on a comparison between a phi 775/// node and a value. If we can identify when the comparison is true between 776/// the phi inputs and the value, we can fold the compare for that edge and 777/// thread through it. 778bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) { 779 PHINode *PN = cast<PHINode>(Cmp->getOperand(0)); 780 Value *RHS = Cmp->getOperand(1); 781 782 // If the phi isn't in the current block, an incoming edge to this block 783 // doesn't control the destination. 784 if (PN->getParent() != BB) 785 return false; 786 787 // We can do this simplification if any comparisons fold to true or false. 788 // See if any do. 789 Value *PredVal = 0; 790 bool TrueDirection = false; 791 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 792 PredVal = PN->getIncomingValue(i); 793 794 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal, 795 RHS, Cmp->getContext()); 796 if (!Res) { 797 PredVal = 0; 798 continue; 799 } 800 801 // If this folded to a constant expr, we can't do anything. 802 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) { 803 TrueDirection = ResC->getZExtValue(); 804 break; 805 } 806 // If this folded to undef, just go the false way. 807 if (isa<UndefValue>(Res)) { 808 TrueDirection = false; 809 break; 810 } 811 812 // Otherwise, we can't fold this input. 813 PredVal = 0; 814 } 815 816 // If no match, bail out. 817 if (PredVal == 0) 818 return false; 819 820 // If so, we can actually do this threading. Merge any common predecessors 821 // that will act the same. 822 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal); 823 824 // Next, get our successor. 825 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection); 826 827 // Ok, try to thread it! 828 return ThreadEdge(BB, PredBB, SuccBB); 829} 830 831/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to 832/// thread across it. 833static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) { 834 /// Ignore PHI nodes, these will be flattened when duplication happens. 835 BasicBlock::const_iterator I = BB->getFirstNonPHI(); 836 837 // Sum up the cost of each instruction until we get to the terminator. Don't 838 // include the terminator because the copy won't include it. 839 unsigned Size = 0; 840 for (; !isa<TerminatorInst>(I); ++I) { 841 // Debugger intrinsics don't incur code size. 842 if (isa<DbgInfoIntrinsic>(I)) continue; 843 844 // If this is a pointer->pointer bitcast, it is free. 845 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType())) 846 continue; 847 848 // All other instructions count for at least one unit. 849 ++Size; 850 851 // Calls are more expensive. If they are non-intrinsic calls, we model them 852 // as having cost of 4. If they are a non-vector intrinsic, we model them 853 // as having cost of 2 total, and if they are a vector intrinsic, we model 854 // them as having cost 1. 855 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 856 if (!isa<IntrinsicInst>(CI)) 857 Size += 3; 858 else if (!isa<VectorType>(CI->getType())) 859 Size += 1; 860 } 861 } 862 863 // Threading through a switch statement is particularly profitable. If this 864 // block ends in a switch, decrease its cost to make it more likely to happen. 865 if (isa<SwitchInst>(I)) 866 Size = Size > 6 ? Size-6 : 0; 867 868 return Size; 869} 870 871 872/// ThreadEdge - We have decided that it is safe and profitable to thread an 873/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this 874/// change. 875bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, 876 BasicBlock *SuccBB) { 877 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB); 878 if (JumpThreadCost > Threshold) { 879 DEBUG(errs() << " Not threading BB '" << BB->getName() 880 << "' - Cost is too high: " << JumpThreadCost << "\n"); 881 return false; 882 } 883 884 // If threading to the same block as we come from, we would infinite loop. 885 if (SuccBB == BB) { 886 DEBUG(errs() << " Not threading across BB '" << BB->getName() 887 << "' - would thread to self!\n"); 888 return false; 889 } 890 891 // If threading this would thread across a loop header, don't thread the edge. 892 // See the comments above FindLoopHeaders for justifications and caveats. 893 if (LoopHeaders.count(BB)) { 894 DEBUG(errs() << " Not threading from '" << PredBB->getName() 895 << "' across loop header BB '" << BB->getName() 896 << "' to dest BB '" << SuccBB->getName() 897 << "' - it might create an irreducible loop!\n"); 898 return false; 899 } 900 901 // And finally, do it! 902 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '" 903 << SuccBB->getName() << "' with cost: " << JumpThreadCost 904 << ", across block:\n " 905 << *BB << "\n"); 906 907 // We are going to have to map operands from the original BB block to the new 908 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 909 // account for entry from PredBB. 910 DenseMap<Instruction*, Value*> ValueMapping; 911 912 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 913 BB->getName()+".thread", 914 BB->getParent(), BB); 915 NewBB->moveAfter(PredBB); 916 917 BasicBlock::iterator BI = BB->begin(); 918 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 919 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 920 921 // Clone the non-phi instructions of BB into NewBB, keeping track of the 922 // mapping and using it to remap operands in the cloned instructions. 923 for (; !isa<TerminatorInst>(BI); ++BI) { 924 Instruction *New = BI->clone(); 925 New->setName(BI->getName()); 926 NewBB->getInstList().push_back(New); 927 ValueMapping[BI] = New; 928 929 // Remap operands to patch up intra-block references. 930 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 931 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 932 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 933 if (I != ValueMapping.end()) 934 New->setOperand(i, I->second); 935 } 936 } 937 938 // We didn't copy the terminator from BB over to NewBB, because there is now 939 // an unconditional jump to SuccBB. Insert the unconditional jump. 940 BranchInst::Create(SuccBB, NewBB); 941 942 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 943 // PHI nodes for NewBB now. 944 for (BasicBlock::iterator PNI = SuccBB->begin(); 945 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) { 946 // Ok, we have a PHI node. Figure out what the incoming value was for the 947 // DestBlock. 948 Value *IV = PN->getIncomingValueForBlock(BB); 949 950 // Remap the value if necessary. 951 if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 952 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 953 if (I != ValueMapping.end()) 954 IV = I->second; 955 } 956 PN->addIncoming(IV, NewBB); 957 } 958 959 // If there were values defined in BB that are used outside the block, then we 960 // now have to update all uses of the value to use either the original value, 961 // the cloned value, or some PHI derived value. This can require arbitrary 962 // PHI insertion, of which we are prepared to do, clean these up now. 963 SSAUpdater SSAUpdate; 964 SmallVector<Use*, 16> UsesToRename; 965 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { 966 // Scan all uses of this instruction to see if it is used outside of its 967 // block, and if so, record them in UsesToRename. 968 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 969 ++UI) { 970 Instruction *User = cast<Instruction>(*UI); 971 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 972 if (UserPN->getIncomingBlock(UI) == BB) 973 continue; 974 } else if (User->getParent() == BB) 975 continue; 976 977 UsesToRename.push_back(&UI.getUse()); 978 } 979 980 // If there are no uses outside the block, we're done with this instruction. 981 if (UsesToRename.empty()) 982 continue; 983 984 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n"); 985 986 // We found a use of I outside of BB. Rename all uses of I that are outside 987 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 988 // with the two values we know. 989 SSAUpdate.Initialize(I); 990 SSAUpdate.AddAvailableValue(BB, I); 991 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]); 992 993 while (!UsesToRename.empty()) 994 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 995 DEBUG(errs() << "\n"); 996 } 997 998 999 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to 1000 // NewBB instead of BB. This eliminates predecessors from BB, which requires 1001 // us to simplify any PHI nodes in BB. 1002 TerminatorInst *PredTerm = PredBB->getTerminator(); 1003 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 1004 if (PredTerm->getSuccessor(i) == BB) { 1005 BB->removePredecessor(PredBB); 1006 PredTerm->setSuccessor(i, NewBB); 1007 } 1008 1009 // At this point, the IR is fully up to date and consistent. Do a quick scan 1010 // over the new instructions and zap any that are constants or dead. This 1011 // frequently happens because of phi translation. 1012 BI = NewBB->begin(); 1013 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) { 1014 Instruction *Inst = BI++; 1015 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) { 1016 Inst->replaceAllUsesWith(C); 1017 Inst->eraseFromParent(); 1018 continue; 1019 } 1020 1021 RecursivelyDeleteTriviallyDeadInstructions(Inst); 1022 } 1023 1024 // Threaded an edge! 1025 ++NumThreads; 1026 return true; 1027} 1028