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.layout_size()); 471 size_t LayoutIndex = 0; 472 for (BinaryBasicBlock *BB : BF.layout()) { 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.layout_size()); 512 HotChains.reserve(BF.layout_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 cold blocks to reduce code size 646 void mergeColdChains() { 647 for (BinaryBasicBlock *SrcBB : BF.layout()) { 648 // Iterating in reverse order to make sure original fallthrough jumps are 649 // merged first 650 for (auto Itr = SrcBB->succ_rbegin(); Itr != SrcBB->succ_rend(); ++Itr) { 651 BinaryBasicBlock *DstBB = *Itr; 652 size_t SrcIndex = SrcBB->getLayoutIndex(); 653 size_t DstIndex = DstBB->getLayoutIndex(); 654 Chain *SrcChain = AllBlocks[SrcIndex].CurChain; 655 Chain *DstChain = AllBlocks[DstIndex].CurChain; 656 if (SrcChain != DstChain && !DstChain->isEntryPoint() && 657 SrcChain->blocks().back()->Index == SrcIndex && 658 DstChain->blocks().front()->Index == DstIndex) 659 mergeChains(SrcChain, DstChain, 0, MergeTypeTy::X_Y); 660 } 661 } 662 } 663 664 /// Compute ExtTSP score for a given order of basic blocks 665 double score(const MergedChain &MergedBlocks, const JumpList &Jumps) const { 666 if (Jumps.empty()) 667 return 0.0; 668 uint64_t CurAddr = 0; 669 MergedBlocks.forEach( 670 [&](const Block *BB) { 671 BB->EstimatedAddr = CurAddr; 672 CurAddr += BB->Size; 673 } 674 ); 675 676 double Score = 0; 677 for (const std::pair<std::pair<Block *, Block *>, uint64_t> &Jump : Jumps) { 678 const Block *SrcBlock = Jump.first.first; 679 const Block *DstBlock = Jump.first.second; 680 Score += extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size, 681 DstBlock->EstimatedAddr, Jump.second); 682 } 683 return Score; 684 } 685 686 /// Compute the gain of merging two chains 687 /// 688 /// The function considers all possible ways of merging two chains and 689 /// computes the one having the largest increase in ExtTSP objective. The 690 /// result is a pair with the first element being the gain and the second 691 /// element being the corresponding merging type. 692 MergeGainTy mergeGain(Chain *ChainPred, Chain *ChainSucc, Edge *Edge) const { 693 if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) 694 return Edge->getCachedMergeGain(ChainPred, ChainSucc); 695 696 // Precompute jumps between ChainPred and ChainSucc 697 JumpList Jumps = Edge->jumps(); 698 class Edge *EdgePP = ChainPred->getEdge(ChainPred); 699 if (EdgePP != nullptr) 700 Jumps.insert(Jumps.end(), EdgePP->jumps().begin(), EdgePP->jumps().end()); 701 assert(Jumps.size() > 0 && "trying to merge chains w/o jumps"); 702 703 MergeGainTy Gain = MergeGainTy(); 704 // Try to concatenate two chains w/o splitting 705 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, 0, 706 MergeTypeTy::X_Y); 707 708 // Try to break ChainPred in various ways and concatenate with ChainSucc 709 if (ChainPred->blocks().size() <= opts::ChainSplitThreshold) { 710 for (size_t Offset = 1; Offset < ChainPred->blocks().size(); Offset++) { 711 Block *BB1 = ChainPred->blocks()[Offset - 1]; 712 Block *BB2 = ChainPred->blocks()[Offset]; 713 // Does the splitting break FT successors? 714 if (BB1->FallthroughSucc != nullptr) { 715 (void)BB2; 716 assert(BB1->FallthroughSucc == BB2 && "Fallthrough not preserved"); 717 continue; 718 } 719 720 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 721 MergeTypeTy::X1_Y_X2); 722 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 723 MergeTypeTy::Y_X2_X1); 724 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 725 MergeTypeTy::X2_X1_Y); 726 } 727 } 728 729 Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain); 730 return Gain; 731 } 732 733 /// Merge two chains and update the best Gain 734 MergeGainTy computeMergeGain(const MergeGainTy &CurGain, 735 const Chain *ChainPred, const Chain *ChainSucc, 736 const JumpList &Jumps, size_t MergeOffset, 737 MergeTypeTy MergeType) const { 738 MergedChain MergedBlocks = mergeBlocks( 739 ChainPred->blocks(), ChainSucc->blocks(), MergeOffset, MergeType); 740 741 // Do not allow a merge that does not preserve the original entry block 742 if ((ChainPred->isEntryPoint() || ChainSucc->isEntryPoint()) && 743 MergedBlocks.getFirstBlock()->Index != 0) 744 return CurGain; 745 746 // The gain for the new chain 747 const double NewScore = score(MergedBlocks, Jumps) - ChainPred->score(); 748 auto NewGain = MergeGainTy(NewScore, MergeOffset, MergeType); 749 return CurGain < NewGain ? NewGain : CurGain; 750 } 751 752 /// Merge two chains of blocks respecting a given merge 'type' and 'offset' 753 /// 754 /// If MergeType == 0, then the result is a concatentation of two chains. 755 /// Otherwise, the first chain is cut into two sub-chains at the offset, 756 /// and merged using all possible ways of concatenating three chains. 757 MergedChain mergeBlocks(const std::vector<Block *> &X, 758 const std::vector<Block *> &Y, size_t MergeOffset, 759 MergeTypeTy MergeType) const { 760 // Split the first chain, X, into X1 and X2 761 BlockIter BeginX1 = X.begin(); 762 BlockIter EndX1 = X.begin() + MergeOffset; 763 BlockIter BeginX2 = X.begin() + MergeOffset; 764 BlockIter EndX2 = X.end(); 765 BlockIter BeginY = Y.begin(); 766 BlockIter EndY = Y.end(); 767 768 // Construct a new chain from the three existing ones 769 switch (MergeType) { 770 case MergeTypeTy::X_Y: 771 return MergedChain(BeginX1, EndX2, BeginY, EndY); 772 case MergeTypeTy::X1_Y_X2: 773 return MergedChain(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2); 774 case MergeTypeTy::Y_X2_X1: 775 return MergedChain(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1); 776 case MergeTypeTy::X2_X1_Y: 777 return MergedChain(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY); 778 } 779 780 llvm_unreachable("unexpected merge type"); 781 } 782 783 /// Merge chain From into chain Into, update the list of active chains, 784 /// adjacency information, and the corresponding cached values 785 void mergeChains(Chain *Into, Chain *From, size_t MergeOffset, 786 MergeTypeTy MergeType) { 787 assert(Into != From && "a chain cannot be merged with itself"); 788 789 // Merge the blocks 790 MergedChain MergedBlocks = 791 mergeBlocks(Into->blocks(), From->blocks(), MergeOffset, MergeType); 792 Into->merge(From, MergedBlocks.getBlocks()); 793 Into->mergeEdges(From); 794 From->clear(); 795 796 // Update cached ext-tsp score for the new chain 797 Edge *SelfEdge = Into->getEdge(Into); 798 if (SelfEdge != nullptr) { 799 MergedBlocks = MergedChain(Into->blocks().begin(), Into->blocks().end()); 800 Into->setScore(score(MergedBlocks, SelfEdge->jumps())); 801 } 802 803 // Remove chain From from the list of active chains 804 auto Iter = std::remove(HotChains.begin(), HotChains.end(), From); 805 HotChains.erase(Iter, HotChains.end()); 806 807 // Invalidate caches 808 for (std::pair<Chain *, Edge *> EdgeIter : Into->edges()) 809 EdgeIter.second->invalidateCache(); 810 } 811 812 /// Concatenate all chains into a final order 813 void concatChains(BinaryFunction::BasicBlockOrderType &Order) { 814 // Collect chains 815 std::vector<Chain *> SortedChains; 816 for (Chain &Chain : AllChains) 817 if (Chain.blocks().size() > 0) 818 SortedChains.push_back(&Chain); 819 820 // Sorting chains by density in decreasing order 821 std::stable_sort( 822 SortedChains.begin(), SortedChains.end(), 823 [](const Chain *C1, const Chain *C2) { 824 // Original entry point to the front 825 if (C1->isEntryPoint() != C2->isEntryPoint()) { 826 if (C1->isEntryPoint()) 827 return true; 828 if (C2->isEntryPoint()) 829 return false; 830 } 831 832 const double D1 = C1->density(); 833 const double D2 = C2->density(); 834 if (D1 != D2) 835 return D1 > D2; 836 837 // Making the order deterministic 838 return C1->id() < C2->id(); 839 } 840 ); 841 842 // Collect the basic blocks in the order specified by their chains 843 Order.reserve(BF.layout_size()); 844 for (Chain *Chain : SortedChains) 845 for (Block *Block : Chain->blocks()) 846 Order.push_back(Block->BB); 847 } 848 849 private: 850 // The binary function 851 const BinaryFunction &BF; 852 853 // All CFG nodes (basic blocks) 854 std::vector<Block> AllBlocks; 855 856 // All chains of blocks 857 std::vector<Chain> AllChains; 858 859 // Active chains. The vector gets updated at runtime when chains are merged 860 std::vector<Chain *> HotChains; 861 862 // All edges between chains 863 std::vector<Edge> AllEdges; 864 }; 865 866 void ExtTSPReorderAlgorithm::reorderBasicBlocks(const BinaryFunction &BF, 867 BasicBlockOrder &Order) const { 868 if (BF.layout_empty()) 869 return; 870 871 // Do not change layout of functions w/o profile information 872 if (!BF.hasValidProfile() || BF.layout_size() <= 2) { 873 for (BinaryBasicBlock *BB : BF.layout()) 874 Order.push_back(BB); 875 return; 876 } 877 878 // Apply the algorithm 879 ExtTSP(BF).run(Order); 880 881 // Verify correctness 882 assert(Order[0]->isEntryPoint() && "Original entry point is not preserved"); 883 assert(Order.size() == BF.layout_size() && "Wrong size of reordered layout"); 884 } 885 886 } // namespace bolt 887 } // namespace llvm 888