1 //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements basic block placement transformations using the CFG 10 // structure and branch probability estimates. 11 // 12 // The pass strives to preserve the structure of the CFG (that is, retain 13 // a topological ordering of basic blocks) in the absence of a *strong* signal 14 // to the contrary from probabilities. However, within the CFG structure, it 15 // attempts to choose an ordering which favors placing more likely sequences of 16 // blocks adjacent to each other. 17 // 18 // The algorithm works from the inner-most loop within a function outward, and 19 // at each stage walks through the basic blocks, trying to coalesce them into 20 // sequential chains where allowed by the CFG (or demanded by heavy 21 // probabilities). Finally, it walks the blocks in topological order, and the 22 // first time it reaches a chain of basic blocks, it schedules them in the 23 // function in-order. 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "BranchFolding.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SetVector.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 39 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineFunctionPass.h" 42 #include "llvm/CodeGen/MachineLoopInfo.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachinePostDominators.h" 45 #include "llvm/CodeGen/MachineSizeOpts.h" 46 #include "llvm/CodeGen/TailDuplicator.h" 47 #include "llvm/CodeGen/TargetInstrInfo.h" 48 #include "llvm/CodeGen/TargetLowering.h" 49 #include "llvm/CodeGen/TargetPassConfig.h" 50 #include "llvm/CodeGen/TargetSubtargetInfo.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/InitializePasses.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/Allocator.h" 56 #include "llvm/Support/BlockFrequency.h" 57 #include "llvm/Support/BranchProbability.h" 58 #include "llvm/Support/CodeGen.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Target/TargetMachine.h" 64 #include "llvm/Transforms/Utils/CodeLayout.h" 65 #include <algorithm> 66 #include <cassert> 67 #include <cstdint> 68 #include <iterator> 69 #include <memory> 70 #include <string> 71 #include <tuple> 72 #include <utility> 73 #include <vector> 74 75 using namespace llvm; 76 77 #define DEBUG_TYPE "block-placement" 78 79 STATISTIC(NumCondBranches, "Number of conditional branches"); 80 STATISTIC(NumUncondBranches, "Number of unconditional branches"); 81 STATISTIC(CondBranchTakenFreq, 82 "Potential frequency of taking conditional branches"); 83 STATISTIC(UncondBranchTakenFreq, 84 "Potential frequency of taking unconditional branches"); 85 86 static cl::opt<unsigned> AlignAllBlock( 87 "align-all-blocks", 88 cl::desc("Force the alignment of all blocks in the function in log2 format " 89 "(e.g 4 means align on 16B boundaries)."), 90 cl::init(0), cl::Hidden); 91 92 static cl::opt<unsigned> AlignAllNonFallThruBlocks( 93 "align-all-nofallthru-blocks", 94 cl::desc("Force the alignment of all blocks that have no fall-through " 95 "predecessors (i.e. don't add nops that are executed). In log2 " 96 "format (e.g 4 means align on 16B boundaries)."), 97 cl::init(0), cl::Hidden); 98 99 // FIXME: Find a good default for this flag and remove the flag. 100 static cl::opt<unsigned> ExitBlockBias( 101 "block-placement-exit-block-bias", 102 cl::desc("Block frequency percentage a loop exit block needs " 103 "over the original exit to be considered the new exit."), 104 cl::init(0), cl::Hidden); 105 106 // Definition: 107 // - Outlining: placement of a basic block outside the chain or hot path. 108 109 static cl::opt<unsigned> LoopToColdBlockRatio( 110 "loop-to-cold-block-ratio", 111 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " 112 "(frequency of block) is greater than this ratio"), 113 cl::init(5), cl::Hidden); 114 115 static cl::opt<bool> ForceLoopColdBlock( 116 "force-loop-cold-block", 117 cl::desc("Force outlining cold blocks from loops."), 118 cl::init(false), cl::Hidden); 119 120 static cl::opt<bool> 121 PreciseRotationCost("precise-rotation-cost", 122 cl::desc("Model the cost of loop rotation more " 123 "precisely by using profile data."), 124 cl::init(false), cl::Hidden); 125 126 static cl::opt<bool> 127 ForcePreciseRotationCost("force-precise-rotation-cost", 128 cl::desc("Force the use of precise cost " 129 "loop rotation strategy."), 130 cl::init(false), cl::Hidden); 131 132 static cl::opt<unsigned> MisfetchCost( 133 "misfetch-cost", 134 cl::desc("Cost that models the probabilistic risk of an instruction " 135 "misfetch due to a jump comparing to falling through, whose cost " 136 "is zero."), 137 cl::init(1), cl::Hidden); 138 139 static cl::opt<unsigned> JumpInstCost("jump-inst-cost", 140 cl::desc("Cost of jump instructions."), 141 cl::init(1), cl::Hidden); 142 static cl::opt<bool> 143 TailDupPlacement("tail-dup-placement", 144 cl::desc("Perform tail duplication during placement. " 145 "Creates more fallthrough opportunites in " 146 "outline branches."), 147 cl::init(true), cl::Hidden); 148 149 static cl::opt<bool> 150 BranchFoldPlacement("branch-fold-placement", 151 cl::desc("Perform branch folding during placement. " 152 "Reduces code size."), 153 cl::init(true), cl::Hidden); 154 155 // Heuristic for tail duplication. 156 static cl::opt<unsigned> TailDupPlacementThreshold( 157 "tail-dup-placement-threshold", 158 cl::desc("Instruction cutoff for tail duplication during layout. " 159 "Tail merging during layout is forced to have a threshold " 160 "that won't conflict."), cl::init(2), 161 cl::Hidden); 162 163 // Heuristic for aggressive tail duplication. 164 static cl::opt<unsigned> TailDupPlacementAggressiveThreshold( 165 "tail-dup-placement-aggressive-threshold", 166 cl::desc("Instruction cutoff for aggressive tail duplication during " 167 "layout. Used at -O3. Tail merging during layout is forced to " 168 "have a threshold that won't conflict."), cl::init(4), 169 cl::Hidden); 170 171 // Heuristic for tail duplication. 172 static cl::opt<unsigned> TailDupPlacementPenalty( 173 "tail-dup-placement-penalty", 174 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. " 175 "Copying can increase fallthrough, but it also increases icache " 176 "pressure. This parameter controls the penalty to account for that. " 177 "Percent as integer."), 178 cl::init(2), 179 cl::Hidden); 180 181 // Heuristic for tail duplication if profile count is used in cost model. 182 static cl::opt<unsigned> TailDupProfilePercentThreshold( 183 "tail-dup-profile-percent-threshold", 184 cl::desc("If profile count information is used in tail duplication cost " 185 "model, the gained fall through number from tail duplication " 186 "should be at least this percent of hot count."), 187 cl::init(50), cl::Hidden); 188 189 // Heuristic for triangle chains. 190 static cl::opt<unsigned> TriangleChainCount( 191 "triangle-chain-count", 192 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the " 193 "triangle tail duplication heuristic to kick in. 0 to disable."), 194 cl::init(2), 195 cl::Hidden); 196 197 static cl::opt<bool> EnableExtTspBlockPlacement( 198 "enable-ext-tsp-block-placement", cl::Hidden, cl::init(false), 199 cl::desc("Enable machine block placement based on the ext-tsp model, " 200 "optimizing I-cache utilization.")); 201 202 namespace llvm { 203 extern cl::opt<unsigned> StaticLikelyProb; 204 extern cl::opt<unsigned> ProfileLikelyProb; 205 206 // Internal option used to control BFI display only after MBP pass. 207 // Defined in CodeGen/MachineBlockFrequencyInfo.cpp: 208 // -view-block-layout-with-bfi= 209 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI; 210 211 // Command line option to specify the name of the function for CFG dump 212 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 213 extern cl::opt<std::string> ViewBlockFreqFuncName; 214 } // namespace llvm 215 216 namespace { 217 218 class BlockChain; 219 220 /// Type for our function-wide basic block -> block chain mapping. 221 using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>; 222 223 /// A chain of blocks which will be laid out contiguously. 224 /// 225 /// This is the datastructure representing a chain of consecutive blocks that 226 /// are profitable to layout together in order to maximize fallthrough 227 /// probabilities and code locality. We also can use a block chain to represent 228 /// a sequence of basic blocks which have some external (correctness) 229 /// requirement for sequential layout. 230 /// 231 /// Chains can be built around a single basic block and can be merged to grow 232 /// them. They participate in a block-to-chain mapping, which is updated 233 /// automatically as chains are merged together. 234 class BlockChain { 235 /// The sequence of blocks belonging to this chain. 236 /// 237 /// This is the sequence of blocks for a particular chain. These will be laid 238 /// out in-order within the function. 239 SmallVector<MachineBasicBlock *, 4> Blocks; 240 241 /// A handle to the function-wide basic block to block chain mapping. 242 /// 243 /// This is retained in each block chain to simplify the computation of child 244 /// block chains for SCC-formation and iteration. We store the edges to child 245 /// basic blocks, and map them back to their associated chains using this 246 /// structure. 247 BlockToChainMapType &BlockToChain; 248 249 public: 250 /// Construct a new BlockChain. 251 /// 252 /// This builds a new block chain representing a single basic block in the 253 /// function. It also registers itself as the chain that block participates 254 /// in with the BlockToChain mapping. 255 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 256 : Blocks(1, BB), BlockToChain(BlockToChain) { 257 assert(BB && "Cannot create a chain with a null basic block"); 258 BlockToChain[BB] = this; 259 } 260 261 /// Iterator over blocks within the chain. 262 using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator; 263 using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator; 264 265 /// Beginning of blocks within the chain. 266 iterator begin() { return Blocks.begin(); } 267 const_iterator begin() const { return Blocks.begin(); } 268 269 /// End of blocks within the chain. 270 iterator end() { return Blocks.end(); } 271 const_iterator end() const { return Blocks.end(); } 272 273 bool remove(MachineBasicBlock* BB) { 274 for(iterator i = begin(); i != end(); ++i) { 275 if (*i == BB) { 276 Blocks.erase(i); 277 return true; 278 } 279 } 280 return false; 281 } 282 283 /// Merge a block chain into this one. 284 /// 285 /// This routine merges a block chain into this one. It takes care of forming 286 /// a contiguous sequence of basic blocks, updating the edge list, and 287 /// updating the block -> chain mapping. It does not free or tear down the 288 /// old chain, but the old chain's block list is no longer valid. 289 void merge(MachineBasicBlock *BB, BlockChain *Chain) { 290 assert(BB && "Can't merge a null block."); 291 assert(!Blocks.empty() && "Can't merge into an empty chain."); 292 293 // Fast path in case we don't have a chain already. 294 if (!Chain) { 295 assert(!BlockToChain[BB] && 296 "Passed chain is null, but BB has entry in BlockToChain."); 297 Blocks.push_back(BB); 298 BlockToChain[BB] = this; 299 return; 300 } 301 302 assert(BB == *Chain->begin() && "Passed BB is not head of Chain."); 303 assert(Chain->begin() != Chain->end()); 304 305 // Update the incoming blocks to point to this chain, and add them to the 306 // chain structure. 307 for (MachineBasicBlock *ChainBB : *Chain) { 308 Blocks.push_back(ChainBB); 309 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain."); 310 BlockToChain[ChainBB] = this; 311 } 312 } 313 314 #ifndef NDEBUG 315 /// Dump the blocks in this chain. 316 LLVM_DUMP_METHOD void dump() { 317 for (MachineBasicBlock *MBB : *this) 318 MBB->dump(); 319 } 320 #endif // NDEBUG 321 322 /// Count of predecessors of any block within the chain which have not 323 /// yet been scheduled. In general, we will delay scheduling this chain 324 /// until those predecessors are scheduled (or we find a sufficiently good 325 /// reason to override this heuristic.) Note that when forming loop chains, 326 /// blocks outside the loop are ignored and treated as if they were already 327 /// scheduled. 328 /// 329 /// Note: This field is reinitialized multiple times - once for each loop, 330 /// and then once for the function as a whole. 331 unsigned UnscheduledPredecessors = 0; 332 }; 333 334 class MachineBlockPlacement : public MachineFunctionPass { 335 /// A type for a block filter set. 336 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>; 337 338 /// Pair struct containing basic block and taildup profitability 339 struct BlockAndTailDupResult { 340 MachineBasicBlock *BB; 341 bool ShouldTailDup; 342 }; 343 344 /// Triple struct containing edge weight and the edge. 345 struct WeightedEdge { 346 BlockFrequency Weight; 347 MachineBasicBlock *Src; 348 MachineBasicBlock *Dest; 349 }; 350 351 /// work lists of blocks that are ready to be laid out 352 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 353 SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 354 355 /// Edges that have already been computed as optimal. 356 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges; 357 358 /// Machine Function 359 MachineFunction *F; 360 361 /// A handle to the branch probability pass. 362 const MachineBranchProbabilityInfo *MBPI; 363 364 /// A handle to the function-wide block frequency pass. 365 std::unique_ptr<MBFIWrapper> MBFI; 366 367 /// A handle to the loop info. 368 MachineLoopInfo *MLI; 369 370 /// Preferred loop exit. 371 /// Member variable for convenience. It may be removed by duplication deep 372 /// in the call stack. 373 MachineBasicBlock *PreferredLoopExit; 374 375 /// A handle to the target's instruction info. 376 const TargetInstrInfo *TII; 377 378 /// A handle to the target's lowering info. 379 const TargetLoweringBase *TLI; 380 381 /// A handle to the post dominator tree. 382 MachinePostDominatorTree *MPDT; 383 384 ProfileSummaryInfo *PSI; 385 386 /// Duplicator used to duplicate tails during placement. 387 /// 388 /// Placement decisions can open up new tail duplication opportunities, but 389 /// since tail duplication affects placement decisions of later blocks, it 390 /// must be done inline. 391 TailDuplicator TailDup; 392 393 /// Partial tail duplication threshold. 394 BlockFrequency DupThreshold; 395 396 /// True: use block profile count to compute tail duplication cost. 397 /// False: use block frequency to compute tail duplication cost. 398 bool UseProfileCount; 399 400 /// Allocator and owner of BlockChain structures. 401 /// 402 /// We build BlockChains lazily while processing the loop structure of 403 /// a function. To reduce malloc traffic, we allocate them using this 404 /// slab-like allocator, and destroy them after the pass completes. An 405 /// important guarantee is that this allocator produces stable pointers to 406 /// the chains. 407 SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 408 409 /// Function wide BasicBlock to BlockChain mapping. 410 /// 411 /// This mapping allows efficiently moving from any given basic block to the 412 /// BlockChain it participates in, if any. We use it to, among other things, 413 /// allow implicitly defining edges between chains as the existing edges 414 /// between basic blocks. 415 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain; 416 417 #ifndef NDEBUG 418 /// The set of basic blocks that have terminators that cannot be fully 419 /// analyzed. These basic blocks cannot be re-ordered safely by 420 /// MachineBlockPlacement, and we must preserve physical layout of these 421 /// blocks and their successors through the pass. 422 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits; 423 #endif 424 425 /// Get block profile count or frequency according to UseProfileCount. 426 /// The return value is used to model tail duplication cost. 427 BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) { 428 if (UseProfileCount) { 429 auto Count = MBFI->getBlockProfileCount(BB); 430 if (Count) 431 return *Count; 432 else 433 return 0; 434 } else 435 return MBFI->getBlockFreq(BB); 436 } 437 438 /// Scale the DupThreshold according to basic block size. 439 BlockFrequency scaleThreshold(MachineBasicBlock *BB); 440 void initDupThreshold(); 441 442 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 443 /// if the count goes to 0, add them to the appropriate work list. 444 void markChainSuccessors( 445 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 446 const BlockFilterSet *BlockFilter = nullptr); 447 448 /// Decrease the UnscheduledPredecessors count for a single block, and 449 /// if the count goes to 0, add them to the appropriate work list. 450 void markBlockSuccessors( 451 const BlockChain &Chain, const MachineBasicBlock *BB, 452 const MachineBasicBlock *LoopHeaderBB, 453 const BlockFilterSet *BlockFilter = nullptr); 454 455 BranchProbability 456 collectViableSuccessors( 457 const MachineBasicBlock *BB, const BlockChain &Chain, 458 const BlockFilterSet *BlockFilter, 459 SmallVector<MachineBasicBlock *, 4> &Successors); 460 bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred, 461 BlockFilterSet *BlockFilter); 462 void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates, 463 MachineBasicBlock *BB, 464 BlockFilterSet *BlockFilter); 465 bool repeatedlyTailDuplicateBlock( 466 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 467 const MachineBasicBlock *LoopHeaderBB, 468 BlockChain &Chain, BlockFilterSet *BlockFilter, 469 MachineFunction::iterator &PrevUnplacedBlockIt); 470 bool maybeTailDuplicateBlock( 471 MachineBasicBlock *BB, MachineBasicBlock *LPred, 472 BlockChain &Chain, BlockFilterSet *BlockFilter, 473 MachineFunction::iterator &PrevUnplacedBlockIt, 474 bool &DuplicatedToLPred); 475 bool hasBetterLayoutPredecessor( 476 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 477 const BlockChain &SuccChain, BranchProbability SuccProb, 478 BranchProbability RealSuccProb, const BlockChain &Chain, 479 const BlockFilterSet *BlockFilter); 480 BlockAndTailDupResult selectBestSuccessor( 481 const MachineBasicBlock *BB, const BlockChain &Chain, 482 const BlockFilterSet *BlockFilter); 483 MachineBasicBlock *selectBestCandidateBlock( 484 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList); 485 MachineBasicBlock *getFirstUnplacedBlock( 486 const BlockChain &PlacedChain, 487 MachineFunction::iterator &PrevUnplacedBlockIt, 488 const BlockFilterSet *BlockFilter); 489 490 /// Add a basic block to the work list if it is appropriate. 491 /// 492 /// If the optional parameter BlockFilter is provided, only MBB 493 /// present in the set will be added to the worklist. If nullptr 494 /// is provided, no filtering occurs. 495 void fillWorkLists(const MachineBasicBlock *MBB, 496 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 497 const BlockFilterSet *BlockFilter); 498 499 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain, 500 BlockFilterSet *BlockFilter = nullptr); 501 bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock, 502 const MachineBasicBlock *OldTop); 503 bool hasViableTopFallthrough(const MachineBasicBlock *Top, 504 const BlockFilterSet &LoopBlockSet); 505 BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top, 506 const BlockFilterSet &LoopBlockSet); 507 BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop, 508 const MachineBasicBlock *OldTop, 509 const MachineBasicBlock *ExitBB, 510 const BlockFilterSet &LoopBlockSet); 511 MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop, 512 const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 513 MachineBasicBlock *findBestLoopTop( 514 const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 515 MachineBasicBlock *findBestLoopExit( 516 const MachineLoop &L, const BlockFilterSet &LoopBlockSet, 517 BlockFrequency &ExitFreq); 518 BlockFilterSet collectLoopBlockSet(const MachineLoop &L); 519 void buildLoopChains(const MachineLoop &L); 520 void rotateLoop( 521 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB, 522 BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet); 523 void rotateLoopWithProfile( 524 BlockChain &LoopChain, const MachineLoop &L, 525 const BlockFilterSet &LoopBlockSet); 526 void buildCFGChains(); 527 void optimizeBranches(); 528 void alignBlocks(); 529 /// Returns true if a block should be tail-duplicated to increase fallthrough 530 /// opportunities. 531 bool shouldTailDuplicate(MachineBasicBlock *BB); 532 /// Check the edge frequencies to see if tail duplication will increase 533 /// fallthroughs. 534 bool isProfitableToTailDup( 535 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 536 BranchProbability QProb, 537 const BlockChain &Chain, const BlockFilterSet *BlockFilter); 538 539 /// Check for a trellis layout. 540 bool isTrellis(const MachineBasicBlock *BB, 541 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 542 const BlockChain &Chain, const BlockFilterSet *BlockFilter); 543 544 /// Get the best successor given a trellis layout. 545 BlockAndTailDupResult getBestTrellisSuccessor( 546 const MachineBasicBlock *BB, 547 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 548 BranchProbability AdjustedSumProb, const BlockChain &Chain, 549 const BlockFilterSet *BlockFilter); 550 551 /// Get the best pair of non-conflicting edges. 552 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges( 553 const MachineBasicBlock *BB, 554 MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges); 555 556 /// Returns true if a block can tail duplicate into all unplaced 557 /// predecessors. Filters based on loop. 558 bool canTailDuplicateUnplacedPreds( 559 const MachineBasicBlock *BB, MachineBasicBlock *Succ, 560 const BlockChain &Chain, const BlockFilterSet *BlockFilter); 561 562 /// Find chains of triangles to tail-duplicate where a global analysis works, 563 /// but a local analysis would not find them. 564 void precomputeTriangleChains(); 565 566 /// Apply a post-processing step optimizing block placement. 567 void applyExtTsp(); 568 569 /// Modify the existing block placement in the function and adjust all jumps. 570 void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder); 571 572 /// Create a single CFG chain from the current block order. 573 void createCFGChainExtTsp(); 574 575 public: 576 static char ID; // Pass identification, replacement for typeid 577 578 MachineBlockPlacement() : MachineFunctionPass(ID) { 579 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 580 } 581 582 bool runOnMachineFunction(MachineFunction &F) override; 583 584 bool allowTailDupPlacement() const { 585 assert(F); 586 return TailDupPlacement && !F->getTarget().requiresStructuredCFG(); 587 } 588 589 void getAnalysisUsage(AnalysisUsage &AU) const override { 590 AU.addRequired<MachineBranchProbabilityInfo>(); 591 AU.addRequired<MachineBlockFrequencyInfo>(); 592 if (TailDupPlacement) 593 AU.addRequired<MachinePostDominatorTree>(); 594 AU.addRequired<MachineLoopInfo>(); 595 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 596 AU.addRequired<TargetPassConfig>(); 597 MachineFunctionPass::getAnalysisUsage(AU); 598 } 599 }; 600 601 } // end anonymous namespace 602 603 char MachineBlockPlacement::ID = 0; 604 605 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 606 607 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE, 608 "Branch Probability Basic Block Placement", false, false) 609 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 610 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 611 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 612 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 613 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 614 INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE, 615 "Branch Probability Basic Block Placement", false, false) 616 617 #ifndef NDEBUG 618 /// Helper to print the name of a MBB. 619 /// 620 /// Only used by debug logging. 621 static std::string getBlockName(const MachineBasicBlock *BB) { 622 std::string Result; 623 raw_string_ostream OS(Result); 624 OS << printMBBReference(*BB); 625 OS << " ('" << BB->getName() << "')"; 626 OS.flush(); 627 return Result; 628 } 629 #endif 630 631 /// Mark a chain's successors as having one fewer preds. 632 /// 633 /// When a chain is being merged into the "placed" chain, this routine will 634 /// quickly walk the successors of each block in the chain and mark them as 635 /// having one fewer active predecessor. It also adds any successors of this 636 /// chain which reach the zero-predecessor state to the appropriate worklist. 637 void MachineBlockPlacement::markChainSuccessors( 638 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 639 const BlockFilterSet *BlockFilter) { 640 // Walk all the blocks in this chain, marking their successors as having 641 // a predecessor placed. 642 for (MachineBasicBlock *MBB : Chain) { 643 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 644 } 645 } 646 647 /// Mark a single block's successors as having one fewer preds. 648 /// 649 /// Under normal circumstances, this is only called by markChainSuccessors, 650 /// but if a block that was to be placed is completely tail-duplicated away, 651 /// and was duplicated into the chain end, we need to redo markBlockSuccessors 652 /// for just that block. 653 void MachineBlockPlacement::markBlockSuccessors( 654 const BlockChain &Chain, const MachineBasicBlock *MBB, 655 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) { 656 // Add any successors for which this is the only un-placed in-loop 657 // predecessor to the worklist as a viable candidate for CFG-neutral 658 // placement. No subsequent placement of this block will violate the CFG 659 // shape, so we get to use heuristics to choose a favorable placement. 660 for (MachineBasicBlock *Succ : MBB->successors()) { 661 if (BlockFilter && !BlockFilter->count(Succ)) 662 continue; 663 BlockChain &SuccChain = *BlockToChain[Succ]; 664 // Disregard edges within a fixed chain, or edges to the loop header. 665 if (&Chain == &SuccChain || Succ == LoopHeaderBB) 666 continue; 667 668 // This is a cross-chain edge that is within the loop, so decrement the 669 // loop predecessor count of the destination chain. 670 if (SuccChain.UnscheduledPredecessors == 0 || 671 --SuccChain.UnscheduledPredecessors > 0) 672 continue; 673 674 auto *NewBB = *SuccChain.begin(); 675 if (NewBB->isEHPad()) 676 EHPadWorkList.push_back(NewBB); 677 else 678 BlockWorkList.push_back(NewBB); 679 } 680 } 681 682 /// This helper function collects the set of successors of block 683 /// \p BB that are allowed to be its layout successors, and return 684 /// the total branch probability of edges from \p BB to those 685 /// blocks. 686 BranchProbability MachineBlockPlacement::collectViableSuccessors( 687 const MachineBasicBlock *BB, const BlockChain &Chain, 688 const BlockFilterSet *BlockFilter, 689 SmallVector<MachineBasicBlock *, 4> &Successors) { 690 // Adjust edge probabilities by excluding edges pointing to blocks that is 691 // either not in BlockFilter or is already in the current chain. Consider the 692 // following CFG: 693 // 694 // --->A 695 // | / \ 696 // | B C 697 // | \ / \ 698 // ----D E 699 // 700 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 701 // A->C is chosen as a fall-through, D won't be selected as a successor of C 702 // due to CFG constraint (the probability of C->D is not greater than 703 // HotProb to break topo-order). If we exclude E that is not in BlockFilter 704 // when calculating the probability of C->D, D will be selected and we 705 // will get A C D B as the layout of this loop. 706 auto AdjustedSumProb = BranchProbability::getOne(); 707 for (MachineBasicBlock *Succ : BB->successors()) { 708 bool SkipSucc = false; 709 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 710 SkipSucc = true; 711 } else { 712 BlockChain *SuccChain = BlockToChain[Succ]; 713 if (SuccChain == &Chain) { 714 SkipSucc = true; 715 } else if (Succ != *SuccChain->begin()) { 716 LLVM_DEBUG(dbgs() << " " << getBlockName(Succ) 717 << " -> Mid chain!\n"); 718 continue; 719 } 720 } 721 if (SkipSucc) 722 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 723 else 724 Successors.push_back(Succ); 725 } 726 727 return AdjustedSumProb; 728 } 729 730 /// The helper function returns the branch probability that is adjusted 731 /// or normalized over the new total \p AdjustedSumProb. 732 static BranchProbability 733 getAdjustedProbability(BranchProbability OrigProb, 734 BranchProbability AdjustedSumProb) { 735 BranchProbability SuccProb; 736 uint32_t SuccProbN = OrigProb.getNumerator(); 737 uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 738 if (SuccProbN >= SuccProbD) 739 SuccProb = BranchProbability::getOne(); 740 else 741 SuccProb = BranchProbability(SuccProbN, SuccProbD); 742 743 return SuccProb; 744 } 745 746 /// Check if \p BB has exactly the successors in \p Successors. 747 static bool 748 hasSameSuccessors(MachineBasicBlock &BB, 749 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) { 750 if (BB.succ_size() != Successors.size()) 751 return false; 752 // We don't want to count self-loops 753 if (Successors.count(&BB)) 754 return false; 755 for (MachineBasicBlock *Succ : BB.successors()) 756 if (!Successors.count(Succ)) 757 return false; 758 return true; 759 } 760 761 /// Check if a block should be tail duplicated to increase fallthrough 762 /// opportunities. 763 /// \p BB Block to check. 764 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) { 765 // Blocks with single successors don't create additional fallthrough 766 // opportunities. Don't duplicate them. TODO: When conditional exits are 767 // analyzable, allow them to be duplicated. 768 bool IsSimple = TailDup.isSimpleBB(BB); 769 770 if (BB->succ_size() == 1) 771 return false; 772 return TailDup.shouldTailDuplicate(IsSimple, *BB); 773 } 774 775 /// Compare 2 BlockFrequency's with a small penalty for \p A. 776 /// In order to be conservative, we apply a X% penalty to account for 777 /// increased icache pressure and static heuristics. For small frequencies 778 /// we use only the numerators to improve accuracy. For simplicity, we assume the 779 /// penalty is less than 100% 780 /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere. 781 static bool greaterWithBias(BlockFrequency A, BlockFrequency B, 782 uint64_t EntryFreq) { 783 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 784 BlockFrequency Gain = A - B; 785 return (Gain / ThresholdProb).getFrequency() >= EntryFreq; 786 } 787 788 /// Check the edge frequencies to see if tail duplication will increase 789 /// fallthroughs. It only makes sense to call this function when 790 /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is 791 /// always locally profitable if we would have picked \p Succ without 792 /// considering duplication. 793 bool MachineBlockPlacement::isProfitableToTailDup( 794 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 795 BranchProbability QProb, 796 const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 797 // We need to do a probability calculation to make sure this is profitable. 798 // First: does succ have a successor that post-dominates? This affects the 799 // calculation. The 2 relevant cases are: 800 // BB BB 801 // | \Qout | \Qout 802 // P| C |P C 803 // = C' = C' 804 // | /Qin | /Qin 805 // | / | / 806 // Succ Succ 807 // / \ | \ V 808 // U/ =V |U \ 809 // / \ = D 810 // D E | / 811 // | / 812 // |/ 813 // PDom 814 // '=' : Branch taken for that CFG edge 815 // In the second case, Placing Succ while duplicating it into C prevents the 816 // fallthrough of Succ into either D or PDom, because they now have C as an 817 // unplaced predecessor 818 819 // Start by figuring out which case we fall into 820 MachineBasicBlock *PDom = nullptr; 821 SmallVector<MachineBasicBlock *, 4> SuccSuccs; 822 // Only scan the relevant successors 823 auto AdjustedSuccSumProb = 824 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs); 825 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ); 826 auto BBFreq = MBFI->getBlockFreq(BB); 827 auto SuccFreq = MBFI->getBlockFreq(Succ); 828 BlockFrequency P = BBFreq * PProb; 829 BlockFrequency Qout = BBFreq * QProb; 830 uint64_t EntryFreq = MBFI->getEntryFreq(); 831 // If there are no more successors, it is profitable to copy, as it strictly 832 // increases fallthrough. 833 if (SuccSuccs.size() == 0) 834 return greaterWithBias(P, Qout, EntryFreq); 835 836 auto BestSuccSucc = BranchProbability::getZero(); 837 // Find the PDom or the best Succ if no PDom exists. 838 for (MachineBasicBlock *SuccSucc : SuccSuccs) { 839 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc); 840 if (Prob > BestSuccSucc) 841 BestSuccSucc = Prob; 842 if (PDom == nullptr) 843 if (MPDT->dominates(SuccSucc, Succ)) { 844 PDom = SuccSucc; 845 break; 846 } 847 } 848 // For the comparisons, we need to know Succ's best incoming edge that isn't 849 // from BB. 850 auto SuccBestPred = BlockFrequency(0); 851 for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 852 if (SuccPred == Succ || SuccPred == BB 853 || BlockToChain[SuccPred] == &Chain 854 || (BlockFilter && !BlockFilter->count(SuccPred))) 855 continue; 856 auto Freq = MBFI->getBlockFreq(SuccPred) 857 * MBPI->getEdgeProbability(SuccPred, Succ); 858 if (Freq > SuccBestPred) 859 SuccBestPred = Freq; 860 } 861 // Qin is Succ's best unplaced incoming edge that isn't BB 862 BlockFrequency Qin = SuccBestPred; 863 // If it doesn't have a post-dominating successor, here is the calculation: 864 // BB BB 865 // | \Qout | \ 866 // P| C | = 867 // = C' | C 868 // | /Qin | | 869 // | / | C' (+Succ) 870 // Succ Succ /| 871 // / \ | \/ | 872 // U/ =V | == | 873 // / \ | / \| 874 // D E D E 875 // '=' : Branch taken for that CFG edge 876 // Cost in the first case is: P + V 877 // For this calculation, we always assume P > Qout. If Qout > P 878 // The result of this function will be ignored at the caller. 879 // Let F = SuccFreq - Qin 880 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V 881 882 if (PDom == nullptr || !Succ->isSuccessor(PDom)) { 883 BranchProbability UProb = BestSuccSucc; 884 BranchProbability VProb = AdjustedSuccSumProb - UProb; 885 BlockFrequency F = SuccFreq - Qin; 886 BlockFrequency V = SuccFreq * VProb; 887 BlockFrequency QinU = std::min(Qin, F) * UProb; 888 BlockFrequency BaseCost = P + V; 889 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb; 890 return greaterWithBias(BaseCost, DupCost, EntryFreq); 891 } 892 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom); 893 BranchProbability VProb = AdjustedSuccSumProb - UProb; 894 BlockFrequency U = SuccFreq * UProb; 895 BlockFrequency V = SuccFreq * VProb; 896 BlockFrequency F = SuccFreq - Qin; 897 // If there is a post-dominating successor, here is the calculation: 898 // BB BB BB BB 899 // | \Qout | \ | \Qout | \ 900 // |P C | = |P C | = 901 // = C' |P C = C' |P C 902 // | /Qin | | | /Qin | | 903 // | / | C' (+Succ) | / | C' (+Succ) 904 // Succ Succ /| Succ Succ /| 905 // | \ V | \/ | | \ V | \/ | 906 // |U \ |U /\ =? |U = |U /\ | 907 // = D = = =?| | D | = =| 908 // | / |/ D | / |/ D 909 // | / | / | = | / 910 // |/ | / |/ | = 911 // Dom Dom Dom Dom 912 // '=' : Branch taken for that CFG edge 913 // The cost for taken branches in the first case is P + U 914 // Let F = SuccFreq - Qin 915 // The cost in the second case (assuming independence), given the layout: 916 // BB, Succ, (C+Succ), D, Dom or the layout: 917 // BB, Succ, D, Dom, (C+Succ) 918 // is Qout + max(F, Qin) * U + min(F, Qin) 919 // compare P + U vs Qout + P * U + Qin. 920 // 921 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ. 922 // 923 // For the 3rd case, the cost is P + 2 * V 924 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V 925 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V 926 if (UProb > AdjustedSuccSumProb / 2 && 927 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb, 928 Chain, BlockFilter)) 929 // Cases 3 & 4 930 return greaterWithBias( 931 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb), 932 EntryFreq); 933 // Cases 1 & 2 934 return greaterWithBias((P + U), 935 (Qout + std::min(Qin, F) * AdjustedSuccSumProb + 936 std::max(Qin, F) * UProb), 937 EntryFreq); 938 } 939 940 /// Check for a trellis layout. \p BB is the upper part of a trellis if its 941 /// successors form the lower part of a trellis. A successor set S forms the 942 /// lower part of a trellis if all of the predecessors of S are either in S or 943 /// have all of S as successors. We ignore trellises where BB doesn't have 2 944 /// successors because for fewer than 2, it's trivial, and for 3 or greater they 945 /// are very uncommon and complex to compute optimally. Allowing edges within S 946 /// is not strictly a trellis, but the same algorithm works, so we allow it. 947 bool MachineBlockPlacement::isTrellis( 948 const MachineBasicBlock *BB, 949 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 950 const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 951 // Technically BB could form a trellis with branching factor higher than 2. 952 // But that's extremely uncommon. 953 if (BB->succ_size() != 2 || ViableSuccs.size() != 2) 954 return false; 955 956 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(), 957 BB->succ_end()); 958 // To avoid reviewing the same predecessors twice. 959 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds; 960 961 for (MachineBasicBlock *Succ : ViableSuccs) { 962 int PredCount = 0; 963 for (auto SuccPred : Succ->predecessors()) { 964 // Allow triangle successors, but don't count them. 965 if (Successors.count(SuccPred)) { 966 // Make sure that it is actually a triangle. 967 for (MachineBasicBlock *CheckSucc : SuccPred->successors()) 968 if (!Successors.count(CheckSucc)) 969 return false; 970 continue; 971 } 972 const BlockChain *PredChain = BlockToChain[SuccPred]; 973 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) || 974 PredChain == &Chain || PredChain == BlockToChain[Succ]) 975 continue; 976 ++PredCount; 977 // Perform the successor check only once. 978 if (!SeenPreds.insert(SuccPred).second) 979 continue; 980 if (!hasSameSuccessors(*SuccPred, Successors)) 981 return false; 982 } 983 // If one of the successors has only BB as a predecessor, it is not a 984 // trellis. 985 if (PredCount < 1) 986 return false; 987 } 988 return true; 989 } 990 991 /// Pick the highest total weight pair of edges that can both be laid out. 992 /// The edges in \p Edges[0] are assumed to have a different destination than 993 /// the edges in \p Edges[1]. Simple counting shows that the best pair is either 994 /// the individual highest weight edges to the 2 different destinations, or in 995 /// case of a conflict, one of them should be replaced with a 2nd best edge. 996 std::pair<MachineBlockPlacement::WeightedEdge, 997 MachineBlockPlacement::WeightedEdge> 998 MachineBlockPlacement::getBestNonConflictingEdges( 999 const MachineBasicBlock *BB, 1000 MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>> 1001 Edges) { 1002 // Sort the edges, and then for each successor, find the best incoming 1003 // predecessor. If the best incoming predecessors aren't the same, 1004 // then that is clearly the best layout. If there is a conflict, one of the 1005 // successors will have to fallthrough from the second best predecessor. We 1006 // compare which combination is better overall. 1007 1008 // Sort for highest frequency. 1009 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; }; 1010 1011 llvm::stable_sort(Edges[0], Cmp); 1012 llvm::stable_sort(Edges[1], Cmp); 1013 auto BestA = Edges[0].begin(); 1014 auto BestB = Edges[1].begin(); 1015 // Arrange for the correct answer to be in BestA and BestB 1016 // If the 2 best edges don't conflict, the answer is already there. 1017 if (BestA->Src == BestB->Src) { 1018 // Compare the total fallthrough of (Best + Second Best) for both pairs 1019 auto SecondBestA = std::next(BestA); 1020 auto SecondBestB = std::next(BestB); 1021 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight; 1022 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight; 1023 if (BestAScore < BestBScore) 1024 BestA = SecondBestA; 1025 else 1026 BestB = SecondBestB; 1027 } 1028 // Arrange for the BB edge to be in BestA if it exists. 1029 if (BestB->Src == BB) 1030 std::swap(BestA, BestB); 1031 return std::make_pair(*BestA, *BestB); 1032 } 1033 1034 /// Get the best successor from \p BB based on \p BB being part of a trellis. 1035 /// We only handle trellises with 2 successors, so the algorithm is 1036 /// straightforward: Find the best pair of edges that don't conflict. We find 1037 /// the best incoming edge for each successor in the trellis. If those conflict, 1038 /// we consider which of them should be replaced with the second best. 1039 /// Upon return the two best edges will be in \p BestEdges. If one of the edges 1040 /// comes from \p BB, it will be in \p BestEdges[0] 1041 MachineBlockPlacement::BlockAndTailDupResult 1042 MachineBlockPlacement::getBestTrellisSuccessor( 1043 const MachineBasicBlock *BB, 1044 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 1045 BranchProbability AdjustedSumProb, const BlockChain &Chain, 1046 const BlockFilterSet *BlockFilter) { 1047 1048 BlockAndTailDupResult Result = {nullptr, false}; 1049 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 1050 BB->succ_end()); 1051 1052 // We assume size 2 because it's common. For general n, we would have to do 1053 // the Hungarian algorithm, but it's not worth the complexity because more 1054 // than 2 successors is fairly uncommon, and a trellis even more so. 1055 if (Successors.size() != 2 || ViableSuccs.size() != 2) 1056 return Result; 1057 1058 // Collect the edge frequencies of all edges that form the trellis. 1059 SmallVector<WeightedEdge, 8> Edges[2]; 1060 int SuccIndex = 0; 1061 for (auto Succ : ViableSuccs) { 1062 for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 1063 // Skip any placed predecessors that are not BB 1064 if (SuccPred != BB) 1065 if ((BlockFilter && !BlockFilter->count(SuccPred)) || 1066 BlockToChain[SuccPred] == &Chain || 1067 BlockToChain[SuccPred] == BlockToChain[Succ]) 1068 continue; 1069 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) * 1070 MBPI->getEdgeProbability(SuccPred, Succ); 1071 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ}); 1072 } 1073 ++SuccIndex; 1074 } 1075 1076 // Pick the best combination of 2 edges from all the edges in the trellis. 1077 WeightedEdge BestA, BestB; 1078 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges); 1079 1080 if (BestA.Src != BB) { 1081 // If we have a trellis, and BB doesn't have the best fallthrough edges, 1082 // we shouldn't choose any successor. We've already looked and there's a 1083 // better fallthrough edge for all the successors. 1084 LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n"); 1085 return Result; 1086 } 1087 1088 // Did we pick the triangle edge? If tail-duplication is profitable, do 1089 // that instead. Otherwise merge the triangle edge now while we know it is 1090 // optimal. 1091 if (BestA.Dest == BestB.Src) { 1092 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2 1093 // would be better. 1094 MachineBasicBlock *Succ1 = BestA.Dest; 1095 MachineBasicBlock *Succ2 = BestB.Dest; 1096 // Check to see if tail-duplication would be profitable. 1097 if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) && 1098 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) && 1099 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1), 1100 Chain, BlockFilter)) { 1101 LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability( 1102 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb); 1103 dbgs() << " Selected: " << getBlockName(Succ2) 1104 << ", probability: " << Succ2Prob 1105 << " (Tail Duplicate)\n"); 1106 Result.BB = Succ2; 1107 Result.ShouldTailDup = true; 1108 return Result; 1109 } 1110 } 1111 // We have already computed the optimal edge for the other side of the 1112 // trellis. 1113 ComputedEdges[BestB.Src] = { BestB.Dest, false }; 1114 1115 auto TrellisSucc = BestA.Dest; 1116 LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability( 1117 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb); 1118 dbgs() << " Selected: " << getBlockName(TrellisSucc) 1119 << ", probability: " << SuccProb << " (Trellis)\n"); 1120 Result.BB = TrellisSucc; 1121 return Result; 1122 } 1123 1124 /// When the option allowTailDupPlacement() is on, this method checks if the 1125 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated 1126 /// into all of its unplaced, unfiltered predecessors, that are not BB. 1127 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds( 1128 const MachineBasicBlock *BB, MachineBasicBlock *Succ, 1129 const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 1130 if (!shouldTailDuplicate(Succ)) 1131 return false; 1132 1133 // The result of canTailDuplicate. 1134 bool Duplicate = true; 1135 // Number of possible duplication. 1136 unsigned int NumDup = 0; 1137 1138 // For CFG checking. 1139 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 1140 BB->succ_end()); 1141 for (MachineBasicBlock *Pred : Succ->predecessors()) { 1142 // Make sure all unplaced and unfiltered predecessors can be 1143 // tail-duplicated into. 1144 // Skip any blocks that are already placed or not in this loop. 1145 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) 1146 || BlockToChain[Pred] == &Chain) 1147 continue; 1148 if (!TailDup.canTailDuplicate(Succ, Pred)) { 1149 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors)) 1150 // This will result in a trellis after tail duplication, so we don't 1151 // need to copy Succ into this predecessor. In the presence 1152 // of a trellis tail duplication can continue to be profitable. 1153 // For example: 1154 // A A 1155 // |\ |\ 1156 // | \ | \ 1157 // | C | C+BB 1158 // | / | | 1159 // |/ | | 1160 // BB => BB | 1161 // |\ |\/| 1162 // | \ |/\| 1163 // | D | D 1164 // | / | / 1165 // |/ |/ 1166 // Succ Succ 1167 // 1168 // After BB was duplicated into C, the layout looks like the one on the 1169 // right. BB and C now have the same successors. When considering 1170 // whether Succ can be duplicated into all its unplaced predecessors, we 1171 // ignore C. 1172 // We can do this because C already has a profitable fallthrough, namely 1173 // D. TODO(iteratee): ignore sufficiently cold predecessors for 1174 // duplication and for this test. 1175 // 1176 // This allows trellises to be laid out in 2 separate chains 1177 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic 1178 // because it allows the creation of 2 fallthrough paths with links 1179 // between them, and we correctly identify the best layout for these 1180 // CFGs. We want to extend trellises that the user created in addition 1181 // to trellises created by tail-duplication, so we just look for the 1182 // CFG. 1183 continue; 1184 Duplicate = false; 1185 continue; 1186 } 1187 NumDup++; 1188 } 1189 1190 // No possible duplication in current filter set. 1191 if (NumDup == 0) 1192 return false; 1193 1194 // If profile information is available, findDuplicateCandidates can do more 1195 // precise benefit analysis. 1196 if (F->getFunction().hasProfileData()) 1197 return true; 1198 1199 // This is mainly for function exit BB. 1200 // The integrated tail duplication is really designed for increasing 1201 // fallthrough from predecessors from Succ to its successors. We may need 1202 // other machanism to handle different cases. 1203 if (Succ->succ_empty()) 1204 return true; 1205 1206 // Plus the already placed predecessor. 1207 NumDup++; 1208 1209 // If the duplication candidate has more unplaced predecessors than 1210 // successors, the extra duplication can't bring more fallthrough. 1211 // 1212 // Pred1 Pred2 Pred3 1213 // \ | / 1214 // \ | / 1215 // \ | / 1216 // Dup 1217 // / \ 1218 // / \ 1219 // Succ1 Succ2 1220 // 1221 // In this example Dup has 2 successors and 3 predecessors, duplication of Dup 1222 // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2, 1223 // but the duplication into Pred3 can't increase fallthrough. 1224 // 1225 // A small number of extra duplication may not hurt too much. We need a better 1226 // heuristic to handle it. 1227 if ((NumDup > Succ->succ_size()) || !Duplicate) 1228 return false; 1229 1230 return true; 1231 } 1232 1233 /// Find chains of triangles where we believe it would be profitable to 1234 /// tail-duplicate them all, but a local analysis would not find them. 1235 /// There are 3 ways this can be profitable: 1236 /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with 1237 /// longer chains) 1238 /// 2) The chains are statically correlated. Branch probabilities have a very 1239 /// U-shaped distribution. 1240 /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805] 1241 /// If the branches in a chain are likely to be from the same side of the 1242 /// distribution as their predecessor, but are independent at runtime, this 1243 /// transformation is profitable. (Because the cost of being wrong is a small 1244 /// fixed cost, unlike the standard triangle layout where the cost of being 1245 /// wrong scales with the # of triangles.) 1246 /// 3) The chains are dynamically correlated. If the probability that a previous 1247 /// branch was taken positively influences whether the next branch will be 1248 /// taken 1249 /// We believe that 2 and 3 are common enough to justify the small margin in 1. 1250 void MachineBlockPlacement::precomputeTriangleChains() { 1251 struct TriangleChain { 1252 std::vector<MachineBasicBlock *> Edges; 1253 1254 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst) 1255 : Edges({src, dst}) {} 1256 1257 void append(MachineBasicBlock *dst) { 1258 assert(getKey()->isSuccessor(dst) && 1259 "Attempting to append a block that is not a successor."); 1260 Edges.push_back(dst); 1261 } 1262 1263 unsigned count() const { return Edges.size() - 1; } 1264 1265 MachineBasicBlock *getKey() const { 1266 return Edges.back(); 1267 } 1268 }; 1269 1270 if (TriangleChainCount == 0) 1271 return; 1272 1273 LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n"); 1274 // Map from last block to the chain that contains it. This allows us to extend 1275 // chains as we find new triangles. 1276 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap; 1277 for (MachineBasicBlock &BB : *F) { 1278 // If BB doesn't have 2 successors, it doesn't start a triangle. 1279 if (BB.succ_size() != 2) 1280 continue; 1281 MachineBasicBlock *PDom = nullptr; 1282 for (MachineBasicBlock *Succ : BB.successors()) { 1283 if (!MPDT->dominates(Succ, &BB)) 1284 continue; 1285 PDom = Succ; 1286 break; 1287 } 1288 // If BB doesn't have a post-dominating successor, it doesn't form a 1289 // triangle. 1290 if (PDom == nullptr) 1291 continue; 1292 // If PDom has a hint that it is low probability, skip this triangle. 1293 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100)) 1294 continue; 1295 // If PDom isn't eligible for duplication, this isn't the kind of triangle 1296 // we're looking for. 1297 if (!shouldTailDuplicate(PDom)) 1298 continue; 1299 bool CanTailDuplicate = true; 1300 // If PDom can't tail-duplicate into it's non-BB predecessors, then this 1301 // isn't the kind of triangle we're looking for. 1302 for (MachineBasicBlock* Pred : PDom->predecessors()) { 1303 if (Pred == &BB) 1304 continue; 1305 if (!TailDup.canTailDuplicate(PDom, Pred)) { 1306 CanTailDuplicate = false; 1307 break; 1308 } 1309 } 1310 // If we can't tail-duplicate PDom to its predecessors, then skip this 1311 // triangle. 1312 if (!CanTailDuplicate) 1313 continue; 1314 1315 // Now we have an interesting triangle. Insert it if it's not part of an 1316 // existing chain. 1317 // Note: This cannot be replaced with a call insert() or emplace() because 1318 // the find key is BB, but the insert/emplace key is PDom. 1319 auto Found = TriangleChainMap.find(&BB); 1320 // If it is, remove the chain from the map, grow it, and put it back in the 1321 // map with the end as the new key. 1322 if (Found != TriangleChainMap.end()) { 1323 TriangleChain Chain = std::move(Found->second); 1324 TriangleChainMap.erase(Found); 1325 Chain.append(PDom); 1326 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain))); 1327 } else { 1328 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom); 1329 assert(InsertResult.second && "Block seen twice."); 1330 (void)InsertResult; 1331 } 1332 } 1333 1334 // Iterating over a DenseMap is safe here, because the only thing in the body 1335 // of the loop is inserting into another DenseMap (ComputedEdges). 1336 // ComputedEdges is never iterated, so this doesn't lead to non-determinism. 1337 for (auto &ChainPair : TriangleChainMap) { 1338 TriangleChain &Chain = ChainPair.second; 1339 // Benchmarking has shown that due to branch correlation duplicating 2 or 1340 // more triangles is profitable, despite the calculations assuming 1341 // independence. 1342 if (Chain.count() < TriangleChainCount) 1343 continue; 1344 MachineBasicBlock *dst = Chain.Edges.back(); 1345 Chain.Edges.pop_back(); 1346 for (MachineBasicBlock *src : reverse(Chain.Edges)) { 1347 LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" 1348 << getBlockName(dst) 1349 << " as pre-computed based on triangles.\n"); 1350 1351 auto InsertResult = ComputedEdges.insert({src, {dst, true}}); 1352 assert(InsertResult.second && "Block seen twice."); 1353 (void)InsertResult; 1354 1355 dst = src; 1356 } 1357 } 1358 } 1359 1360 // When profile is not present, return the StaticLikelyProb. 1361 // When profile is available, we need to handle the triangle-shape CFG. 1362 static BranchProbability getLayoutSuccessorProbThreshold( 1363 const MachineBasicBlock *BB) { 1364 if (!BB->getParent()->getFunction().hasProfileData()) 1365 return BranchProbability(StaticLikelyProb, 100); 1366 if (BB->succ_size() == 2) { 1367 const MachineBasicBlock *Succ1 = *BB->succ_begin(); 1368 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 1369 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 1370 /* See case 1 below for the cost analysis. For BB->Succ to 1371 * be taken with smaller cost, the following needs to hold: 1372 * Prob(BB->Succ) > 2 * Prob(BB->Pred) 1373 * So the threshold T in the calculation below 1374 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred) 1375 * So T / (1 - T) = 2, Yielding T = 2/3 1376 * Also adding user specified branch bias, we have 1377 * T = (2/3)*(ProfileLikelyProb/50) 1378 * = (2*ProfileLikelyProb)/150) 1379 */ 1380 return BranchProbability(2 * ProfileLikelyProb, 150); 1381 } 1382 } 1383 return BranchProbability(ProfileLikelyProb, 100); 1384 } 1385 1386 /// Checks to see if the layout candidate block \p Succ has a better layout 1387 /// predecessor than \c BB. If yes, returns true. 1388 /// \p SuccProb: The probability adjusted for only remaining blocks. 1389 /// Only used for logging 1390 /// \p RealSuccProb: The un-adjusted probability. 1391 /// \p Chain: The chain that BB belongs to and Succ is being considered for. 1392 /// \p BlockFilter: if non-null, the set of blocks that make up the loop being 1393 /// considered 1394 bool MachineBlockPlacement::hasBetterLayoutPredecessor( 1395 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 1396 const BlockChain &SuccChain, BranchProbability SuccProb, 1397 BranchProbability RealSuccProb, const BlockChain &Chain, 1398 const BlockFilterSet *BlockFilter) { 1399 1400 // There isn't a better layout when there are no unscheduled predecessors. 1401 if (SuccChain.UnscheduledPredecessors == 0) 1402 return false; 1403 1404 // There are two basic scenarios here: 1405 // ------------------------------------- 1406 // Case 1: triangular shape CFG (if-then): 1407 // BB 1408 // | \ 1409 // | \ 1410 // | Pred 1411 // | / 1412 // Succ 1413 // In this case, we are evaluating whether to select edge -> Succ, e.g. 1414 // set Succ as the layout successor of BB. Picking Succ as BB's 1415 // successor breaks the CFG constraints (FIXME: define these constraints). 1416 // With this layout, Pred BB 1417 // is forced to be outlined, so the overall cost will be cost of the 1418 // branch taken from BB to Pred, plus the cost of back taken branch 1419 // from Pred to Succ, as well as the additional cost associated 1420 // with the needed unconditional jump instruction from Pred To Succ. 1421 1422 // The cost of the topological order layout is the taken branch cost 1423 // from BB to Succ, so to make BB->Succ a viable candidate, the following 1424 // must hold: 1425 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 1426 // < freq(BB->Succ) * taken_branch_cost. 1427 // Ignoring unconditional jump cost, we get 1428 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 1429 // prob(BB->Succ) > 2 * prob(BB->Pred) 1430 // 1431 // When real profile data is available, we can precisely compute the 1432 // probability threshold that is needed for edge BB->Succ to be considered. 1433 // Without profile data, the heuristic requires the branch bias to be 1434 // a lot larger to make sure the signal is very strong (e.g. 80% default). 1435 // ----------------------------------------------------------------- 1436 // Case 2: diamond like CFG (if-then-else): 1437 // S 1438 // / \ 1439 // | \ 1440 // BB Pred 1441 // \ / 1442 // Succ 1443 // .. 1444 // 1445 // The current block is BB and edge BB->Succ is now being evaluated. 1446 // Note that edge S->BB was previously already selected because 1447 // prob(S->BB) > prob(S->Pred). 1448 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 1449 // choose Pred, we will have a topological ordering as shown on the left 1450 // in the picture below. If we choose Succ, we have the solution as shown 1451 // on the right: 1452 // 1453 // topo-order: 1454 // 1455 // S----- ---S 1456 // | | | | 1457 // ---BB | | BB 1458 // | | | | 1459 // | Pred-- | Succ-- 1460 // | | | | 1461 // ---Succ ---Pred-- 1462 // 1463 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 1464 // = freq(S->Pred) + freq(S->BB) 1465 // 1466 // If we have profile data (i.e, branch probabilities can be trusted), the 1467 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 1468 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 1469 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 1470 // means the cost of topological order is greater. 1471 // When profile data is not available, however, we need to be more 1472 // conservative. If the branch prediction is wrong, breaking the topo-order 1473 // will actually yield a layout with large cost. For this reason, we need 1474 // strong biased branch at block S with Prob(S->BB) in order to select 1475 // BB->Succ. This is equivalent to looking the CFG backward with backward 1476 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 1477 // profile data). 1478 // -------------------------------------------------------------------------- 1479 // Case 3: forked diamond 1480 // S 1481 // / \ 1482 // / \ 1483 // BB Pred 1484 // | \ / | 1485 // | \ / | 1486 // | X | 1487 // | / \ | 1488 // | / \ | 1489 // S1 S2 1490 // 1491 // The current block is BB and edge BB->S1 is now being evaluated. 1492 // As above S->BB was already selected because 1493 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 1494 // 1495 // topo-order: 1496 // 1497 // S-------| ---S 1498 // | | | | 1499 // ---BB | | BB 1500 // | | | | 1501 // | Pred----| | S1---- 1502 // | | | | 1503 // --(S1 or S2) ---Pred-- 1504 // | 1505 // S2 1506 // 1507 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 1508 // + min(freq(Pred->S1), freq(Pred->S2)) 1509 // Non-topo-order cost: 1510 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 1511 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 1512 // is 0. Then the non topo layout is better when 1513 // freq(S->Pred) < freq(BB->S1). 1514 // This is exactly what is checked below. 1515 // Note there are other shapes that apply (Pred may not be a single block, 1516 // but they all fit this general pattern.) 1517 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 1518 1519 // Make sure that a hot successor doesn't have a globally more 1520 // important predecessor. 1521 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 1522 bool BadCFGConflict = false; 1523 1524 for (MachineBasicBlock *Pred : Succ->predecessors()) { 1525 BlockChain *PredChain = BlockToChain[Pred]; 1526 if (Pred == Succ || PredChain == &SuccChain || 1527 (BlockFilter && !BlockFilter->count(Pred)) || 1528 PredChain == &Chain || Pred != *std::prev(PredChain->end()) || 1529 // This check is redundant except for look ahead. This function is 1530 // called for lookahead by isProfitableToTailDup when BB hasn't been 1531 // placed yet. 1532 (Pred == BB)) 1533 continue; 1534 // Do backward checking. 1535 // For all cases above, we need a backward checking to filter out edges that 1536 // are not 'strongly' biased. 1537 // BB Pred 1538 // \ / 1539 // Succ 1540 // We select edge BB->Succ if 1541 // freq(BB->Succ) > freq(Succ) * HotProb 1542 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 1543 // HotProb 1544 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 1545 // Case 1 is covered too, because the first equation reduces to: 1546 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 1547 BlockFrequency PredEdgeFreq = 1548 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 1549 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 1550 BadCFGConflict = true; 1551 break; 1552 } 1553 } 1554 1555 if (BadCFGConflict) { 1556 LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " 1557 << SuccProb << " (prob) (non-cold CFG conflict)\n"); 1558 return true; 1559 } 1560 1561 return false; 1562 } 1563 1564 /// Select the best successor for a block. 1565 /// 1566 /// This looks across all successors of a particular block and attempts to 1567 /// select the "best" one to be the layout successor. It only considers direct 1568 /// successors which also pass the block filter. It will attempt to avoid 1569 /// breaking CFG structure, but cave and break such structures in the case of 1570 /// very hot successor edges. 1571 /// 1572 /// \returns The best successor block found, or null if none are viable, along 1573 /// with a boolean indicating if tail duplication is necessary. 1574 MachineBlockPlacement::BlockAndTailDupResult 1575 MachineBlockPlacement::selectBestSuccessor( 1576 const MachineBasicBlock *BB, const BlockChain &Chain, 1577 const BlockFilterSet *BlockFilter) { 1578 const BranchProbability HotProb(StaticLikelyProb, 100); 1579 1580 BlockAndTailDupResult BestSucc = { nullptr, false }; 1581 auto BestProb = BranchProbability::getZero(); 1582 1583 SmallVector<MachineBasicBlock *, 4> Successors; 1584 auto AdjustedSumProb = 1585 collectViableSuccessors(BB, Chain, BlockFilter, Successors); 1586 1587 LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) 1588 << "\n"); 1589 1590 // if we already precomputed the best successor for BB, return that if still 1591 // applicable. 1592 auto FoundEdge = ComputedEdges.find(BB); 1593 if (FoundEdge != ComputedEdges.end()) { 1594 MachineBasicBlock *Succ = FoundEdge->second.BB; 1595 ComputedEdges.erase(FoundEdge); 1596 BlockChain *SuccChain = BlockToChain[Succ]; 1597 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) && 1598 SuccChain != &Chain && Succ == *SuccChain->begin()) 1599 return FoundEdge->second; 1600 } 1601 1602 // if BB is part of a trellis, Use the trellis to determine the optimal 1603 // fallthrough edges 1604 if (isTrellis(BB, Successors, Chain, BlockFilter)) 1605 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain, 1606 BlockFilter); 1607 1608 // For blocks with CFG violations, we may be able to lay them out anyway with 1609 // tail-duplication. We keep this vector so we can perform the probability 1610 // calculations the minimum number of times. 1611 SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4> 1612 DupCandidates; 1613 for (MachineBasicBlock *Succ : Successors) { 1614 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 1615 BranchProbability SuccProb = 1616 getAdjustedProbability(RealSuccProb, AdjustedSumProb); 1617 1618 BlockChain &SuccChain = *BlockToChain[Succ]; 1619 // Skip the edge \c BB->Succ if block \c Succ has a better layout 1620 // predecessor that yields lower global cost. 1621 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 1622 Chain, BlockFilter)) { 1623 // If tail duplication would make Succ profitable, place it. 1624 if (allowTailDupPlacement() && shouldTailDuplicate(Succ)) 1625 DupCandidates.emplace_back(SuccProb, Succ); 1626 continue; 1627 } 1628 1629 LLVM_DEBUG( 1630 dbgs() << " Candidate: " << getBlockName(Succ) 1631 << ", probability: " << SuccProb 1632 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 1633 << "\n"); 1634 1635 if (BestSucc.BB && BestProb >= SuccProb) { 1636 LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n"); 1637 continue; 1638 } 1639 1640 LLVM_DEBUG(dbgs() << " Setting it as best candidate\n"); 1641 BestSucc.BB = Succ; 1642 BestProb = SuccProb; 1643 } 1644 // Handle the tail duplication candidates in order of decreasing probability. 1645 // Stop at the first one that is profitable. Also stop if they are less 1646 // profitable than BestSucc. Position is important because we preserve it and 1647 // prefer first best match. Here we aren't comparing in order, so we capture 1648 // the position instead. 1649 llvm::stable_sort(DupCandidates, 1650 [](std::tuple<BranchProbability, MachineBasicBlock *> L, 1651 std::tuple<BranchProbability, MachineBasicBlock *> R) { 1652 return std::get<0>(L) > std::get<0>(R); 1653 }); 1654 for (auto &Tup : DupCandidates) { 1655 BranchProbability DupProb; 1656 MachineBasicBlock *Succ; 1657 std::tie(DupProb, Succ) = Tup; 1658 if (DupProb < BestProb) 1659 break; 1660 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) 1661 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) { 1662 LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ) 1663 << ", probability: " << DupProb 1664 << " (Tail Duplicate)\n"); 1665 BestSucc.BB = Succ; 1666 BestSucc.ShouldTailDup = true; 1667 break; 1668 } 1669 } 1670 1671 if (BestSucc.BB) 1672 LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n"); 1673 1674 return BestSucc; 1675 } 1676 1677 /// Select the best block from a worklist. 1678 /// 1679 /// This looks through the provided worklist as a list of candidate basic 1680 /// blocks and select the most profitable one to place. The definition of 1681 /// profitable only really makes sense in the context of a loop. This returns 1682 /// the most frequently visited block in the worklist, which in the case of 1683 /// a loop, is the one most desirable to be physically close to the rest of the 1684 /// loop body in order to improve i-cache behavior. 1685 /// 1686 /// \returns The best block found, or null if none are viable. 1687 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 1688 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 1689 // Once we need to walk the worklist looking for a candidate, cleanup the 1690 // worklist of already placed entries. 1691 // FIXME: If this shows up on profiles, it could be folded (at the cost of 1692 // some code complexity) into the loop below. 1693 llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) { 1694 return BlockToChain.lookup(BB) == &Chain; 1695 }); 1696 1697 if (WorkList.empty()) 1698 return nullptr; 1699 1700 bool IsEHPad = WorkList[0]->isEHPad(); 1701 1702 MachineBasicBlock *BestBlock = nullptr; 1703 BlockFrequency BestFreq; 1704 for (MachineBasicBlock *MBB : WorkList) { 1705 assert(MBB->isEHPad() == IsEHPad && 1706 "EHPad mismatch between block and work list."); 1707 1708 BlockChain &SuccChain = *BlockToChain[MBB]; 1709 if (&SuccChain == &Chain) 1710 continue; 1711 1712 assert(SuccChain.UnscheduledPredecessors == 0 && 1713 "Found CFG-violating block"); 1714 1715 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 1716 LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; 1717 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 1718 1719 // For ehpad, we layout the least probable first as to avoid jumping back 1720 // from least probable landingpads to more probable ones. 1721 // 1722 // FIXME: Using probability is probably (!) not the best way to achieve 1723 // this. We should probably have a more principled approach to layout 1724 // cleanup code. 1725 // 1726 // The goal is to get: 1727 // 1728 // +--------------------------+ 1729 // | V 1730 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 1731 // 1732 // Rather than: 1733 // 1734 // +-------------------------------------+ 1735 // V | 1736 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 1737 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 1738 continue; 1739 1740 BestBlock = MBB; 1741 BestFreq = CandidateFreq; 1742 } 1743 1744 return BestBlock; 1745 } 1746 1747 /// Retrieve the first unplaced basic block. 1748 /// 1749 /// This routine is called when we are unable to use the CFG to walk through 1750 /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 1751 /// We walk through the function's blocks in order, starting from the 1752 /// LastUnplacedBlockIt. We update this iterator on each call to avoid 1753 /// re-scanning the entire sequence on repeated calls to this routine. 1754 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 1755 const BlockChain &PlacedChain, 1756 MachineFunction::iterator &PrevUnplacedBlockIt, 1757 const BlockFilterSet *BlockFilter) { 1758 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 1759 ++I) { 1760 if (BlockFilter && !BlockFilter->count(&*I)) 1761 continue; 1762 if (BlockToChain[&*I] != &PlacedChain) { 1763 PrevUnplacedBlockIt = I; 1764 // Now select the head of the chain to which the unplaced block belongs 1765 // as the block to place. This will force the entire chain to be placed, 1766 // and satisfies the requirements of merging chains. 1767 return *BlockToChain[&*I]->begin(); 1768 } 1769 } 1770 return nullptr; 1771 } 1772 1773 void MachineBlockPlacement::fillWorkLists( 1774 const MachineBasicBlock *MBB, 1775 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 1776 const BlockFilterSet *BlockFilter = nullptr) { 1777 BlockChain &Chain = *BlockToChain[MBB]; 1778 if (!UpdatedPreds.insert(&Chain).second) 1779 return; 1780 1781 assert( 1782 Chain.UnscheduledPredecessors == 0 && 1783 "Attempting to place block with unscheduled predecessors in worklist."); 1784 for (MachineBasicBlock *ChainBB : Chain) { 1785 assert(BlockToChain[ChainBB] == &Chain && 1786 "Block in chain doesn't match BlockToChain map."); 1787 for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 1788 if (BlockFilter && !BlockFilter->count(Pred)) 1789 continue; 1790 if (BlockToChain[Pred] == &Chain) 1791 continue; 1792 ++Chain.UnscheduledPredecessors; 1793 } 1794 } 1795 1796 if (Chain.UnscheduledPredecessors != 0) 1797 return; 1798 1799 MachineBasicBlock *BB = *Chain.begin(); 1800 if (BB->isEHPad()) 1801 EHPadWorkList.push_back(BB); 1802 else 1803 BlockWorkList.push_back(BB); 1804 } 1805 1806 void MachineBlockPlacement::buildChain( 1807 const MachineBasicBlock *HeadBB, BlockChain &Chain, 1808 BlockFilterSet *BlockFilter) { 1809 assert(HeadBB && "BB must not be null.\n"); 1810 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n"); 1811 MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 1812 1813 const MachineBasicBlock *LoopHeaderBB = HeadBB; 1814 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 1815 MachineBasicBlock *BB = *std::prev(Chain.end()); 1816 while (true) { 1817 assert(BB && "null block found at end of chain in loop."); 1818 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 1819 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 1820 1821 1822 // Look for the best viable successor if there is one to place immediately 1823 // after this block. 1824 auto Result = selectBestSuccessor(BB, Chain, BlockFilter); 1825 MachineBasicBlock* BestSucc = Result.BB; 1826 bool ShouldTailDup = Result.ShouldTailDup; 1827 if (allowTailDupPlacement()) 1828 ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc, 1829 Chain, 1830 BlockFilter)); 1831 1832 // If an immediate successor isn't available, look for the best viable 1833 // block among those we've identified as not violating the loop's CFG at 1834 // this point. This won't be a fallthrough, but it will increase locality. 1835 if (!BestSucc) 1836 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 1837 if (!BestSucc) 1838 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 1839 1840 if (!BestSucc) { 1841 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); 1842 if (!BestSucc) 1843 break; 1844 1845 LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 1846 "layout successor until the CFG reduces\n"); 1847 } 1848 1849 // Placement may have changed tail duplication opportunities. 1850 // Check for that now. 1851 if (allowTailDupPlacement() && BestSucc && ShouldTailDup) { 1852 repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 1853 BlockFilter, PrevUnplacedBlockIt); 1854 // If the chosen successor was duplicated into BB, don't bother laying 1855 // it out, just go round the loop again with BB as the chain end. 1856 if (!BB->isSuccessor(BestSucc)) 1857 continue; 1858 } 1859 1860 // Place this block, updating the datastructures to reflect its placement. 1861 BlockChain &SuccChain = *BlockToChain[BestSucc]; 1862 // Zero out UnscheduledPredecessors for the successor we're about to merge in case 1863 // we selected a successor that didn't fit naturally into the CFG. 1864 SuccChain.UnscheduledPredecessors = 0; 1865 LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 1866 << getBlockName(BestSucc) << "\n"); 1867 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 1868 Chain.merge(BestSucc, &SuccChain); 1869 BB = *std::prev(Chain.end()); 1870 } 1871 1872 LLVM_DEBUG(dbgs() << "Finished forming chain for header block " 1873 << getBlockName(*Chain.begin()) << "\n"); 1874 } 1875 1876 // If bottom of block BB has only one successor OldTop, in most cases it is 1877 // profitable to move it before OldTop, except the following case: 1878 // 1879 // -->OldTop<- 1880 // | . | 1881 // | . | 1882 // | . | 1883 // ---Pred | 1884 // | | 1885 // BB----- 1886 // 1887 // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't 1888 // layout the other successor below it, so it can't reduce taken branch. 1889 // In this case we keep its original layout. 1890 bool 1891 MachineBlockPlacement::canMoveBottomBlockToTop( 1892 const MachineBasicBlock *BottomBlock, 1893 const MachineBasicBlock *OldTop) { 1894 if (BottomBlock->pred_size() != 1) 1895 return true; 1896 MachineBasicBlock *Pred = *BottomBlock->pred_begin(); 1897 if (Pred->succ_size() != 2) 1898 return true; 1899 1900 MachineBasicBlock *OtherBB = *Pred->succ_begin(); 1901 if (OtherBB == BottomBlock) 1902 OtherBB = *Pred->succ_rbegin(); 1903 if (OtherBB == OldTop) 1904 return false; 1905 1906 return true; 1907 } 1908 1909 // Find out the possible fall through frequence to the top of a loop. 1910 BlockFrequency 1911 MachineBlockPlacement::TopFallThroughFreq( 1912 const MachineBasicBlock *Top, 1913 const BlockFilterSet &LoopBlockSet) { 1914 BlockFrequency MaxFreq = 0; 1915 for (MachineBasicBlock *Pred : Top->predecessors()) { 1916 BlockChain *PredChain = BlockToChain[Pred]; 1917 if (!LoopBlockSet.count(Pred) && 1918 (!PredChain || Pred == *std::prev(PredChain->end()))) { 1919 // Found a Pred block can be placed before Top. 1920 // Check if Top is the best successor of Pred. 1921 auto TopProb = MBPI->getEdgeProbability(Pred, Top); 1922 bool TopOK = true; 1923 for (MachineBasicBlock *Succ : Pred->successors()) { 1924 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 1925 BlockChain *SuccChain = BlockToChain[Succ]; 1926 // Check if Succ can be placed after Pred. 1927 // Succ should not be in any chain, or it is the head of some chain. 1928 if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) && 1929 (!SuccChain || Succ == *SuccChain->begin())) { 1930 TopOK = false; 1931 break; 1932 } 1933 } 1934 if (TopOK) { 1935 BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 1936 MBPI->getEdgeProbability(Pred, Top); 1937 if (EdgeFreq > MaxFreq) 1938 MaxFreq = EdgeFreq; 1939 } 1940 } 1941 } 1942 return MaxFreq; 1943 } 1944 1945 // Compute the fall through gains when move NewTop before OldTop. 1946 // 1947 // In following diagram, edges marked as "-" are reduced fallthrough, edges 1948 // marked as "+" are increased fallthrough, this function computes 1949 // 1950 // SUM(increased fallthrough) - SUM(decreased fallthrough) 1951 // 1952 // | 1953 // | - 1954 // V 1955 // --->OldTop 1956 // | . 1957 // | . 1958 // +| . + 1959 // | Pred ---> 1960 // | |- 1961 // | V 1962 // --- NewTop <--- 1963 // |- 1964 // V 1965 // 1966 BlockFrequency 1967 MachineBlockPlacement::FallThroughGains( 1968 const MachineBasicBlock *NewTop, 1969 const MachineBasicBlock *OldTop, 1970 const MachineBasicBlock *ExitBB, 1971 const BlockFilterSet &LoopBlockSet) { 1972 BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet); 1973 BlockFrequency FallThrough2Exit = 0; 1974 if (ExitBB) 1975 FallThrough2Exit = MBFI->getBlockFreq(NewTop) * 1976 MBPI->getEdgeProbability(NewTop, ExitBB); 1977 BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) * 1978 MBPI->getEdgeProbability(NewTop, OldTop); 1979 1980 // Find the best Pred of NewTop. 1981 MachineBasicBlock *BestPred = nullptr; 1982 BlockFrequency FallThroughFromPred = 0; 1983 for (MachineBasicBlock *Pred : NewTop->predecessors()) { 1984 if (!LoopBlockSet.count(Pred)) 1985 continue; 1986 BlockChain *PredChain = BlockToChain[Pred]; 1987 if (!PredChain || Pred == *std::prev(PredChain->end())) { 1988 BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 1989 MBPI->getEdgeProbability(Pred, NewTop); 1990 if (EdgeFreq > FallThroughFromPred) { 1991 FallThroughFromPred = EdgeFreq; 1992 BestPred = Pred; 1993 } 1994 } 1995 } 1996 1997 // If NewTop is not placed after Pred, another successor can be placed 1998 // after Pred. 1999 BlockFrequency NewFreq = 0; 2000 if (BestPred) { 2001 for (MachineBasicBlock *Succ : BestPred->successors()) { 2002 if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ)) 2003 continue; 2004 if (ComputedEdges.find(Succ) != ComputedEdges.end()) 2005 continue; 2006 BlockChain *SuccChain = BlockToChain[Succ]; 2007 if ((SuccChain && (Succ != *SuccChain->begin())) || 2008 (SuccChain == BlockToChain[BestPred])) 2009 continue; 2010 BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) * 2011 MBPI->getEdgeProbability(BestPred, Succ); 2012 if (EdgeFreq > NewFreq) 2013 NewFreq = EdgeFreq; 2014 } 2015 BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) * 2016 MBPI->getEdgeProbability(BestPred, NewTop); 2017 if (NewFreq > OrigEdgeFreq) { 2018 // If NewTop is not the best successor of Pred, then Pred doesn't 2019 // fallthrough to NewTop. So there is no FallThroughFromPred and 2020 // NewFreq. 2021 NewFreq = 0; 2022 FallThroughFromPred = 0; 2023 } 2024 } 2025 2026 BlockFrequency Result = 0; 2027 BlockFrequency Gains = BackEdgeFreq + NewFreq; 2028 BlockFrequency Lost = FallThrough2Top + FallThrough2Exit + 2029 FallThroughFromPred; 2030 if (Gains > Lost) 2031 Result = Gains - Lost; 2032 return Result; 2033 } 2034 2035 /// Helper function of findBestLoopTop. Find the best loop top block 2036 /// from predecessors of old top. 2037 /// 2038 /// Look for a block which is strictly better than the old top for laying 2039 /// out before the old top of the loop. This looks for only two patterns: 2040 /// 2041 /// 1. a block has only one successor, the old loop top 2042 /// 2043 /// Because such a block will always result in an unconditional jump, 2044 /// rotating it in front of the old top is always profitable. 2045 /// 2046 /// 2. a block has two successors, one is old top, another is exit 2047 /// and it has more than one predecessors 2048 /// 2049 /// If it is below one of its predecessors P, only P can fall through to 2050 /// it, all other predecessors need a jump to it, and another conditional 2051 /// jump to loop header. If it is moved before loop header, all its 2052 /// predecessors jump to it, then fall through to loop header. So all its 2053 /// predecessors except P can reduce one taken branch. 2054 /// At the same time, move it before old top increases the taken branch 2055 /// to loop exit block, so the reduced taken branch will be compared with 2056 /// the increased taken branch to the loop exit block. 2057 MachineBasicBlock * 2058 MachineBlockPlacement::findBestLoopTopHelper( 2059 MachineBasicBlock *OldTop, 2060 const MachineLoop &L, 2061 const BlockFilterSet &LoopBlockSet) { 2062 // Check that the header hasn't been fused with a preheader block due to 2063 // crazy branches. If it has, we need to start with the header at the top to 2064 // prevent pulling the preheader into the loop body. 2065 BlockChain &HeaderChain = *BlockToChain[OldTop]; 2066 if (!LoopBlockSet.count(*HeaderChain.begin())) 2067 return OldTop; 2068 if (OldTop != *HeaderChain.begin()) 2069 return OldTop; 2070 2071 LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop) 2072 << "\n"); 2073 2074 BlockFrequency BestGains = 0; 2075 MachineBasicBlock *BestPred = nullptr; 2076 for (MachineBasicBlock *Pred : OldTop->predecessors()) { 2077 if (!LoopBlockSet.count(Pred)) 2078 continue; 2079 if (Pred == L.getHeader()) 2080 continue; 2081 LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has " 2082 << Pred->succ_size() << " successors, "; 2083 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 2084 if (Pred->succ_size() > 2) 2085 continue; 2086 2087 MachineBasicBlock *OtherBB = nullptr; 2088 if (Pred->succ_size() == 2) { 2089 OtherBB = *Pred->succ_begin(); 2090 if (OtherBB == OldTop) 2091 OtherBB = *Pred->succ_rbegin(); 2092 } 2093 2094 if (!canMoveBottomBlockToTop(Pred, OldTop)) 2095 continue; 2096 2097 BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB, 2098 LoopBlockSet); 2099 if ((Gains > 0) && (Gains > BestGains || 2100 ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) { 2101 BestPred = Pred; 2102 BestGains = Gains; 2103 } 2104 } 2105 2106 // If no direct predecessor is fine, just use the loop header. 2107 if (!BestPred) { 2108 LLVM_DEBUG(dbgs() << " final top unchanged\n"); 2109 return OldTop; 2110 } 2111 2112 // Walk backwards through any straight line of predecessors. 2113 while (BestPred->pred_size() == 1 && 2114 (*BestPred->pred_begin())->succ_size() == 1 && 2115 *BestPred->pred_begin() != L.getHeader()) 2116 BestPred = *BestPred->pred_begin(); 2117 2118 LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 2119 return BestPred; 2120 } 2121 2122 /// Find the best loop top block for layout. 2123 /// 2124 /// This function iteratively calls findBestLoopTopHelper, until no new better 2125 /// BB can be found. 2126 MachineBasicBlock * 2127 MachineBlockPlacement::findBestLoopTop(const MachineLoop &L, 2128 const BlockFilterSet &LoopBlockSet) { 2129 // Placing the latch block before the header may introduce an extra branch 2130 // that skips this block the first time the loop is executed, which we want 2131 // to avoid when optimising for size. 2132 // FIXME: in theory there is a case that does not introduce a new branch, 2133 // i.e. when the layout predecessor does not fallthrough to the loop header. 2134 // In practice this never happens though: there always seems to be a preheader 2135 // that can fallthrough and that is also placed before the header. 2136 bool OptForSize = F->getFunction().hasOptSize() || 2137 llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get()); 2138 if (OptForSize) 2139 return L.getHeader(); 2140 2141 MachineBasicBlock *OldTop = nullptr; 2142 MachineBasicBlock *NewTop = L.getHeader(); 2143 while (NewTop != OldTop) { 2144 OldTop = NewTop; 2145 NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet); 2146 if (NewTop != OldTop) 2147 ComputedEdges[NewTop] = { OldTop, false }; 2148 } 2149 return NewTop; 2150 } 2151 2152 /// Find the best loop exiting block for layout. 2153 /// 2154 /// This routine implements the logic to analyze the loop looking for the best 2155 /// block to layout at the top of the loop. Typically this is done to maximize 2156 /// fallthrough opportunities. 2157 MachineBasicBlock * 2158 MachineBlockPlacement::findBestLoopExit(const MachineLoop &L, 2159 const BlockFilterSet &LoopBlockSet, 2160 BlockFrequency &ExitFreq) { 2161 // We don't want to layout the loop linearly in all cases. If the loop header 2162 // is just a normal basic block in the loop, we want to look for what block 2163 // within the loop is the best one to layout at the top. However, if the loop 2164 // header has be pre-merged into a chain due to predecessors not having 2165 // analyzable branches, *and* the predecessor it is merged with is *not* part 2166 // of the loop, rotating the header into the middle of the loop will create 2167 // a non-contiguous range of blocks which is Very Bad. So start with the 2168 // header and only rotate if safe. 2169 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 2170 if (!LoopBlockSet.count(*HeaderChain.begin())) 2171 return nullptr; 2172 2173 BlockFrequency BestExitEdgeFreq; 2174 unsigned BestExitLoopDepth = 0; 2175 MachineBasicBlock *ExitingBB = nullptr; 2176 // If there are exits to outer loops, loop rotation can severely limit 2177 // fallthrough opportunities unless it selects such an exit. Keep a set of 2178 // blocks where rotating to exit with that block will reach an outer loop. 2179 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 2180 2181 LLVM_DEBUG(dbgs() << "Finding best loop exit for: " 2182 << getBlockName(L.getHeader()) << "\n"); 2183 for (MachineBasicBlock *MBB : L.getBlocks()) { 2184 BlockChain &Chain = *BlockToChain[MBB]; 2185 // Ensure that this block is at the end of a chain; otherwise it could be 2186 // mid-way through an inner loop or a successor of an unanalyzable branch. 2187 if (MBB != *std::prev(Chain.end())) 2188 continue; 2189 2190 // Now walk the successors. We need to establish whether this has a viable 2191 // exiting successor and whether it has a viable non-exiting successor. 2192 // We store the old exiting state and restore it if a viable looping 2193 // successor isn't found. 2194 MachineBasicBlock *OldExitingBB = ExitingBB; 2195 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 2196 bool HasLoopingSucc = false; 2197 for (MachineBasicBlock *Succ : MBB->successors()) { 2198 if (Succ->isEHPad()) 2199 continue; 2200 if (Succ == MBB) 2201 continue; 2202 BlockChain &SuccChain = *BlockToChain[Succ]; 2203 // Don't split chains, either this chain or the successor's chain. 2204 if (&Chain == &SuccChain) { 2205 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 2206 << getBlockName(Succ) << " (chain conflict)\n"); 2207 continue; 2208 } 2209 2210 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 2211 if (LoopBlockSet.count(Succ)) { 2212 LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 2213 << getBlockName(Succ) << " (" << SuccProb << ")\n"); 2214 HasLoopingSucc = true; 2215 continue; 2216 } 2217 2218 unsigned SuccLoopDepth = 0; 2219 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 2220 SuccLoopDepth = ExitLoop->getLoopDepth(); 2221 if (ExitLoop->contains(&L)) 2222 BlocksExitingToOuterLoop.insert(MBB); 2223 } 2224 2225 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 2226 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 2227 << getBlockName(Succ) << " [L:" << SuccLoopDepth 2228 << "] ("; 2229 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 2230 // Note that we bias this toward an existing layout successor to retain 2231 // incoming order in the absence of better information. The exit must have 2232 // a frequency higher than the current exit before we consider breaking 2233 // the layout. 2234 BranchProbability Bias(100 - ExitBlockBias, 100); 2235 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 2236 ExitEdgeFreq > BestExitEdgeFreq || 2237 (MBB->isLayoutSuccessor(Succ) && 2238 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 2239 BestExitEdgeFreq = ExitEdgeFreq; 2240 ExitingBB = MBB; 2241 } 2242 } 2243 2244 if (!HasLoopingSucc) { 2245 // Restore the old exiting state, no viable looping successor was found. 2246 ExitingBB = OldExitingBB; 2247 BestExitEdgeFreq = OldBestExitEdgeFreq; 2248 } 2249 } 2250 // Without a candidate exiting block or with only a single block in the 2251 // loop, just use the loop header to layout the loop. 2252 if (!ExitingBB) { 2253 LLVM_DEBUG( 2254 dbgs() << " No other candidate exit blocks, using loop header\n"); 2255 return nullptr; 2256 } 2257 if (L.getNumBlocks() == 1) { 2258 LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 2259 return nullptr; 2260 } 2261 2262 // Also, if we have exit blocks which lead to outer loops but didn't select 2263 // one of them as the exiting block we are rotating toward, disable loop 2264 // rotation altogether. 2265 if (!BlocksExitingToOuterLoop.empty() && 2266 !BlocksExitingToOuterLoop.count(ExitingBB)) 2267 return nullptr; 2268 2269 LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) 2270 << "\n"); 2271 ExitFreq = BestExitEdgeFreq; 2272 return ExitingBB; 2273 } 2274 2275 /// Check if there is a fallthrough to loop header Top. 2276 /// 2277 /// 1. Look for a Pred that can be layout before Top. 2278 /// 2. Check if Top is the most possible successor of Pred. 2279 bool 2280 MachineBlockPlacement::hasViableTopFallthrough( 2281 const MachineBasicBlock *Top, 2282 const BlockFilterSet &LoopBlockSet) { 2283 for (MachineBasicBlock *Pred : Top->predecessors()) { 2284 BlockChain *PredChain = BlockToChain[Pred]; 2285 if (!LoopBlockSet.count(Pred) && 2286 (!PredChain || Pred == *std::prev(PredChain->end()))) { 2287 // Found a Pred block can be placed before Top. 2288 // Check if Top is the best successor of Pred. 2289 auto TopProb = MBPI->getEdgeProbability(Pred, Top); 2290 bool TopOK = true; 2291 for (MachineBasicBlock *Succ : Pred->successors()) { 2292 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 2293 BlockChain *SuccChain = BlockToChain[Succ]; 2294 // Check if Succ can be placed after Pred. 2295 // Succ should not be in any chain, or it is the head of some chain. 2296 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) { 2297 TopOK = false; 2298 break; 2299 } 2300 } 2301 if (TopOK) 2302 return true; 2303 } 2304 } 2305 return false; 2306 } 2307 2308 /// Attempt to rotate an exiting block to the bottom of the loop. 2309 /// 2310 /// Once we have built a chain, try to rotate it to line up the hot exit block 2311 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 2312 /// branches. For example, if the loop has fallthrough into its header and out 2313 /// of its bottom already, don't rotate it. 2314 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 2315 const MachineBasicBlock *ExitingBB, 2316 BlockFrequency ExitFreq, 2317 const BlockFilterSet &LoopBlockSet) { 2318 if (!ExitingBB) 2319 return; 2320 2321 MachineBasicBlock *Top = *LoopChain.begin(); 2322 MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 2323 2324 // If ExitingBB is already the last one in a chain then nothing to do. 2325 if (Bottom == ExitingBB) 2326 return; 2327 2328 // The entry block should always be the first BB in a function. 2329 if (Top->isEntryBlock()) 2330 return; 2331 2332 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet); 2333 2334 // If the header has viable fallthrough, check whether the current loop 2335 // bottom is a viable exiting block. If so, bail out as rotating will 2336 // introduce an unnecessary branch. 2337 if (ViableTopFallthrough) { 2338 for (MachineBasicBlock *Succ : Bottom->successors()) { 2339 BlockChain *SuccChain = BlockToChain[Succ]; 2340 if (!LoopBlockSet.count(Succ) && 2341 (!SuccChain || Succ == *SuccChain->begin())) 2342 return; 2343 } 2344 2345 // Rotate will destroy the top fallthrough, we need to ensure the new exit 2346 // frequency is larger than top fallthrough. 2347 BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet); 2348 if (FallThrough2Top >= ExitFreq) 2349 return; 2350 } 2351 2352 BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB); 2353 if (ExitIt == LoopChain.end()) 2354 return; 2355 2356 // Rotating a loop exit to the bottom when there is a fallthrough to top 2357 // trades the entry fallthrough for an exit fallthrough. 2358 // If there is no bottom->top edge, but the chosen exit block does have 2359 // a fallthrough, we break that fallthrough for nothing in return. 2360 2361 // Let's consider an example. We have a built chain of basic blocks 2362 // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block. 2363 // By doing a rotation we get 2364 // Bk+1, ..., Bn, B1, ..., Bk 2365 // Break of fallthrough to B1 is compensated by a fallthrough from Bk. 2366 // If we had a fallthrough Bk -> Bk+1 it is broken now. 2367 // It might be compensated by fallthrough Bn -> B1. 2368 // So we have a condition to avoid creation of extra branch by loop rotation. 2369 // All below must be true to avoid loop rotation: 2370 // If there is a fallthrough to top (B1) 2371 // There was fallthrough from chosen exit block (Bk) to next one (Bk+1) 2372 // There is no fallthrough from bottom (Bn) to top (B1). 2373 // Please note that there is no exit fallthrough from Bn because we checked it 2374 // above. 2375 if (ViableTopFallthrough) { 2376 assert(std::next(ExitIt) != LoopChain.end() && 2377 "Exit should not be last BB"); 2378 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt); 2379 if (ExitingBB->isSuccessor(NextBlockInChain)) 2380 if (!Bottom->isSuccessor(Top)) 2381 return; 2382 } 2383 2384 LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB) 2385 << " at bottom\n"); 2386 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 2387 } 2388 2389 /// Attempt to rotate a loop based on profile data to reduce branch cost. 2390 /// 2391 /// With profile data, we can determine the cost in terms of missed fall through 2392 /// opportunities when rotating a loop chain and select the best rotation. 2393 /// Basically, there are three kinds of cost to consider for each rotation: 2394 /// 1. The possibly missed fall through edge (if it exists) from BB out of 2395 /// the loop to the loop header. 2396 /// 2. The possibly missed fall through edges (if they exist) from the loop 2397 /// exits to BB out of the loop. 2398 /// 3. The missed fall through edge (if it exists) from the last BB to the 2399 /// first BB in the loop chain. 2400 /// Therefore, the cost for a given rotation is the sum of costs listed above. 2401 /// We select the best rotation with the smallest cost. 2402 void MachineBlockPlacement::rotateLoopWithProfile( 2403 BlockChain &LoopChain, const MachineLoop &L, 2404 const BlockFilterSet &LoopBlockSet) { 2405 auto RotationPos = LoopChain.end(); 2406 MachineBasicBlock *ChainHeaderBB = *LoopChain.begin(); 2407 2408 // The entry block should always be the first BB in a function. 2409 if (ChainHeaderBB->isEntryBlock()) 2410 return; 2411 2412 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); 2413 2414 // A utility lambda that scales up a block frequency by dividing it by a 2415 // branch probability which is the reciprocal of the scale. 2416 auto ScaleBlockFrequency = [](BlockFrequency Freq, 2417 unsigned Scale) -> BlockFrequency { 2418 if (Scale == 0) 2419 return 0; 2420 // Use operator / between BlockFrequency and BranchProbability to implement 2421 // saturating multiplication. 2422 return Freq / BranchProbability(1, Scale); 2423 }; 2424 2425 // Compute the cost of the missed fall-through edge to the loop header if the 2426 // chain head is not the loop header. As we only consider natural loops with 2427 // single header, this computation can be done only once. 2428 BlockFrequency HeaderFallThroughCost(0); 2429 for (auto *Pred : ChainHeaderBB->predecessors()) { 2430 BlockChain *PredChain = BlockToChain[Pred]; 2431 if (!LoopBlockSet.count(Pred) && 2432 (!PredChain || Pred == *std::prev(PredChain->end()))) { 2433 auto EdgeFreq = MBFI->getBlockFreq(Pred) * 2434 MBPI->getEdgeProbability(Pred, ChainHeaderBB); 2435 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 2436 // If the predecessor has only an unconditional jump to the header, we 2437 // need to consider the cost of this jump. 2438 if (Pred->succ_size() == 1) 2439 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 2440 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 2441 } 2442 } 2443 2444 // Here we collect all exit blocks in the loop, and for each exit we find out 2445 // its hottest exit edge. For each loop rotation, we define the loop exit cost 2446 // as the sum of frequencies of exit edges we collect here, excluding the exit 2447 // edge from the tail of the loop chain. 2448 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 2449 for (auto BB : LoopChain) { 2450 auto LargestExitEdgeProb = BranchProbability::getZero(); 2451 for (auto *Succ : BB->successors()) { 2452 BlockChain *SuccChain = BlockToChain[Succ]; 2453 if (!LoopBlockSet.count(Succ) && 2454 (!SuccChain || Succ == *SuccChain->begin())) { 2455 auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 2456 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 2457 } 2458 } 2459 if (LargestExitEdgeProb > BranchProbability::getZero()) { 2460 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 2461 ExitsWithFreq.emplace_back(BB, ExitFreq); 2462 } 2463 } 2464 2465 // In this loop we iterate every block in the loop chain and calculate the 2466 // cost assuming the block is the head of the loop chain. When the loop ends, 2467 // we should have found the best candidate as the loop chain's head. 2468 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 2469 EndIter = LoopChain.end(); 2470 Iter != EndIter; Iter++, TailIter++) { 2471 // TailIter is used to track the tail of the loop chain if the block we are 2472 // checking (pointed by Iter) is the head of the chain. 2473 if (TailIter == LoopChain.end()) 2474 TailIter = LoopChain.begin(); 2475 2476 auto TailBB = *TailIter; 2477 2478 // Calculate the cost by putting this BB to the top. 2479 BlockFrequency Cost = 0; 2480 2481 // If the current BB is the loop header, we need to take into account the 2482 // cost of the missed fall through edge from outside of the loop to the 2483 // header. 2484 if (Iter != LoopChain.begin()) 2485 Cost += HeaderFallThroughCost; 2486 2487 // Collect the loop exit cost by summing up frequencies of all exit edges 2488 // except the one from the chain tail. 2489 for (auto &ExitWithFreq : ExitsWithFreq) 2490 if (TailBB != ExitWithFreq.first) 2491 Cost += ExitWithFreq.second; 2492 2493 // The cost of breaking the once fall-through edge from the tail to the top 2494 // of the loop chain. Here we need to consider three cases: 2495 // 1. If the tail node has only one successor, then we will get an 2496 // additional jmp instruction. So the cost here is (MisfetchCost + 2497 // JumpInstCost) * tail node frequency. 2498 // 2. If the tail node has two successors, then we may still get an 2499 // additional jmp instruction if the layout successor after the loop 2500 // chain is not its CFG successor. Note that the more frequently executed 2501 // jmp instruction will be put ahead of the other one. Assume the 2502 // frequency of those two branches are x and y, where x is the frequency 2503 // of the edge to the chain head, then the cost will be 2504 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 2505 // 3. If the tail node has more than two successors (this rarely happens), 2506 // we won't consider any additional cost. 2507 if (TailBB->isSuccessor(*Iter)) { 2508 auto TailBBFreq = MBFI->getBlockFreq(TailBB); 2509 if (TailBB->succ_size() == 1) 2510 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), 2511 MisfetchCost + JumpInstCost); 2512 else if (TailBB->succ_size() == 2) { 2513 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 2514 auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 2515 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 2516 ? TailBBFreq * TailToHeadProb.getCompl() 2517 : TailToHeadFreq; 2518 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 2519 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 2520 } 2521 } 2522 2523 LLVM_DEBUG(dbgs() << "The cost of loop rotation by making " 2524 << getBlockName(*Iter) 2525 << " to the top: " << Cost.getFrequency() << "\n"); 2526 2527 if (Cost < SmallestRotationCost) { 2528 SmallestRotationCost = Cost; 2529 RotationPos = Iter; 2530 } 2531 } 2532 2533 if (RotationPos != LoopChain.end()) { 2534 LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 2535 << " to the top\n"); 2536 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 2537 } 2538 } 2539 2540 /// Collect blocks in the given loop that are to be placed. 2541 /// 2542 /// When profile data is available, exclude cold blocks from the returned set; 2543 /// otherwise, collect all blocks in the loop. 2544 MachineBlockPlacement::BlockFilterSet 2545 MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) { 2546 BlockFilterSet LoopBlockSet; 2547 2548 // Filter cold blocks off from LoopBlockSet when profile data is available. 2549 // Collect the sum of frequencies of incoming edges to the loop header from 2550 // outside. If we treat the loop as a super block, this is the frequency of 2551 // the loop. Then for each block in the loop, we calculate the ratio between 2552 // its frequency and the frequency of the loop block. When it is too small, 2553 // don't add it to the loop chain. If there are outer loops, then this block 2554 // will be merged into the first outer loop chain for which this block is not 2555 // cold anymore. This needs precise profile data and we only do this when 2556 // profile data is available. 2557 if (F->getFunction().hasProfileData() || ForceLoopColdBlock) { 2558 BlockFrequency LoopFreq(0); 2559 for (auto LoopPred : L.getHeader()->predecessors()) 2560 if (!L.contains(LoopPred)) 2561 LoopFreq += MBFI->getBlockFreq(LoopPred) * 2562 MBPI->getEdgeProbability(LoopPred, L.getHeader()); 2563 2564 for (MachineBasicBlock *LoopBB : L.getBlocks()) { 2565 if (LoopBlockSet.count(LoopBB)) 2566 continue; 2567 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 2568 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 2569 continue; 2570 BlockChain *Chain = BlockToChain[LoopBB]; 2571 for (MachineBasicBlock *ChainBB : *Chain) 2572 LoopBlockSet.insert(ChainBB); 2573 } 2574 } else 2575 LoopBlockSet.insert(L.block_begin(), L.block_end()); 2576 2577 return LoopBlockSet; 2578 } 2579 2580 /// Forms basic block chains from the natural loop structures. 2581 /// 2582 /// These chains are designed to preserve the existing *structure* of the code 2583 /// as much as possible. We can then stitch the chains together in a way which 2584 /// both preserves the topological structure and minimizes taken conditional 2585 /// branches. 2586 void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) { 2587 // First recurse through any nested loops, building chains for those inner 2588 // loops. 2589 for (const MachineLoop *InnerLoop : L) 2590 buildLoopChains(*InnerLoop); 2591 2592 assert(BlockWorkList.empty() && 2593 "BlockWorkList not empty when starting to build loop chains."); 2594 assert(EHPadWorkList.empty() && 2595 "EHPadWorkList not empty when starting to build loop chains."); 2596 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 2597 2598 // Check if we have profile data for this function. If yes, we will rotate 2599 // this loop by modeling costs more precisely which requires the profile data 2600 // for better layout. 2601 bool RotateLoopWithProfile = 2602 ForcePreciseRotationCost || 2603 (PreciseRotationCost && F->getFunction().hasProfileData()); 2604 2605 // First check to see if there is an obviously preferable top block for the 2606 // loop. This will default to the header, but may end up as one of the 2607 // predecessors to the header if there is one which will result in strictly 2608 // fewer branches in the loop body. 2609 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet); 2610 2611 // If we selected just the header for the loop top, look for a potentially 2612 // profitable exit block in the event that rotating the loop can eliminate 2613 // branches by placing an exit edge at the bottom. 2614 // 2615 // Loops are processed innermost to uttermost, make sure we clear 2616 // PreferredLoopExit before processing a new loop. 2617 PreferredLoopExit = nullptr; 2618 BlockFrequency ExitFreq; 2619 if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 2620 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq); 2621 2622 BlockChain &LoopChain = *BlockToChain[LoopTop]; 2623 2624 // FIXME: This is a really lame way of walking the chains in the loop: we 2625 // walk the blocks, and use a set to prevent visiting a particular chain 2626 // twice. 2627 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 2628 assert(LoopChain.UnscheduledPredecessors == 0 && 2629 "LoopChain should not have unscheduled predecessors."); 2630 UpdatedPreds.insert(&LoopChain); 2631 2632 for (const MachineBasicBlock *LoopBB : LoopBlockSet) 2633 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 2634 2635 buildChain(LoopTop, LoopChain, &LoopBlockSet); 2636 2637 if (RotateLoopWithProfile) 2638 rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 2639 else 2640 rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet); 2641 2642 LLVM_DEBUG({ 2643 // Crash at the end so we get all of the debugging output first. 2644 bool BadLoop = false; 2645 if (LoopChain.UnscheduledPredecessors) { 2646 BadLoop = true; 2647 dbgs() << "Loop chain contains a block without its preds placed!\n" 2648 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2649 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 2650 } 2651 for (MachineBasicBlock *ChainBB : LoopChain) { 2652 dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 2653 if (!LoopBlockSet.remove(ChainBB)) { 2654 // We don't mark the loop as bad here because there are real situations 2655 // where this can occur. For example, with an unanalyzable fallthrough 2656 // from a loop block to a non-loop block or vice versa. 2657 dbgs() << "Loop chain contains a block not contained by the loop!\n" 2658 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2659 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 2660 << " Bad block: " << getBlockName(ChainBB) << "\n"; 2661 } 2662 } 2663 2664 if (!LoopBlockSet.empty()) { 2665 BadLoop = true; 2666 for (const MachineBasicBlock *LoopBB : LoopBlockSet) 2667 dbgs() << "Loop contains blocks never placed into a chain!\n" 2668 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2669 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 2670 << " Bad block: " << getBlockName(LoopBB) << "\n"; 2671 } 2672 assert(!BadLoop && "Detected problems with the placement of this loop."); 2673 }); 2674 2675 BlockWorkList.clear(); 2676 EHPadWorkList.clear(); 2677 } 2678 2679 void MachineBlockPlacement::buildCFGChains() { 2680 // Ensure that every BB in the function has an associated chain to simplify 2681 // the assumptions of the remaining algorithm. 2682 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 2683 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 2684 ++FI) { 2685 MachineBasicBlock *BB = &*FI; 2686 BlockChain *Chain = 2687 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 2688 // Also, merge any blocks which we cannot reason about and must preserve 2689 // the exact fallthrough behavior for. 2690 while (true) { 2691 Cond.clear(); 2692 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2693 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 2694 break; 2695 2696 MachineFunction::iterator NextFI = std::next(FI); 2697 MachineBasicBlock *NextBB = &*NextFI; 2698 // Ensure that the layout successor is a viable block, as we know that 2699 // fallthrough is a possibility. 2700 assert(NextFI != FE && "Can't fallthrough past the last block."); 2701 LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 2702 << getBlockName(BB) << " -> " << getBlockName(NextBB) 2703 << "\n"); 2704 Chain->merge(NextBB, nullptr); 2705 #ifndef NDEBUG 2706 BlocksWithUnanalyzableExits.insert(&*BB); 2707 #endif 2708 FI = NextFI; 2709 BB = NextBB; 2710 } 2711 } 2712 2713 // Build any loop-based chains. 2714 PreferredLoopExit = nullptr; 2715 for (MachineLoop *L : *MLI) 2716 buildLoopChains(*L); 2717 2718 assert(BlockWorkList.empty() && 2719 "BlockWorkList should be empty before building final chain."); 2720 assert(EHPadWorkList.empty() && 2721 "EHPadWorkList should be empty before building final chain."); 2722 2723 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 2724 for (MachineBasicBlock &MBB : *F) 2725 fillWorkLists(&MBB, UpdatedPreds); 2726 2727 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 2728 buildChain(&F->front(), FunctionChain); 2729 2730 #ifndef NDEBUG 2731 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>; 2732 #endif 2733 LLVM_DEBUG({ 2734 // Crash at the end so we get all of the debugging output first. 2735 bool BadFunc = false; 2736 FunctionBlockSetType FunctionBlockSet; 2737 for (MachineBasicBlock &MBB : *F) 2738 FunctionBlockSet.insert(&MBB); 2739 2740 for (MachineBasicBlock *ChainBB : FunctionChain) 2741 if (!FunctionBlockSet.erase(ChainBB)) { 2742 BadFunc = true; 2743 dbgs() << "Function chain contains a block not in the function!\n" 2744 << " Bad block: " << getBlockName(ChainBB) << "\n"; 2745 } 2746 2747 if (!FunctionBlockSet.empty()) { 2748 BadFunc = true; 2749 for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 2750 dbgs() << "Function contains blocks never placed into a chain!\n" 2751 << " Bad block: " << getBlockName(RemainingBB) << "\n"; 2752 } 2753 assert(!BadFunc && "Detected problems with the block placement."); 2754 }); 2755 2756 // Remember original layout ordering, so we can update terminators after 2757 // reordering to point to the original layout successor. 2758 SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors( 2759 F->getNumBlockIDs()); 2760 { 2761 MachineBasicBlock *LastMBB = nullptr; 2762 for (auto &MBB : *F) { 2763 if (LastMBB != nullptr) 2764 OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB; 2765 LastMBB = &MBB; 2766 } 2767 OriginalLayoutSuccessors[F->back().getNumber()] = nullptr; 2768 } 2769 2770 // Splice the blocks into place. 2771 MachineFunction::iterator InsertPos = F->begin(); 2772 LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n"); 2773 for (MachineBasicBlock *ChainBB : FunctionChain) { 2774 LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 2775 : " ... ") 2776 << getBlockName(ChainBB) << "\n"); 2777 if (InsertPos != MachineFunction::iterator(ChainBB)) 2778 F->splice(InsertPos, ChainBB); 2779 else 2780 ++InsertPos; 2781 2782 // Update the terminator of the previous block. 2783 if (ChainBB == *FunctionChain.begin()) 2784 continue; 2785 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 2786 2787 // FIXME: It would be awesome of updateTerminator would just return rather 2788 // than assert when the branch cannot be analyzed in order to remove this 2789 // boiler plate. 2790 Cond.clear(); 2791 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2792 2793 #ifndef NDEBUG 2794 if (!BlocksWithUnanalyzableExits.count(PrevBB)) { 2795 // Given the exact block placement we chose, we may actually not _need_ to 2796 // be able to edit PrevBB's terminator sequence, but not being _able_ to 2797 // do that at this point is a bug. 2798 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) || 2799 !PrevBB->canFallThrough()) && 2800 "Unexpected block with un-analyzable fallthrough!"); 2801 Cond.clear(); 2802 TBB = FBB = nullptr; 2803 } 2804 #endif 2805 2806 // The "PrevBB" is not yet updated to reflect current code layout, so, 2807 // o. it may fall-through to a block without explicit "goto" instruction 2808 // before layout, and no longer fall-through it after layout; or 2809 // o. just opposite. 2810 // 2811 // analyzeBranch() may return erroneous value for FBB when these two 2812 // situations take place. For the first scenario FBB is mistakenly set NULL; 2813 // for the 2nd scenario, the FBB, which is expected to be NULL, is 2814 // mistakenly pointing to "*BI". 2815 // Thus, if the future change needs to use FBB before the layout is set, it 2816 // has to correct FBB first by using the code similar to the following: 2817 // 2818 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 2819 // PrevBB->updateTerminator(); 2820 // Cond.clear(); 2821 // TBB = FBB = nullptr; 2822 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 2823 // // FIXME: This should never take place. 2824 // TBB = FBB = nullptr; 2825 // } 2826 // } 2827 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 2828 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 2829 } 2830 } 2831 2832 // Fixup the last block. 2833 Cond.clear(); 2834 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2835 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) { 2836 MachineBasicBlock *PrevBB = &F->back(); 2837 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 2838 } 2839 2840 BlockWorkList.clear(); 2841 EHPadWorkList.clear(); 2842 } 2843 2844 void MachineBlockPlacement::optimizeBranches() { 2845 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 2846 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 2847 2848 // Now that all the basic blocks in the chain have the proper layout, 2849 // make a final call to analyzeBranch with AllowModify set. 2850 // Indeed, the target may be able to optimize the branches in a way we 2851 // cannot because all branches may not be analyzable. 2852 // E.g., the target may be able to remove an unconditional branch to 2853 // a fallthrough when it occurs after predicated terminators. 2854 for (MachineBasicBlock *ChainBB : FunctionChain) { 2855 Cond.clear(); 2856 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2857 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 2858 // If PrevBB has a two-way branch, try to re-order the branches 2859 // such that we branch to the successor with higher probability first. 2860 if (TBB && !Cond.empty() && FBB && 2861 MBPI->getEdgeProbability(ChainBB, FBB) > 2862 MBPI->getEdgeProbability(ChainBB, TBB) && 2863 !TII->reverseBranchCondition(Cond)) { 2864 LLVM_DEBUG(dbgs() << "Reverse order of the two branches: " 2865 << getBlockName(ChainBB) << "\n"); 2866 LLVM_DEBUG(dbgs() << " Edge probability: " 2867 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 2868 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 2869 DebugLoc dl; // FIXME: this is nowhere 2870 TII->removeBranch(*ChainBB); 2871 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 2872 } 2873 } 2874 } 2875 } 2876 2877 void MachineBlockPlacement::alignBlocks() { 2878 // Walk through the backedges of the function now that we have fully laid out 2879 // the basic blocks and align the destination of each backedge. We don't rely 2880 // exclusively on the loop info here so that we can align backedges in 2881 // unnatural CFGs and backedges that were introduced purely because of the 2882 // loop rotations done during this layout pass. 2883 if (F->getFunction().hasMinSize() || 2884 (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize())) 2885 return; 2886 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 2887 if (FunctionChain.begin() == FunctionChain.end()) 2888 return; // Empty chain. 2889 2890 const BranchProbability ColdProb(1, 5); // 20% 2891 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 2892 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 2893 for (MachineBasicBlock *ChainBB : FunctionChain) { 2894 if (ChainBB == *FunctionChain.begin()) 2895 continue; 2896 2897 // Don't align non-looping basic blocks. These are unlikely to execute 2898 // enough times to matter in practice. Note that we'll still handle 2899 // unnatural CFGs inside of a natural outer loop (the common case) and 2900 // rotated loops. 2901 MachineLoop *L = MLI->getLoopFor(ChainBB); 2902 if (!L) 2903 continue; 2904 2905 const Align Align = TLI->getPrefLoopAlignment(L); 2906 if (Align == 1) 2907 continue; // Don't care about loop alignment. 2908 2909 // If the block is cold relative to the function entry don't waste space 2910 // aligning it. 2911 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 2912 if (Freq < WeightedEntryFreq) 2913 continue; 2914 2915 // If the block is cold relative to its loop header, don't align it 2916 // regardless of what edges into the block exist. 2917 MachineBasicBlock *LoopHeader = L->getHeader(); 2918 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 2919 if (Freq < (LoopHeaderFreq * ColdProb)) 2920 continue; 2921 2922 // If the global profiles indicates so, don't align it. 2923 if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) && 2924 !TLI->alignLoopsWithOptSize()) 2925 continue; 2926 2927 // Check for the existence of a non-layout predecessor which would benefit 2928 // from aligning this block. 2929 MachineBasicBlock *LayoutPred = 2930 &*std::prev(MachineFunction::iterator(ChainBB)); 2931 2932 // Force alignment if all the predecessors are jumps. We already checked 2933 // that the block isn't cold above. 2934 if (!LayoutPred->isSuccessor(ChainBB)) { 2935 ChainBB->setAlignment(Align); 2936 continue; 2937 } 2938 2939 // Align this block if the layout predecessor's edge into this block is 2940 // cold relative to the block. When this is true, other predecessors make up 2941 // all of the hot entries into the block and thus alignment is likely to be 2942 // important. 2943 BranchProbability LayoutProb = 2944 MBPI->getEdgeProbability(LayoutPred, ChainBB); 2945 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 2946 if (LayoutEdgeFreq <= (Freq * ColdProb)) 2947 ChainBB->setAlignment(Align); 2948 } 2949 } 2950 2951 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 2952 /// it was duplicated into its chain predecessor and removed. 2953 /// \p BB - Basic block that may be duplicated. 2954 /// 2955 /// \p LPred - Chosen layout predecessor of \p BB. 2956 /// Updated to be the chain end if LPred is removed. 2957 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 2958 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 2959 /// Used to identify which blocks to update predecessor 2960 /// counts. 2961 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 2962 /// chosen in the given order due to unnatural CFG 2963 /// only needed if \p BB is removed and 2964 /// \p PrevUnplacedBlockIt pointed to \p BB. 2965 /// @return true if \p BB was removed. 2966 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 2967 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 2968 const MachineBasicBlock *LoopHeaderBB, 2969 BlockChain &Chain, BlockFilterSet *BlockFilter, 2970 MachineFunction::iterator &PrevUnplacedBlockIt) { 2971 bool Removed, DuplicatedToLPred; 2972 bool DuplicatedToOriginalLPred; 2973 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, 2974 PrevUnplacedBlockIt, 2975 DuplicatedToLPred); 2976 if (!Removed) 2977 return false; 2978 DuplicatedToOriginalLPred = DuplicatedToLPred; 2979 // Iteratively try to duplicate again. It can happen that a block that is 2980 // duplicated into is still small enough to be duplicated again. 2981 // No need to call markBlockSuccessors in this case, as the blocks being 2982 // duplicated from here on are already scheduled. 2983 while (DuplicatedToLPred && Removed) { 2984 MachineBasicBlock *DupBB, *DupPred; 2985 // The removal callback causes Chain.end() to be updated when a block is 2986 // removed. On the first pass through the loop, the chain end should be the 2987 // same as it was on function entry. On subsequent passes, because we are 2988 // duplicating the block at the end of the chain, if it is removed the 2989 // chain will have shrunk by one block. 2990 BlockChain::iterator ChainEnd = Chain.end(); 2991 DupBB = *(--ChainEnd); 2992 // Now try to duplicate again. 2993 if (ChainEnd == Chain.begin()) 2994 break; 2995 DupPred = *std::prev(ChainEnd); 2996 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, 2997 PrevUnplacedBlockIt, 2998 DuplicatedToLPred); 2999 } 3000 // If BB was duplicated into LPred, it is now scheduled. But because it was 3001 // removed, markChainSuccessors won't be called for its chain. Instead we 3002 // call markBlockSuccessors for LPred to achieve the same effect. This must go 3003 // at the end because repeating the tail duplication can increase the number 3004 // of unscheduled predecessors. 3005 LPred = *std::prev(Chain.end()); 3006 if (DuplicatedToOriginalLPred) 3007 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 3008 return true; 3009 } 3010 3011 /// Tail duplicate \p BB into (some) predecessors if profitable. 3012 /// \p BB - Basic block that may be duplicated 3013 /// \p LPred - Chosen layout predecessor of \p BB 3014 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 3015 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 3016 /// Used to identify which blocks to update predecessor 3017 /// counts. 3018 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 3019 /// chosen in the given order due to unnatural CFG 3020 /// only needed if \p BB is removed and 3021 /// \p PrevUnplacedBlockIt pointed to \p BB. 3022 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. 3023 /// \return - True if the block was duplicated into all preds and removed. 3024 bool MachineBlockPlacement::maybeTailDuplicateBlock( 3025 MachineBasicBlock *BB, MachineBasicBlock *LPred, 3026 BlockChain &Chain, BlockFilterSet *BlockFilter, 3027 MachineFunction::iterator &PrevUnplacedBlockIt, 3028 bool &DuplicatedToLPred) { 3029 DuplicatedToLPred = false; 3030 if (!shouldTailDuplicate(BB)) 3031 return false; 3032 3033 LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber() 3034 << "\n"); 3035 3036 // This has to be a callback because none of it can be done after 3037 // BB is deleted. 3038 bool Removed = false; 3039 auto RemovalCallback = 3040 [&](MachineBasicBlock *RemBB) { 3041 // Signal to outer function 3042 Removed = true; 3043 3044 // Conservative default. 3045 bool InWorkList = true; 3046 // Remove from the Chain and Chain Map 3047 if (BlockToChain.count(RemBB)) { 3048 BlockChain *Chain = BlockToChain[RemBB]; 3049 InWorkList = Chain->UnscheduledPredecessors == 0; 3050 Chain->remove(RemBB); 3051 BlockToChain.erase(RemBB); 3052 } 3053 3054 // Handle the unplaced block iterator 3055 if (&(*PrevUnplacedBlockIt) == RemBB) { 3056 PrevUnplacedBlockIt++; 3057 } 3058 3059 // Handle the Work Lists 3060 if (InWorkList) { 3061 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 3062 if (RemBB->isEHPad()) 3063 RemoveList = EHPadWorkList; 3064 llvm::erase_value(RemoveList, RemBB); 3065 } 3066 3067 // Handle the filter set 3068 if (BlockFilter) { 3069 BlockFilter->remove(RemBB); 3070 } 3071 3072 // Remove the block from loop info. 3073 MLI->removeBlock(RemBB); 3074 if (RemBB == PreferredLoopExit) 3075 PreferredLoopExit = nullptr; 3076 3077 LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: " 3078 << getBlockName(RemBB) << "\n"); 3079 }; 3080 auto RemovalCallbackRef = 3081 function_ref<void(MachineBasicBlock*)>(RemovalCallback); 3082 3083 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 3084 bool IsSimple = TailDup.isSimpleBB(BB); 3085 SmallVector<MachineBasicBlock *, 8> CandidatePreds; 3086 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr; 3087 if (F->getFunction().hasProfileData()) { 3088 // We can do partial duplication with precise profile information. 3089 findDuplicateCandidates(CandidatePreds, BB, BlockFilter); 3090 if (CandidatePreds.size() == 0) 3091 return false; 3092 if (CandidatePreds.size() < BB->pred_size()) 3093 CandidatePtr = &CandidatePreds; 3094 } 3095 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds, 3096 &RemovalCallbackRef, CandidatePtr); 3097 3098 // Update UnscheduledPredecessors to reflect tail-duplication. 3099 DuplicatedToLPred = false; 3100 for (MachineBasicBlock *Pred : DuplicatedPreds) { 3101 // We're only looking for unscheduled predecessors that match the filter. 3102 BlockChain* PredChain = BlockToChain[Pred]; 3103 if (Pred == LPred) 3104 DuplicatedToLPred = true; 3105 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 3106 || PredChain == &Chain) 3107 continue; 3108 for (MachineBasicBlock *NewSucc : Pred->successors()) { 3109 if (BlockFilter && !BlockFilter->count(NewSucc)) 3110 continue; 3111 BlockChain *NewChain = BlockToChain[NewSucc]; 3112 if (NewChain != &Chain && NewChain != PredChain) 3113 NewChain->UnscheduledPredecessors++; 3114 } 3115 } 3116 return Removed; 3117 } 3118 3119 // Count the number of actual machine instructions. 3120 static uint64_t countMBBInstruction(MachineBasicBlock *MBB) { 3121 uint64_t InstrCount = 0; 3122 for (MachineInstr &MI : *MBB) { 3123 if (!MI.isPHI() && !MI.isMetaInstruction()) 3124 InstrCount += 1; 3125 } 3126 return InstrCount; 3127 } 3128 3129 // The size cost of duplication is the instruction size of the duplicated block. 3130 // So we should scale the threshold accordingly. But the instruction size is not 3131 // available on all targets, so we use the number of instructions instead. 3132 BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) { 3133 return DupThreshold.getFrequency() * countMBBInstruction(BB); 3134 } 3135 3136 // Returns true if BB is Pred's best successor. 3137 bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB, 3138 MachineBasicBlock *Pred, 3139 BlockFilterSet *BlockFilter) { 3140 if (BB == Pred) 3141 return false; 3142 if (BlockFilter && !BlockFilter->count(Pred)) 3143 return false; 3144 BlockChain *PredChain = BlockToChain[Pred]; 3145 if (PredChain && (Pred != *std::prev(PredChain->end()))) 3146 return false; 3147 3148 // Find the successor with largest probability excluding BB. 3149 BranchProbability BestProb = BranchProbability::getZero(); 3150 for (MachineBasicBlock *Succ : Pred->successors()) 3151 if (Succ != BB) { 3152 if (BlockFilter && !BlockFilter->count(Succ)) 3153 continue; 3154 BlockChain *SuccChain = BlockToChain[Succ]; 3155 if (SuccChain && (Succ != *SuccChain->begin())) 3156 continue; 3157 BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ); 3158 if (SuccProb > BestProb) 3159 BestProb = SuccProb; 3160 } 3161 3162 BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB); 3163 if (BBProb <= BestProb) 3164 return false; 3165 3166 // Compute the number of reduced taken branches if Pred falls through to BB 3167 // instead of another successor. Then compare it with threshold. 3168 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 3169 BlockFrequency Gain = PredFreq * (BBProb - BestProb); 3170 return Gain > scaleThreshold(BB); 3171 } 3172 3173 // Find out the predecessors of BB and BB can be beneficially duplicated into 3174 // them. 3175 void MachineBlockPlacement::findDuplicateCandidates( 3176 SmallVectorImpl<MachineBasicBlock *> &Candidates, 3177 MachineBasicBlock *BB, 3178 BlockFilterSet *BlockFilter) { 3179 MachineBasicBlock *Fallthrough = nullptr; 3180 BranchProbability DefaultBranchProb = BranchProbability::getZero(); 3181 BlockFrequency BBDupThreshold(scaleThreshold(BB)); 3182 SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors()); 3183 SmallVector<MachineBasicBlock *, 8> Succs(BB->successors()); 3184 3185 // Sort for highest frequency. 3186 auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 3187 return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B); 3188 }; 3189 auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 3190 return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B); 3191 }; 3192 llvm::stable_sort(Succs, CmpSucc); 3193 llvm::stable_sort(Preds, CmpPred); 3194 3195 auto SuccIt = Succs.begin(); 3196 if (SuccIt != Succs.end()) { 3197 DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl(); 3198 } 3199 3200 // For each predecessors of BB, compute the benefit of duplicating BB, 3201 // if it is larger than the threshold, add it into Candidates. 3202 // 3203 // If we have following control flow. 3204 // 3205 // PB1 PB2 PB3 PB4 3206 // \ | / /\ 3207 // \ | / / \ 3208 // \ |/ / \ 3209 // BB----/ OB 3210 // /\ 3211 // / \ 3212 // SB1 SB2 3213 // 3214 // And it can be partially duplicated as 3215 // 3216 // PB2+BB 3217 // | PB1 PB3 PB4 3218 // | | / /\ 3219 // | | / / \ 3220 // | |/ / \ 3221 // | BB----/ OB 3222 // |\ /| 3223 // | X | 3224 // |/ \| 3225 // SB2 SB1 3226 // 3227 // The benefit of duplicating into a predecessor is defined as 3228 // Orig_taken_branch - Duplicated_taken_branch 3229 // 3230 // The Orig_taken_branch is computed with the assumption that predecessor 3231 // jumps to BB and the most possible successor is laid out after BB. 3232 // 3233 // The Duplicated_taken_branch is computed with the assumption that BB is 3234 // duplicated into PB, and one successor is layout after it (SB1 for PB1 and 3235 // SB2 for PB2 in our case). If there is no available successor, the combined 3236 // block jumps to all BB's successor, like PB3 in this example. 3237 // 3238 // If a predecessor has multiple successors, so BB can't be duplicated into 3239 // it. But it can beneficially fall through to BB, and duplicate BB into other 3240 // predecessors. 3241 for (MachineBasicBlock *Pred : Preds) { 3242 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 3243 3244 if (!TailDup.canTailDuplicate(BB, Pred)) { 3245 // BB can't be duplicated into Pred, but it is possible to be layout 3246 // below Pred. 3247 if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) { 3248 Fallthrough = Pred; 3249 if (SuccIt != Succs.end()) 3250 SuccIt++; 3251 } 3252 continue; 3253 } 3254 3255 BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb; 3256 BlockFrequency DupCost; 3257 if (SuccIt == Succs.end()) { 3258 // Jump to all successors; 3259 if (Succs.size() > 0) 3260 DupCost += PredFreq; 3261 } else { 3262 // Fallthrough to *SuccIt, jump to all other successors; 3263 DupCost += PredFreq; 3264 DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt); 3265 } 3266 3267 assert(OrigCost >= DupCost); 3268 OrigCost -= DupCost; 3269 if (OrigCost > BBDupThreshold) { 3270 Candidates.push_back(Pred); 3271 if (SuccIt != Succs.end()) 3272 SuccIt++; 3273 } 3274 } 3275 3276 // No predecessors can optimally fallthrough to BB. 3277 // So we can change one duplication into fallthrough. 3278 if (!Fallthrough) { 3279 if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) { 3280 Candidates[0] = Candidates.back(); 3281 Candidates.pop_back(); 3282 } 3283 } 3284 } 3285 3286 void MachineBlockPlacement::initDupThreshold() { 3287 DupThreshold = 0; 3288 if (!F->getFunction().hasProfileData()) 3289 return; 3290 3291 // We prefer to use prifile count. 3292 uint64_t HotThreshold = PSI->getOrCompHotCountThreshold(); 3293 if (HotThreshold != UINT64_MAX) { 3294 UseProfileCount = true; 3295 DupThreshold = HotThreshold * TailDupProfilePercentThreshold / 100; 3296 return; 3297 } 3298 3299 // Profile count is not available, we can use block frequency instead. 3300 BlockFrequency MaxFreq = 0; 3301 for (MachineBasicBlock &MBB : *F) { 3302 BlockFrequency Freq = MBFI->getBlockFreq(&MBB); 3303 if (Freq > MaxFreq) 3304 MaxFreq = Freq; 3305 } 3306 3307 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 3308 DupThreshold = MaxFreq * ThresholdProb; 3309 UseProfileCount = false; 3310 } 3311 3312 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 3313 if (skipFunction(MF.getFunction())) 3314 return false; 3315 3316 // Check for single-block functions and skip them. 3317 if (std::next(MF.begin()) == MF.end()) 3318 return false; 3319 3320 F = &MF; 3321 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 3322 MBFI = std::make_unique<MBFIWrapper>( 3323 getAnalysis<MachineBlockFrequencyInfo>()); 3324 MLI = &getAnalysis<MachineLoopInfo>(); 3325 TII = MF.getSubtarget().getInstrInfo(); 3326 TLI = MF.getSubtarget().getTargetLowering(); 3327 MPDT = nullptr; 3328 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 3329 3330 initDupThreshold(); 3331 3332 // Initialize PreferredLoopExit to nullptr here since it may never be set if 3333 // there are no MachineLoops. 3334 PreferredLoopExit = nullptr; 3335 3336 assert(BlockToChain.empty() && 3337 "BlockToChain map should be empty before starting placement."); 3338 assert(ComputedEdges.empty() && 3339 "Computed Edge map should be empty before starting placement."); 3340 3341 unsigned TailDupSize = TailDupPlacementThreshold; 3342 // If only the aggressive threshold is explicitly set, use it. 3343 if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 && 3344 TailDupPlacementThreshold.getNumOccurrences() == 0) 3345 TailDupSize = TailDupPlacementAggressiveThreshold; 3346 3347 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 3348 // For aggressive optimization, we can adjust some thresholds to be less 3349 // conservative. 3350 if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) { 3351 // At O3 we should be more willing to copy blocks for tail duplication. This 3352 // increases size pressure, so we only do it at O3 3353 // Do this unless only the regular threshold is explicitly set. 3354 if (TailDupPlacementThreshold.getNumOccurrences() == 0 || 3355 TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0) 3356 TailDupSize = TailDupPlacementAggressiveThreshold; 3357 } 3358 3359 // If there's no threshold provided through options, query the target 3360 // information for a threshold instead. 3361 if (TailDupPlacementThreshold.getNumOccurrences() == 0 && 3362 (PassConfig->getOptLevel() < CodeGenOpt::Aggressive || 3363 TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0)) 3364 TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel()); 3365 3366 if (allowTailDupPlacement()) { 3367 MPDT = &getAnalysis<MachinePostDominatorTree>(); 3368 bool OptForSize = MF.getFunction().hasOptSize() || 3369 llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI()); 3370 if (OptForSize) 3371 TailDupSize = 1; 3372 bool PreRegAlloc = false; 3373 TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI, 3374 /* LayoutMode */ true, TailDupSize); 3375 precomputeTriangleChains(); 3376 } 3377 3378 buildCFGChains(); 3379 3380 // Changing the layout can create new tail merging opportunities. 3381 // TailMerge can create jump into if branches that make CFG irreducible for 3382 // HW that requires structured CFG. 3383 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 3384 PassConfig->getEnableTailMerge() && 3385 BranchFoldPlacement; 3386 // No tail merging opportunities if the block number is less than four. 3387 if (MF.size() > 3 && EnableTailMerge) { 3388 unsigned TailMergeSize = TailDupSize + 1; 3389 BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false, 3390 *MBFI, *MBPI, PSI, TailMergeSize); 3391 3392 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI, 3393 /*AfterPlacement=*/true)) { 3394 // Redo the layout if tail merging creates/removes/moves blocks. 3395 BlockToChain.clear(); 3396 ComputedEdges.clear(); 3397 // Must redo the post-dominator tree if blocks were changed. 3398 if (MPDT) 3399 MPDT->runOnMachineFunction(MF); 3400 ChainAllocator.DestroyAll(); 3401 buildCFGChains(); 3402 } 3403 } 3404 3405 // Apply a post-processing optimizing block placement. 3406 if (MF.size() >= 3 && EnableExtTspBlockPlacement) { 3407 // Find a new placement and modify the layout of the blocks in the function. 3408 applyExtTsp(); 3409 3410 // Re-create CFG chain so that we can optimizeBranches and alignBlocks. 3411 createCFGChainExtTsp(); 3412 } 3413 3414 optimizeBranches(); 3415 alignBlocks(); 3416 3417 BlockToChain.clear(); 3418 ComputedEdges.clear(); 3419 ChainAllocator.DestroyAll(); 3420 3421 if (AlignAllBlock) 3422 // Align all of the blocks in the function to a specific alignment. 3423 for (MachineBasicBlock &MBB : MF) 3424 MBB.setAlignment(Align(1ULL << AlignAllBlock)); 3425 else if (AlignAllNonFallThruBlocks) { 3426 // Align all of the blocks that have no fall-through predecessors to a 3427 // specific alignment. 3428 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 3429 auto LayoutPred = std::prev(MBI); 3430 if (!LayoutPred->isSuccessor(&*MBI)) 3431 MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks)); 3432 } 3433 } 3434 if (ViewBlockLayoutWithBFI != GVDT_None && 3435 (ViewBlockFreqFuncName.empty() || 3436 F->getFunction().getName().equals(ViewBlockFreqFuncName))) { 3437 MBFI->view("MBP." + MF.getName(), false); 3438 } 3439 3440 // We always return true as we have no way to track whether the final order 3441 // differs from the original order. 3442 return true; 3443 } 3444 3445 void MachineBlockPlacement::applyExtTsp() { 3446 // Prepare data; blocks are indexed by their index in the current ordering. 3447 DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex; 3448 BlockIndex.reserve(F->size()); 3449 std::vector<const MachineBasicBlock *> CurrentBlockOrder; 3450 CurrentBlockOrder.reserve(F->size()); 3451 size_t NumBlocks = 0; 3452 for (const MachineBasicBlock &MBB : *F) { 3453 BlockIndex[&MBB] = NumBlocks++; 3454 CurrentBlockOrder.push_back(&MBB); 3455 } 3456 3457 auto BlockSizes = std::vector<uint64_t>(F->size()); 3458 auto BlockCounts = std::vector<uint64_t>(F->size()); 3459 DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> JumpCounts; 3460 for (MachineBasicBlock &MBB : *F) { 3461 // Getting the block frequency. 3462 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 3463 BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency(); 3464 // Getting the block size: 3465 // - approximate the size of an instruction by 4 bytes, and 3466 // - ignore debug instructions. 3467 // Note: getting the exact size of each block is target-dependent and can be 3468 // done by extending the interface of MCCodeEmitter. Experimentally we do 3469 // not see a perf improvement with the exact block sizes. 3470 auto NonDbgInsts = 3471 instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end()); 3472 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end()); 3473 BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts; 3474 // Getting jump frequencies. 3475 for (MachineBasicBlock *Succ : MBB.successors()) { 3476 auto EP = MBPI->getEdgeProbability(&MBB, Succ); 3477 BlockFrequency EdgeFreq = BlockFreq * EP; 3478 auto Edge = std::make_pair(BlockIndex[&MBB], BlockIndex[Succ]); 3479 JumpCounts[Edge] = EdgeFreq.getFrequency(); 3480 } 3481 } 3482 3483 LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size() 3484 << " with profile = " << F->getFunction().hasProfileData() 3485 << " (" << F->getName().str() << ")" 3486 << "\n"); 3487 LLVM_DEBUG( 3488 dbgs() << format(" original layout score: %0.2f\n", 3489 calcExtTspScore(BlockSizes, BlockCounts, JumpCounts))); 3490 3491 // Run the layout algorithm. 3492 auto NewOrder = applyExtTspLayout(BlockSizes, BlockCounts, JumpCounts); 3493 std::vector<const MachineBasicBlock *> NewBlockOrder; 3494 NewBlockOrder.reserve(F->size()); 3495 for (uint64_t Node : NewOrder) { 3496 NewBlockOrder.push_back(CurrentBlockOrder[Node]); 3497 } 3498 LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n", 3499 calcExtTspScore(NewOrder, BlockSizes, BlockCounts, 3500 JumpCounts))); 3501 3502 // Assign new block order. 3503 assignBlockOrder(NewBlockOrder); 3504 } 3505 3506 void MachineBlockPlacement::assignBlockOrder( 3507 const std::vector<const MachineBasicBlock *> &NewBlockOrder) { 3508 assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order"); 3509 F->RenumberBlocks(); 3510 3511 bool HasChanges = false; 3512 for (size_t I = 0; I < NewBlockOrder.size(); I++) { 3513 if (NewBlockOrder[I] != F->getBlockNumbered(I)) { 3514 HasChanges = true; 3515 break; 3516 } 3517 } 3518 // Stop early if the new block order is identical to the existing one. 3519 if (!HasChanges) 3520 return; 3521 3522 SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs()); 3523 for (auto &MBB : *F) { 3524 PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 3525 } 3526 3527 // Sort basic blocks in the function according to the computed order. 3528 DenseMap<const MachineBasicBlock *, size_t> NewIndex; 3529 for (const MachineBasicBlock *MBB : NewBlockOrder) { 3530 NewIndex[MBB] = NewIndex.size(); 3531 } 3532 F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) { 3533 return NewIndex[&L] < NewIndex[&R]; 3534 }); 3535 3536 // Update basic block branches by inserting explicit fallthrough branches 3537 // when required and re-optimize branches when possible. 3538 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo(); 3539 SmallVector<MachineOperand, 4> Cond; 3540 for (auto &MBB : *F) { 3541 MachineFunction::iterator NextMBB = std::next(MBB.getIterator()); 3542 MachineFunction::iterator EndIt = MBB.getParent()->end(); 3543 auto *FTMBB = PrevFallThroughs[MBB.getNumber()]; 3544 // If this block had a fallthrough before we need an explicit unconditional 3545 // branch to that block if the fallthrough block is not adjacent to the 3546 // block in the new order. 3547 if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) { 3548 TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 3549 } 3550 3551 // It might be possible to optimize branches by flipping the condition. 3552 Cond.clear(); 3553 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 3554 if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 3555 continue; 3556 MBB.updateTerminator(FTMBB); 3557 } 3558 3559 #ifndef NDEBUG 3560 // Make sure we correctly constructed all branches. 3561 F->verify(this, "After optimized block reordering"); 3562 #endif 3563 } 3564 3565 void MachineBlockPlacement::createCFGChainExtTsp() { 3566 BlockToChain.clear(); 3567 ComputedEdges.clear(); 3568 ChainAllocator.DestroyAll(); 3569 3570 MachineBasicBlock *HeadBB = &F->front(); 3571 BlockChain *FunctionChain = 3572 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB); 3573 3574 for (MachineBasicBlock &MBB : *F) { 3575 if (HeadBB == &MBB) 3576 continue; // Ignore head of the chain 3577 FunctionChain->merge(&MBB, nullptr); 3578 } 3579 } 3580 3581 namespace { 3582 3583 /// A pass to compute block placement statistics. 3584 /// 3585 /// A separate pass to compute interesting statistics for evaluating block 3586 /// placement. This is separate from the actual placement pass so that they can 3587 /// be computed in the absence of any placement transformations or when using 3588 /// alternative placement strategies. 3589 class MachineBlockPlacementStats : public MachineFunctionPass { 3590 /// A handle to the branch probability pass. 3591 const MachineBranchProbabilityInfo *MBPI; 3592 3593 /// A handle to the function-wide block frequency pass. 3594 const MachineBlockFrequencyInfo *MBFI; 3595 3596 public: 3597 static char ID; // Pass identification, replacement for typeid 3598 3599 MachineBlockPlacementStats() : MachineFunctionPass(ID) { 3600 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 3601 } 3602 3603 bool runOnMachineFunction(MachineFunction &F) override; 3604 3605 void getAnalysisUsage(AnalysisUsage &AU) const override { 3606 AU.addRequired<MachineBranchProbabilityInfo>(); 3607 AU.addRequired<MachineBlockFrequencyInfo>(); 3608 AU.setPreservesAll(); 3609 MachineFunctionPass::getAnalysisUsage(AU); 3610 } 3611 }; 3612 3613 } // end anonymous namespace 3614 3615 char MachineBlockPlacementStats::ID = 0; 3616 3617 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 3618 3619 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 3620 "Basic Block Placement Stats", false, false) 3621 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 3622 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 3623 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 3624 "Basic Block Placement Stats", false, false) 3625 3626 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 3627 // Check for single-block functions and skip them. 3628 if (std::next(F.begin()) == F.end()) 3629 return false; 3630 3631 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 3632 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 3633 3634 for (MachineBasicBlock &MBB : F) { 3635 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 3636 Statistic &NumBranches = 3637 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 3638 Statistic &BranchTakenFreq = 3639 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 3640 for (MachineBasicBlock *Succ : MBB.successors()) { 3641 // Skip if this successor is a fallthrough. 3642 if (MBB.isLayoutSuccessor(Succ)) 3643 continue; 3644 3645 BlockFrequency EdgeFreq = 3646 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 3647 ++NumBranches; 3648 BranchTakenFreq += EdgeFreq.getFrequency(); 3649 } 3650 } 3651 3652 return false; 3653 } 3654