1 //===- bolt/Passes/ExtTSPReorderAlgorithm.cpp - Order basic blocks --------===// 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 // ExtTSP - layout of basic blocks with i-cache optimization. 10 // 11 // The algorithm is a greedy heuristic that works with chains (ordered lists) 12 // of basic blocks. Initially all chains are isolated basic blocks. On every 13 // iteration, we pick a pair of chains whose merging yields the biggest increase 14 // in the ExtTSP value, which models how i-cache "friendly" a specific chain is. 15 // A pair of chains giving the maximum gain is merged into a new chain. The 16 // procedure stops when there is only one chain left, or when merging does not 17 // increase ExtTSP. In the latter case, the remaining chains are sorted by 18 // density in decreasing order. 19 // 20 // An important aspect is the way two chains are merged. Unlike earlier 21 // algorithms (e.g., OptimizeCacheReorderAlgorithm or Pettis-Hansen), two 22 // chains, X and Y, are first split into three, X1, X2, and Y. Then we 23 // consider all possible ways of gluing the three chains (e.g., X1YX2, X1X2Y, 24 // X2X1Y, X2YX1, YX1X2, YX2X1) and choose the one producing the largest score. 25 // This improves the quality of the final result (the search space is larger) 26 // while keeping the implementation sufficiently fast. 27 // 28 // Reference: 29 // * A. Newell and S. Pupyrev, Improved Basic Block Reordering, 30 // IEEE Transactions on Computers, 2020 31 // https://arxiv.org/abs/1809.04676 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "bolt/Core/BinaryBasicBlock.h" 36 #include "bolt/Core/BinaryFunction.h" 37 #include "bolt/Passes/ReorderAlgorithm.h" 38 #include "llvm/Support/CommandLine.h" 39 40 using namespace llvm; 41 using namespace bolt; 42 43 namespace opts { 44 45 extern cl::OptionCategory BoltOptCategory; 46 extern cl::opt<bool> NoThreads; 47 48 cl::opt<unsigned> ChainSplitThreshold( 49 "chain-split-threshold", 50 cl::desc("The maximum size of a chain to apply splitting"), cl::init(128), 51 cl::ReallyHidden, cl::cat(BoltOptCategory)); 52 53 cl::opt<double> 54 ForwardWeight("forward-weight", 55 cl::desc("The weight of forward jumps for ExtTSP value"), 56 cl::init(0.1), cl::ReallyHidden, cl::cat(BoltOptCategory)); 57 58 cl::opt<double> 59 BackwardWeight("backward-weight", 60 cl::desc("The weight of backward jumps for ExtTSP value"), 61 cl::init(0.1), cl::ReallyHidden, cl::cat(BoltOptCategory)); 62 63 cl::opt<unsigned> ForwardDistance( 64 "forward-distance", 65 cl::desc( 66 "The maximum distance (in bytes) of forward jumps for ExtTSP value"), 67 cl::init(1024), cl::ReallyHidden, cl::cat(BoltOptCategory)); 68 69 cl::opt<unsigned> BackwardDistance( 70 "backward-distance", 71 cl::desc( 72 "The maximum distance (in bytes) of backward jumps for ExtTSP value"), 73 cl::init(640), cl::ReallyHidden, cl::cat(BoltOptCategory)); 74 } 75 76 namespace llvm { 77 namespace bolt { 78 79 // Epsilon for comparison of doubles 80 constexpr double EPS = 1e-8; 81 82 class Block; 83 class Chain; 84 class Edge; 85 86 // Calculate Ext-TSP value, which quantifies the expected number of i-cache 87 // misses for a given ordering of basic blocks 88 double extTSPScore(uint64_t SrcAddr, uint64_t SrcSize, uint64_t DstAddr, 89 uint64_t Count) { 90 assert(Count != BinaryBasicBlock::COUNT_NO_PROFILE); 91 92 // Fallthrough 93 if (SrcAddr + SrcSize == DstAddr) { 94 // Assume that FallthroughWeight = 1.0 after normalization 95 return static_cast<double>(Count); 96 } 97 // Forward 98 if (SrcAddr + SrcSize < DstAddr) { 99 const uint64_t Dist = DstAddr - (SrcAddr + SrcSize); 100 if (Dist <= opts::ForwardDistance) { 101 double Prob = 1.0 - static_cast<double>(Dist) / opts::ForwardDistance; 102 return opts::ForwardWeight * Prob * Count; 103 } 104 return 0; 105 } 106 // Backward 107 const uint64_t Dist = SrcAddr + SrcSize - DstAddr; 108 if (Dist <= opts::BackwardDistance) { 109 double Prob = 1.0 - static_cast<double>(Dist) / opts::BackwardDistance; 110 return opts::BackwardWeight * Prob * Count; 111 } 112 return 0; 113 } 114 115 using BlockPair = std::pair<Block *, Block *>; 116 using JumpList = std::vector<std::pair<BlockPair, uint64_t>>; 117 using BlockIter = std::vector<Block *>::const_iterator; 118 119 enum MergeTypeTy { 120 X_Y = 0, 121 X1_Y_X2 = 1, 122 Y_X2_X1 = 2, 123 X2_X1_Y = 3, 124 }; 125 126 class MergeGainTy { 127 public: 128 explicit MergeGainTy() {} 129 explicit MergeGainTy(double Score, size_t MergeOffset, MergeTypeTy MergeType) 130 : Score(Score), MergeOffset(MergeOffset), MergeType(MergeType) {} 131 132 double score() const { return Score; } 133 134 size_t mergeOffset() const { return MergeOffset; } 135 136 MergeTypeTy mergeType() const { return MergeType; } 137 138 // returns 'true' iff Other is preferred over this 139 bool operator<(const MergeGainTy &Other) const { 140 return (Other.Score > EPS && Other.Score > Score + EPS); 141 } 142 143 private: 144 double Score{-1.0}; 145 size_t MergeOffset{0}; 146 MergeTypeTy MergeType{MergeTypeTy::X_Y}; 147 }; 148 149 // A node in CFG corresponding to a BinaryBasicBlock. 150 // The class wraps several mutable fields utilized in the ExtTSP algorithm 151 class Block { 152 public: 153 Block(const Block &) = delete; 154 Block(Block &&) = default; 155 Block &operator=(const Block &) = delete; 156 Block &operator=(Block &&) = default; 157 158 // Corresponding basic block 159 BinaryBasicBlock *BB{nullptr}; 160 // Current chain of the basic block 161 Chain *CurChain{nullptr}; 162 // (Estimated) size of the block in the binary 163 uint64_t Size{0}; 164 // Execution count of the block in the binary 165 uint64_t ExecutionCount{0}; 166 // An original index of the node in CFG 167 size_t Index{0}; 168 // The index of the block in the current chain 169 size_t CurIndex{0}; 170 // An offset of the block in the current chain 171 mutable uint64_t EstimatedAddr{0}; 172 // Fallthrough successor of the node in CFG 173 Block *FallthroughSucc{nullptr}; 174 // Fallthrough predecessor of the node in CFG 175 Block *FallthroughPred{nullptr}; 176 // Outgoing jumps from the block 177 std::vector<std::pair<Block *, uint64_t>> OutJumps; 178 // Incoming jumps to the block 179 std::vector<std::pair<Block *, uint64_t>> InJumps; 180 // Total execution count of incoming jumps 181 uint64_t InWeight{0}; 182 // Total execution count of outgoing jumps 183 uint64_t OutWeight{0}; 184 185 public: 186 explicit Block(BinaryBasicBlock *BB_, uint64_t Size_) 187 : BB(BB_), Size(Size_), ExecutionCount(BB_->getKnownExecutionCount()), 188 Index(BB->getLayoutIndex()) {} 189 190 bool adjacent(const Block *Other) const { 191 return hasOutJump(Other) || hasInJump(Other); 192 } 193 194 bool hasOutJump(const Block *Other) const { 195 for (std::pair<Block *, uint64_t> Jump : OutJumps) { 196 if (Jump.first == Other) 197 return true; 198 } 199 return false; 200 } 201 202 bool hasInJump(const Block *Other) const { 203 for (std::pair<Block *, uint64_t> Jump : InJumps) { 204 if (Jump.first == Other) 205 return true; 206 } 207 return false; 208 } 209 }; 210 211 // A chain (ordered sequence) of CFG nodes (basic blocks) 212 class Chain { 213 public: 214 Chain(const Chain &) = delete; 215 Chain(Chain &&) = default; 216 Chain &operator=(const Chain &) = delete; 217 Chain &operator=(Chain &&) = default; 218 219 explicit Chain(size_t Id, Block *Block) 220 : Id(Id), IsEntry(Block->Index == 0), 221 ExecutionCount(Block->ExecutionCount), Size(Block->Size), Score(0), 222 Blocks(1, Block) {} 223 224 size_t id() const { return Id; } 225 226 uint64_t size() const { return Size; } 227 228 double density() const { return static_cast<double>(ExecutionCount) / Size; } 229 230 uint64_t executionCount() const { return ExecutionCount; } 231 232 bool isEntryPoint() const { return IsEntry; } 233 234 double score() const { return Score; } 235 236 void setScore(double NewScore) { Score = NewScore; } 237 238 const std::vector<Block *> &blocks() const { return Blocks; } 239 240 const std::vector<std::pair<Chain *, Edge *>> &edges() const { return Edges; } 241 242 Edge *getEdge(Chain *Other) const { 243 for (std::pair<Chain *, Edge *> It : Edges) 244 if (It.first == Other) 245 return It.second; 246 return nullptr; 247 } 248 249 void removeEdge(Chain *Other) { 250 auto It = Edges.begin(); 251 while (It != Edges.end()) { 252 if (It->first == Other) { 253 Edges.erase(It); 254 return; 255 } 256 It++; 257 } 258 } 259 260 void addEdge(Chain *Other, Edge *Edge) { Edges.emplace_back(Other, Edge); } 261 262 void merge(Chain *Other, const std::vector<Block *> &MergedBlocks) { 263 Blocks = MergedBlocks; 264 IsEntry |= Other->IsEntry; 265 ExecutionCount += Other->ExecutionCount; 266 Size += Other->Size; 267 // Update block's chains 268 for (size_t Idx = 0; Idx < Blocks.size(); Idx++) { 269 Blocks[Idx]->CurChain = this; 270 Blocks[Idx]->CurIndex = Idx; 271 } 272 } 273 274 void mergeEdges(Chain *Other); 275 276 void clear() { 277 Blocks.clear(); 278 Edges.clear(); 279 } 280 281 private: 282 size_t Id; 283 bool IsEntry; 284 uint64_t ExecutionCount; 285 uint64_t Size; 286 // Cached ext-tsp score for the chain 287 double Score; 288 // Blocks of the chain 289 std::vector<Block *> Blocks; 290 // Adjacent chains and corresponding edges (lists of jumps) 291 std::vector<std::pair<Chain *, Edge *>> Edges; 292 }; 293 294 // An edge in CFG reprsenting jumps between chains of BinaryBasicBlocks. 295 // When blocks are merged into chains, the edges are combined too so that 296 // there is always at most one edge between a pair of chains 297 class Edge { 298 public: 299 Edge(const Edge &) = delete; 300 Edge(Edge &&) = default; 301 Edge &operator=(const Edge &) = delete; 302 Edge &operator=(Edge &&) = default; 303 304 explicit Edge(Block *SrcBlock, Block *DstBlock, uint64_t EC) 305 : SrcChain(SrcBlock->CurChain), DstChain(DstBlock->CurChain), 306 Jumps(1, std::make_pair(std::make_pair(SrcBlock, DstBlock), EC)) {} 307 308 const JumpList &jumps() const { return Jumps; } 309 310 void changeEndpoint(Chain *From, Chain *To) { 311 if (From == SrcChain) 312 SrcChain = To; 313 if (From == DstChain) 314 DstChain = To; 315 } 316 317 void appendJump(Block *SrcBlock, Block *DstBlock, uint64_t EC) { 318 Jumps.emplace_back(std::make_pair(SrcBlock, DstBlock), EC); 319 } 320 321 void moveJumps(Edge *Other) { 322 Jumps.insert(Jumps.end(), Other->Jumps.begin(), Other->Jumps.end()); 323 Other->Jumps.clear(); 324 } 325 326 bool hasCachedMergeGain(Chain *Src, Chain *Dst) const { 327 return Src == SrcChain ? CacheValidForward : CacheValidBackward; 328 } 329 330 MergeGainTy getCachedMergeGain(Chain *Src, Chain *Dst) const { 331 return Src == SrcChain ? CachedGainForward : CachedGainBackward; 332 } 333 334 void setCachedMergeGain(Chain *Src, Chain *Dst, MergeGainTy MergeGain) { 335 if (Src == SrcChain) { 336 CachedGainForward = MergeGain; 337 CacheValidForward = true; 338 } else { 339 CachedGainBackward = MergeGain; 340 CacheValidBackward = true; 341 } 342 } 343 344 void invalidateCache() { 345 CacheValidForward = false; 346 CacheValidBackward = false; 347 } 348 349 private: 350 Chain *SrcChain{nullptr}; 351 Chain *DstChain{nullptr}; 352 // Original jumps in the binary with correspinding execution counts 353 JumpList Jumps; 354 // Cached ext-tsp value for merging the pair of chains 355 // Since the gain of merging (Src, Dst) and (Dst, Src) might be different, 356 // we store both values here 357 MergeGainTy CachedGainForward; 358 MergeGainTy CachedGainBackward; 359 // Whether the cached value must be recomputed 360 bool CacheValidForward{false}; 361 bool CacheValidBackward{false}; 362 }; 363 364 void Chain::mergeEdges(Chain *Other) { 365 assert(this != Other && "cannot merge a chain with itself"); 366 367 // Update edges adjacent to chain Other 368 for (auto EdgeIt : Other->Edges) { 369 Chain *const DstChain = EdgeIt.first; 370 Edge *const DstEdge = EdgeIt.second; 371 Chain *const TargetChain = DstChain == Other ? this : DstChain; 372 373 // Find the corresponding edge in the current chain 374 Edge *curEdge = getEdge(TargetChain); 375 if (curEdge == nullptr) { 376 DstEdge->changeEndpoint(Other, this); 377 this->addEdge(TargetChain, DstEdge); 378 if (DstChain != this && DstChain != Other) 379 DstChain->addEdge(this, DstEdge); 380 } else { 381 curEdge->moveJumps(DstEdge); 382 } 383 // Cleanup leftover edge 384 if (DstChain != Other) 385 DstChain->removeEdge(Other); 386 } 387 } 388 389 // A wrapper around three chains of basic blocks; it is used to avoid extra 390 // instantiation of the vectors. 391 class MergedChain { 392 public: 393 MergedChain(BlockIter Begin1, BlockIter End1, BlockIter Begin2 = BlockIter(), 394 BlockIter End2 = BlockIter(), BlockIter Begin3 = BlockIter(), 395 BlockIter End3 = BlockIter()) 396 : Begin1(Begin1), End1(End1), Begin2(Begin2), End2(End2), Begin3(Begin3), 397 End3(End3) {} 398 399 template <typename F> void forEach(const F &Func) const { 400 for (auto It = Begin1; It != End1; It++) 401 Func(*It); 402 for (auto It = Begin2; It != End2; It++) 403 Func(*It); 404 for (auto It = Begin3; It != End3; It++) 405 Func(*It); 406 } 407 408 std::vector<Block *> getBlocks() const { 409 std::vector<Block *> Result; 410 Result.reserve(std::distance(Begin1, End1) + std::distance(Begin2, End2) + 411 std::distance(Begin3, End3)); 412 Result.insert(Result.end(), Begin1, End1); 413 Result.insert(Result.end(), Begin2, End2); 414 Result.insert(Result.end(), Begin3, End3); 415 return Result; 416 } 417 418 const Block *getFirstBlock() const { return *Begin1; } 419 420 private: 421 BlockIter Begin1; 422 BlockIter End1; 423 BlockIter Begin2; 424 BlockIter End2; 425 BlockIter Begin3; 426 BlockIter End3; 427 }; 428 429 /// Deterministically compare pairs of chains 430 bool compareChainPairs(const Chain *A1, const Chain *B1, const Chain *A2, 431 const Chain *B2) { 432 const uint64_t Samples1 = A1->executionCount() + B1->executionCount(); 433 const uint64_t Samples2 = A2->executionCount() + B2->executionCount(); 434 if (Samples1 != Samples2) 435 return Samples1 < Samples2; 436 437 // Making the order deterministic 438 if (A1 != A2) 439 return A1->id() < A2->id(); 440 return B1->id() < B2->id(); 441 } 442 class ExtTSP { 443 public: 444 ExtTSP(const BinaryFunction &BF) : BF(BF) { initialize(); } 445 446 /// Run the algorithm and return an ordering of basic block 447 void run(BinaryFunction::BasicBlockOrderType &Order) { 448 // Pass 1: Merge blocks with their fallthrough successors 449 mergeFallthroughs(); 450 451 // Pass 2: Merge pairs of chains while improving the ExtTSP objective 452 mergeChainPairs(); 453 454 // Pass 3: Merge cold blocks to reduce code size 455 mergeColdChains(); 456 457 // Collect blocks from all chains 458 concatChains(Order); 459 } 460 461 private: 462 /// Initialize algorithm's data structures 463 void initialize() { 464 // Create a separate MCCodeEmitter to allow lock-free execution 465 BinaryContext::IndependentCodeEmitter Emitter; 466 if (!opts::NoThreads) 467 Emitter = BF.getBinaryContext().createIndependentMCCodeEmitter(); 468 469 // Initialize CFG nodes 470 AllBlocks.reserve(BF.getLayout().block_size()); 471 size_t LayoutIndex = 0; 472 for (BinaryBasicBlock *BB : BF.getLayout().blocks()) { 473 BB->setLayoutIndex(LayoutIndex++); 474 uint64_t Size = 475 std::max<uint64_t>(BB->estimateSize(Emitter.MCE.get()), 1); 476 AllBlocks.emplace_back(BB, Size); 477 } 478 479 // Initialize edges for the blocks and compute their total in/out weights 480 size_t NumEdges = 0; 481 for (Block &Block : AllBlocks) { 482 auto BI = Block.BB->branch_info_begin(); 483 for (BinaryBasicBlock *SuccBB : Block.BB->successors()) { 484 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE && 485 "missing profile for a jump"); 486 if (SuccBB != Block.BB && BI->Count > 0) { 487 class Block &SuccBlock = AllBlocks[SuccBB->getLayoutIndex()]; 488 uint64_t Count = BI->Count; 489 SuccBlock.InWeight += Count; 490 SuccBlock.InJumps.emplace_back(&Block, Count); 491 Block.OutWeight += Count; 492 Block.OutJumps.emplace_back(&SuccBlock, Count); 493 NumEdges++; 494 } 495 ++BI; 496 } 497 } 498 499 // Initialize execution count for every basic block, which is the 500 // maximum over the sums of all in and out edge weights. 501 // Also execution count of the entry point is set to at least 1 502 for (Block &Block : AllBlocks) { 503 size_t Index = Block.Index; 504 Block.ExecutionCount = std::max(Block.ExecutionCount, Block.InWeight); 505 Block.ExecutionCount = std::max(Block.ExecutionCount, Block.OutWeight); 506 if (Index == 0 && Block.ExecutionCount == 0) 507 Block.ExecutionCount = 1; 508 } 509 510 // Initialize chains 511 AllChains.reserve(BF.getLayout().block_size()); 512 HotChains.reserve(BF.getLayout().block_size()); 513 for (Block &Block : AllBlocks) { 514 AllChains.emplace_back(Block.Index, &Block); 515 Block.CurChain = &AllChains.back(); 516 if (Block.ExecutionCount > 0) 517 HotChains.push_back(&AllChains.back()); 518 } 519 520 // Initialize edges 521 AllEdges.reserve(NumEdges); 522 for (Block &Block : AllBlocks) { 523 for (std::pair<class Block *, uint64_t> &Jump : Block.OutJumps) { 524 class Block *const SuccBlock = Jump.first; 525 Edge *CurEdge = Block.CurChain->getEdge(SuccBlock->CurChain); 526 // this edge is already present in the graph 527 if (CurEdge != nullptr) { 528 assert(SuccBlock->CurChain->getEdge(Block.CurChain) != nullptr); 529 CurEdge->appendJump(&Block, SuccBlock, Jump.second); 530 continue; 531 } 532 // this is a new edge 533 AllEdges.emplace_back(&Block, SuccBlock, Jump.second); 534 Block.CurChain->addEdge(SuccBlock->CurChain, &AllEdges.back()); 535 SuccBlock->CurChain->addEdge(Block.CurChain, &AllEdges.back()); 536 } 537 } 538 assert(AllEdges.size() <= NumEdges && "Incorrect number of created edges"); 539 } 540 541 /// For a pair of blocks, A and B, block B is the fallthrough successor of A, 542 /// if (i) all jumps (based on profile) from A goes to B and (ii) all jumps 543 /// to B are from A. Such blocks should be adjacent in an optimal ordering; 544 /// the method finds and merges such pairs of blocks 545 void mergeFallthroughs() { 546 // Find fallthroughs based on edge weights 547 for (Block &Block : AllBlocks) { 548 if (Block.BB->succ_size() == 1 && 549 Block.BB->getSuccessor()->pred_size() == 1 && 550 Block.BB->getSuccessor()->getLayoutIndex() != 0) { 551 size_t SuccIndex = Block.BB->getSuccessor()->getLayoutIndex(); 552 Block.FallthroughSucc = &AllBlocks[SuccIndex]; 553 AllBlocks[SuccIndex].FallthroughPred = &Block; 554 continue; 555 } 556 557 if (Block.OutWeight == 0) 558 continue; 559 for (std::pair<class Block *, uint64_t> &Edge : Block.OutJumps) { 560 class Block *const SuccBlock = Edge.first; 561 // Successor cannot be the first BB, which is pinned 562 if (Block.OutWeight == Edge.second && 563 SuccBlock->InWeight == Edge.second && SuccBlock->Index != 0) { 564 Block.FallthroughSucc = SuccBlock; 565 SuccBlock->FallthroughPred = &Block; 566 break; 567 } 568 } 569 } 570 571 // There might be 'cycles' in the fallthrough dependencies (since profile 572 // data isn't 100% accurate). 573 // Break the cycles by choosing the block with smallest index as the tail 574 for (Block &Block : AllBlocks) { 575 if (Block.FallthroughSucc == nullptr || Block.FallthroughPred == nullptr) 576 continue; 577 578 class Block *SuccBlock = Block.FallthroughSucc; 579 while (SuccBlock != nullptr && SuccBlock != &Block) 580 SuccBlock = SuccBlock->FallthroughSucc; 581 582 if (SuccBlock == nullptr) 583 continue; 584 // break the cycle 585 AllBlocks[Block.FallthroughPred->Index].FallthroughSucc = nullptr; 586 Block.FallthroughPred = nullptr; 587 } 588 589 // Merge blocks with their fallthrough successors 590 for (Block &Block : AllBlocks) { 591 if (Block.FallthroughPred == nullptr && 592 Block.FallthroughSucc != nullptr) { 593 class Block *CurBlock = &Block; 594 while (CurBlock->FallthroughSucc != nullptr) { 595 class Block *const NextBlock = CurBlock->FallthroughSucc; 596 mergeChains(Block.CurChain, NextBlock->CurChain, 0, MergeTypeTy::X_Y); 597 CurBlock = NextBlock; 598 } 599 } 600 } 601 } 602 603 /// Merge pairs of chains while improving the ExtTSP objective 604 void mergeChainPairs() { 605 while (HotChains.size() > 1) { 606 Chain *BestChainPred = nullptr; 607 Chain *BestChainSucc = nullptr; 608 auto BestGain = MergeGainTy(); 609 // Iterate over all pairs of chains 610 for (Chain *ChainPred : HotChains) { 611 // Get candidates for merging with the current chain 612 for (auto EdgeIter : ChainPred->edges()) { 613 Chain *ChainSucc = EdgeIter.first; 614 Edge *ChainEdge = EdgeIter.second; 615 // Ignore loop edges 616 if (ChainPred == ChainSucc) 617 continue; 618 619 // Compute the gain of merging the two chains 620 MergeGainTy CurGain = mergeGain(ChainPred, ChainSucc, ChainEdge); 621 if (CurGain.score() <= EPS) 622 continue; 623 624 if (BestGain < CurGain || 625 (std::abs(CurGain.score() - BestGain.score()) < EPS && 626 compareChainPairs(ChainPred, ChainSucc, BestChainPred, 627 BestChainSucc))) { 628 BestGain = CurGain; 629 BestChainPred = ChainPred; 630 BestChainSucc = ChainSucc; 631 } 632 } 633 } 634 635 // Stop merging when there is no improvement 636 if (BestGain.score() <= EPS) 637 break; 638 639 // Merge the best pair of chains 640 mergeChains(BestChainPred, BestChainSucc, BestGain.mergeOffset(), 641 BestGain.mergeType()); 642 } 643 } 644 645 /// Merge remaining blocks into chains w/o taking jump counts into 646 /// consideration. This allows to maintain the original block order in the 647 /// absense of profile data 648 void mergeColdChains() { 649 for (BinaryBasicBlock *SrcBB : BF.getLayout().blocks()) { 650 // Iterating in reverse order to make sure original fallthrough jumps are 651 // merged first; this might be beneficial for code size. 652 for (auto Itr = SrcBB->succ_rbegin(); Itr != SrcBB->succ_rend(); ++Itr) { 653 BinaryBasicBlock *DstBB = *Itr; 654 size_t SrcIndex = SrcBB->getLayoutIndex(); 655 size_t DstIndex = DstBB->getLayoutIndex(); 656 Chain *SrcChain = AllBlocks[SrcIndex].CurChain; 657 Chain *DstChain = AllBlocks[DstIndex].CurChain; 658 bool IsColdSrc = SrcChain->executionCount() == 0; 659 bool IsColdDst = DstChain->executionCount() == 0; 660 if (SrcChain != DstChain && !DstChain->isEntryPoint() && 661 SrcChain->blocks().back()->Index == SrcIndex && 662 DstChain->blocks().front()->Index == DstIndex && 663 IsColdSrc == IsColdDst) 664 mergeChains(SrcChain, DstChain, 0, MergeTypeTy::X_Y); 665 } 666 } 667 } 668 669 /// Compute ExtTSP score for a given order of basic blocks 670 double score(const MergedChain &MergedBlocks, const JumpList &Jumps) const { 671 if (Jumps.empty()) 672 return 0.0; 673 uint64_t CurAddr = 0; 674 MergedBlocks.forEach( 675 [&](const Block *BB) { 676 BB->EstimatedAddr = CurAddr; 677 CurAddr += BB->Size; 678 } 679 ); 680 681 double Score = 0; 682 for (const std::pair<std::pair<Block *, Block *>, uint64_t> &Jump : Jumps) { 683 const Block *SrcBlock = Jump.first.first; 684 const Block *DstBlock = Jump.first.second; 685 Score += extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size, 686 DstBlock->EstimatedAddr, Jump.second); 687 } 688 return Score; 689 } 690 691 /// Compute the gain of merging two chains 692 /// 693 /// The function considers all possible ways of merging two chains and 694 /// computes the one having the largest increase in ExtTSP objective. The 695 /// result is a pair with the first element being the gain and the second 696 /// element being the corresponding merging type. 697 MergeGainTy mergeGain(Chain *ChainPred, Chain *ChainSucc, Edge *Edge) const { 698 if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) 699 return Edge->getCachedMergeGain(ChainPred, ChainSucc); 700 701 // Precompute jumps between ChainPred and ChainSucc 702 JumpList Jumps = Edge->jumps(); 703 class Edge *EdgePP = ChainPred->getEdge(ChainPred); 704 if (EdgePP != nullptr) 705 Jumps.insert(Jumps.end(), EdgePP->jumps().begin(), EdgePP->jumps().end()); 706 assert(Jumps.size() > 0 && "trying to merge chains w/o jumps"); 707 708 MergeGainTy Gain = MergeGainTy(); 709 // Try to concatenate two chains w/o splitting 710 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, 0, 711 MergeTypeTy::X_Y); 712 713 // Try to break ChainPred in various ways and concatenate with ChainSucc 714 if (ChainPred->blocks().size() <= opts::ChainSplitThreshold) { 715 for (size_t Offset = 1; Offset < ChainPred->blocks().size(); Offset++) { 716 Block *BB1 = ChainPred->blocks()[Offset - 1]; 717 Block *BB2 = ChainPred->blocks()[Offset]; 718 // Does the splitting break FT successors? 719 if (BB1->FallthroughSucc != nullptr) { 720 (void)BB2; 721 assert(BB1->FallthroughSucc == BB2 && "Fallthrough not preserved"); 722 continue; 723 } 724 725 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 726 MergeTypeTy::X1_Y_X2); 727 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 728 MergeTypeTy::Y_X2_X1); 729 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 730 MergeTypeTy::X2_X1_Y); 731 } 732 } 733 734 Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain); 735 return Gain; 736 } 737 738 /// Merge two chains and update the best Gain 739 MergeGainTy computeMergeGain(const MergeGainTy &CurGain, 740 const Chain *ChainPred, const Chain *ChainSucc, 741 const JumpList &Jumps, size_t MergeOffset, 742 MergeTypeTy MergeType) const { 743 MergedChain MergedBlocks = mergeBlocks( 744 ChainPred->blocks(), ChainSucc->blocks(), MergeOffset, MergeType); 745 746 // Do not allow a merge that does not preserve the original entry block 747 if ((ChainPred->isEntryPoint() || ChainSucc->isEntryPoint()) && 748 MergedBlocks.getFirstBlock()->Index != 0) 749 return CurGain; 750 751 // The gain for the new chain 752 const double NewScore = score(MergedBlocks, Jumps) - ChainPred->score(); 753 auto NewGain = MergeGainTy(NewScore, MergeOffset, MergeType); 754 return CurGain < NewGain ? NewGain : CurGain; 755 } 756 757 /// Merge two chains of blocks respecting a given merge 'type' and 'offset' 758 /// 759 /// If MergeType == 0, then the result is a concatentation of two chains. 760 /// Otherwise, the first chain is cut into two sub-chains at the offset, 761 /// and merged using all possible ways of concatenating three chains. 762 MergedChain mergeBlocks(const std::vector<Block *> &X, 763 const std::vector<Block *> &Y, size_t MergeOffset, 764 MergeTypeTy MergeType) const { 765 // Split the first chain, X, into X1 and X2 766 BlockIter BeginX1 = X.begin(); 767 BlockIter EndX1 = X.begin() + MergeOffset; 768 BlockIter BeginX2 = X.begin() + MergeOffset; 769 BlockIter EndX2 = X.end(); 770 BlockIter BeginY = Y.begin(); 771 BlockIter EndY = Y.end(); 772 773 // Construct a new chain from the three existing ones 774 switch (MergeType) { 775 case MergeTypeTy::X_Y: 776 return MergedChain(BeginX1, EndX2, BeginY, EndY); 777 case MergeTypeTy::X1_Y_X2: 778 return MergedChain(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2); 779 case MergeTypeTy::Y_X2_X1: 780 return MergedChain(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1); 781 case MergeTypeTy::X2_X1_Y: 782 return MergedChain(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY); 783 } 784 785 llvm_unreachable("unexpected merge type"); 786 } 787 788 /// Merge chain From into chain Into, update the list of active chains, 789 /// adjacency information, and the corresponding cached values 790 void mergeChains(Chain *Into, Chain *From, size_t MergeOffset, 791 MergeTypeTy MergeType) { 792 assert(Into != From && "a chain cannot be merged with itself"); 793 794 // Merge the blocks 795 MergedChain MergedBlocks = 796 mergeBlocks(Into->blocks(), From->blocks(), MergeOffset, MergeType); 797 Into->merge(From, MergedBlocks.getBlocks()); 798 Into->mergeEdges(From); 799 From->clear(); 800 801 // Update cached ext-tsp score for the new chain 802 Edge *SelfEdge = Into->getEdge(Into); 803 if (SelfEdge != nullptr) { 804 MergedBlocks = MergedChain(Into->blocks().begin(), Into->blocks().end()); 805 Into->setScore(score(MergedBlocks, SelfEdge->jumps())); 806 } 807 808 // Remove chain From from the list of active chains 809 llvm::erase_value(HotChains, From); 810 811 // Invalidate caches 812 for (std::pair<Chain *, Edge *> EdgeIter : Into->edges()) 813 EdgeIter.second->invalidateCache(); 814 } 815 816 /// Concatenate all chains into a final order 817 void concatChains(BinaryFunction::BasicBlockOrderType &Order) { 818 // Collect chains 819 std::vector<Chain *> SortedChains; 820 for (Chain &Chain : AllChains) 821 if (Chain.blocks().size() > 0) 822 SortedChains.push_back(&Chain); 823 824 // Sorting chains by density in decreasing order 825 llvm::stable_sort(SortedChains, [](const Chain *C1, const Chain *C2) { 826 // Original entry point to the front 827 if (C1->isEntryPoint() != C2->isEntryPoint()) { 828 if (C1->isEntryPoint()) 829 return true; 830 if (C2->isEntryPoint()) 831 return false; 832 } 833 834 const double D1 = C1->density(); 835 const double D2 = C2->density(); 836 if (D1 != D2) 837 return D1 > D2; 838 839 // Making the order deterministic 840 return C1->id() < C2->id(); 841 }); 842 843 // Collect the basic blocks in the order specified by their chains 844 Order.reserve(BF.getLayout().block_size()); 845 for (Chain *Chain : SortedChains) 846 for (Block *Block : Chain->blocks()) 847 Order.push_back(Block->BB); 848 } 849 850 private: 851 // The binary function 852 const BinaryFunction &BF; 853 854 // All CFG nodes (basic blocks) 855 std::vector<Block> AllBlocks; 856 857 // All chains of blocks 858 std::vector<Chain> AllChains; 859 860 // Active chains. The vector gets updated at runtime when chains are merged 861 std::vector<Chain *> HotChains; 862 863 // All edges between chains 864 std::vector<Edge> AllEdges; 865 }; 866 867 void ExtTSPReorderAlgorithm::reorderBasicBlocks(const BinaryFunction &BF, 868 BasicBlockOrder &Order) const { 869 if (BF.getLayout().block_empty()) 870 return; 871 872 // Do not change layout of functions w/o profile information 873 if (!BF.hasValidProfile() || BF.getLayout().block_size() <= 2) { 874 for (BinaryBasicBlock *BB : BF.getLayout().blocks()) 875 Order.push_back(BB); 876 return; 877 } 878 879 // Apply the algorithm 880 ExtTSP(BF).run(Order); 881 882 // Verify correctness 883 assert(Order[0]->isEntryPoint() && "Original entry point is not preserved"); 884 assert(Order.size() == BF.getLayout().block_size() && 885 "Wrong size of reordered layout"); 886 } 887 888 } // namespace bolt 889 } // namespace llvm 890