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