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 absence 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 #include "llvm/CodeGen/Passes.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallVector.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/CodeGen/MachineBasicBlock.h" 34 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 35 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 36 #include "llvm/CodeGen/MachineDominators.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineFunctionPass.h" 39 #include "llvm/CodeGen/MachineLoopInfo.h" 40 #include "llvm/CodeGen/MachineModuleInfo.h" 41 #include "llvm/Support/Allocator.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Target/TargetInstrInfo.h" 45 #include "llvm/Target/TargetLowering.h" 46 #include "llvm/Target/TargetSubtargetInfo.h" 47 #include <algorithm> 48 using namespace llvm; 49 50 #define DEBUG_TYPE "block-placement2" 51 52 STATISTIC(NumCondBranches, "Number of conditional branches"); 53 STATISTIC(NumUncondBranches, "Number of uncondittional branches"); 54 STATISTIC(CondBranchTakenFreq, 55 "Potential frequency of taking conditional branches"); 56 STATISTIC(UncondBranchTakenFreq, 57 "Potential frequency of taking unconditional branches"); 58 59 static cl::opt<unsigned> AlignAllBlock("align-all-blocks", 60 cl::desc("Force the alignment of all " 61 "blocks in the function."), 62 cl::init(0), cl::Hidden); 63 64 // FIXME: Find a good default for this flag and remove the flag. 65 static cl::opt<unsigned> 66 ExitBlockBias("block-placement-exit-block-bias", 67 cl::desc("Block frequency percentage a loop exit block needs " 68 "over the original exit to be considered the new exit."), 69 cl::init(0), cl::Hidden); 70 71 static cl::opt<bool> PlaceLastSuccessor( 72 "place-last-successor", 73 cl::desc("When selecting a non-successor block, choose the last block to " 74 "have been a successor. This represents the block whose " 75 "predecessor was most recently placed."), 76 cl::init(false), cl::Hidden); 77 78 static cl::opt<bool> OutlineOptionalBranches( 79 "outline-optional-branches", 80 cl::desc("Put completely optional branches, i.e. branches with a common " 81 "post dominator, out of line."), 82 cl::init(false), cl::Hidden); 83 84 namespace { 85 class BlockChain; 86 /// \brief Type for our function-wide basic block -> block chain mapping. 87 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType; 88 } 89 90 namespace { 91 /// \brief A chain of blocks which will be laid out contiguously. 92 /// 93 /// This is the datastructure representing a chain of consecutive blocks that 94 /// are profitable to layout together in order to maximize fallthrough 95 /// probabilities and code locality. We also can use a block chain to represent 96 /// a sequence of basic blocks which have some external (correctness) 97 /// requirement for sequential layout. 98 /// 99 /// Chains can be built around a single basic block and can be merged to grow 100 /// them. They participate in a block-to-chain mapping, which is updated 101 /// automatically as chains are merged together. 102 class BlockChain { 103 /// \brief The sequence of blocks belonging to this chain. 104 /// 105 /// This is the sequence of blocks for a particular chain. These will be laid 106 /// out in-order within the function. 107 SmallVector<MachineBasicBlock *, 4> Blocks; 108 109 /// \brief A handle to the function-wide basic block to block chain mapping. 110 /// 111 /// This is retained in each block chain to simplify the computation of child 112 /// block chains for SCC-formation and iteration. We store the edges to child 113 /// basic blocks, and map them back to their associated chains using this 114 /// structure. 115 BlockToChainMapType &BlockToChain; 116 117 public: 118 /// \brief Construct a new BlockChain. 119 /// 120 /// This builds a new block chain representing a single basic block in the 121 /// function. It also registers itself as the chain that block participates 122 /// in with the BlockToChain mapping. 123 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 124 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) { 125 assert(BB && "Cannot create a chain with a null basic block"); 126 BlockToChain[BB] = this; 127 } 128 129 /// \brief Iterator over blocks within the chain. 130 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator; 131 132 /// \brief Beginning of blocks within the chain. 133 iterator begin() { return Blocks.begin(); } 134 135 /// \brief End of blocks within the chain. 136 iterator end() { return Blocks.end(); } 137 138 /// \brief Merge a block chain into this one. 139 /// 140 /// This routine merges a block chain into this one. It takes care of forming 141 /// a contiguous sequence of basic blocks, updating the edge list, and 142 /// updating the block -> chain mapping. It does not free or tear down the 143 /// old chain, but the old chain's block list is no longer valid. 144 void merge(MachineBasicBlock *BB, BlockChain *Chain) { 145 assert(BB); 146 assert(!Blocks.empty()); 147 148 // Fast path in case we don't have a chain already. 149 if (!Chain) { 150 assert(!BlockToChain[BB]); 151 Blocks.push_back(BB); 152 BlockToChain[BB] = this; 153 return; 154 } 155 156 assert(BB == *Chain->begin()); 157 assert(Chain->begin() != Chain->end()); 158 159 // Update the incoming blocks to point to this chain, and add them to the 160 // chain structure. 161 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end(); 162 BI != BE; ++BI) { 163 Blocks.push_back(*BI); 164 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain"); 165 BlockToChain[*BI] = this; 166 } 167 } 168 169 #ifndef NDEBUG 170 /// \brief Dump the blocks in this chain. 171 LLVM_DUMP_METHOD void dump() { 172 for (iterator I = begin(), E = end(); I != E; ++I) 173 (*I)->dump(); 174 } 175 #endif // NDEBUG 176 177 /// \brief Count of predecessors within the loop currently being processed. 178 /// 179 /// This count is updated at each loop we process to represent the number of 180 /// in-loop predecessors of this chain. 181 unsigned LoopPredecessors; 182 }; 183 } 184 185 namespace { 186 class MachineBlockPlacement : public MachineFunctionPass { 187 /// \brief A typedef for a block filter set. 188 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet; 189 190 /// \brief A handle to the branch probability pass. 191 const MachineBranchProbabilityInfo *MBPI; 192 193 /// \brief A handle to the function-wide block frequency pass. 194 const MachineBlockFrequencyInfo *MBFI; 195 196 /// \brief A handle to the loop info. 197 const MachineLoopInfo *MLI; 198 199 /// \brief A handle to the target's instruction info. 200 const TargetInstrInfo *TII; 201 202 /// \brief A handle to the target's lowering info. 203 const TargetLoweringBase *TLI; 204 205 /// \brief A handle to the post dominator tree. 206 MachineDominatorTree *MDT; 207 208 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate 209 /// all terminators of the MachineFunction. 210 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks; 211 212 /// \brief Allocator and owner of BlockChain structures. 213 /// 214 /// We build BlockChains lazily while processing the loop structure of 215 /// a function. To reduce malloc traffic, we allocate them using this 216 /// slab-like allocator, and destroy them after the pass completes. An 217 /// important guarantee is that this allocator produces stable pointers to 218 /// the chains. 219 SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 220 221 /// \brief Function wide BasicBlock to BlockChain mapping. 222 /// 223 /// This mapping allows efficiently moving from any given basic block to the 224 /// BlockChain it participates in, if any. We use it to, among other things, 225 /// allow implicitly defining edges between chains as the existing edges 226 /// between basic blocks. 227 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain; 228 229 void markChainSuccessors(BlockChain &Chain, 230 MachineBasicBlock *LoopHeaderBB, 231 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 232 const BlockFilterSet *BlockFilter = nullptr); 233 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB, 234 BlockChain &Chain, 235 const BlockFilterSet *BlockFilter); 236 MachineBasicBlock *selectBestCandidateBlock( 237 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList, 238 const BlockFilterSet *BlockFilter); 239 MachineBasicBlock *getFirstUnplacedBlock( 240 MachineFunction &F, 241 const BlockChain &PlacedChain, 242 MachineFunction::iterator &PrevUnplacedBlockIt, 243 const BlockFilterSet *BlockFilter); 244 void buildChain(MachineBasicBlock *BB, BlockChain &Chain, 245 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 246 const BlockFilterSet *BlockFilter = nullptr); 247 MachineBasicBlock *findBestLoopTop(MachineLoop &L, 248 const BlockFilterSet &LoopBlockSet); 249 MachineBasicBlock *findBestLoopExit(MachineFunction &F, 250 MachineLoop &L, 251 const BlockFilterSet &LoopBlockSet); 252 void buildLoopChains(MachineFunction &F, MachineLoop &L); 253 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB, 254 const BlockFilterSet &LoopBlockSet); 255 void buildCFGChains(MachineFunction &F); 256 257 public: 258 static char ID; // Pass identification, replacement for typeid 259 MachineBlockPlacement() : MachineFunctionPass(ID) { 260 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 261 } 262 263 bool runOnMachineFunction(MachineFunction &F) override; 264 265 void getAnalysisUsage(AnalysisUsage &AU) const override { 266 AU.addRequired<MachineBranchProbabilityInfo>(); 267 AU.addRequired<MachineBlockFrequencyInfo>(); 268 AU.addRequired<MachineDominatorTree>(); 269 AU.addRequired<MachineLoopInfo>(); 270 MachineFunctionPass::getAnalysisUsage(AU); 271 } 272 }; 273 } 274 275 char MachineBlockPlacement::ID = 0; 276 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 277 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2", 278 "Branch Probability Basic Block Placement", false, false) 279 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 280 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 281 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 282 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 283 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2", 284 "Branch Probability Basic Block Placement", false, false) 285 286 #ifndef NDEBUG 287 /// \brief Helper to print the name of a MBB. 288 /// 289 /// Only used by debug logging. 290 static std::string getBlockName(MachineBasicBlock *BB) { 291 std::string Result; 292 raw_string_ostream OS(Result); 293 OS << "BB#" << BB->getNumber() 294 << " (derived from LLVM BB '" << BB->getName() << "')"; 295 OS.flush(); 296 return Result; 297 } 298 299 /// \brief Helper to print the number of a MBB. 300 /// 301 /// Only used by debug logging. 302 static std::string getBlockNum(MachineBasicBlock *BB) { 303 std::string Result; 304 raw_string_ostream OS(Result); 305 OS << "BB#" << BB->getNumber(); 306 OS.flush(); 307 return Result; 308 } 309 #endif 310 311 /// \brief Mark a chain's successors as having one fewer preds. 312 /// 313 /// When a chain is being merged into the "placed" chain, this routine will 314 /// quickly walk the successors of each block in the chain and mark them as 315 /// having one fewer active predecessor. It also adds any successors of this 316 /// chain which reach the zero-predecessor state to the worklist passed in. 317 void MachineBlockPlacement::markChainSuccessors( 318 BlockChain &Chain, 319 MachineBasicBlock *LoopHeaderBB, 320 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 321 const BlockFilterSet *BlockFilter) { 322 // Walk all the blocks in this chain, marking their successors as having 323 // a predecessor placed. 324 for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end(); 325 CBI != CBE; ++CBI) { 326 // Add any successors for which this is the only un-placed in-loop 327 // predecessor to the worklist as a viable candidate for CFG-neutral 328 // placement. No subsequent placement of this block will violate the CFG 329 // shape, so we get to use heuristics to choose a favorable placement. 330 for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(), 331 SE = (*CBI)->succ_end(); 332 SI != SE; ++SI) { 333 if (BlockFilter && !BlockFilter->count(*SI)) 334 continue; 335 BlockChain &SuccChain = *BlockToChain[*SI]; 336 // Disregard edges within a fixed chain, or edges to the loop header. 337 if (&Chain == &SuccChain || *SI == LoopHeaderBB) 338 continue; 339 340 // This is a cross-chain edge that is within the loop, so decrement the 341 // loop predecessor count of the destination chain. 342 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0) 343 BlockWorkList.push_back(*SuccChain.begin()); 344 } 345 } 346 } 347 348 /// \brief Select the best successor for a block. 349 /// 350 /// This looks across all successors of a particular block and attempts to 351 /// select the "best" one to be the layout successor. It only considers direct 352 /// successors which also pass the block filter. It will attempt to avoid 353 /// breaking CFG structure, but cave and break such structures in the case of 354 /// very hot successor edges. 355 /// 356 /// \returns The best successor block found, or null if none are viable. 357 MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor( 358 MachineBasicBlock *BB, BlockChain &Chain, 359 const BlockFilterSet *BlockFilter) { 360 const BranchProbability HotProb(4, 5); // 80% 361 362 MachineBasicBlock *BestSucc = nullptr; 363 // FIXME: Due to the performance of the probability and weight routines in 364 // the MBPI analysis, we manually compute probabilities using the edge 365 // weights. This is suboptimal as it means that the somewhat subtle 366 // definition of edge weight semantics is encoded here as well. We should 367 // improve the MBPI interface to efficiently support query patterns such as 368 // this. 369 uint32_t BestWeight = 0; 370 uint32_t WeightScale = 0; 371 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale); 372 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n"); 373 for (MachineBasicBlock *Succ : BB->successors()) { 374 if (BlockFilter && !BlockFilter->count(Succ)) 375 continue; 376 BlockChain &SuccChain = *BlockToChain[Succ]; 377 if (&SuccChain == &Chain) { 378 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Already merged!\n"); 379 continue; 380 } 381 if (Succ != *SuccChain.begin()) { 382 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n"); 383 continue; 384 } 385 386 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ); 387 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight); 388 389 // If we outline optional branches, look whether Succ is unavoidable, i.e. 390 // dominates all terminators of the MachineFunction. If it does, other 391 // successors must be optional. Don't do this for cold branches. 392 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() && 393 UnavoidableBlocks.count(Succ) > 0) 394 return Succ; 395 396 // Only consider successors which are either "hot", or wouldn't violate 397 // any CFG constraints. 398 if (SuccChain.LoopPredecessors != 0) { 399 if (SuccProb < HotProb) { 400 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb 401 << " (prob) (CFG conflict)\n"); 402 continue; 403 } 404 405 // Make sure that a hot successor doesn't have a globally more 406 // important predecessor. 407 BlockFrequency CandidateEdgeFreq = 408 MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl(); 409 bool BadCFGConflict = false; 410 for (MachineBasicBlock *Pred : Succ->predecessors()) { 411 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) || 412 BlockToChain[Pred] == &Chain) 413 continue; 414 BlockFrequency PredEdgeFreq = 415 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 416 if (PredEdgeFreq >= CandidateEdgeFreq) { 417 BadCFGConflict = true; 418 break; 419 } 420 } 421 if (BadCFGConflict) { 422 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb 423 << " (prob) (non-cold CFG conflict)\n"); 424 continue; 425 } 426 } 427 428 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb 429 << " (prob)" 430 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "") 431 << "\n"); 432 if (BestSucc && BestWeight >= SuccWeight) 433 continue; 434 BestSucc = Succ; 435 BestWeight = SuccWeight; 436 } 437 return BestSucc; 438 } 439 440 /// \brief Select the best block from a worklist. 441 /// 442 /// This looks through the provided worklist as a list of candidate basic 443 /// blocks and select the most profitable one to place. The definition of 444 /// profitable only really makes sense in the context of a loop. This returns 445 /// the most frequently visited block in the worklist, which in the case of 446 /// a loop, is the one most desirable to be physically close to the rest of the 447 /// loop body in order to improve icache behavior. 448 /// 449 /// \returns The best block found, or null if none are viable. 450 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 451 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList, 452 const BlockFilterSet *BlockFilter) { 453 if (PlaceLastSuccessor) { 454 // If we're just placing the last successor as the best candidate, the 455 // logic is super simple. We skip the already placed entries on the 456 // worklist and return the most recently added entry that isn't placed. 457 while (!WorkList.empty()) { 458 MachineBasicBlock *SuccBB = WorkList.pop_back_val(); 459 BlockChain &SuccChain = *BlockToChain.lookup(SuccBB); 460 if (&SuccChain == &Chain) { 461 DEBUG(dbgs() << " " << getBlockName(SuccBB) 462 << " -> Already merged!\n"); 463 continue; 464 } 465 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block"); 466 return SuccBB; 467 } 468 469 return nullptr; 470 } 471 472 // Once we need to walk the worklist looking for a candidate, cleanup the 473 // worklist of already placed entries. 474 // FIXME: If this shows up on profiles, it could be folded (at the cost of 475 // some code complexity) into the loop below. 476 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(), 477 [&](MachineBasicBlock *BB) { 478 return BlockToChain.lookup(BB) == &Chain; 479 }), 480 WorkList.end()); 481 482 MachineBasicBlock *BestBlock = nullptr; 483 BlockFrequency BestFreq; 484 for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(), 485 WBE = WorkList.end(); 486 WBI != WBE; ++WBI) { 487 BlockChain &SuccChain = *BlockToChain[*WBI]; 488 if (&SuccChain == &Chain) { 489 DEBUG(dbgs() << " " << getBlockName(*WBI) 490 << " -> Already merged!\n"); 491 continue; 492 } 493 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block"); 494 495 BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI); 496 DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> "; 497 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 498 if (BestBlock && BestFreq >= CandidateFreq) 499 continue; 500 BestBlock = *WBI; 501 BestFreq = CandidateFreq; 502 } 503 return BestBlock; 504 } 505 506 /// \brief Retrieve the first unplaced basic block. 507 /// 508 /// This routine is called when we are unable to use the CFG to walk through 509 /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 510 /// We walk through the function's blocks in order, starting from the 511 /// LastUnplacedBlockIt. We update this iterator on each call to avoid 512 /// re-scanning the entire sequence on repeated calls to this routine. 513 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 514 MachineFunction &F, const BlockChain &PlacedChain, 515 MachineFunction::iterator &PrevUnplacedBlockIt, 516 const BlockFilterSet *BlockFilter) { 517 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E; 518 ++I) { 519 if (BlockFilter && !BlockFilter->count(I)) 520 continue; 521 if (BlockToChain[I] != &PlacedChain) { 522 PrevUnplacedBlockIt = I; 523 // Now select the head of the chain to which the unplaced block belongs 524 // as the block to place. This will force the entire chain to be placed, 525 // and satisfies the requirements of merging chains. 526 return *BlockToChain[I]->begin(); 527 } 528 } 529 return nullptr; 530 } 531 532 void MachineBlockPlacement::buildChain( 533 MachineBasicBlock *BB, BlockChain &Chain, 534 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList, 535 const BlockFilterSet *BlockFilter) { 536 assert(BB); 537 assert(BlockToChain[BB] == &Chain); 538 MachineFunction &F = *BB->getParent(); 539 MachineFunction::iterator PrevUnplacedBlockIt = F.begin(); 540 541 MachineBasicBlock *LoopHeaderBB = BB; 542 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter); 543 BB = *std::prev(Chain.end()); 544 for (;;) { 545 assert(BB); 546 assert(BlockToChain[BB] == &Chain); 547 assert(*std::prev(Chain.end()) == BB); 548 549 // Look for the best viable successor if there is one to place immediately 550 // after this block. 551 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter); 552 553 // If an immediate successor isn't available, look for the best viable 554 // block among those we've identified as not violating the loop's CFG at 555 // this point. This won't be a fallthrough, but it will increase locality. 556 if (!BestSucc) 557 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter); 558 559 if (!BestSucc) { 560 BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, 561 BlockFilter); 562 if (!BestSucc) 563 break; 564 565 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 566 "layout successor until the CFG reduces\n"); 567 } 568 569 // Place this block, updating the datastructures to reflect its placement. 570 BlockChain &SuccChain = *BlockToChain[BestSucc]; 571 // Zero out LoopPredecessors for the successor we're about to merge in case 572 // we selected a successor that didn't fit naturally into the CFG. 573 SuccChain.LoopPredecessors = 0; 574 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) 575 << " to " << getBlockNum(BestSucc) << "\n"); 576 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter); 577 Chain.merge(BestSucc, &SuccChain); 578 BB = *std::prev(Chain.end()); 579 } 580 581 DEBUG(dbgs() << "Finished forming chain for header block " 582 << getBlockNum(*Chain.begin()) << "\n"); 583 } 584 585 /// \brief Find the best loop top block for layout. 586 /// 587 /// Look for a block which is strictly better than the loop header for laying 588 /// out at the top of the loop. This looks for one and only one pattern: 589 /// a latch block with no conditional exit. This block will cause a conditional 590 /// jump around it or will be the bottom of the loop if we lay it out in place, 591 /// but if it it doesn't end up at the bottom of the loop for any reason, 592 /// rotation alone won't fix it. Because such a block will always result in an 593 /// unconditional jump (for the backedge) rotating it in front of the loop 594 /// header is always profitable. 595 MachineBasicBlock * 596 MachineBlockPlacement::findBestLoopTop(MachineLoop &L, 597 const BlockFilterSet &LoopBlockSet) { 598 // Check that the header hasn't been fused with a preheader block due to 599 // crazy branches. If it has, we need to start with the header at the top to 600 // prevent pulling the preheader into the loop body. 601 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 602 if (!LoopBlockSet.count(*HeaderChain.begin())) 603 return L.getHeader(); 604 605 DEBUG(dbgs() << "Finding best loop top for: " 606 << getBlockName(L.getHeader()) << "\n"); 607 608 BlockFrequency BestPredFreq; 609 MachineBasicBlock *BestPred = nullptr; 610 for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(), 611 PE = L.getHeader()->pred_end(); 612 PI != PE; ++PI) { 613 MachineBasicBlock *Pred = *PI; 614 if (!LoopBlockSet.count(Pred)) 615 continue; 616 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", " 617 << Pred->succ_size() << " successors, "; 618 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 619 if (Pred->succ_size() > 1) 620 continue; 621 622 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred); 623 if (!BestPred || PredFreq > BestPredFreq || 624 (!(PredFreq < BestPredFreq) && 625 Pred->isLayoutSuccessor(L.getHeader()))) { 626 BestPred = Pred; 627 BestPredFreq = PredFreq; 628 } 629 } 630 631 // If no direct predecessor is fine, just use the loop header. 632 if (!BestPred) 633 return L.getHeader(); 634 635 // Walk backwards through any straight line of predecessors. 636 while (BestPred->pred_size() == 1 && 637 (*BestPred->pred_begin())->succ_size() == 1 && 638 *BestPred->pred_begin() != L.getHeader()) 639 BestPred = *BestPred->pred_begin(); 640 641 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 642 return BestPred; 643 } 644 645 646 /// \brief Find the best loop exiting block for layout. 647 /// 648 /// This routine implements the logic to analyze the loop looking for the best 649 /// block to layout at the top of the loop. Typically this is done to maximize 650 /// fallthrough opportunities. 651 MachineBasicBlock * 652 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, 653 MachineLoop &L, 654 const BlockFilterSet &LoopBlockSet) { 655 // We don't want to layout the loop linearly in all cases. If the loop header 656 // is just a normal basic block in the loop, we want to look for what block 657 // within the loop is the best one to layout at the top. However, if the loop 658 // header has be pre-merged into a chain due to predecessors not having 659 // analyzable branches, *and* the predecessor it is merged with is *not* part 660 // of the loop, rotating the header into the middle of the loop will create 661 // a non-contiguous range of blocks which is Very Bad. So start with the 662 // header and only rotate if safe. 663 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 664 if (!LoopBlockSet.count(*HeaderChain.begin())) 665 return nullptr; 666 667 BlockFrequency BestExitEdgeFreq; 668 unsigned BestExitLoopDepth = 0; 669 MachineBasicBlock *ExitingBB = nullptr; 670 // If there are exits to outer loops, loop rotation can severely limit 671 // fallthrough opportunites unless it selects such an exit. Keep a set of 672 // blocks where rotating to exit with that block will reach an outer loop. 673 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 674 675 DEBUG(dbgs() << "Finding best loop exit for: " 676 << getBlockName(L.getHeader()) << "\n"); 677 for (MachineLoop::block_iterator I = L.block_begin(), 678 E = L.block_end(); 679 I != E; ++I) { 680 BlockChain &Chain = *BlockToChain[*I]; 681 // Ensure that this block is at the end of a chain; otherwise it could be 682 // mid-way through an inner loop or a successor of an analyzable branch. 683 if (*I != *std::prev(Chain.end())) 684 continue; 685 686 // Now walk the successors. We need to establish whether this has a viable 687 // exiting successor and whether it has a viable non-exiting successor. 688 // We store the old exiting state and restore it if a viable looping 689 // successor isn't found. 690 MachineBasicBlock *OldExitingBB = ExitingBB; 691 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 692 bool HasLoopingSucc = false; 693 // FIXME: Due to the performance of the probability and weight routines in 694 // the MBPI analysis, we use the internal weights and manually compute the 695 // probabilities to avoid quadratic behavior. 696 uint32_t WeightScale = 0; 697 uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale); 698 for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(), 699 SE = (*I)->succ_end(); 700 SI != SE; ++SI) { 701 if ((*SI)->isLandingPad()) 702 continue; 703 if (*SI == *I) 704 continue; 705 BlockChain &SuccChain = *BlockToChain[*SI]; 706 // Don't split chains, either this chain or the successor's chain. 707 if (&Chain == &SuccChain) { 708 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> " 709 << getBlockName(*SI) << " (chain conflict)\n"); 710 continue; 711 } 712 713 uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI); 714 if (LoopBlockSet.count(*SI)) { 715 DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> " 716 << getBlockName(*SI) << " (" << SuccWeight << ")\n"); 717 HasLoopingSucc = true; 718 continue; 719 } 720 721 unsigned SuccLoopDepth = 0; 722 if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) { 723 SuccLoopDepth = ExitLoop->getLoopDepth(); 724 if (ExitLoop->contains(&L)) 725 BlocksExitingToOuterLoop.insert(*I); 726 } 727 728 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight); 729 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb; 730 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> " 731 << getBlockName(*SI) << " [L:" << SuccLoopDepth 732 << "] ("; 733 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 734 // Note that we bias this toward an existing layout successor to retain 735 // incoming order in the absence of better information. The exit must have 736 // a frequency higher than the current exit before we consider breaking 737 // the layout. 738 BranchProbability Bias(100 - ExitBlockBias, 100); 739 if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth || 740 ExitEdgeFreq > BestExitEdgeFreq || 741 ((*I)->isLayoutSuccessor(*SI) && 742 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 743 BestExitEdgeFreq = ExitEdgeFreq; 744 ExitingBB = *I; 745 } 746 } 747 748 // Restore the old exiting state, no viable looping successor was found. 749 if (!HasLoopingSucc) { 750 ExitingBB = OldExitingBB; 751 BestExitEdgeFreq = OldBestExitEdgeFreq; 752 continue; 753 } 754 } 755 // Without a candidate exiting block or with only a single block in the 756 // loop, just use the loop header to layout the loop. 757 if (!ExitingBB || L.getNumBlocks() == 1) 758 return nullptr; 759 760 // Also, if we have exit blocks which lead to outer loops but didn't select 761 // one of them as the exiting block we are rotating toward, disable loop 762 // rotation altogether. 763 if (!BlocksExitingToOuterLoop.empty() && 764 !BlocksExitingToOuterLoop.count(ExitingBB)) 765 return nullptr; 766 767 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n"); 768 return ExitingBB; 769 } 770 771 /// \brief Attempt to rotate an exiting block to the bottom of the loop. 772 /// 773 /// Once we have built a chain, try to rotate it to line up the hot exit block 774 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 775 /// branches. For example, if the loop has fallthrough into its header and out 776 /// of its bottom already, don't rotate it. 777 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 778 MachineBasicBlock *ExitingBB, 779 const BlockFilterSet &LoopBlockSet) { 780 if (!ExitingBB) 781 return; 782 783 MachineBasicBlock *Top = *LoopChain.begin(); 784 bool ViableTopFallthrough = false; 785 for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(), 786 PE = Top->pred_end(); 787 PI != PE; ++PI) { 788 BlockChain *PredChain = BlockToChain[*PI]; 789 if (!LoopBlockSet.count(*PI) && 790 (!PredChain || *PI == *std::prev(PredChain->end()))) { 791 ViableTopFallthrough = true; 792 break; 793 } 794 } 795 796 // If the header has viable fallthrough, check whether the current loop 797 // bottom is a viable exiting block. If so, bail out as rotating will 798 // introduce an unnecessary branch. 799 if (ViableTopFallthrough) { 800 MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 801 for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(), 802 SE = Bottom->succ_end(); 803 SI != SE; ++SI) { 804 BlockChain *SuccChain = BlockToChain[*SI]; 805 if (!LoopBlockSet.count(*SI) && 806 (!SuccChain || *SI == *SuccChain->begin())) 807 return; 808 } 809 } 810 811 BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(), 812 ExitingBB); 813 if (ExitIt == LoopChain.end()) 814 return; 815 816 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 817 } 818 819 /// \brief Forms basic block chains from the natural loop structures. 820 /// 821 /// These chains are designed to preserve the existing *structure* of the code 822 /// as much as possible. We can then stitch the chains together in a way which 823 /// both preserves the topological structure and minimizes taken conditional 824 /// branches. 825 void MachineBlockPlacement::buildLoopChains(MachineFunction &F, 826 MachineLoop &L) { 827 // First recurse through any nested loops, building chains for those inner 828 // loops. 829 for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI) 830 buildLoopChains(F, **LI); 831 832 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 833 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end()); 834 835 // First check to see if there is an obviously preferable top block for the 836 // loop. This will default to the header, but may end up as one of the 837 // predecessors to the header if there is one which will result in strictly 838 // fewer branches in the loop body. 839 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet); 840 841 // If we selected just the header for the loop top, look for a potentially 842 // profitable exit block in the event that rotating the loop can eliminate 843 // branches by placing an exit edge at the bottom. 844 MachineBasicBlock *ExitingBB = nullptr; 845 if (LoopTop == L.getHeader()) 846 ExitingBB = findBestLoopExit(F, L, LoopBlockSet); 847 848 BlockChain &LoopChain = *BlockToChain[LoopTop]; 849 850 // FIXME: This is a really lame way of walking the chains in the loop: we 851 // walk the blocks, and use a set to prevent visiting a particular chain 852 // twice. 853 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 854 assert(LoopChain.LoopPredecessors == 0); 855 UpdatedPreds.insert(&LoopChain); 856 for (MachineLoop::block_iterator BI = L.block_begin(), 857 BE = L.block_end(); 858 BI != BE; ++BI) { 859 BlockChain &Chain = *BlockToChain[*BI]; 860 if (!UpdatedPreds.insert(&Chain).second) 861 continue; 862 863 assert(Chain.LoopPredecessors == 0); 864 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end(); 865 BCI != BCE; ++BCI) { 866 assert(BlockToChain[*BCI] == &Chain); 867 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(), 868 PE = (*BCI)->pred_end(); 869 PI != PE; ++PI) { 870 if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI)) 871 continue; 872 ++Chain.LoopPredecessors; 873 } 874 } 875 876 if (Chain.LoopPredecessors == 0) 877 BlockWorkList.push_back(*Chain.begin()); 878 } 879 880 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet); 881 rotateLoop(LoopChain, ExitingBB, LoopBlockSet); 882 883 DEBUG({ 884 // Crash at the end so we get all of the debugging output first. 885 bool BadLoop = false; 886 if (LoopChain.LoopPredecessors) { 887 BadLoop = true; 888 dbgs() << "Loop chain contains a block without its preds placed!\n" 889 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 890 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 891 } 892 for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end(); 893 BCI != BCE; ++BCI) { 894 dbgs() << " ... " << getBlockName(*BCI) << "\n"; 895 if (!LoopBlockSet.erase(*BCI)) { 896 // We don't mark the loop as bad here because there are real situations 897 // where this can occur. For example, with an unanalyzable fallthrough 898 // from a loop block to a non-loop block or vice versa. 899 dbgs() << "Loop chain contains a block not contained by the loop!\n" 900 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 901 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 902 << " Bad block: " << getBlockName(*BCI) << "\n"; 903 } 904 } 905 906 if (!LoopBlockSet.empty()) { 907 BadLoop = true; 908 for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(), 909 LBE = LoopBlockSet.end(); 910 LBI != LBE; ++LBI) 911 dbgs() << "Loop contains blocks never placed into a chain!\n" 912 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 913 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 914 << " Bad block: " << getBlockName(*LBI) << "\n"; 915 } 916 assert(!BadLoop && "Detected problems with the placement of this loop."); 917 }); 918 } 919 920 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) { 921 // Ensure that every BB in the function has an associated chain to simplify 922 // the assumptions of the remaining algorithm. 923 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 924 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { 925 MachineBasicBlock *BB = FI; 926 BlockChain *Chain 927 = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 928 // Also, merge any blocks which we cannot reason about and must preserve 929 // the exact fallthrough behavior for. 930 for (;;) { 931 Cond.clear(); 932 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 933 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 934 break; 935 936 MachineFunction::iterator NextFI(std::next(FI)); 937 MachineBasicBlock *NextBB = NextFI; 938 // Ensure that the layout successor is a viable block, as we know that 939 // fallthrough is a possibility. 940 assert(NextFI != FE && "Can't fallthrough past the last block."); 941 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 942 << getBlockName(BB) << " -> " << getBlockName(NextBB) 943 << "\n"); 944 Chain->merge(NextBB, nullptr); 945 FI = NextFI; 946 BB = NextBB; 947 } 948 } 949 950 if (OutlineOptionalBranches) { 951 // Find the nearest common dominator of all of F's terminators. 952 MachineBasicBlock *Terminator = nullptr; 953 for (MachineBasicBlock &MBB : F) { 954 if (MBB.succ_size() == 0) { 955 if (Terminator == nullptr) 956 Terminator = &MBB; 957 else 958 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB); 959 } 960 } 961 962 // MBBs dominating this common dominator are unavoidable. 963 UnavoidableBlocks.clear(); 964 for (MachineBasicBlock &MBB : F) { 965 if (MDT->dominates(&MBB, Terminator)) { 966 UnavoidableBlocks.insert(&MBB); 967 } 968 } 969 } 970 971 // Build any loop-based chains. 972 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE; 973 ++LI) 974 buildLoopChains(F, **LI); 975 976 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 977 978 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 979 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { 980 MachineBasicBlock *BB = &*FI; 981 BlockChain &Chain = *BlockToChain[BB]; 982 if (!UpdatedPreds.insert(&Chain).second) 983 continue; 984 985 assert(Chain.LoopPredecessors == 0); 986 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end(); 987 BCI != BCE; ++BCI) { 988 assert(BlockToChain[*BCI] == &Chain); 989 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(), 990 PE = (*BCI)->pred_end(); 991 PI != PE; ++PI) { 992 if (BlockToChain[*PI] == &Chain) 993 continue; 994 ++Chain.LoopPredecessors; 995 } 996 } 997 998 if (Chain.LoopPredecessors == 0) 999 BlockWorkList.push_back(*Chain.begin()); 1000 } 1001 1002 BlockChain &FunctionChain = *BlockToChain[&F.front()]; 1003 buildChain(&F.front(), FunctionChain, BlockWorkList); 1004 1005 #ifndef NDEBUG 1006 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType; 1007 #endif 1008 DEBUG({ 1009 // Crash at the end so we get all of the debugging output first. 1010 bool BadFunc = false; 1011 FunctionBlockSetType FunctionBlockSet; 1012 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) 1013 FunctionBlockSet.insert(FI); 1014 1015 for (BlockChain::iterator BCI = FunctionChain.begin(), 1016 BCE = FunctionChain.end(); 1017 BCI != BCE; ++BCI) 1018 if (!FunctionBlockSet.erase(*BCI)) { 1019 BadFunc = true; 1020 dbgs() << "Function chain contains a block not in the function!\n" 1021 << " Bad block: " << getBlockName(*BCI) << "\n"; 1022 } 1023 1024 if (!FunctionBlockSet.empty()) { 1025 BadFunc = true; 1026 for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(), 1027 FBE = FunctionBlockSet.end(); 1028 FBI != FBE; ++FBI) 1029 dbgs() << "Function contains blocks never placed into a chain!\n" 1030 << " Bad block: " << getBlockName(*FBI) << "\n"; 1031 } 1032 assert(!BadFunc && "Detected problems with the block placement."); 1033 }); 1034 1035 // Splice the blocks into place. 1036 MachineFunction::iterator InsertPos = F.begin(); 1037 for (BlockChain::iterator BI = FunctionChain.begin(), 1038 BE = FunctionChain.end(); 1039 BI != BE; ++BI) { 1040 DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain " 1041 : " ... ") 1042 << getBlockName(*BI) << "\n"); 1043 if (InsertPos != MachineFunction::iterator(*BI)) 1044 F.splice(InsertPos, *BI); 1045 else 1046 ++InsertPos; 1047 1048 // Update the terminator of the previous block. 1049 if (BI == FunctionChain.begin()) 1050 continue; 1051 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI)); 1052 1053 // FIXME: It would be awesome of updateTerminator would just return rather 1054 // than assert when the branch cannot be analyzed in order to remove this 1055 // boiler plate. 1056 Cond.clear(); 1057 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1058 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) { 1059 // The "PrevBB" is not yet updated to reflect current code layout, so, 1060 // o. it may fall-through to a block without explict "goto" instruction 1061 // before layout, and no longer fall-through it after layout; or 1062 // o. just opposite. 1063 // 1064 // AnalyzeBranch() may return erroneous value for FBB when these two 1065 // situations take place. For the first scenario FBB is mistakenly set 1066 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL, 1067 // is mistakenly pointing to "*BI". 1068 // 1069 bool needUpdateBr = true; 1070 if (!Cond.empty() && (!FBB || FBB == *BI)) { 1071 PrevBB->updateTerminator(); 1072 needUpdateBr = false; 1073 Cond.clear(); 1074 TBB = FBB = nullptr; 1075 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) { 1076 // FIXME: This should never take place. 1077 TBB = FBB = nullptr; 1078 } 1079 } 1080 1081 // If PrevBB has a two-way branch, try to re-order the branches 1082 // such that we branch to the successor with higher weight first. 1083 if (TBB && !Cond.empty() && FBB && 1084 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) && 1085 !TII->ReverseBranchCondition(Cond)) { 1086 DEBUG(dbgs() << "Reverse order of the two branches: " 1087 << getBlockName(PrevBB) << "\n"); 1088 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB) 1089 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n"); 1090 DebugLoc dl; // FIXME: this is nowhere 1091 TII->RemoveBranch(*PrevBB); 1092 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl); 1093 needUpdateBr = true; 1094 } 1095 if (needUpdateBr) 1096 PrevBB->updateTerminator(); 1097 } 1098 } 1099 1100 // Fixup the last block. 1101 Cond.clear(); 1102 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1103 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond)) 1104 F.back().updateTerminator(); 1105 1106 // Walk through the backedges of the function now that we have fully laid out 1107 // the basic blocks and align the destination of each backedge. We don't rely 1108 // exclusively on the loop info here so that we can align backedges in 1109 // unnatural CFGs and backedges that were introduced purely because of the 1110 // loop rotations done during this layout pass. 1111 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize)) 1112 return; 1113 if (FunctionChain.begin() == FunctionChain.end()) 1114 return; // Empty chain. 1115 1116 const BranchProbability ColdProb(1, 5); // 20% 1117 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin()); 1118 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 1119 for (BlockChain::iterator BI = std::next(FunctionChain.begin()), 1120 BE = FunctionChain.end(); 1121 BI != BE; ++BI) { 1122 // Don't align non-looping basic blocks. These are unlikely to execute 1123 // enough times to matter in practice. Note that we'll still handle 1124 // unnatural CFGs inside of a natural outer loop (the common case) and 1125 // rotated loops. 1126 MachineLoop *L = MLI->getLoopFor(*BI); 1127 if (!L) 1128 continue; 1129 1130 unsigned Align = TLI->getPrefLoopAlignment(L); 1131 if (!Align) 1132 continue; // Don't care about loop alignment. 1133 1134 // If the block is cold relative to the function entry don't waste space 1135 // aligning it. 1136 BlockFrequency Freq = MBFI->getBlockFreq(*BI); 1137 if (Freq < WeightedEntryFreq) 1138 continue; 1139 1140 // If the block is cold relative to its loop header, don't align it 1141 // regardless of what edges into the block exist. 1142 MachineBasicBlock *LoopHeader = L->getHeader(); 1143 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 1144 if (Freq < (LoopHeaderFreq * ColdProb)) 1145 continue; 1146 1147 // Check for the existence of a non-layout predecessor which would benefit 1148 // from aligning this block. 1149 MachineBasicBlock *LayoutPred = *std::prev(BI); 1150 1151 // Force alignment if all the predecessors are jumps. We already checked 1152 // that the block isn't cold above. 1153 if (!LayoutPred->isSuccessor(*BI)) { 1154 (*BI)->setAlignment(Align); 1155 continue; 1156 } 1157 1158 // Align this block if the layout predecessor's edge into this block is 1159 // cold relative to the block. When this is true, other predecessors make up 1160 // all of the hot entries into the block and thus alignment is likely to be 1161 // important. 1162 BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI); 1163 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 1164 if (LayoutEdgeFreq <= (Freq * ColdProb)) 1165 (*BI)->setAlignment(Align); 1166 } 1167 } 1168 1169 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) { 1170 // Check for single-block functions and skip them. 1171 if (std::next(F.begin()) == F.end()) 1172 return false; 1173 1174 if (skipOptnoneFunction(*F.getFunction())) 1175 return false; 1176 1177 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 1178 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 1179 MLI = &getAnalysis<MachineLoopInfo>(); 1180 TII = F.getSubtarget().getInstrInfo(); 1181 TLI = F.getSubtarget().getTargetLowering(); 1182 MDT = &getAnalysis<MachineDominatorTree>(); 1183 assert(BlockToChain.empty()); 1184 1185 buildCFGChains(F); 1186 1187 BlockToChain.clear(); 1188 ChainAllocator.DestroyAll(); 1189 1190 if (AlignAllBlock) 1191 // Align all of the blocks in the function to a specific alignment. 1192 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); 1193 FI != FE; ++FI) 1194 FI->setAlignment(AlignAllBlock); 1195 1196 // We always return true as we have no way to track whether the final order 1197 // differs from the original order. 1198 return true; 1199 } 1200 1201 namespace { 1202 /// \brief A pass to compute block placement statistics. 1203 /// 1204 /// A separate pass to compute interesting statistics for evaluating block 1205 /// placement. This is separate from the actual placement pass so that they can 1206 /// be computed in the absence of any placement transformations or when using 1207 /// alternative placement strategies. 1208 class MachineBlockPlacementStats : public MachineFunctionPass { 1209 /// \brief A handle to the branch probability pass. 1210 const MachineBranchProbabilityInfo *MBPI; 1211 1212 /// \brief A handle to the function-wide block frequency pass. 1213 const MachineBlockFrequencyInfo *MBFI; 1214 1215 public: 1216 static char ID; // Pass identification, replacement for typeid 1217 MachineBlockPlacementStats() : MachineFunctionPass(ID) { 1218 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 1219 } 1220 1221 bool runOnMachineFunction(MachineFunction &F) override; 1222 1223 void getAnalysisUsage(AnalysisUsage &AU) const override { 1224 AU.addRequired<MachineBranchProbabilityInfo>(); 1225 AU.addRequired<MachineBlockFrequencyInfo>(); 1226 AU.setPreservesAll(); 1227 MachineFunctionPass::getAnalysisUsage(AU); 1228 } 1229 }; 1230 } 1231 1232 char MachineBlockPlacementStats::ID = 0; 1233 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 1234 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 1235 "Basic Block Placement Stats", false, false) 1236 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 1237 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 1238 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 1239 "Basic Block Placement Stats", false, false) 1240 1241 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 1242 // Check for single-block functions and skip them. 1243 if (std::next(F.begin()) == F.end()) 1244 return false; 1245 1246 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 1247 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 1248 1249 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { 1250 BlockFrequency BlockFreq = MBFI->getBlockFreq(I); 1251 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches 1252 : NumUncondBranches; 1253 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq 1254 : UncondBranchTakenFreq; 1255 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(), 1256 SE = I->succ_end(); 1257 SI != SE; ++SI) { 1258 // Skip if this successor is a fallthrough. 1259 if (I->isLayoutSuccessor(*SI)) 1260 continue; 1261 1262 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI); 1263 ++NumBranches; 1264 BranchTakenFreq += EdgeFreq.getFrequency(); 1265 } 1266 } 1267 1268 return false; 1269 } 1270 1271