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/CodeGen/TargetPassConfig.h" 30 #include "BranchFolding.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/CodeGen/MachineBasicBlock.h" 36 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 37 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 38 #include "llvm/CodeGen/MachineDominators.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineFunctionPass.h" 41 #include "llvm/CodeGen/MachineLoopInfo.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/TailDuplicator.h" 44 #include "llvm/Support/Allocator.h" 45 #include "llvm/Support/CommandLine.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include "llvm/Target/TargetInstrInfo.h" 49 #include "llvm/Target/TargetLowering.h" 50 #include "llvm/Target/TargetSubtargetInfo.h" 51 #include <algorithm> 52 using namespace llvm; 53 54 #define DEBUG_TYPE "block-placement" 55 56 STATISTIC(NumCondBranches, "Number of conditional branches"); 57 STATISTIC(NumUncondBranches, "Number of unconditional branches"); 58 STATISTIC(CondBranchTakenFreq, 59 "Potential frequency of taking conditional branches"); 60 STATISTIC(UncondBranchTakenFreq, 61 "Potential frequency of taking unconditional branches"); 62 63 static cl::opt<unsigned> AlignAllBlock("align-all-blocks", 64 cl::desc("Force the alignment of all " 65 "blocks in the function."), 66 cl::init(0), cl::Hidden); 67 68 static cl::opt<unsigned> AlignAllNonFallThruBlocks( 69 "align-all-nofallthru-blocks", 70 cl::desc("Force the alignment of all " 71 "blocks that have no fall-through predecessors (i.e. don't add " 72 "nops that are executed)."), 73 cl::init(0), cl::Hidden); 74 75 // FIXME: Find a good default for this flag and remove the flag. 76 static cl::opt<unsigned> ExitBlockBias( 77 "block-placement-exit-block-bias", 78 cl::desc("Block frequency percentage a loop exit block needs " 79 "over the original exit to be considered the new exit."), 80 cl::init(0), cl::Hidden); 81 82 // Definition: 83 // - Outlining: placement of a basic block outside the chain or hot path. 84 85 static cl::opt<bool> OutlineOptionalBranches( 86 "outline-optional-branches", 87 cl::desc("Outlining optional branches will place blocks that are optional " 88 "branches, i.e. branches with a common post dominator, outside " 89 "the hot path or chain"), 90 cl::init(false), cl::Hidden); 91 92 static cl::opt<unsigned> OutlineOptionalThreshold( 93 "outline-optional-threshold", 94 cl::desc("Don't outline optional branches that are a single block with an " 95 "instruction count below this threshold"), 96 cl::init(4), cl::Hidden); 97 98 static cl::opt<unsigned> LoopToColdBlockRatio( 99 "loop-to-cold-block-ratio", 100 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " 101 "(frequency of block) is greater than this ratio"), 102 cl::init(5), cl::Hidden); 103 104 static cl::opt<bool> 105 PreciseRotationCost("precise-rotation-cost", 106 cl::desc("Model the cost of loop rotation more " 107 "precisely by using profile data."), 108 cl::init(false), cl::Hidden); 109 static cl::opt<bool> 110 ForcePreciseRotationCost("force-precise-rotation-cost", 111 cl::desc("Force the use of precise cost " 112 "loop rotation strategy."), 113 cl::init(false), cl::Hidden); 114 115 static cl::opt<unsigned> MisfetchCost( 116 "misfetch-cost", 117 cl::desc("Cost that models the probabilistic risk of an instruction " 118 "misfetch due to a jump comparing to falling through, whose cost " 119 "is zero."), 120 cl::init(1), cl::Hidden); 121 122 static cl::opt<unsigned> JumpInstCost("jump-inst-cost", 123 cl::desc("Cost of jump instructions."), 124 cl::init(1), cl::Hidden); 125 static cl::opt<bool> 126 TailDupPlacement("tail-dup-placement", 127 cl::desc("Perform tail duplication during placement. " 128 "Creates more fallthrough opportunites in " 129 "outline branches."), 130 cl::init(true), cl::Hidden); 131 132 static cl::opt<bool> 133 BranchFoldPlacement("branch-fold-placement", 134 cl::desc("Perform branch folding during placement. " 135 "Reduces code size."), 136 cl::init(true), cl::Hidden); 137 138 // Heuristic for tail duplication. 139 static cl::opt<unsigned> TailDuplicatePlacementThreshold( 140 "tail-dup-placement-threshold", 141 cl::desc("Instruction cutoff for tail duplication during layout. " 142 "Tail merging during layout is forced to have a threshold " 143 "that won't conflict."), cl::init(2), 144 cl::Hidden); 145 146 extern cl::opt<unsigned> StaticLikelyProb; 147 extern cl::opt<unsigned> ProfileLikelyProb; 148 149 namespace { 150 class BlockChain; 151 /// \brief Type for our function-wide basic block -> block chain mapping. 152 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType; 153 } 154 155 namespace { 156 /// \brief A chain of blocks which will be laid out contiguously. 157 /// 158 /// This is the datastructure representing a chain of consecutive blocks that 159 /// are profitable to layout together in order to maximize fallthrough 160 /// probabilities and code locality. We also can use a block chain to represent 161 /// a sequence of basic blocks which have some external (correctness) 162 /// requirement for sequential layout. 163 /// 164 /// Chains can be built around a single basic block and can be merged to grow 165 /// them. They participate in a block-to-chain mapping, which is updated 166 /// automatically as chains are merged together. 167 class BlockChain { 168 /// \brief The sequence of blocks belonging to this chain. 169 /// 170 /// This is the sequence of blocks for a particular chain. These will be laid 171 /// out in-order within the function. 172 SmallVector<MachineBasicBlock *, 4> Blocks; 173 174 /// \brief A handle to the function-wide basic block to block chain mapping. 175 /// 176 /// This is retained in each block chain to simplify the computation of child 177 /// block chains for SCC-formation and iteration. We store the edges to child 178 /// basic blocks, and map them back to their associated chains using this 179 /// structure. 180 BlockToChainMapType &BlockToChain; 181 182 public: 183 /// \brief Construct a new BlockChain. 184 /// 185 /// This builds a new block chain representing a single basic block in the 186 /// function. It also registers itself as the chain that block participates 187 /// in with the BlockToChain mapping. 188 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 189 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) { 190 assert(BB && "Cannot create a chain with a null basic block"); 191 BlockToChain[BB] = this; 192 } 193 194 /// \brief Iterator over blocks within the chain. 195 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator; 196 197 /// \brief Beginning of blocks within the chain. 198 iterator begin() { return Blocks.begin(); } 199 200 /// \brief End of blocks within the chain. 201 iterator end() { return Blocks.end(); } 202 203 bool remove(MachineBasicBlock* BB) { 204 for(iterator i = begin(); i != end(); ++i) { 205 if (*i == BB) { 206 Blocks.erase(i); 207 return true; 208 } 209 } 210 return false; 211 } 212 213 /// \brief Merge a block chain into this one. 214 /// 215 /// This routine merges a block chain into this one. It takes care of forming 216 /// a contiguous sequence of basic blocks, updating the edge list, and 217 /// updating the block -> chain mapping. It does not free or tear down the 218 /// old chain, but the old chain's block list is no longer valid. 219 void merge(MachineBasicBlock *BB, BlockChain *Chain) { 220 assert(BB); 221 assert(!Blocks.empty()); 222 223 // Fast path in case we don't have a chain already. 224 if (!Chain) { 225 assert(!BlockToChain[BB]); 226 Blocks.push_back(BB); 227 BlockToChain[BB] = this; 228 return; 229 } 230 231 assert(BB == *Chain->begin()); 232 assert(Chain->begin() != Chain->end()); 233 234 // Update the incoming blocks to point to this chain, and add them to the 235 // chain structure. 236 for (MachineBasicBlock *ChainBB : *Chain) { 237 Blocks.push_back(ChainBB); 238 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain"); 239 BlockToChain[ChainBB] = this; 240 } 241 } 242 243 #ifndef NDEBUG 244 /// \brief Dump the blocks in this chain. 245 LLVM_DUMP_METHOD void dump() { 246 for (MachineBasicBlock *MBB : *this) 247 MBB->dump(); 248 } 249 #endif // NDEBUG 250 251 /// \brief Count of predecessors of any block within the chain which have not 252 /// yet been scheduled. In general, we will delay scheduling this chain 253 /// until those predecessors are scheduled (or we find a sufficiently good 254 /// reason to override this heuristic.) Note that when forming loop chains, 255 /// blocks outside the loop are ignored and treated as if they were already 256 /// scheduled. 257 /// 258 /// Note: This field is reinitialized multiple times - once for each loop, 259 /// and then once for the function as a whole. 260 unsigned UnscheduledPredecessors; 261 }; 262 } 263 264 namespace { 265 class MachineBlockPlacement : public MachineFunctionPass { 266 /// \brief A typedef for a block filter set. 267 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet; 268 269 /// \brief work lists of blocks that are ready to be laid out 270 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 271 SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 272 273 /// \brief Machine Function 274 MachineFunction *F; 275 276 /// \brief A handle to the branch probability pass. 277 const MachineBranchProbabilityInfo *MBPI; 278 279 /// \brief A handle to the function-wide block frequency pass. 280 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI; 281 282 /// \brief A handle to the loop info. 283 MachineLoopInfo *MLI; 284 285 /// \brief Preferred loop exit. 286 /// Member variable for convenience. It may be removed by duplication deep 287 /// in the call stack. 288 MachineBasicBlock *PreferredLoopExit; 289 290 /// \brief A handle to the target's instruction info. 291 const TargetInstrInfo *TII; 292 293 /// \brief A handle to the target's lowering info. 294 const TargetLoweringBase *TLI; 295 296 /// \brief A handle to the post dominator tree. 297 MachineDominatorTree *MDT; 298 299 /// \brief Duplicator used to duplicate tails during placement. 300 /// 301 /// Placement decisions can open up new tail duplication opportunities, but 302 /// since tail duplication affects placement decisions of later blocks, it 303 /// must be done inline. 304 TailDuplicator TailDup; 305 306 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate 307 /// all terminators of the MachineFunction. 308 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks; 309 310 /// \brief Allocator and owner of BlockChain structures. 311 /// 312 /// We build BlockChains lazily while processing the loop structure of 313 /// a function. To reduce malloc traffic, we allocate them using this 314 /// slab-like allocator, and destroy them after the pass completes. An 315 /// important guarantee is that this allocator produces stable pointers to 316 /// the chains. 317 SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 318 319 /// \brief Function wide BasicBlock to BlockChain mapping. 320 /// 321 /// This mapping allows efficiently moving from any given basic block to the 322 /// BlockChain it participates in, if any. We use it to, among other things, 323 /// allow implicitly defining edges between chains as the existing edges 324 /// between basic blocks. 325 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain; 326 327 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 328 /// if the count goes to 0, add them to the appropriate work list. 329 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB, 330 const BlockFilterSet *BlockFilter = nullptr); 331 332 /// Decrease the UnscheduledPredecessors count for a single block, and 333 /// if the count goes to 0, add them to the appropriate work list. 334 void markBlockSuccessors( 335 BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB, 336 const BlockFilterSet *BlockFilter = nullptr); 337 338 339 BranchProbability 340 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain, 341 const BlockFilterSet *BlockFilter, 342 SmallVector<MachineBasicBlock *, 4> &Successors); 343 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ, 344 BlockChain &Chain, 345 const BlockFilterSet *BlockFilter, 346 BranchProbability SuccProb, 347 BranchProbability HotProb); 348 bool repeatedlyTailDuplicateBlock( 349 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 350 MachineBasicBlock *LoopHeaderBB, 351 BlockChain &Chain, BlockFilterSet *BlockFilter, 352 MachineFunction::iterator &PrevUnplacedBlockIt); 353 bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred, 354 const BlockChain &Chain, 355 BlockFilterSet *BlockFilter, 356 MachineFunction::iterator &PrevUnplacedBlockIt, 357 bool &DuplicatedToPred); 358 bool 359 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ, 360 BlockChain &SuccChain, BranchProbability SuccProb, 361 BranchProbability RealSuccProb, BlockChain &Chain, 362 const BlockFilterSet *BlockFilter); 363 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB, 364 BlockChain &Chain, 365 const BlockFilterSet *BlockFilter); 366 MachineBasicBlock * 367 selectBestCandidateBlock(BlockChain &Chain, 368 SmallVectorImpl<MachineBasicBlock *> &WorkList); 369 MachineBasicBlock * 370 getFirstUnplacedBlock(const BlockChain &PlacedChain, 371 MachineFunction::iterator &PrevUnplacedBlockIt, 372 const BlockFilterSet *BlockFilter); 373 374 /// \brief Add a basic block to the work list if it is appropriate. 375 /// 376 /// If the optional parameter BlockFilter is provided, only MBB 377 /// present in the set will be added to the worklist. If nullptr 378 /// is provided, no filtering occurs. 379 void fillWorkLists(MachineBasicBlock *MBB, 380 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 381 const BlockFilterSet *BlockFilter); 382 void buildChain(MachineBasicBlock *BB, BlockChain &Chain, 383 BlockFilterSet *BlockFilter = nullptr); 384 MachineBasicBlock *findBestLoopTop(MachineLoop &L, 385 const BlockFilterSet &LoopBlockSet); 386 MachineBasicBlock *findBestLoopExit(MachineLoop &L, 387 const BlockFilterSet &LoopBlockSet); 388 BlockFilterSet collectLoopBlockSet(MachineLoop &L); 389 void buildLoopChains(MachineLoop &L); 390 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB, 391 const BlockFilterSet &LoopBlockSet); 392 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L, 393 const BlockFilterSet &LoopBlockSet); 394 void collectMustExecuteBBs(); 395 void buildCFGChains(); 396 void optimizeBranches(); 397 void alignBlocks(); 398 399 public: 400 static char ID; // Pass identification, replacement for typeid 401 MachineBlockPlacement() : MachineFunctionPass(ID) { 402 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 403 } 404 405 bool runOnMachineFunction(MachineFunction &F) override; 406 407 void getAnalysisUsage(AnalysisUsage &AU) const override { 408 AU.addRequired<MachineBranchProbabilityInfo>(); 409 AU.addRequired<MachineBlockFrequencyInfo>(); 410 AU.addRequired<MachineDominatorTree>(); 411 AU.addRequired<MachineLoopInfo>(); 412 AU.addRequired<TargetPassConfig>(); 413 MachineFunctionPass::getAnalysisUsage(AU); 414 } 415 }; 416 } 417 418 char MachineBlockPlacement::ID = 0; 419 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 420 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement", 421 "Branch Probability Basic Block Placement", false, false) 422 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 423 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 424 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 425 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 426 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement", 427 "Branch Probability Basic Block Placement", false, false) 428 429 #ifndef NDEBUG 430 /// \brief Helper to print the name of a MBB. 431 /// 432 /// Only used by debug logging. 433 static std::string getBlockName(MachineBasicBlock *BB) { 434 std::string Result; 435 raw_string_ostream OS(Result); 436 OS << "BB#" << BB->getNumber(); 437 OS << " ('" << BB->getName() << "')"; 438 OS.flush(); 439 return Result; 440 } 441 #endif 442 443 /// \brief Mark a chain's successors as having one fewer preds. 444 /// 445 /// When a chain is being merged into the "placed" chain, this routine will 446 /// quickly walk the successors of each block in the chain and mark them as 447 /// having one fewer active predecessor. It also adds any successors of this 448 /// chain which reach the zero-predecessor state to the appropriate worklist. 449 void MachineBlockPlacement::markChainSuccessors( 450 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB, 451 const BlockFilterSet *BlockFilter) { 452 // Walk all the blocks in this chain, marking their successors as having 453 // a predecessor placed. 454 for (MachineBasicBlock *MBB : Chain) { 455 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 456 } 457 } 458 459 /// \brief Mark a single block's successors as having one fewer preds. 460 /// 461 /// Under normal circumstances, this is only called by markChainSuccessors, 462 /// but if a block that was to be placed is completely tail-duplicated away, 463 /// and was duplicated into the chain end, we need to redo markBlockSuccessors 464 /// for just that block. 465 void MachineBlockPlacement::markBlockSuccessors( 466 BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB, 467 const BlockFilterSet *BlockFilter) { 468 // Add any successors for which this is the only un-placed in-loop 469 // predecessor to the worklist as a viable candidate for CFG-neutral 470 // placement. No subsequent placement of this block will violate the CFG 471 // shape, so we get to use heuristics to choose a favorable placement. 472 for (MachineBasicBlock *Succ : MBB->successors()) { 473 if (BlockFilter && !BlockFilter->count(Succ)) 474 continue; 475 BlockChain &SuccChain = *BlockToChain[Succ]; 476 // Disregard edges within a fixed chain, or edges to the loop header. 477 if (&Chain == &SuccChain || Succ == LoopHeaderBB) 478 continue; 479 480 // This is a cross-chain edge that is within the loop, so decrement the 481 // loop predecessor count of the destination chain. 482 if (SuccChain.UnscheduledPredecessors == 0 || 483 --SuccChain.UnscheduledPredecessors > 0) 484 continue; 485 486 auto *NewBB = *SuccChain.begin(); 487 if (NewBB->isEHPad()) 488 EHPadWorkList.push_back(NewBB); 489 else 490 BlockWorkList.push_back(NewBB); 491 } 492 } 493 494 /// This helper function collects the set of successors of block 495 /// \p BB that are allowed to be its layout successors, and return 496 /// the total branch probability of edges from \p BB to those 497 /// blocks. 498 BranchProbability MachineBlockPlacement::collectViableSuccessors( 499 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter, 500 SmallVector<MachineBasicBlock *, 4> &Successors) { 501 // Adjust edge probabilities by excluding edges pointing to blocks that is 502 // either not in BlockFilter or is already in the current chain. Consider the 503 // following CFG: 504 // 505 // --->A 506 // | / \ 507 // | B C 508 // | \ / \ 509 // ----D E 510 // 511 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 512 // A->C is chosen as a fall-through, D won't be selected as a successor of C 513 // due to CFG constraint (the probability of C->D is not greater than 514 // HotProb to break top-order). If we exclude E that is not in BlockFilter 515 // when calculating the probability of C->D, D will be selected and we 516 // will get A C D B as the layout of this loop. 517 auto AdjustedSumProb = BranchProbability::getOne(); 518 for (MachineBasicBlock *Succ : BB->successors()) { 519 bool SkipSucc = false; 520 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 521 SkipSucc = true; 522 } else { 523 BlockChain *SuccChain = BlockToChain[Succ]; 524 if (SuccChain == &Chain) { 525 SkipSucc = true; 526 } else if (Succ != *SuccChain->begin()) { 527 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n"); 528 continue; 529 } 530 } 531 if (SkipSucc) 532 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 533 else 534 Successors.push_back(Succ); 535 } 536 537 return AdjustedSumProb; 538 } 539 540 /// The helper function returns the branch probability that is adjusted 541 /// or normalized over the new total \p AdjustedSumProb. 542 static BranchProbability 543 getAdjustedProbability(BranchProbability OrigProb, 544 BranchProbability AdjustedSumProb) { 545 BranchProbability SuccProb; 546 uint32_t SuccProbN = OrigProb.getNumerator(); 547 uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 548 if (SuccProbN >= SuccProbD) 549 SuccProb = BranchProbability::getOne(); 550 else 551 SuccProb = BranchProbability(SuccProbN, SuccProbD); 552 553 return SuccProb; 554 } 555 556 /// When the option OutlineOptionalBranches is on, this method 557 /// checks if the fallthrough candidate block \p Succ (of block 558 /// \p BB) also has other unscheduled predecessor blocks which 559 /// are also successors of \p BB (forming triangular shape CFG). 560 /// If none of such predecessors are small, it returns true. 561 /// The caller can choose to select \p Succ as the layout successors 562 /// so that \p Succ's predecessors (optional branches) can be 563 /// outlined. 564 /// FIXME: fold this with more general layout cost analysis. 565 bool MachineBlockPlacement::shouldPredBlockBeOutlined( 566 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain, 567 const BlockFilterSet *BlockFilter, BranchProbability SuccProb, 568 BranchProbability HotProb) { 569 if (!OutlineOptionalBranches) 570 return false; 571 // If we outline optional branches, look whether Succ is unavoidable, i.e. 572 // dominates all terminators of the MachineFunction. If it does, other 573 // successors must be optional. Don't do this for cold branches. 574 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) { 575 for (MachineBasicBlock *Pred : Succ->predecessors()) { 576 // Check whether there is an unplaced optional branch. 577 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) || 578 BlockToChain[Pred] == &Chain) 579 continue; 580 // Check whether the optional branch has exactly one BB. 581 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB) 582 continue; 583 // Check whether the optional branch is small. 584 if (Pred->size() < OutlineOptionalThreshold) 585 return false; 586 } 587 return true; 588 } else 589 return false; 590 } 591 592 // When profile is not present, return the StaticLikelyProb. 593 // When profile is available, we need to handle the triangle-shape CFG. 594 static BranchProbability getLayoutSuccessorProbThreshold( 595 MachineBasicBlock *BB) { 596 if (!BB->getParent()->getFunction()->getEntryCount()) 597 return BranchProbability(StaticLikelyProb, 100); 598 if (BB->succ_size() == 2) { 599 const MachineBasicBlock *Succ1 = *BB->succ_begin(); 600 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 601 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 602 /* See case 1 below for the cost analysis. For BB->Succ to 603 * be taken with smaller cost, the following needs to hold: 604 * Prob(BB->Succ) > 2* Prob(BB->Pred) 605 * So the threshold T 606 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1, 607 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified 608 * branch bias, we have 609 * T = (2/3)*(ProfileLikelyProb/50) 610 * = (2*ProfileLikelyProb)/150) 611 */ 612 return BranchProbability(2 * ProfileLikelyProb, 150); 613 } 614 } 615 return BranchProbability(ProfileLikelyProb, 100); 616 } 617 618 /// Checks to see if the layout candidate block \p Succ has a better layout 619 /// predecessor than \c BB. If yes, returns true. 620 bool MachineBlockPlacement::hasBetterLayoutPredecessor( 621 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain, 622 BranchProbability SuccProb, BranchProbability RealSuccProb, 623 BlockChain &Chain, const BlockFilterSet *BlockFilter) { 624 625 // There isn't a better layout when there are no unscheduled predecessors. 626 if (SuccChain.UnscheduledPredecessors == 0) 627 return false; 628 629 // There are two basic scenarios here: 630 // ------------------------------------- 631 // Case 1: triangular shape CFG (if-then): 632 // BB 633 // | \ 634 // | \ 635 // | Pred 636 // | / 637 // Succ 638 // In this case, we are evaluating whether to select edge -> Succ, e.g. 639 // set Succ as the layout successor of BB. Picking Succ as BB's 640 // successor breaks the CFG constraints (FIXME: define these constraints). 641 // With this layout, Pred BB 642 // is forced to be outlined, so the overall cost will be cost of the 643 // branch taken from BB to Pred, plus the cost of back taken branch 644 // from Pred to Succ, as well as the additional cost associated 645 // with the needed unconditional jump instruction from Pred To Succ. 646 647 // The cost of the topological order layout is the taken branch cost 648 // from BB to Succ, so to make BB->Succ a viable candidate, the following 649 // must hold: 650 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 651 // < freq(BB->Succ) * taken_branch_cost. 652 // Ignoring unconditional jump cost, we get 653 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 654 // prob(BB->Succ) > 2 * prob(BB->Pred) 655 // 656 // When real profile data is available, we can precisely compute the 657 // probability threshold that is needed for edge BB->Succ to be considered. 658 // Without profile data, the heuristic requires the branch bias to be 659 // a lot larger to make sure the signal is very strong (e.g. 80% default). 660 // ----------------------------------------------------------------- 661 // Case 2: diamond like CFG (if-then-else): 662 // S 663 // / \ 664 // | \ 665 // BB Pred 666 // \ / 667 // Succ 668 // .. 669 // 670 // The current block is BB and edge BB->Succ is now being evaluated. 671 // Note that edge S->BB was previously already selected because 672 // prob(S->BB) > prob(S->Pred). 673 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 674 // choose Pred, we will have a topological ordering as shown on the left 675 // in the picture below. If we choose Succ, we have the solution as shown 676 // on the right: 677 // 678 // topo-order: 679 // 680 // S----- ---S 681 // | | | | 682 // ---BB | | BB 683 // | | | | 684 // | pred-- | Succ-- 685 // | | | | 686 // ---succ ---pred-- 687 // 688 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 689 // = freq(S->Pred) + freq(S->BB) 690 // 691 // If we have profile data (i.e, branch probabilities can be trusted), the 692 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 693 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 694 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 695 // means the cost of topological order is greater. 696 // When profile data is not available, however, we need to be more 697 // conservative. If the branch prediction is wrong, breaking the topo-order 698 // will actually yield a layout with large cost. For this reason, we need 699 // strong biased branch at block S with Prob(S->BB) in order to select 700 // BB->Succ. This is equivalent to looking the CFG backward with backward 701 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 702 // profile data). 703 // -------------------------------------------------------------------------- 704 // Case 3: forked diamond 705 // S 706 // / \ 707 // / \ 708 // BB Pred 709 // | \ / | 710 // | \ / | 711 // | X | 712 // | / \ | 713 // | / \ | 714 // S1 S2 715 // 716 // The current block is BB and edge BB->S1 is now being evaluated. 717 // As above S->BB was already selected because 718 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 719 // 720 // topo-order: 721 // 722 // S-------| ---S 723 // | | | | 724 // ---BB | | BB 725 // | | | | 726 // | Pred----| | S1---- 727 // | | | | 728 // --(S1 or S2) ---Pred-- 729 // 730 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 731 // + min(freq(Pred->S1), freq(Pred->S2)) 732 // Non-topo-order cost: 733 // In the worst case, S2 will not get laid out after Pred. 734 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 735 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 736 // is 0. Then the non topo layout is better when 737 // freq(S->Pred) < freq(BB->S1). 738 // This is exactly what is checked below. 739 // Note there are other shapes that apply (Pred may not be a single block, 740 // but they all fit this general pattern.) 741 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 742 743 // Make sure that a hot successor doesn't have a globally more 744 // important predecessor. 745 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 746 bool BadCFGConflict = false; 747 748 for (MachineBasicBlock *Pred : Succ->predecessors()) { 749 if (Pred == Succ || BlockToChain[Pred] == &SuccChain || 750 (BlockFilter && !BlockFilter->count(Pred)) || 751 BlockToChain[Pred] == &Chain) 752 continue; 753 // Do backward checking. 754 // For all cases above, we need a backward checking to filter out edges that 755 // are not 'strongly' biased. With profile data available, the check is 756 // mostly redundant for case 2 (when threshold prob is set at 50%) unless S 757 // has more than two successors. 758 // BB Pred 759 // \ / 760 // Succ 761 // We select edge BB->Succ if 762 // freq(BB->Succ) > freq(Succ) * HotProb 763 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 764 // HotProb 765 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 766 // Case 1 is covered too, because the first equation reduces to: 767 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 768 BlockFrequency PredEdgeFreq = 769 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 770 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 771 BadCFGConflict = true; 772 break; 773 } 774 } 775 776 if (BadCFGConflict) { 777 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb 778 << " (prob) (non-cold CFG conflict)\n"); 779 return true; 780 } 781 782 return false; 783 } 784 785 /// \brief Select the best successor for a block. 786 /// 787 /// This looks across all successors of a particular block and attempts to 788 /// select the "best" one to be the layout successor. It only considers direct 789 /// successors which also pass the block filter. It will attempt to avoid 790 /// breaking CFG structure, but cave and break such structures in the case of 791 /// very hot successor edges. 792 /// 793 /// \returns The best successor block found, or null if none are viable. 794 MachineBasicBlock * 795 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB, 796 BlockChain &Chain, 797 const BlockFilterSet *BlockFilter) { 798 const BranchProbability HotProb(StaticLikelyProb, 100); 799 800 MachineBasicBlock *BestSucc = nullptr; 801 auto BestProb = BranchProbability::getZero(); 802 803 SmallVector<MachineBasicBlock *, 4> Successors; 804 auto AdjustedSumProb = 805 collectViableSuccessors(BB, Chain, BlockFilter, Successors); 806 807 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n"); 808 for (MachineBasicBlock *Succ : Successors) { 809 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 810 BranchProbability SuccProb = 811 getAdjustedProbability(RealSuccProb, AdjustedSumProb); 812 813 // This heuristic is off by default. 814 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb, 815 HotProb)) 816 return Succ; 817 818 BlockChain &SuccChain = *BlockToChain[Succ]; 819 // Skip the edge \c BB->Succ if block \c Succ has a better layout 820 // predecessor that yields lower global cost. 821 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 822 Chain, BlockFilter)) 823 continue; 824 825 DEBUG( 826 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: " 827 << SuccProb 828 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 829 << "\n"); 830 831 if (BestSucc && BestProb >= SuccProb) { 832 DEBUG(dbgs() << " Not the best candidate, continuing\n"); 833 continue; 834 } 835 836 DEBUG(dbgs() << " Setting it as best candidate\n"); 837 BestSucc = Succ; 838 BestProb = SuccProb; 839 } 840 if (BestSucc) 841 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc) << "\n"); 842 843 return BestSucc; 844 } 845 846 /// \brief Select the best block from a worklist. 847 /// 848 /// This looks through the provided worklist as a list of candidate basic 849 /// blocks and select the most profitable one to place. The definition of 850 /// profitable only really makes sense in the context of a loop. This returns 851 /// the most frequently visited block in the worklist, which in the case of 852 /// a loop, is the one most desirable to be physically close to the rest of the 853 /// loop body in order to improve i-cache behavior. 854 /// 855 /// \returns The best block found, or null if none are viable. 856 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 857 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 858 // Once we need to walk the worklist looking for a candidate, cleanup the 859 // worklist of already placed entries. 860 // FIXME: If this shows up on profiles, it could be folded (at the cost of 861 // some code complexity) into the loop below. 862 WorkList.erase(remove_if(WorkList, 863 [&](MachineBasicBlock *BB) { 864 return BlockToChain.lookup(BB) == &Chain; 865 }), 866 WorkList.end()); 867 868 if (WorkList.empty()) 869 return nullptr; 870 871 bool IsEHPad = WorkList[0]->isEHPad(); 872 873 MachineBasicBlock *BestBlock = nullptr; 874 BlockFrequency BestFreq; 875 for (MachineBasicBlock *MBB : WorkList) { 876 assert(MBB->isEHPad() == IsEHPad); 877 878 BlockChain &SuccChain = *BlockToChain[MBB]; 879 if (&SuccChain == &Chain) 880 continue; 881 882 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block"); 883 884 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 885 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; 886 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 887 888 // For ehpad, we layout the least probable first as to avoid jumping back 889 // from least probable landingpads to more probable ones. 890 // 891 // FIXME: Using probability is probably (!) not the best way to achieve 892 // this. We should probably have a more principled approach to layout 893 // cleanup code. 894 // 895 // The goal is to get: 896 // 897 // +--------------------------+ 898 // | V 899 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 900 // 901 // Rather than: 902 // 903 // +-------------------------------------+ 904 // V | 905 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 906 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 907 continue; 908 909 BestBlock = MBB; 910 BestFreq = CandidateFreq; 911 } 912 913 return BestBlock; 914 } 915 916 /// \brief Retrieve the first unplaced basic block. 917 /// 918 /// This routine is called when we are unable to use the CFG to walk through 919 /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 920 /// We walk through the function's blocks in order, starting from the 921 /// LastUnplacedBlockIt. We update this iterator on each call to avoid 922 /// re-scanning the entire sequence on repeated calls to this routine. 923 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 924 const BlockChain &PlacedChain, 925 MachineFunction::iterator &PrevUnplacedBlockIt, 926 const BlockFilterSet *BlockFilter) { 927 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 928 ++I) { 929 if (BlockFilter && !BlockFilter->count(&*I)) 930 continue; 931 if (BlockToChain[&*I] != &PlacedChain) { 932 PrevUnplacedBlockIt = I; 933 // Now select the head of the chain to which the unplaced block belongs 934 // as the block to place. This will force the entire chain to be placed, 935 // and satisfies the requirements of merging chains. 936 return *BlockToChain[&*I]->begin(); 937 } 938 } 939 return nullptr; 940 } 941 942 void MachineBlockPlacement::fillWorkLists( 943 MachineBasicBlock *MBB, 944 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 945 const BlockFilterSet *BlockFilter = nullptr) { 946 BlockChain &Chain = *BlockToChain[MBB]; 947 if (!UpdatedPreds.insert(&Chain).second) 948 return; 949 950 assert(Chain.UnscheduledPredecessors == 0); 951 for (MachineBasicBlock *ChainBB : Chain) { 952 assert(BlockToChain[ChainBB] == &Chain); 953 for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 954 if (BlockFilter && !BlockFilter->count(Pred)) 955 continue; 956 if (BlockToChain[Pred] == &Chain) 957 continue; 958 ++Chain.UnscheduledPredecessors; 959 } 960 } 961 962 if (Chain.UnscheduledPredecessors != 0) 963 return; 964 965 MBB = *Chain.begin(); 966 if (MBB->isEHPad()) 967 EHPadWorkList.push_back(MBB); 968 else 969 BlockWorkList.push_back(MBB); 970 } 971 972 void MachineBlockPlacement::buildChain( 973 MachineBasicBlock *BB, BlockChain &Chain, 974 BlockFilterSet *BlockFilter) { 975 assert(BB && "BB must not be null.\n"); 976 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n"); 977 MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 978 979 MachineBasicBlock *LoopHeaderBB = BB; 980 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 981 BB = *std::prev(Chain.end()); 982 for (;;) { 983 assert(BB && "null block found at end of chain in loop."); 984 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 985 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 986 987 988 // Look for the best viable successor if there is one to place immediately 989 // after this block. 990 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter); 991 992 // If an immediate successor isn't available, look for the best viable 993 // block among those we've identified as not violating the loop's CFG at 994 // this point. This won't be a fallthrough, but it will increase locality. 995 if (!BestSucc) 996 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 997 if (!BestSucc) 998 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 999 1000 if (!BestSucc) { 1001 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); 1002 if (!BestSucc) 1003 break; 1004 1005 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 1006 "layout successor until the CFG reduces\n"); 1007 } 1008 1009 // Placement may have changed tail duplication opportunities. 1010 // Check for that now. 1011 if (TailDupPlacement && BestSucc) { 1012 // If the chosen successor was duplicated into all its predecessors, 1013 // don't bother laying it out, just go round the loop again with BB as 1014 // the chain end. 1015 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 1016 BlockFilter, PrevUnplacedBlockIt)) 1017 continue; 1018 } 1019 1020 // Place this block, updating the datastructures to reflect its placement. 1021 BlockChain &SuccChain = *BlockToChain[BestSucc]; 1022 // Zero out UnscheduledPredecessors for the successor we're about to merge in case 1023 // we selected a successor that didn't fit naturally into the CFG. 1024 SuccChain.UnscheduledPredecessors = 0; 1025 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 1026 << getBlockName(BestSucc) << "\n"); 1027 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 1028 Chain.merge(BestSucc, &SuccChain); 1029 BB = *std::prev(Chain.end()); 1030 } 1031 1032 DEBUG(dbgs() << "Finished forming chain for header block " 1033 << getBlockName(*Chain.begin()) << "\n"); 1034 } 1035 1036 /// \brief Find the best loop top block for layout. 1037 /// 1038 /// Look for a block which is strictly better than the loop header for laying 1039 /// out at the top of the loop. This looks for one and only one pattern: 1040 /// a latch block with no conditional exit. This block will cause a conditional 1041 /// jump around it or will be the bottom of the loop if we lay it out in place, 1042 /// but if it it doesn't end up at the bottom of the loop for any reason, 1043 /// rotation alone won't fix it. Because such a block will always result in an 1044 /// unconditional jump (for the backedge) rotating it in front of the loop 1045 /// header is always profitable. 1046 MachineBasicBlock * 1047 MachineBlockPlacement::findBestLoopTop(MachineLoop &L, 1048 const BlockFilterSet &LoopBlockSet) { 1049 // Placing the latch block before the header may introduce an extra branch 1050 // that skips this block the first time the loop is executed, which we want 1051 // to avoid when optimising for size. 1052 // FIXME: in theory there is a case that does not introduce a new branch, 1053 // i.e. when the layout predecessor does not fallthrough to the loop header. 1054 // In practice this never happens though: there always seems to be a preheader 1055 // that can fallthrough and that is also placed before the header. 1056 if (F->getFunction()->optForSize()) 1057 return L.getHeader(); 1058 1059 // Check that the header hasn't been fused with a preheader block due to 1060 // crazy branches. If it has, we need to start with the header at the top to 1061 // prevent pulling the preheader into the loop body. 1062 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 1063 if (!LoopBlockSet.count(*HeaderChain.begin())) 1064 return L.getHeader(); 1065 1066 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader()) 1067 << "\n"); 1068 1069 BlockFrequency BestPredFreq; 1070 MachineBasicBlock *BestPred = nullptr; 1071 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) { 1072 if (!LoopBlockSet.count(Pred)) 1073 continue; 1074 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has " 1075 << Pred->succ_size() << " successors, "; 1076 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 1077 if (Pred->succ_size() > 1) 1078 continue; 1079 1080 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred); 1081 if (!BestPred || PredFreq > BestPredFreq || 1082 (!(PredFreq < BestPredFreq) && 1083 Pred->isLayoutSuccessor(L.getHeader()))) { 1084 BestPred = Pred; 1085 BestPredFreq = PredFreq; 1086 } 1087 } 1088 1089 // If no direct predecessor is fine, just use the loop header. 1090 if (!BestPred) { 1091 DEBUG(dbgs() << " final top unchanged\n"); 1092 return L.getHeader(); 1093 } 1094 1095 // Walk backwards through any straight line of predecessors. 1096 while (BestPred->pred_size() == 1 && 1097 (*BestPred->pred_begin())->succ_size() == 1 && 1098 *BestPred->pred_begin() != L.getHeader()) 1099 BestPred = *BestPred->pred_begin(); 1100 1101 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 1102 return BestPred; 1103 } 1104 1105 /// \brief Find the best loop exiting block for layout. 1106 /// 1107 /// This routine implements the logic to analyze the loop looking for the best 1108 /// block to layout at the top of the loop. Typically this is done to maximize 1109 /// fallthrough opportunities. 1110 MachineBasicBlock * 1111 MachineBlockPlacement::findBestLoopExit(MachineLoop &L, 1112 const BlockFilterSet &LoopBlockSet) { 1113 // We don't want to layout the loop linearly in all cases. If the loop header 1114 // is just a normal basic block in the loop, we want to look for what block 1115 // within the loop is the best one to layout at the top. However, if the loop 1116 // header has be pre-merged into a chain due to predecessors not having 1117 // analyzable branches, *and* the predecessor it is merged with is *not* part 1118 // of the loop, rotating the header into the middle of the loop will create 1119 // a non-contiguous range of blocks which is Very Bad. So start with the 1120 // header and only rotate if safe. 1121 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 1122 if (!LoopBlockSet.count(*HeaderChain.begin())) 1123 return nullptr; 1124 1125 BlockFrequency BestExitEdgeFreq; 1126 unsigned BestExitLoopDepth = 0; 1127 MachineBasicBlock *ExitingBB = nullptr; 1128 // If there are exits to outer loops, loop rotation can severely limit 1129 // fallthrough opportunities unless it selects such an exit. Keep a set of 1130 // blocks where rotating to exit with that block will reach an outer loop. 1131 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 1132 1133 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader()) 1134 << "\n"); 1135 for (MachineBasicBlock *MBB : L.getBlocks()) { 1136 BlockChain &Chain = *BlockToChain[MBB]; 1137 // Ensure that this block is at the end of a chain; otherwise it could be 1138 // mid-way through an inner loop or a successor of an unanalyzable branch. 1139 if (MBB != *std::prev(Chain.end())) 1140 continue; 1141 1142 // Now walk the successors. We need to establish whether this has a viable 1143 // exiting successor and whether it has a viable non-exiting successor. 1144 // We store the old exiting state and restore it if a viable looping 1145 // successor isn't found. 1146 MachineBasicBlock *OldExitingBB = ExitingBB; 1147 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 1148 bool HasLoopingSucc = false; 1149 for (MachineBasicBlock *Succ : MBB->successors()) { 1150 if (Succ->isEHPad()) 1151 continue; 1152 if (Succ == MBB) 1153 continue; 1154 BlockChain &SuccChain = *BlockToChain[Succ]; 1155 // Don't split chains, either this chain or the successor's chain. 1156 if (&Chain == &SuccChain) { 1157 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 1158 << getBlockName(Succ) << " (chain conflict)\n"); 1159 continue; 1160 } 1161 1162 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 1163 if (LoopBlockSet.count(Succ)) { 1164 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 1165 << getBlockName(Succ) << " (" << SuccProb << ")\n"); 1166 HasLoopingSucc = true; 1167 continue; 1168 } 1169 1170 unsigned SuccLoopDepth = 0; 1171 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 1172 SuccLoopDepth = ExitLoop->getLoopDepth(); 1173 if (ExitLoop->contains(&L)) 1174 BlocksExitingToOuterLoop.insert(MBB); 1175 } 1176 1177 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 1178 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 1179 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] ("; 1180 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 1181 // Note that we bias this toward an existing layout successor to retain 1182 // incoming order in the absence of better information. The exit must have 1183 // a frequency higher than the current exit before we consider breaking 1184 // the layout. 1185 BranchProbability Bias(100 - ExitBlockBias, 100); 1186 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 1187 ExitEdgeFreq > BestExitEdgeFreq || 1188 (MBB->isLayoutSuccessor(Succ) && 1189 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 1190 BestExitEdgeFreq = ExitEdgeFreq; 1191 ExitingBB = MBB; 1192 } 1193 } 1194 1195 if (!HasLoopingSucc) { 1196 // Restore the old exiting state, no viable looping successor was found. 1197 ExitingBB = OldExitingBB; 1198 BestExitEdgeFreq = OldBestExitEdgeFreq; 1199 } 1200 } 1201 // Without a candidate exiting block or with only a single block in the 1202 // loop, just use the loop header to layout the loop. 1203 if (!ExitingBB) { 1204 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n"); 1205 return nullptr; 1206 } 1207 if (L.getNumBlocks() == 1) { 1208 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 1209 return nullptr; 1210 } 1211 1212 // Also, if we have exit blocks which lead to outer loops but didn't select 1213 // one of them as the exiting block we are rotating toward, disable loop 1214 // rotation altogether. 1215 if (!BlocksExitingToOuterLoop.empty() && 1216 !BlocksExitingToOuterLoop.count(ExitingBB)) 1217 return nullptr; 1218 1219 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n"); 1220 return ExitingBB; 1221 } 1222 1223 /// \brief Attempt to rotate an exiting block to the bottom of the loop. 1224 /// 1225 /// Once we have built a chain, try to rotate it to line up the hot exit block 1226 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 1227 /// branches. For example, if the loop has fallthrough into its header and out 1228 /// of its bottom already, don't rotate it. 1229 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 1230 MachineBasicBlock *ExitingBB, 1231 const BlockFilterSet &LoopBlockSet) { 1232 if (!ExitingBB) 1233 return; 1234 1235 MachineBasicBlock *Top = *LoopChain.begin(); 1236 bool ViableTopFallthrough = false; 1237 for (MachineBasicBlock *Pred : Top->predecessors()) { 1238 BlockChain *PredChain = BlockToChain[Pred]; 1239 if (!LoopBlockSet.count(Pred) && 1240 (!PredChain || Pred == *std::prev(PredChain->end()))) { 1241 ViableTopFallthrough = true; 1242 break; 1243 } 1244 } 1245 1246 // If the header has viable fallthrough, check whether the current loop 1247 // bottom is a viable exiting block. If so, bail out as rotating will 1248 // introduce an unnecessary branch. 1249 if (ViableTopFallthrough) { 1250 MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 1251 for (MachineBasicBlock *Succ : Bottom->successors()) { 1252 BlockChain *SuccChain = BlockToChain[Succ]; 1253 if (!LoopBlockSet.count(Succ) && 1254 (!SuccChain || Succ == *SuccChain->begin())) 1255 return; 1256 } 1257 } 1258 1259 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB); 1260 if (ExitIt == LoopChain.end()) 1261 return; 1262 1263 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 1264 } 1265 1266 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost. 1267 /// 1268 /// With profile data, we can determine the cost in terms of missed fall through 1269 /// opportunities when rotating a loop chain and select the best rotation. 1270 /// Basically, there are three kinds of cost to consider for each rotation: 1271 /// 1. The possibly missed fall through edge (if it exists) from BB out of 1272 /// the loop to the loop header. 1273 /// 2. The possibly missed fall through edges (if they exist) from the loop 1274 /// exits to BB out of the loop. 1275 /// 3. The missed fall through edge (if it exists) from the last BB to the 1276 /// first BB in the loop chain. 1277 /// Therefore, the cost for a given rotation is the sum of costs listed above. 1278 /// We select the best rotation with the smallest cost. 1279 void MachineBlockPlacement::rotateLoopWithProfile( 1280 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) { 1281 auto HeaderBB = L.getHeader(); 1282 auto HeaderIter = find(LoopChain, HeaderBB); 1283 auto RotationPos = LoopChain.end(); 1284 1285 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); 1286 1287 // A utility lambda that scales up a block frequency by dividing it by a 1288 // branch probability which is the reciprocal of the scale. 1289 auto ScaleBlockFrequency = [](BlockFrequency Freq, 1290 unsigned Scale) -> BlockFrequency { 1291 if (Scale == 0) 1292 return 0; 1293 // Use operator / between BlockFrequency and BranchProbability to implement 1294 // saturating multiplication. 1295 return Freq / BranchProbability(1, Scale); 1296 }; 1297 1298 // Compute the cost of the missed fall-through edge to the loop header if the 1299 // chain head is not the loop header. As we only consider natural loops with 1300 // single header, this computation can be done only once. 1301 BlockFrequency HeaderFallThroughCost(0); 1302 for (auto *Pred : HeaderBB->predecessors()) { 1303 BlockChain *PredChain = BlockToChain[Pred]; 1304 if (!LoopBlockSet.count(Pred) && 1305 (!PredChain || Pred == *std::prev(PredChain->end()))) { 1306 auto EdgeFreq = 1307 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB); 1308 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 1309 // If the predecessor has only an unconditional jump to the header, we 1310 // need to consider the cost of this jump. 1311 if (Pred->succ_size() == 1) 1312 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 1313 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 1314 } 1315 } 1316 1317 // Here we collect all exit blocks in the loop, and for each exit we find out 1318 // its hottest exit edge. For each loop rotation, we define the loop exit cost 1319 // as the sum of frequencies of exit edges we collect here, excluding the exit 1320 // edge from the tail of the loop chain. 1321 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 1322 for (auto BB : LoopChain) { 1323 auto LargestExitEdgeProb = BranchProbability::getZero(); 1324 for (auto *Succ : BB->successors()) { 1325 BlockChain *SuccChain = BlockToChain[Succ]; 1326 if (!LoopBlockSet.count(Succ) && 1327 (!SuccChain || Succ == *SuccChain->begin())) { 1328 auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 1329 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 1330 } 1331 } 1332 if (LargestExitEdgeProb > BranchProbability::getZero()) { 1333 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 1334 ExitsWithFreq.emplace_back(BB, ExitFreq); 1335 } 1336 } 1337 1338 // In this loop we iterate every block in the loop chain and calculate the 1339 // cost assuming the block is the head of the loop chain. When the loop ends, 1340 // we should have found the best candidate as the loop chain's head. 1341 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 1342 EndIter = LoopChain.end(); 1343 Iter != EndIter; Iter++, TailIter++) { 1344 // TailIter is used to track the tail of the loop chain if the block we are 1345 // checking (pointed by Iter) is the head of the chain. 1346 if (TailIter == LoopChain.end()) 1347 TailIter = LoopChain.begin(); 1348 1349 auto TailBB = *TailIter; 1350 1351 // Calculate the cost by putting this BB to the top. 1352 BlockFrequency Cost = 0; 1353 1354 // If the current BB is the loop header, we need to take into account the 1355 // cost of the missed fall through edge from outside of the loop to the 1356 // header. 1357 if (Iter != HeaderIter) 1358 Cost += HeaderFallThroughCost; 1359 1360 // Collect the loop exit cost by summing up frequencies of all exit edges 1361 // except the one from the chain tail. 1362 for (auto &ExitWithFreq : ExitsWithFreq) 1363 if (TailBB != ExitWithFreq.first) 1364 Cost += ExitWithFreq.second; 1365 1366 // The cost of breaking the once fall-through edge from the tail to the top 1367 // of the loop chain. Here we need to consider three cases: 1368 // 1. If the tail node has only one successor, then we will get an 1369 // additional jmp instruction. So the cost here is (MisfetchCost + 1370 // JumpInstCost) * tail node frequency. 1371 // 2. If the tail node has two successors, then we may still get an 1372 // additional jmp instruction if the layout successor after the loop 1373 // chain is not its CFG successor. Note that the more frequently executed 1374 // jmp instruction will be put ahead of the other one. Assume the 1375 // frequency of those two branches are x and y, where x is the frequency 1376 // of the edge to the chain head, then the cost will be 1377 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 1378 // 3. If the tail node has more than two successors (this rarely happens), 1379 // we won't consider any additional cost. 1380 if (TailBB->isSuccessor(*Iter)) { 1381 auto TailBBFreq = MBFI->getBlockFreq(TailBB); 1382 if (TailBB->succ_size() == 1) 1383 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), 1384 MisfetchCost + JumpInstCost); 1385 else if (TailBB->succ_size() == 2) { 1386 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 1387 auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 1388 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 1389 ? TailBBFreq * TailToHeadProb.getCompl() 1390 : TailToHeadFreq; 1391 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 1392 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 1393 } 1394 } 1395 1396 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter) 1397 << " to the top: " << Cost.getFrequency() << "\n"); 1398 1399 if (Cost < SmallestRotationCost) { 1400 SmallestRotationCost = Cost; 1401 RotationPos = Iter; 1402 } 1403 } 1404 1405 if (RotationPos != LoopChain.end()) { 1406 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 1407 << " to the top\n"); 1408 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 1409 } 1410 } 1411 1412 /// \brief Collect blocks in the given loop that are to be placed. 1413 /// 1414 /// When profile data is available, exclude cold blocks from the returned set; 1415 /// otherwise, collect all blocks in the loop. 1416 MachineBlockPlacement::BlockFilterSet 1417 MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) { 1418 BlockFilterSet LoopBlockSet; 1419 1420 // Filter cold blocks off from LoopBlockSet when profile data is available. 1421 // Collect the sum of frequencies of incoming edges to the loop header from 1422 // outside. If we treat the loop as a super block, this is the frequency of 1423 // the loop. Then for each block in the loop, we calculate the ratio between 1424 // its frequency and the frequency of the loop block. When it is too small, 1425 // don't add it to the loop chain. If there are outer loops, then this block 1426 // will be merged into the first outer loop chain for which this block is not 1427 // cold anymore. This needs precise profile data and we only do this when 1428 // profile data is available. 1429 if (F->getFunction()->getEntryCount()) { 1430 BlockFrequency LoopFreq(0); 1431 for (auto LoopPred : L.getHeader()->predecessors()) 1432 if (!L.contains(LoopPred)) 1433 LoopFreq += MBFI->getBlockFreq(LoopPred) * 1434 MBPI->getEdgeProbability(LoopPred, L.getHeader()); 1435 1436 for (MachineBasicBlock *LoopBB : L.getBlocks()) { 1437 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 1438 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 1439 continue; 1440 LoopBlockSet.insert(LoopBB); 1441 } 1442 } else 1443 LoopBlockSet.insert(L.block_begin(), L.block_end()); 1444 1445 return LoopBlockSet; 1446 } 1447 1448 /// \brief Forms basic block chains from the natural loop structures. 1449 /// 1450 /// These chains are designed to preserve the existing *structure* of the code 1451 /// as much as possible. We can then stitch the chains together in a way which 1452 /// both preserves the topological structure and minimizes taken conditional 1453 /// branches. 1454 void MachineBlockPlacement::buildLoopChains(MachineLoop &L) { 1455 // First recurse through any nested loops, building chains for those inner 1456 // loops. 1457 for (MachineLoop *InnerLoop : L) 1458 buildLoopChains(*InnerLoop); 1459 1460 assert(BlockWorkList.empty()); 1461 assert(EHPadWorkList.empty()); 1462 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 1463 1464 // Check if we have profile data for this function. If yes, we will rotate 1465 // this loop by modeling costs more precisely which requires the profile data 1466 // for better layout. 1467 bool RotateLoopWithProfile = 1468 ForcePreciseRotationCost || 1469 (PreciseRotationCost && F->getFunction()->getEntryCount()); 1470 1471 // First check to see if there is an obviously preferable top block for the 1472 // loop. This will default to the header, but may end up as one of the 1473 // predecessors to the header if there is one which will result in strictly 1474 // fewer branches in the loop body. 1475 // When we use profile data to rotate the loop, this is unnecessary. 1476 MachineBasicBlock *LoopTop = 1477 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet); 1478 1479 // If we selected just the header for the loop top, look for a potentially 1480 // profitable exit block in the event that rotating the loop can eliminate 1481 // branches by placing an exit edge at the bottom. 1482 if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 1483 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet); 1484 1485 BlockChain &LoopChain = *BlockToChain[LoopTop]; 1486 1487 // FIXME: This is a really lame way of walking the chains in the loop: we 1488 // walk the blocks, and use a set to prevent visiting a particular chain 1489 // twice. 1490 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 1491 assert(LoopChain.UnscheduledPredecessors == 0); 1492 UpdatedPreds.insert(&LoopChain); 1493 1494 for (MachineBasicBlock *LoopBB : LoopBlockSet) 1495 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 1496 1497 buildChain(LoopTop, LoopChain, &LoopBlockSet); 1498 1499 if (RotateLoopWithProfile) 1500 rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 1501 else 1502 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet); 1503 1504 DEBUG({ 1505 // Crash at the end so we get all of the debugging output first. 1506 bool BadLoop = false; 1507 if (LoopChain.UnscheduledPredecessors) { 1508 BadLoop = true; 1509 dbgs() << "Loop chain contains a block without its preds placed!\n" 1510 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 1511 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 1512 } 1513 for (MachineBasicBlock *ChainBB : LoopChain) { 1514 dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 1515 if (!LoopBlockSet.erase(ChainBB)) { 1516 // We don't mark the loop as bad here because there are real situations 1517 // where this can occur. For example, with an unanalyzable fallthrough 1518 // from a loop block to a non-loop block or vice versa. 1519 dbgs() << "Loop chain contains a block not contained by the loop!\n" 1520 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 1521 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 1522 << " Bad block: " << getBlockName(ChainBB) << "\n"; 1523 } 1524 } 1525 1526 if (!LoopBlockSet.empty()) { 1527 BadLoop = true; 1528 for (MachineBasicBlock *LoopBB : LoopBlockSet) 1529 dbgs() << "Loop contains blocks never placed into a chain!\n" 1530 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 1531 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 1532 << " Bad block: " << getBlockName(LoopBB) << "\n"; 1533 } 1534 assert(!BadLoop && "Detected problems with the placement of this loop."); 1535 }); 1536 1537 BlockWorkList.clear(); 1538 EHPadWorkList.clear(); 1539 } 1540 1541 /// When OutlineOpitonalBranches is on, this method collects BBs that 1542 /// dominates all terminator blocks of the function \p F. 1543 void MachineBlockPlacement::collectMustExecuteBBs() { 1544 if (OutlineOptionalBranches) { 1545 // Find the nearest common dominator of all of F's terminators. 1546 MachineBasicBlock *Terminator = nullptr; 1547 for (MachineBasicBlock &MBB : *F) { 1548 if (MBB.succ_size() == 0) { 1549 if (Terminator == nullptr) 1550 Terminator = &MBB; 1551 else 1552 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB); 1553 } 1554 } 1555 1556 // MBBs dominating this common dominator are unavoidable. 1557 UnavoidableBlocks.clear(); 1558 for (MachineBasicBlock &MBB : *F) { 1559 if (MDT->dominates(&MBB, Terminator)) { 1560 UnavoidableBlocks.insert(&MBB); 1561 } 1562 } 1563 } 1564 } 1565 1566 void MachineBlockPlacement::buildCFGChains() { 1567 // Ensure that every BB in the function has an associated chain to simplify 1568 // the assumptions of the remaining algorithm. 1569 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 1570 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 1571 ++FI) { 1572 MachineBasicBlock *BB = &*FI; 1573 BlockChain *Chain = 1574 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 1575 // Also, merge any blocks which we cannot reason about and must preserve 1576 // the exact fallthrough behavior for. 1577 for (;;) { 1578 Cond.clear(); 1579 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1580 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 1581 break; 1582 1583 MachineFunction::iterator NextFI = std::next(FI); 1584 MachineBasicBlock *NextBB = &*NextFI; 1585 // Ensure that the layout successor is a viable block, as we know that 1586 // fallthrough is a possibility. 1587 assert(NextFI != FE && "Can't fallthrough past the last block."); 1588 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 1589 << getBlockName(BB) << " -> " << getBlockName(NextBB) 1590 << "\n"); 1591 Chain->merge(NextBB, nullptr); 1592 FI = NextFI; 1593 BB = NextBB; 1594 } 1595 } 1596 1597 // Turned on with OutlineOptionalBranches option 1598 collectMustExecuteBBs(); 1599 1600 // Build any loop-based chains. 1601 PreferredLoopExit = nullptr; 1602 for (MachineLoop *L : *MLI) 1603 buildLoopChains(*L); 1604 1605 assert(BlockWorkList.empty()); 1606 assert(EHPadWorkList.empty()); 1607 1608 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 1609 for (MachineBasicBlock &MBB : *F) 1610 fillWorkLists(&MBB, UpdatedPreds); 1611 1612 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 1613 buildChain(&F->front(), FunctionChain); 1614 1615 #ifndef NDEBUG 1616 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType; 1617 #endif 1618 DEBUG({ 1619 // Crash at the end so we get all of the debugging output first. 1620 bool BadFunc = false; 1621 FunctionBlockSetType FunctionBlockSet; 1622 for (MachineBasicBlock &MBB : *F) 1623 FunctionBlockSet.insert(&MBB); 1624 1625 for (MachineBasicBlock *ChainBB : FunctionChain) 1626 if (!FunctionBlockSet.erase(ChainBB)) { 1627 BadFunc = true; 1628 dbgs() << "Function chain contains a block not in the function!\n" 1629 << " Bad block: " << getBlockName(ChainBB) << "\n"; 1630 } 1631 1632 if (!FunctionBlockSet.empty()) { 1633 BadFunc = true; 1634 for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 1635 dbgs() << "Function contains blocks never placed into a chain!\n" 1636 << " Bad block: " << getBlockName(RemainingBB) << "\n"; 1637 } 1638 assert(!BadFunc && "Detected problems with the block placement."); 1639 }); 1640 1641 // Splice the blocks into place. 1642 MachineFunction::iterator InsertPos = F->begin(); 1643 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n"); 1644 for (MachineBasicBlock *ChainBB : FunctionChain) { 1645 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 1646 : " ... ") 1647 << getBlockName(ChainBB) << "\n"); 1648 if (InsertPos != MachineFunction::iterator(ChainBB)) 1649 F->splice(InsertPos, ChainBB); 1650 else 1651 ++InsertPos; 1652 1653 // Update the terminator of the previous block. 1654 if (ChainBB == *FunctionChain.begin()) 1655 continue; 1656 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 1657 1658 // FIXME: It would be awesome of updateTerminator would just return rather 1659 // than assert when the branch cannot be analyzed in order to remove this 1660 // boiler plate. 1661 Cond.clear(); 1662 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1663 1664 // The "PrevBB" is not yet updated to reflect current code layout, so, 1665 // o. it may fall-through to a block without explicit "goto" instruction 1666 // before layout, and no longer fall-through it after layout; or 1667 // o. just opposite. 1668 // 1669 // analyzeBranch() may return erroneous value for FBB when these two 1670 // situations take place. For the first scenario FBB is mistakenly set NULL; 1671 // for the 2nd scenario, the FBB, which is expected to be NULL, is 1672 // mistakenly pointing to "*BI". 1673 // Thus, if the future change needs to use FBB before the layout is set, it 1674 // has to correct FBB first by using the code similar to the following: 1675 // 1676 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 1677 // PrevBB->updateTerminator(); 1678 // Cond.clear(); 1679 // TBB = FBB = nullptr; 1680 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 1681 // // FIXME: This should never take place. 1682 // TBB = FBB = nullptr; 1683 // } 1684 // } 1685 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) 1686 PrevBB->updateTerminator(); 1687 } 1688 1689 // Fixup the last block. 1690 Cond.clear(); 1691 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1692 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) 1693 F->back().updateTerminator(); 1694 1695 BlockWorkList.clear(); 1696 EHPadWorkList.clear(); 1697 } 1698 1699 void MachineBlockPlacement::optimizeBranches() { 1700 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 1701 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 1702 1703 // Now that all the basic blocks in the chain have the proper layout, 1704 // make a final call to AnalyzeBranch with AllowModify set. 1705 // Indeed, the target may be able to optimize the branches in a way we 1706 // cannot because all branches may not be analyzable. 1707 // E.g., the target may be able to remove an unconditional branch to 1708 // a fallthrough when it occurs after predicated terminators. 1709 for (MachineBasicBlock *ChainBB : FunctionChain) { 1710 Cond.clear(); 1711 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1712 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 1713 // If PrevBB has a two-way branch, try to re-order the branches 1714 // such that we branch to the successor with higher probability first. 1715 if (TBB && !Cond.empty() && FBB && 1716 MBPI->getEdgeProbability(ChainBB, FBB) > 1717 MBPI->getEdgeProbability(ChainBB, TBB) && 1718 !TII->reverseBranchCondition(Cond)) { 1719 DEBUG(dbgs() << "Reverse order of the two branches: " 1720 << getBlockName(ChainBB) << "\n"); 1721 DEBUG(dbgs() << " Edge probability: " 1722 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 1723 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 1724 DebugLoc dl; // FIXME: this is nowhere 1725 TII->removeBranch(*ChainBB); 1726 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 1727 ChainBB->updateTerminator(); 1728 } 1729 } 1730 } 1731 } 1732 1733 void MachineBlockPlacement::alignBlocks() { 1734 // Walk through the backedges of the function now that we have fully laid out 1735 // the basic blocks and align the destination of each backedge. We don't rely 1736 // exclusively on the loop info here so that we can align backedges in 1737 // unnatural CFGs and backedges that were introduced purely because of the 1738 // loop rotations done during this layout pass. 1739 if (F->getFunction()->optForSize()) 1740 return; 1741 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 1742 if (FunctionChain.begin() == FunctionChain.end()) 1743 return; // Empty chain. 1744 1745 const BranchProbability ColdProb(1, 5); // 20% 1746 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 1747 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 1748 for (MachineBasicBlock *ChainBB : FunctionChain) { 1749 if (ChainBB == *FunctionChain.begin()) 1750 continue; 1751 1752 // Don't align non-looping basic blocks. These are unlikely to execute 1753 // enough times to matter in practice. Note that we'll still handle 1754 // unnatural CFGs inside of a natural outer loop (the common case) and 1755 // rotated loops. 1756 MachineLoop *L = MLI->getLoopFor(ChainBB); 1757 if (!L) 1758 continue; 1759 1760 unsigned Align = TLI->getPrefLoopAlignment(L); 1761 if (!Align) 1762 continue; // Don't care about loop alignment. 1763 1764 // If the block is cold relative to the function entry don't waste space 1765 // aligning it. 1766 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 1767 if (Freq < WeightedEntryFreq) 1768 continue; 1769 1770 // If the block is cold relative to its loop header, don't align it 1771 // regardless of what edges into the block exist. 1772 MachineBasicBlock *LoopHeader = L->getHeader(); 1773 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 1774 if (Freq < (LoopHeaderFreq * ColdProb)) 1775 continue; 1776 1777 // Check for the existence of a non-layout predecessor which would benefit 1778 // from aligning this block. 1779 MachineBasicBlock *LayoutPred = 1780 &*std::prev(MachineFunction::iterator(ChainBB)); 1781 1782 // Force alignment if all the predecessors are jumps. We already checked 1783 // that the block isn't cold above. 1784 if (!LayoutPred->isSuccessor(ChainBB)) { 1785 ChainBB->setAlignment(Align); 1786 continue; 1787 } 1788 1789 // Align this block if the layout predecessor's edge into this block is 1790 // cold relative to the block. When this is true, other predecessors make up 1791 // all of the hot entries into the block and thus alignment is likely to be 1792 // important. 1793 BranchProbability LayoutProb = 1794 MBPI->getEdgeProbability(LayoutPred, ChainBB); 1795 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 1796 if (LayoutEdgeFreq <= (Freq * ColdProb)) 1797 ChainBB->setAlignment(Align); 1798 } 1799 } 1800 1801 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 1802 /// it was duplicated into its chain predecessor and removed. 1803 /// \p BB - Basic block that may be duplicated. 1804 /// 1805 /// \p LPred - Chosen layout predecessor of \p BB. 1806 /// Updated to be the chain end if LPred is removed. 1807 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 1808 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 1809 /// Used to identify which blocks to update predecessor 1810 /// counts. 1811 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 1812 /// chosen in the given order due to unnatural CFG 1813 /// only needed if \p BB is removed and 1814 /// \p PrevUnplacedBlockIt pointed to \p BB. 1815 /// @return true if \p BB was removed. 1816 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 1817 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 1818 MachineBasicBlock *LoopHeaderBB, 1819 BlockChain &Chain, BlockFilterSet *BlockFilter, 1820 MachineFunction::iterator &PrevUnplacedBlockIt) { 1821 bool Removed, DuplicatedToLPred; 1822 bool DuplicatedToOriginalLPred; 1823 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, 1824 PrevUnplacedBlockIt, 1825 DuplicatedToLPred); 1826 if (!Removed) 1827 return false; 1828 DuplicatedToOriginalLPred = DuplicatedToLPred; 1829 // Iteratively try to duplicate again. It can happen that a block that is 1830 // duplicated into is still small enough to be duplicated again. 1831 // No need to call markBlockSuccessors in this case, as the blocks being 1832 // duplicated from here on are already scheduled. 1833 // Note that DuplicatedToLPred always implies Removed. 1834 while (DuplicatedToLPred) { 1835 assert (Removed && "Block must have been removed to be duplicated into its " 1836 "layout predecessor."); 1837 MachineBasicBlock *DupBB, *DupPred; 1838 // The removal callback causes Chain.end() to be updated when a block is 1839 // removed. On the first pass through the loop, the chain end should be the 1840 // same as it was on function entry. On subsequent passes, because we are 1841 // duplicating the block at the end of the chain, if it is removed the 1842 // chain will have shrunk by one block. 1843 BlockChain::iterator ChainEnd = Chain.end(); 1844 DupBB = *(--ChainEnd); 1845 // Now try to duplicate again. 1846 if (ChainEnd == Chain.begin()) 1847 break; 1848 DupPred = *std::prev(ChainEnd); 1849 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, 1850 PrevUnplacedBlockIt, 1851 DuplicatedToLPred); 1852 } 1853 // If BB was duplicated into LPred, it is now scheduled. But because it was 1854 // removed, markChainSuccessors won't be called for its chain. Instead we 1855 // call markBlockSuccessors for LPred to achieve the same effect. This must go 1856 // at the end because repeating the tail duplication can increase the number 1857 // of unscheduled predecessors. 1858 LPred = *std::prev(Chain.end()); 1859 if (DuplicatedToOriginalLPred) 1860 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 1861 return true; 1862 } 1863 1864 /// Tail duplicate \p BB into (some) predecessors if profitable. 1865 /// \p BB - Basic block that may be duplicated 1866 /// \p LPred - Chosen layout predecessor of \p BB 1867 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 1868 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 1869 /// Used to identify which blocks to update predecessor 1870 /// counts. 1871 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 1872 /// chosen in the given order due to unnatural CFG 1873 /// only needed if \p BB is removed and 1874 /// \p PrevUnplacedBlockIt pointed to \p BB. 1875 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will 1876 /// only be true if the block was removed. 1877 /// \return - True if the block was duplicated into all preds and removed. 1878 bool MachineBlockPlacement::maybeTailDuplicateBlock( 1879 MachineBasicBlock *BB, MachineBasicBlock *LPred, 1880 const BlockChain &Chain, BlockFilterSet *BlockFilter, 1881 MachineFunction::iterator &PrevUnplacedBlockIt, 1882 bool &DuplicatedToLPred) { 1883 1884 DuplicatedToLPred = false; 1885 DEBUG(dbgs() << "Redoing tail duplication for Succ#" 1886 << BB->getNumber() << "\n"); 1887 bool IsSimple = TailDup.isSimpleBB(BB); 1888 // Blocks with single successors don't create additional fallthrough 1889 // opportunities. Don't duplicate them. TODO: When conditional exits are 1890 // analyzable, allow them to be duplicated. 1891 if (!IsSimple && BB->succ_size() == 1) 1892 return false; 1893 if (!TailDup.shouldTailDuplicate(IsSimple, *BB)) 1894 return false; 1895 // This has to be a callback because none of it can be done after 1896 // BB is deleted. 1897 bool Removed = false; 1898 auto RemovalCallback = 1899 [&](MachineBasicBlock *RemBB) { 1900 // Signal to outer function 1901 Removed = true; 1902 1903 // Conservative default. 1904 bool InWorkList = true; 1905 // Remove from the Chain and Chain Map 1906 if (BlockToChain.count(RemBB)) { 1907 BlockChain *Chain = BlockToChain[RemBB]; 1908 InWorkList = Chain->UnscheduledPredecessors == 0; 1909 Chain->remove(RemBB); 1910 BlockToChain.erase(RemBB); 1911 } 1912 1913 // Handle the unplaced block iterator 1914 if (&(*PrevUnplacedBlockIt) == RemBB) { 1915 PrevUnplacedBlockIt++; 1916 } 1917 1918 // Handle the Work Lists 1919 if (InWorkList) { 1920 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 1921 if (RemBB->isEHPad()) 1922 RemoveList = EHPadWorkList; 1923 RemoveList.erase( 1924 remove_if(RemoveList, 1925 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}), 1926 RemoveList.end()); 1927 } 1928 1929 // Handle the filter set 1930 if (BlockFilter) { 1931 BlockFilter->erase(RemBB); 1932 } 1933 1934 // Remove the block from loop info. 1935 MLI->removeBlock(RemBB); 1936 if (RemBB == PreferredLoopExit) 1937 PreferredLoopExit = nullptr; 1938 1939 DEBUG(dbgs() << "TailDuplicator deleted block: " 1940 << getBlockName(RemBB) << "\n"); 1941 }; 1942 auto RemovalCallbackRef = 1943 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback); 1944 1945 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 1946 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, 1947 &DuplicatedPreds, &RemovalCallbackRef); 1948 1949 // Update UnscheduledPredecessors to reflect tail-duplication. 1950 DuplicatedToLPred = false; 1951 for (MachineBasicBlock *Pred : DuplicatedPreds) { 1952 // We're only looking for unscheduled predecessors that match the filter. 1953 BlockChain* PredChain = BlockToChain[Pred]; 1954 if (Pred == LPred) 1955 DuplicatedToLPred = true; 1956 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 1957 || PredChain == &Chain) 1958 continue; 1959 for (MachineBasicBlock *NewSucc : Pred->successors()) { 1960 if (BlockFilter && !BlockFilter->count(NewSucc)) 1961 continue; 1962 BlockChain *NewChain = BlockToChain[NewSucc]; 1963 if (NewChain != &Chain && NewChain != PredChain) 1964 NewChain->UnscheduledPredecessors++; 1965 } 1966 } 1967 return Removed; 1968 } 1969 1970 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 1971 if (skipFunction(*MF.getFunction())) 1972 return false; 1973 1974 // Check for single-block functions and skip them. 1975 if (std::next(MF.begin()) == MF.end()) 1976 return false; 1977 1978 F = &MF; 1979 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 1980 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>( 1981 getAnalysis<MachineBlockFrequencyInfo>()); 1982 MLI = &getAnalysis<MachineLoopInfo>(); 1983 TII = MF.getSubtarget().getInstrInfo(); 1984 TLI = MF.getSubtarget().getTargetLowering(); 1985 MDT = &getAnalysis<MachineDominatorTree>(); 1986 1987 // Initialize PreferredLoopExit to nullptr here since it may never be set if 1988 // there are no MachineLoops. 1989 PreferredLoopExit = nullptr; 1990 1991 if (TailDupPlacement) { 1992 unsigned TailDupSize = TailDuplicatePlacementThreshold; 1993 if (MF.getFunction()->optForSize()) 1994 TailDupSize = 1; 1995 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize); 1996 } 1997 1998 assert(BlockToChain.empty()); 1999 2000 buildCFGChains(); 2001 2002 // Changing the layout can create new tail merging opportunities. 2003 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 2004 // TailMerge can create jump into if branches that make CFG irreducible for 2005 // HW that requires structured CFG. 2006 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 2007 PassConfig->getEnableTailMerge() && 2008 BranchFoldPlacement; 2009 // No tail merging opportunities if the block number is less than four. 2010 if (MF.size() > 3 && EnableTailMerge) { 2011 unsigned TailMergeSize = TailDuplicatePlacementThreshold + 1; 2012 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI, 2013 *MBPI, TailMergeSize); 2014 2015 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), 2016 getAnalysisIfAvailable<MachineModuleInfo>(), MLI, 2017 /*AfterBlockPlacement=*/true)) { 2018 // Redo the layout if tail merging creates/removes/moves blocks. 2019 BlockToChain.clear(); 2020 // Must redo the dominator tree if blocks were changed. 2021 MDT->runOnMachineFunction(MF); 2022 ChainAllocator.DestroyAll(); 2023 buildCFGChains(); 2024 } 2025 } 2026 2027 optimizeBranches(); 2028 alignBlocks(); 2029 2030 BlockToChain.clear(); 2031 ChainAllocator.DestroyAll(); 2032 2033 if (AlignAllBlock) 2034 // Align all of the blocks in the function to a specific alignment. 2035 for (MachineBasicBlock &MBB : MF) 2036 MBB.setAlignment(AlignAllBlock); 2037 else if (AlignAllNonFallThruBlocks) { 2038 // Align all of the blocks that have no fall-through predecessors to a 2039 // specific alignment. 2040 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 2041 auto LayoutPred = std::prev(MBI); 2042 if (!LayoutPred->isSuccessor(&*MBI)) 2043 MBI->setAlignment(AlignAllNonFallThruBlocks); 2044 } 2045 } 2046 2047 // We always return true as we have no way to track whether the final order 2048 // differs from the original order. 2049 return true; 2050 } 2051 2052 namespace { 2053 /// \brief A pass to compute block placement statistics. 2054 /// 2055 /// A separate pass to compute interesting statistics for evaluating block 2056 /// placement. This is separate from the actual placement pass so that they can 2057 /// be computed in the absence of any placement transformations or when using 2058 /// alternative placement strategies. 2059 class MachineBlockPlacementStats : public MachineFunctionPass { 2060 /// \brief A handle to the branch probability pass. 2061 const MachineBranchProbabilityInfo *MBPI; 2062 2063 /// \brief A handle to the function-wide block frequency pass. 2064 const MachineBlockFrequencyInfo *MBFI; 2065 2066 public: 2067 static char ID; // Pass identification, replacement for typeid 2068 MachineBlockPlacementStats() : MachineFunctionPass(ID) { 2069 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 2070 } 2071 2072 bool runOnMachineFunction(MachineFunction &F) override; 2073 2074 void getAnalysisUsage(AnalysisUsage &AU) const override { 2075 AU.addRequired<MachineBranchProbabilityInfo>(); 2076 AU.addRequired<MachineBlockFrequencyInfo>(); 2077 AU.setPreservesAll(); 2078 MachineFunctionPass::getAnalysisUsage(AU); 2079 } 2080 }; 2081 } 2082 2083 char MachineBlockPlacementStats::ID = 0; 2084 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 2085 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 2086 "Basic Block Placement Stats", false, false) 2087 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 2088 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 2089 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 2090 "Basic Block Placement Stats", false, false) 2091 2092 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 2093 // Check for single-block functions and skip them. 2094 if (std::next(F.begin()) == F.end()) 2095 return false; 2096 2097 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 2098 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 2099 2100 for (MachineBasicBlock &MBB : F) { 2101 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 2102 Statistic &NumBranches = 2103 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 2104 Statistic &BranchTakenFreq = 2105 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 2106 for (MachineBasicBlock *Succ : MBB.successors()) { 2107 // Skip if this successor is a fallthrough. 2108 if (MBB.isLayoutSuccessor(Succ)) 2109 continue; 2110 2111 BlockFrequency EdgeFreq = 2112 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 2113 ++NumBranches; 2114 BranchTakenFreq += EdgeFreq.getFrequency(); 2115 } 2116 } 2117 2118 return false; 2119 } 2120