1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===// 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 basic block placement transformations using the CFG 11 // structure and branch probability estimates. 12 // 13 // The pass strives to preserve the structure of the CFG (that is, retain 14 // a topological ordering of basic blocks) in the absense of a *strong* signal 15 // to the contrary from probabilities. However, within the CFG structure, it 16 // attempts to choose an ordering which favors placing more likely sequences of 17 // blocks adjacent to each other. 18 // 19 // The algorithm works from the inner-most loop within a function outward, and 20 // at each stage walks through the basic blocks, trying to coalesce them into 21 // sequential chains where allowed by the CFG (or demanded by heavy 22 // probabilities). Finally, it walks the blocks in topological order, and the 23 // first time it reaches a chain of basic blocks, it schedules them in the 24 // function in-order. 25 // 26 //===----------------------------------------------------------------------===// 27 28 #define DEBUG_TYPE "block-placement2" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 31 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 32 #include "llvm/CodeGen/MachineFunction.h" 33 #include "llvm/CodeGen/MachineFunctionPass.h" 34 #include "llvm/CodeGen/MachineLoopInfo.h" 35 #include "llvm/CodeGen/MachineModuleInfo.h" 36 #include "llvm/CodeGen/Passes.h" 37 #include "llvm/Support/Allocator.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/ADT/DenseMap.h" 40 #include "llvm/ADT/SmallPtrSet.h" 41 #include "llvm/ADT/SmallVector.h" 42 #include "llvm/ADT/Statistic.h" 43 #include "llvm/Target/TargetInstrInfo.h" 44 #include "llvm/Target/TargetLowering.h" 45 #include <algorithm> 46 using namespace llvm; 47 48 STATISTIC(NumCondBranches, "Number of conditional branches"); 49 STATISTIC(NumUncondBranches, "Number of uncondittional branches"); 50 STATISTIC(CondBranchTakenFreq, 51 "Potential frequency of taking conditional branches"); 52 STATISTIC(UncondBranchTakenFreq, 53 "Potential frequency of taking unconditional branches"); 54 55 namespace { 56 class BlockChain; 57 /// \brief Type for our function-wide basic block -> block chain mapping. 58 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType; 59 } 60 61 namespace { 62 /// \brief A chain of blocks which will be laid out contiguously. 63 /// 64 /// This is the datastructure representing a chain of consecutive blocks that 65 /// are profitable to layout together in order to maximize fallthrough 66 /// probabilities. We also can use a block chain to represent a sequence of 67 /// basic blocks which have some external (correctness) requirement for 68 /// sequential layout. 69 /// 70 /// Eventually, the block chains will form a directed graph over the function. 71 /// We provide an SCC-supporting-iterator in order to quicky build and walk the 72 /// SCCs of block chains within a function. 73 /// 74 /// The block chains also have support for calculating and caching probability 75 /// information related to the chain itself versus other chains. This is used 76 /// for ranking during the final layout of block chains. 77 class BlockChain { 78 /// \brief The sequence of blocks belonging to this chain. 79 /// 80 /// This is the sequence of blocks for a particular chain. These will be laid 81 /// out in-order within the function. 82 SmallVector<MachineBasicBlock *, 4> Blocks; 83 84 /// \brief A handle to the function-wide basic block to block chain mapping. 85 /// 86 /// This is retained in each block chain to simplify the computation of child 87 /// block chains for SCC-formation and iteration. We store the edges to child 88 /// basic blocks, and map them back to their associated chains using this 89 /// structure. 90 BlockToChainMapType &BlockToChain; 91 92 public: 93 /// \brief Construct a new BlockChain. 94 /// 95 /// This builds a new block chain representing a single basic block in the 96 /// function. It also registers itself as the chain that block participates 97 /// in with the BlockToChain mapping. 98 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 99 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) { 100 assert(BB && "Cannot create a chain with a null basic block"); 101 BlockToChain[BB] = this; 102 } 103 104 /// \brief Iterator over blocks within the chain. 105 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator iterator; 106 107 /// \brief Beginning of blocks within the chain. 108 iterator begin() const { return Blocks.begin(); } 109 110 /// \brief End of blocks within the chain. 111 iterator end() const { return Blocks.end(); } 112 113 /// \brief Merge a block chain into this one. 114 /// 115 /// This routine merges a block chain into this one. It takes care of forming 116 /// a contiguous sequence of basic blocks, updating the edge list, and 117 /// updating the block -> chain mapping. It does not free or tear down the 118 /// old chain, but the old chain's block list is no longer valid. 119 void merge(MachineBasicBlock *BB, BlockChain *Chain) { 120 assert(BB); 121 assert(!Blocks.empty()); 122 123 // Fast path in case we don't have a chain already. 124 if (!Chain) { 125 assert(!BlockToChain[BB]); 126 Blocks.push_back(BB); 127 BlockToChain[BB] = this; 128 return; 129 } 130 131 assert(BB == *Chain->begin()); 132 assert(Chain->begin() != Chain->end()); 133 134 // Update the incoming blocks to point to this chain, and add them to the 135 // chain structure. 136 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end(); 137 BI != BE; ++BI) { 138 Blocks.push_back(*BI); 139 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain"); 140 BlockToChain[*BI] = this; 141 } 142 } 143 144 /// \brief Count of predecessors within the loop currently being processed. 145 /// 146 /// This count is updated at each loop we process to represent the number of 147 /// in-loop predecessors of this chain. 148 unsigned LoopPredecessors; 149 }; 150 } 151 152 namespace { 153 class MachineBlockPlacement : public MachineFunctionPass { 154 /// \brief A typedef for a block filter set. 155 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet; 156 157 /// \brief A handle to the branch probability pass. 158 const MachineBranchProbabilityInfo *MBPI; 159 160 /// \brief A handle to the function-wide block frequency pass. 161 const MachineBlockFrequencyInfo *MBFI; 162 163 /// \brief A handle to the loop info. 164 const MachineLoopInfo *MLI; 165 166 /// \brief A handle to the target's instruction info. 167 const TargetInstrInfo *TII; 168 169 /// \brief A handle to the target's lowering info. 170 const TargetLowering *TLI; 171 172 /// \brief Allocator and owner of BlockChain structures. 173 /// 174 /// We build BlockChains lazily by merging together high probability BB 175 /// sequences acording to the "Algo2" in the paper mentioned at the top of 176 /// the file. To reduce malloc traffic, we allocate them using this slab-like 177 /// allocator, and destroy them after the pass completes. 178 SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 179 180 /// \brief Function wide BasicBlock to BlockChain mapping. 181 /// 182 /// This mapping allows efficiently moving from any given basic block to the 183 /// BlockChain it participates in, if any. We use it to, among other things, 184 /// allow implicitly defining edges between chains as the existing edges 185 /// between basic blocks. 186 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain; 187 188 void markChainSuccessors(BlockChain &Chain, 189 MachineBasicBlock *LoopHeaderBB, 190 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 191 const BlockFilterSet *BlockFilter = 0); 192 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB, 193 BlockChain &Chain, 194 const BlockFilterSet *BlockFilter); 195 MachineBasicBlock *selectBestCandidateBlock( 196 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList, 197 const BlockFilterSet *BlockFilter); 198 MachineBasicBlock *getFirstUnplacedBlock( 199 MachineFunction &F, 200 const BlockChain &PlacedChain, 201 MachineFunction::iterator &PrevUnplacedBlockIt, 202 const BlockFilterSet *BlockFilter); 203 void buildChain(MachineBasicBlock *BB, BlockChain &Chain, 204 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 205 const BlockFilterSet *BlockFilter = 0); 206 MachineBasicBlock *findBestLoopTop(MachineFunction &F, 207 MachineLoop &L, 208 const BlockFilterSet &LoopBlockSet); 209 void buildLoopChains(MachineFunction &F, MachineLoop &L); 210 void buildCFGChains(MachineFunction &F); 211 void AlignLoops(MachineFunction &F); 212 213 public: 214 static char ID; // Pass identification, replacement for typeid 215 MachineBlockPlacement() : MachineFunctionPass(ID) { 216 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 217 } 218 219 bool runOnMachineFunction(MachineFunction &F); 220 221 void getAnalysisUsage(AnalysisUsage &AU) const { 222 AU.addRequired<MachineBranchProbabilityInfo>(); 223 AU.addRequired<MachineBlockFrequencyInfo>(); 224 AU.addRequired<MachineLoopInfo>(); 225 MachineFunctionPass::getAnalysisUsage(AU); 226 } 227 }; 228 } 229 230 char MachineBlockPlacement::ID = 0; 231 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 232 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2", 233 "Branch Probability Basic Block Placement", false, false) 234 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 235 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 236 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 237 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2", 238 "Branch Probability Basic Block Placement", false, false) 239 240 #ifndef NDEBUG 241 /// \brief Helper to print the name of a MBB. 242 /// 243 /// Only used by debug logging. 244 static std::string getBlockName(MachineBasicBlock *BB) { 245 std::string Result; 246 raw_string_ostream OS(Result); 247 OS << "BB#" << BB->getNumber() 248 << " (derived from LLVM BB '" << BB->getName() << "')"; 249 OS.flush(); 250 return Result; 251 } 252 253 /// \brief Helper to print the number of a MBB. 254 /// 255 /// Only used by debug logging. 256 static std::string getBlockNum(MachineBasicBlock *BB) { 257 std::string Result; 258 raw_string_ostream OS(Result); 259 OS << "BB#" << BB->getNumber(); 260 OS.flush(); 261 return Result; 262 } 263 #endif 264 265 /// \brief Mark a chain's successors as having one fewer preds. 266 /// 267 /// When a chain is being merged into the "placed" chain, this routine will 268 /// quickly walk the successors of each block in the chain and mark them as 269 /// having one fewer active predecessor. It also adds any successors of this 270 /// chain which reach the zero-predecessor state to the worklist passed in. 271 void MachineBlockPlacement::markChainSuccessors( 272 BlockChain &Chain, 273 MachineBasicBlock *LoopHeaderBB, 274 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 275 const BlockFilterSet *BlockFilter) { 276 // Walk all the blocks in this chain, marking their successors as having 277 // a predecessor placed. 278 for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end(); 279 CBI != CBE; ++CBI) { 280 // Add any successors for which this is the only un-placed in-loop 281 // predecessor to the worklist as a viable candidate for CFG-neutral 282 // placement. No subsequent placement of this block will violate the CFG 283 // shape, so we get to use heuristics to choose a favorable placement. 284 for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(), 285 SE = (*CBI)->succ_end(); 286 SI != SE; ++SI) { 287 if (BlockFilter && !BlockFilter->count(*SI)) 288 continue; 289 BlockChain &SuccChain = *BlockToChain[*SI]; 290 // Disregard edges within a fixed chain, or edges to the loop header. 291 if (&Chain == &SuccChain || *SI == LoopHeaderBB) 292 continue; 293 294 // This is a cross-chain edge that is within the loop, so decrement the 295 // loop predecessor count of the destination chain. 296 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0) 297 BlockWorkList.push_back(*SuccChain.begin()); 298 } 299 } 300 } 301 302 /// \brief Select the best successor for a block. 303 /// 304 /// This looks across all successors of a particular block and attempts to 305 /// select the "best" one to be the layout successor. It only considers direct 306 /// successors which also pass the block filter. It will attempt to avoid 307 /// breaking CFG structure, but cave and break such structures in the case of 308 /// very hot successor edges. 309 /// 310 /// \returns The best successor block found, or null if none are viable. 311 MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor( 312 MachineBasicBlock *BB, BlockChain &Chain, 313 const BlockFilterSet *BlockFilter) { 314 const BranchProbability HotProb(4, 5); // 80% 315 316 MachineBasicBlock *BestSucc = 0; 317 // FIXME: Due to the performance of the probability and weight routines in 318 // the MBPI analysis, we manually compute probabilities using the edge 319 // weights. This is suboptimal as it means that the somewhat subtle 320 // definition of edge weight semantics is encoded here as well. We should 321 // improve the MBPI interface to effeciently support query patterns such as 322 // this. 323 uint32_t BestWeight = 0; 324 uint32_t WeightScale = 0; 325 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale); 326 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n"); 327 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 328 SE = BB->succ_end(); 329 SI != SE; ++SI) { 330 if (BlockFilter && !BlockFilter->count(*SI)) 331 continue; 332 BlockChain &SuccChain = *BlockToChain[*SI]; 333 if (&SuccChain == &Chain) { 334 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Already merged!\n"); 335 continue; 336 } 337 if (*SI != *SuccChain.begin()) { 338 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Mid chain!\n"); 339 continue; 340 } 341 342 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI); 343 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight); 344 345 // Only consider successors which are either "hot", or wouldn't violate 346 // any CFG constraints. 347 if (SuccChain.LoopPredecessors != 0) { 348 if (SuccProb < HotProb) { 349 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> CFG conflict\n"); 350 continue; 351 } 352 353 // Make sure that a hot successor doesn't have a globally more important 354 // predecessor. 355 BlockFrequency CandidateEdgeFreq 356 = MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl(); 357 bool BadCFGConflict = false; 358 for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(), 359 PE = (*SI)->pred_end(); 360 PI != PE; ++PI) { 361 if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) || 362 BlockToChain[*PI] == &Chain) 363 continue; 364 BlockFrequency PredEdgeFreq 365 = MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI); 366 if (PredEdgeFreq >= CandidateEdgeFreq) { 367 BadCFGConflict = true; 368 break; 369 } 370 } 371 if (BadCFGConflict) { 372 DEBUG(dbgs() << " " << getBlockName(*SI) 373 << " -> non-cold CFG conflict\n"); 374 continue; 375 } 376 } 377 378 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb 379 << " (prob)" 380 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "") 381 << "\n"); 382 if (BestSucc && BestWeight >= SuccWeight) 383 continue; 384 BestSucc = *SI; 385 BestWeight = SuccWeight; 386 } 387 return BestSucc; 388 } 389 390 namespace { 391 /// \brief Predicate struct to detect blocks already placed. 392 class IsBlockPlaced { 393 const BlockChain &PlacedChain; 394 const BlockToChainMapType &BlockToChain; 395 396 public: 397 IsBlockPlaced(const BlockChain &PlacedChain, 398 const BlockToChainMapType &BlockToChain) 399 : PlacedChain(PlacedChain), BlockToChain(BlockToChain) {} 400 401 bool operator()(MachineBasicBlock *BB) const { 402 return BlockToChain.lookup(BB) == &PlacedChain; 403 } 404 }; 405 } 406 407 /// \brief Select the best block from a worklist. 408 /// 409 /// This looks through the provided worklist as a list of candidate basic 410 /// blocks and select the most profitable one to place. The definition of 411 /// profitable only really makes sense in the context of a loop. This returns 412 /// the most frequently visited block in the worklist, which in the case of 413 /// a loop, is the one most desirable to be physically close to the rest of the 414 /// loop body in order to improve icache behavior. 415 /// 416 /// \returns The best block found, or null if none are viable. 417 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 418 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList, 419 const BlockFilterSet *BlockFilter) { 420 // Once we need to walk the worklist looking for a candidate, cleanup the 421 // worklist of already placed entries. 422 // FIXME: If this shows up on profiles, it could be folded (at the cost of 423 // some code complexity) into the loop below. 424 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(), 425 IsBlockPlaced(Chain, BlockToChain)), 426 WorkList.end()); 427 428 MachineBasicBlock *BestBlock = 0; 429 BlockFrequency BestFreq; 430 for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(), 431 WBE = WorkList.end(); 432 WBI != WBE; ++WBI) { 433 assert(!BlockFilter || BlockFilter->count(*WBI)); 434 BlockChain &SuccChain = *BlockToChain[*WBI]; 435 if (&SuccChain == &Chain) { 436 DEBUG(dbgs() << " " << getBlockName(*WBI) 437 << " -> Already merged!\n"); 438 continue; 439 } 440 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block"); 441 442 BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI); 443 DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> " << CandidateFreq 444 << " (freq)\n"); 445 if (BestBlock && BestFreq >= CandidateFreq) 446 continue; 447 BestBlock = *WBI; 448 BestFreq = CandidateFreq; 449 } 450 return BestBlock; 451 } 452 453 /// \brief Retrieve the first unplaced basic block. 454 /// 455 /// This routine is called when we are unable to use the CFG to walk through 456 /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 457 /// We walk through the function's blocks in order, starting from the 458 /// LastUnplacedBlockIt. We update this iterator on each call to avoid 459 /// re-scanning the entire sequence on repeated calls to this routine. 460 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 461 MachineFunction &F, const BlockChain &PlacedChain, 462 MachineFunction::iterator &PrevUnplacedBlockIt, 463 const BlockFilterSet *BlockFilter) { 464 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E; 465 ++I) { 466 if (BlockFilter && !BlockFilter->count(I)) 467 continue; 468 if (BlockToChain[I] != &PlacedChain) { 469 PrevUnplacedBlockIt = I; 470 // Now select the head of the chain to which the unplaced block belongs 471 // as the block to place. This will force the entire chain to be placed, 472 // and satisfies the requirements of merging chains. 473 return *BlockToChain[I]->begin(); 474 } 475 } 476 return 0; 477 } 478 479 void MachineBlockPlacement::buildChain( 480 MachineBasicBlock *BB, 481 BlockChain &Chain, 482 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 483 const BlockFilterSet *BlockFilter) { 484 assert(BB); 485 assert(BlockToChain[BB] == &Chain); 486 MachineFunction &F = *BB->getParent(); 487 MachineFunction::iterator PrevUnplacedBlockIt = F.begin(); 488 489 MachineBasicBlock *LoopHeaderBB = BB; 490 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter); 491 BB = *llvm::prior(Chain.end()); 492 for (;;) { 493 assert(BB); 494 assert(BlockToChain[BB] == &Chain); 495 assert(*llvm::prior(Chain.end()) == BB); 496 MachineBasicBlock *BestSucc = 0; 497 498 // Look for the best viable successor if there is one to place immediately 499 // after this block. 500 BestSucc = selectBestSuccessor(BB, Chain, BlockFilter); 501 502 // If an immediate successor isn't available, look for the best viable 503 // block among those we've identified as not violating the loop's CFG at 504 // this point. This won't be a fallthrough, but it will increase locality. 505 if (!BestSucc) 506 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter); 507 508 if (!BestSucc) { 509 BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, 510 BlockFilter); 511 if (!BestSucc) 512 break; 513 514 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 515 "layout successor until the CFG reduces\n"); 516 } 517 518 // Place this block, updating the datastructures to reflect its placement. 519 BlockChain &SuccChain = *BlockToChain[BestSucc]; 520 // Zero out LoopPredecessors for the successor we're about to merge in case 521 // we selected a successor that didn't fit naturally into the CFG. 522 SuccChain.LoopPredecessors = 0; 523 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) 524 << " to " << getBlockNum(BestSucc) << "\n"); 525 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter); 526 Chain.merge(BestSucc, &SuccChain); 527 BB = *llvm::prior(Chain.end()); 528 } 529 530 DEBUG(dbgs() << "Finished forming chain for header block " 531 << getBlockNum(*Chain.begin()) << "\n"); 532 } 533 534 /// \brief Find the best loop top block for layout. 535 /// 536 /// This routine implements the logic to analyze the loop looking for the best 537 /// block to layout at the top of the loop. Typically this is done to maximize 538 /// fallthrough opportunities. 539 MachineBasicBlock * 540 MachineBlockPlacement::findBestLoopTop(MachineFunction &F, 541 MachineLoop &L, 542 const BlockFilterSet &LoopBlockSet) { 543 BlockFrequency BestExitEdgeFreq; 544 MachineBasicBlock *ExitingBB = 0; 545 MachineBasicBlock *LoopingBB = 0; 546 // If there are exits to outer loops, loop rotation can severely limit 547 // fallthrough opportunites unless it selects such an exit. Keep a set of 548 // blocks where rotating to exit with that block will reach an outer loop. 549 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 550 551 DEBUG(dbgs() << "Finding best loop exit for: " 552 << getBlockName(L.getHeader()) << "\n"); 553 for (MachineLoop::block_iterator I = L.block_begin(), 554 E = L.block_end(); 555 I != E; ++I) { 556 BlockChain &Chain = *BlockToChain[*I]; 557 // Ensure that this block is at the end of a chain; otherwise it could be 558 // mid-way through an inner loop or a successor of an analyzable branch. 559 if (*I != *llvm::prior(Chain.end())) 560 continue; 561 562 // Now walk the successors. We need to establish whether this has a viable 563 // exiting successor and whether it has a viable non-exiting successor. 564 // We store the old exiting state and restore it if a viable looping 565 // successor isn't found. 566 MachineBasicBlock *OldExitingBB = ExitingBB; 567 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 568 // We also compute and store the best looping successor for use in layout. 569 MachineBasicBlock *BestLoopSucc = 0; 570 // FIXME: Due to the performance of the probability and weight routines in 571 // the MBPI analysis, we use the internal weights. This is only valid 572 // because it is purely a ranking function, we don't care about anything 573 // but the relative values. 574 uint32_t BestLoopSuccWeight = 0; 575 // FIXME: We also manually compute the probabilities to avoid quadratic 576 // behavior. 577 uint32_t WeightScale = 0; 578 uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale); 579 for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(), 580 SE = (*I)->succ_end(); 581 SI != SE; ++SI) { 582 if ((*SI)->isLandingPad()) 583 continue; 584 if (*SI == *I) 585 continue; 586 BlockChain &SuccChain = *BlockToChain[*SI]; 587 // Don't split chains, either this chain or the successor's chain. 588 if (&Chain == &SuccChain || *SI != *SuccChain.begin()) { 589 DEBUG(dbgs() << " " << (LoopBlockSet.count(*SI) ? "looping: " 590 : "exiting: ") 591 << getBlockName(*I) << " -> " 592 << getBlockName(*SI) << " (chain conflict)\n"); 593 continue; 594 } 595 596 uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI); 597 if (LoopBlockSet.count(*SI)) { 598 DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> " 599 << getBlockName(*SI) << " (" << SuccWeight << ")\n"); 600 if (BestLoopSucc && BestLoopSuccWeight >= SuccWeight) 601 continue; 602 603 BestLoopSucc = *SI; 604 BestLoopSuccWeight = SuccWeight; 605 continue; 606 } 607 608 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight); 609 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb; 610 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> " 611 << getBlockName(*SI) << " (" << ExitEdgeFreq << ")\n"); 612 // Note that we slightly bias this toward an existing layout successor to 613 // retain incoming order in the absence of better information. 614 // FIXME: Should we bias this more strongly? It's pretty weak. 615 if (!ExitingBB || ExitEdgeFreq > BestExitEdgeFreq || 616 ((*I)->isLayoutSuccessor(*SI) && 617 !(ExitEdgeFreq < BestExitEdgeFreq))) { 618 BestExitEdgeFreq = ExitEdgeFreq; 619 ExitingBB = *I; 620 } 621 622 if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) 623 if (ExitLoop->contains(&L)) 624 BlocksExitingToOuterLoop.insert(*I); 625 } 626 627 // Restore the old exiting state, no viable looping successor was found. 628 if (!BestLoopSucc) { 629 ExitingBB = OldExitingBB; 630 BestExitEdgeFreq = OldBestExitEdgeFreq; 631 continue; 632 } 633 634 // If this was best exiting block thus far, also record the looping block. 635 if (ExitingBB == *I) 636 LoopingBB = BestLoopSucc; 637 } 638 // Without a candidate exitting block or with only a single block in the 639 // loop, just use the loop header to layout the loop. 640 if (!ExitingBB || L.getNumBlocks() == 1) 641 return L.getHeader(); 642 643 // Also, if we have exit blocks which lead to outer loops but didn't select 644 // one of them as the exiting block we are rotating toward, disable loop 645 // rotation altogether. 646 if (!BlocksExitingToOuterLoop.empty() && 647 !BlocksExitingToOuterLoop.count(ExitingBB)) 648 return L.getHeader(); 649 650 assert(LoopingBB && "All successors of a loop block are exit blocks!"); 651 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n"); 652 DEBUG(dbgs() << " Best top block: " << getBlockName(LoopingBB) << "\n"); 653 return LoopingBB; 654 } 655 656 /// \brief Forms basic block chains from the natural loop structures. 657 /// 658 /// These chains are designed to preserve the existing *structure* of the code 659 /// as much as possible. We can then stitch the chains together in a way which 660 /// both preserves the topological structure and minimizes taken conditional 661 /// branches. 662 void MachineBlockPlacement::buildLoopChains(MachineFunction &F, 663 MachineLoop &L) { 664 // First recurse through any nested loops, building chains for those inner 665 // loops. 666 for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI) 667 buildLoopChains(F, **LI); 668 669 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 670 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end()); 671 672 MachineBasicBlock *LayoutTop = findBestLoopTop(F, L, LoopBlockSet); 673 BlockChain &LoopChain = *BlockToChain[LayoutTop]; 674 675 // FIXME: This is a really lame way of walking the chains in the loop: we 676 // walk the blocks, and use a set to prevent visiting a particular chain 677 // twice. 678 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 679 assert(LoopChain.LoopPredecessors == 0); 680 UpdatedPreds.insert(&LoopChain); 681 for (MachineLoop::block_iterator BI = L.block_begin(), 682 BE = L.block_end(); 683 BI != BE; ++BI) { 684 BlockChain &Chain = *BlockToChain[*BI]; 685 if (!UpdatedPreds.insert(&Chain)) 686 continue; 687 688 assert(Chain.LoopPredecessors == 0); 689 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end(); 690 BCI != BCE; ++BCI) { 691 assert(BlockToChain[*BCI] == &Chain); 692 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(), 693 PE = (*BCI)->pred_end(); 694 PI != PE; ++PI) { 695 if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI)) 696 continue; 697 ++Chain.LoopPredecessors; 698 } 699 } 700 701 if (Chain.LoopPredecessors == 0) 702 BlockWorkList.push_back(*Chain.begin()); 703 } 704 705 buildChain(LayoutTop, LoopChain, BlockWorkList, &LoopBlockSet); 706 707 DEBUG({ 708 // Crash at the end so we get all of the debugging output first. 709 bool BadLoop = false; 710 if (LoopChain.LoopPredecessors) { 711 BadLoop = true; 712 dbgs() << "Loop chain contains a block without its preds placed!\n" 713 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 714 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 715 } 716 for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end(); 717 BCI != BCE; ++BCI) 718 if (!LoopBlockSet.erase(*BCI)) { 719 // We don't mark the loop as bad here because there are real situations 720 // where this can occur. For example, with an unanalyzable fallthrough 721 // from a loop block to a non-loop block or vice versa. 722 dbgs() << "Loop chain contains a block not contained by the loop!\n" 723 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 724 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 725 << " Bad block: " << getBlockName(*BCI) << "\n"; 726 } 727 728 if (!LoopBlockSet.empty()) { 729 BadLoop = true; 730 for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(), 731 LBE = LoopBlockSet.end(); 732 LBI != LBE; ++LBI) 733 dbgs() << "Loop contains blocks never placed into a chain!\n" 734 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 735 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 736 << " Bad block: " << getBlockName(*LBI) << "\n"; 737 } 738 assert(!BadLoop && "Detected problems with the placement of this loop."); 739 }); 740 } 741 742 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) { 743 // Ensure that every BB in the function has an associated chain to simplify 744 // the assumptions of the remaining algorithm. 745 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 746 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { 747 MachineBasicBlock *BB = FI; 748 BlockChain *Chain 749 = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 750 // Also, merge any blocks which we cannot reason about and must preserve 751 // the exact fallthrough behavior for. 752 for (;;) { 753 Cond.clear(); 754 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch. 755 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 756 break; 757 758 MachineFunction::iterator NextFI(llvm::next(FI)); 759 MachineBasicBlock *NextBB = NextFI; 760 // Ensure that the layout successor is a viable block, as we know that 761 // fallthrough is a possibility. 762 assert(NextFI != FE && "Can't fallthrough past the last block."); 763 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 764 << getBlockName(BB) << " -> " << getBlockName(NextBB) 765 << "\n"); 766 Chain->merge(NextBB, 0); 767 FI = NextFI; 768 BB = NextBB; 769 } 770 } 771 772 // Build any loop-based chains. 773 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE; 774 ++LI) 775 buildLoopChains(F, **LI); 776 777 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 778 779 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 780 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { 781 MachineBasicBlock *BB = &*FI; 782 BlockChain &Chain = *BlockToChain[BB]; 783 if (!UpdatedPreds.insert(&Chain)) 784 continue; 785 786 assert(Chain.LoopPredecessors == 0); 787 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end(); 788 BCI != BCE; ++BCI) { 789 assert(BlockToChain[*BCI] == &Chain); 790 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(), 791 PE = (*BCI)->pred_end(); 792 PI != PE; ++PI) { 793 if (BlockToChain[*PI] == &Chain) 794 continue; 795 ++Chain.LoopPredecessors; 796 } 797 } 798 799 if (Chain.LoopPredecessors == 0) 800 BlockWorkList.push_back(*Chain.begin()); 801 } 802 803 BlockChain &FunctionChain = *BlockToChain[&F.front()]; 804 buildChain(&F.front(), FunctionChain, BlockWorkList); 805 806 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType; 807 DEBUG({ 808 // Crash at the end so we get all of the debugging output first. 809 bool BadFunc = false; 810 FunctionBlockSetType FunctionBlockSet; 811 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) 812 FunctionBlockSet.insert(FI); 813 814 for (BlockChain::iterator BCI = FunctionChain.begin(), 815 BCE = FunctionChain.end(); 816 BCI != BCE; ++BCI) 817 if (!FunctionBlockSet.erase(*BCI)) { 818 BadFunc = true; 819 dbgs() << "Function chain contains a block not in the function!\n" 820 << " Bad block: " << getBlockName(*BCI) << "\n"; 821 } 822 823 if (!FunctionBlockSet.empty()) { 824 BadFunc = true; 825 for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(), 826 FBE = FunctionBlockSet.end(); 827 FBI != FBE; ++FBI) 828 dbgs() << "Function contains blocks never placed into a chain!\n" 829 << " Bad block: " << getBlockName(*FBI) << "\n"; 830 } 831 assert(!BadFunc && "Detected problems with the block placement."); 832 }); 833 834 // Splice the blocks into place. 835 MachineFunction::iterator InsertPos = F.begin(); 836 for (BlockChain::iterator BI = FunctionChain.begin(), 837 BE = FunctionChain.end(); 838 BI != BE; ++BI) { 839 DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain " 840 : " ... ") 841 << getBlockName(*BI) << "\n"); 842 if (InsertPos != MachineFunction::iterator(*BI)) 843 F.splice(InsertPos, *BI); 844 else 845 ++InsertPos; 846 847 // Update the terminator of the previous block. 848 if (BI == FunctionChain.begin()) 849 continue; 850 MachineBasicBlock *PrevBB = llvm::prior(MachineFunction::iterator(*BI)); 851 852 // FIXME: It would be awesome of updateTerminator would just return rather 853 // than assert when the branch cannot be analyzed in order to remove this 854 // boiler plate. 855 Cond.clear(); 856 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch. 857 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) 858 PrevBB->updateTerminator(); 859 } 860 861 // Fixup the last block. 862 Cond.clear(); 863 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch. 864 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond)) 865 F.back().updateTerminator(); 866 } 867 868 /// \brief Recursive helper to align a loop and any nested loops. 869 static void AlignLoop(MachineFunction &F, MachineLoop *L, unsigned Align) { 870 // Recurse through nested loops. 871 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) 872 AlignLoop(F, *I, Align); 873 874 L->getTopBlock()->setAlignment(Align); 875 } 876 877 /// \brief Align loop headers to target preferred alignments. 878 void MachineBlockPlacement::AlignLoops(MachineFunction &F) { 879 if (F.getFunction()->hasFnAttr(Attribute::OptimizeForSize)) 880 return; 881 882 unsigned Align = TLI->getPrefLoopAlignment(); 883 if (!Align) 884 return; // Don't care about loop alignment. 885 886 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I) 887 AlignLoop(F, *I, Align); 888 } 889 890 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) { 891 // Check for single-block functions and skip them. 892 if (llvm::next(F.begin()) == F.end()) 893 return false; 894 895 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 896 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 897 MLI = &getAnalysis<MachineLoopInfo>(); 898 TII = F.getTarget().getInstrInfo(); 899 TLI = F.getTarget().getTargetLowering(); 900 assert(BlockToChain.empty()); 901 902 buildCFGChains(F); 903 AlignLoops(F); 904 905 BlockToChain.clear(); 906 ChainAllocator.DestroyAll(); 907 908 // We always return true as we have no way to track whether the final order 909 // differs from the original order. 910 return true; 911 } 912 913 namespace { 914 /// \brief A pass to compute block placement statistics. 915 /// 916 /// A separate pass to compute interesting statistics for evaluating block 917 /// placement. This is separate from the actual placement pass so that they can 918 /// be computed in the absense of any placement transformations or when using 919 /// alternative placement strategies. 920 class MachineBlockPlacementStats : public MachineFunctionPass { 921 /// \brief A handle to the branch probability pass. 922 const MachineBranchProbabilityInfo *MBPI; 923 924 /// \brief A handle to the function-wide block frequency pass. 925 const MachineBlockFrequencyInfo *MBFI; 926 927 public: 928 static char ID; // Pass identification, replacement for typeid 929 MachineBlockPlacementStats() : MachineFunctionPass(ID) { 930 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 931 } 932 933 bool runOnMachineFunction(MachineFunction &F); 934 935 void getAnalysisUsage(AnalysisUsage &AU) const { 936 AU.addRequired<MachineBranchProbabilityInfo>(); 937 AU.addRequired<MachineBlockFrequencyInfo>(); 938 AU.setPreservesAll(); 939 MachineFunctionPass::getAnalysisUsage(AU); 940 } 941 }; 942 } 943 944 char MachineBlockPlacementStats::ID = 0; 945 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 946 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 947 "Basic Block Placement Stats", false, false) 948 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 949 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 950 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 951 "Basic Block Placement Stats", false, false) 952 953 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 954 // Check for single-block functions and skip them. 955 if (llvm::next(F.begin()) == F.end()) 956 return false; 957 958 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 959 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 960 961 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { 962 BlockFrequency BlockFreq = MBFI->getBlockFreq(I); 963 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches 964 : NumUncondBranches; 965 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq 966 : UncondBranchTakenFreq; 967 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(), 968 SE = I->succ_end(); 969 SI != SE; ++SI) { 970 // Skip if this successor is a fallthrough. 971 if (I->isLayoutSuccessor(*SI)) 972 continue; 973 974 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI); 975 ++NumBranches; 976 BranchTakenFreq += EdgeFreq.getFrequency(); 977 } 978 } 979 980 return false; 981 } 982 983