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