1 //===- CodeLayout.cpp - Implementation of code layout algorithms ----------===// 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 tries to find a layout of nodes (basic blocks) of a given CFG 12 // optimizing jump locality and thus processor I-cache utilization. This is 13 // achieved via increasing the number of fall-through jumps and co-locating 14 // frequently executed nodes together. The name follows the underlying 15 // optimization problem, Extended-TSP, which is a generalization of classical 16 // (maximum) Traveling Salesmen Problem. 17 // 18 // The algorithm is a greedy heuristic that works with chains (ordered lists) 19 // of basic blocks. Initially all chains are isolated basic blocks. On every 20 // iteration, we pick a pair of chains whose merging yields the biggest increase 21 // in the ExtTSP score, which models how i-cache "friendly" a specific chain is. 22 // A pair of chains giving the maximum gain is merged into a new chain. The 23 // procedure stops when there is only one chain left, or when merging does not 24 // increase ExtTSP. In the latter case, the remaining chains are sorted by 25 // density in the decreasing order. 26 // 27 // An important aspect is the way two chains are merged. Unlike earlier 28 // algorithms (e.g., based on the approach of Pettis-Hansen), two 29 // chains, X and Y, are first split into three, X1, X2, and Y. Then we 30 // consider all possible ways of gluing the three chains (e.g., X1YX2, X1X2Y, 31 // X2X1Y, X2YX1, YX1X2, YX2X1) and choose the one producing the largest score. 32 // This improves the quality of the final result (the search space is larger) 33 // while keeping the implementation sufficiently fast. 34 // 35 // Reference: 36 // * A. Newell and S. Pupyrev, Improved Basic Block Reordering, 37 // IEEE Transactions on Computers, 2020 38 // 39 //===----------------------------------------------------------------------===// 40 41 #include "llvm/Transforms/Utils/CodeLayout.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 45 using namespace llvm; 46 #define DEBUG_TYPE "code-layout" 47 48 cl::opt<bool> EnableExtTspBlockPlacement( 49 "enable-ext-tsp-block-placement", cl::Hidden, cl::init(false), 50 cl::desc("Enable machine block placement based on the ext-tsp model, " 51 "optimizing I-cache utilization.")); 52 53 // Algorithm-specific constants. The values are tuned for the best performance 54 // of large-scale front-end bound binaries. 55 static cl::opt<double> 56 ForwardWeight("ext-tsp-forward-weight", cl::Hidden, cl::init(0.1), 57 cl::desc("The weight of forward jumps for ExtTSP value")); 58 59 static cl::opt<double> 60 BackwardWeight("ext-tsp-backward-weight", cl::Hidden, cl::init(0.1), 61 cl::desc("The weight of backward jumps for ExtTSP value")); 62 63 static cl::opt<unsigned> ForwardDistance( 64 "ext-tsp-forward-distance", cl::Hidden, cl::init(1024), 65 cl::desc("The maximum distance (in bytes) of a forward jump for ExtTSP")); 66 67 static cl::opt<unsigned> BackwardDistance( 68 "ext-tsp-backward-distance", cl::Hidden, cl::init(640), 69 cl::desc("The maximum distance (in bytes) of a backward jump for ExtTSP")); 70 71 // The maximum size of a chain for splitting. Larger values of the threshold 72 // may yield better quality at the cost of worsen run-time. 73 static cl::opt<unsigned> ChainSplitThreshold( 74 "ext-tsp-chain-split-threshold", cl::Hidden, cl::init(128), 75 cl::desc("The maximum size of a chain to apply splitting")); 76 77 // The option enables splitting (large) chains along in-coming and out-going 78 // jumps. This typically results in a better quality. 79 static cl::opt<bool> EnableChainSplitAlongJumps( 80 "ext-tsp-enable-chain-split-along-jumps", cl::Hidden, cl::init(true), 81 cl::desc("The maximum size of a chain to apply splitting")); 82 83 namespace { 84 85 // Epsilon for comparison of doubles. 86 constexpr double EPS = 1e-8; 87 88 // Compute the Ext-TSP score for a jump between a given pair of blocks, 89 // using their sizes, (estimated) addresses and the jump execution count. 90 double extTSPScore(uint64_t SrcAddr, uint64_t SrcSize, uint64_t DstAddr, 91 uint64_t Count) { 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 auto Dist = DstAddr - (SrcAddr + SrcSize); 100 if (Dist <= ForwardDistance) { 101 double Prob = 1.0 - static_cast<double>(Dist) / ForwardDistance; 102 return ForwardWeight * Prob * Count; 103 } 104 return 0; 105 } 106 // Backward 107 const auto Dist = SrcAddr + SrcSize - DstAddr; 108 if (Dist <= BackwardDistance) { 109 double Prob = 1.0 - static_cast<double>(Dist) / BackwardDistance; 110 return BackwardWeight * Prob * Count; 111 } 112 return 0; 113 } 114 115 /// A type of merging two chains, X and Y. The former chain is split into 116 /// X1 and X2 and then concatenated with Y in the order specified by the type. 117 enum class MergeTypeTy : int { X_Y, X1_Y_X2, Y_X2_X1, X2_X1_Y }; 118 119 /// The gain of merging two chains, that is, the Ext-TSP score of the merge 120 /// together with the corresponfiding merge 'type' and 'offset'. 121 class MergeGainTy { 122 public: 123 explicit MergeGainTy() {} 124 explicit MergeGainTy(double Score, size_t MergeOffset, MergeTypeTy MergeType) 125 : Score(Score), MergeOffset(MergeOffset), MergeType(MergeType) {} 126 127 double score() const { return Score; } 128 129 size_t mergeOffset() const { return MergeOffset; } 130 131 MergeTypeTy mergeType() const { return MergeType; } 132 133 // Returns 'true' iff Other is preferred over this. 134 bool operator<(const MergeGainTy &Other) const { 135 return (Other.Score > EPS && Other.Score > Score + EPS); 136 } 137 138 // Update the current gain if Other is preferred over this. 139 void updateIfLessThan(const MergeGainTy &Other) { 140 if (*this < Other) 141 *this = Other; 142 } 143 144 private: 145 double Score{-1.0}; 146 size_t MergeOffset{0}; 147 MergeTypeTy MergeType{MergeTypeTy::X_Y}; 148 }; 149 150 class Block; 151 class Jump; 152 class Chain; 153 class ChainEdge; 154 155 /// A node in the graph, typically corresponding to a basic block in CFG. 156 class Block { 157 public: 158 Block(const Block &) = delete; 159 Block(Block &&) = default; 160 Block &operator=(const Block &) = delete; 161 Block &operator=(Block &&) = default; 162 163 // The original index of the block in CFG. 164 size_t Index{0}; 165 // The index of the block in the current chain. 166 size_t CurIndex{0}; 167 // Size of the block in the binary. 168 uint64_t Size{0}; 169 // Execution count of the block in the profile data. 170 uint64_t ExecutionCount{0}; 171 // Current chain of the node. 172 Chain *CurChain{nullptr}; 173 // An offset of the block in the current chain. 174 mutable uint64_t EstimatedAddr{0}; 175 // Forced successor of the block in CFG. 176 Block *ForcedSucc{nullptr}; 177 // Forced predecessor of the block in CFG. 178 Block *ForcedPred{nullptr}; 179 // Outgoing jumps from the block. 180 std::vector<Jump *> OutJumps; 181 // Incoming jumps to the block. 182 std::vector<Jump *> InJumps; 183 184 public: 185 explicit Block(size_t Index, uint64_t Size_, uint64_t EC) 186 : Index(Index), Size(Size_), ExecutionCount(EC) {} 187 bool isEntry() const { return Index == 0; } 188 }; 189 190 /// An arc in the graph, typically corresponding to a jump between two blocks. 191 class Jump { 192 public: 193 Jump(const Jump &) = delete; 194 Jump(Jump &&) = default; 195 Jump &operator=(const Jump &) = delete; 196 Jump &operator=(Jump &&) = default; 197 198 // Source block of the jump. 199 Block *Source; 200 // Target block of the jump. 201 Block *Target; 202 // Execution count of the arc in the profile data. 203 uint64_t ExecutionCount{0}; 204 205 public: 206 explicit Jump(Block *Source, Block *Target, uint64_t ExecutionCount) 207 : Source(Source), Target(Target), ExecutionCount(ExecutionCount) {} 208 }; 209 210 /// A chain (ordered sequence) of blocks. 211 class Chain { 212 public: 213 Chain(const Chain &) = delete; 214 Chain(Chain &&) = default; 215 Chain &operator=(const Chain &) = delete; 216 Chain &operator=(Chain &&) = default; 217 218 explicit Chain(uint64_t Id, Block *Block) 219 : Id(Id), Score(0), Blocks(1, Block) {} 220 221 uint64_t id() const { return Id; } 222 223 bool isEntry() const { return Blocks[0]->Index == 0; } 224 225 double score() const { return Score; } 226 227 void setScore(double NewScore) { Score = NewScore; } 228 229 const std::vector<Block *> &blocks() const { return Blocks; } 230 231 const std::vector<std::pair<Chain *, ChainEdge *>> &edges() const { 232 return Edges; 233 } 234 235 ChainEdge *getEdge(Chain *Other) const { 236 for (auto It : Edges) { 237 if (It.first == Other) 238 return It.second; 239 } 240 return nullptr; 241 } 242 243 void removeEdge(Chain *Other) { 244 auto It = Edges.begin(); 245 while (It != Edges.end()) { 246 if (It->first == Other) { 247 Edges.erase(It); 248 return; 249 } 250 It++; 251 } 252 } 253 254 void addEdge(Chain *Other, ChainEdge *Edge) { 255 Edges.push_back(std::make_pair(Other, Edge)); 256 } 257 258 void merge(Chain *Other, const std::vector<Block *> &MergedBlocks) { 259 Blocks = MergedBlocks; 260 // Update the block's chains 261 for (size_t Idx = 0; Idx < Blocks.size(); Idx++) { 262 Blocks[Idx]->CurChain = this; 263 Blocks[Idx]->CurIndex = Idx; 264 } 265 } 266 267 void mergeEdges(Chain *Other); 268 269 void clear() { 270 Blocks.clear(); 271 Blocks.shrink_to_fit(); 272 Edges.clear(); 273 Edges.shrink_to_fit(); 274 } 275 276 private: 277 // Unique chain identifier. 278 uint64_t Id; 279 // Cached ext-tsp score for the chain. 280 double Score; 281 // Blocks of the chain. 282 std::vector<Block *> Blocks; 283 // Adjacent chains and corresponding edges (lists of jumps). 284 std::vector<std::pair<Chain *, ChainEdge *>> Edges; 285 }; 286 287 /// An edge in CFG representing jumps between two chains. 288 /// When blocks are merged into chains, the edges are combined too so that 289 /// there is always at most one edge between a pair of chains 290 class ChainEdge { 291 public: 292 ChainEdge(const ChainEdge &) = delete; 293 ChainEdge(ChainEdge &&) = default; 294 ChainEdge &operator=(const ChainEdge &) = delete; 295 ChainEdge &operator=(ChainEdge &&) = default; 296 297 explicit ChainEdge(Jump *Jump) 298 : SrcChain(Jump->Source->CurChain), DstChain(Jump->Target->CurChain), 299 Jumps(1, Jump) {} 300 301 const std::vector<Jump *> &jumps() const { return Jumps; } 302 303 void changeEndpoint(Chain *From, Chain *To) { 304 if (From == SrcChain) 305 SrcChain = To; 306 if (From == DstChain) 307 DstChain = To; 308 } 309 310 void appendJump(Jump *Jump) { Jumps.push_back(Jump); } 311 312 void moveJumps(ChainEdge *Other) { 313 Jumps.insert(Jumps.end(), Other->Jumps.begin(), Other->Jumps.end()); 314 Other->Jumps.clear(); 315 Other->Jumps.shrink_to_fit(); 316 } 317 318 bool hasCachedMergeGain(Chain *Src, Chain *Dst) const { 319 return Src == SrcChain ? CacheValidForward : CacheValidBackward; 320 } 321 322 MergeGainTy getCachedMergeGain(Chain *Src, Chain *Dst) const { 323 return Src == SrcChain ? CachedGainForward : CachedGainBackward; 324 } 325 326 void setCachedMergeGain(Chain *Src, Chain *Dst, MergeGainTy MergeGain) { 327 if (Src == SrcChain) { 328 CachedGainForward = MergeGain; 329 CacheValidForward = true; 330 } else { 331 CachedGainBackward = MergeGain; 332 CacheValidBackward = true; 333 } 334 } 335 336 void invalidateCache() { 337 CacheValidForward = false; 338 CacheValidBackward = false; 339 } 340 341 private: 342 // Source chain. 343 Chain *SrcChain{nullptr}; 344 // Destination chain. 345 Chain *DstChain{nullptr}; 346 // Original jumps in the binary with correspinding execution counts. 347 std::vector<Jump *> Jumps; 348 // Cached ext-tsp value for merging the pair of chains. 349 // Since the gain of merging (Src, Dst) and (Dst, Src) might be different, 350 // we store both values here. 351 MergeGainTy CachedGainForward; 352 MergeGainTy CachedGainBackward; 353 // Whether the cached value must be recomputed. 354 bool CacheValidForward{false}; 355 bool CacheValidBackward{false}; 356 }; 357 358 void Chain::mergeEdges(Chain *Other) { 359 assert(this != Other && "cannot merge a chain with itself"); 360 361 // Update edges adjacent to chain Other 362 for (auto EdgeIt : Other->Edges) { 363 const auto DstChain = EdgeIt.first; 364 const auto DstEdge = EdgeIt.second; 365 const auto TargetChain = DstChain == Other ? this : DstChain; 366 auto CurEdge = getEdge(TargetChain); 367 if (CurEdge == nullptr) { 368 DstEdge->changeEndpoint(Other, this); 369 this->addEdge(TargetChain, DstEdge); 370 if (DstChain != this && DstChain != Other) { 371 DstChain->addEdge(this, DstEdge); 372 } 373 } else { 374 CurEdge->moveJumps(DstEdge); 375 } 376 // Cleanup leftover edge 377 if (DstChain != Other) { 378 DstChain->removeEdge(Other); 379 } 380 } 381 } 382 383 using BlockIter = std::vector<Block *>::const_iterator; 384 385 /// A wrapper around three chains of blocks; it is used to avoid extra 386 /// instantiation of the vectors. 387 class MergedChain { 388 public: 389 MergedChain(BlockIter Begin1, BlockIter End1, BlockIter Begin2 = BlockIter(), 390 BlockIter End2 = BlockIter(), BlockIter Begin3 = BlockIter(), 391 BlockIter End3 = BlockIter()) 392 : Begin1(Begin1), End1(End1), Begin2(Begin2), End2(End2), Begin3(Begin3), 393 End3(End3) {} 394 395 template <typename F> void forEach(const F &Func) const { 396 for (auto It = Begin1; It != End1; It++) 397 Func(*It); 398 for (auto It = Begin2; It != End2; It++) 399 Func(*It); 400 for (auto It = Begin3; It != End3; It++) 401 Func(*It); 402 } 403 404 std::vector<Block *> getBlocks() const { 405 std::vector<Block *> Result; 406 Result.reserve(std::distance(Begin1, End1) + std::distance(Begin2, End2) + 407 std::distance(Begin3, End3)); 408 Result.insert(Result.end(), Begin1, End1); 409 Result.insert(Result.end(), Begin2, End2); 410 Result.insert(Result.end(), Begin3, End3); 411 return Result; 412 } 413 414 const Block *getFirstBlock() const { return *Begin1; } 415 416 private: 417 BlockIter Begin1; 418 BlockIter End1; 419 BlockIter Begin2; 420 BlockIter End2; 421 BlockIter Begin3; 422 BlockIter End3; 423 }; 424 425 /// The implementation of the ExtTSP algorithm. 426 class ExtTSPImpl { 427 using EdgeT = std::pair<uint64_t, uint64_t>; 428 using EdgeCountMap = DenseMap<EdgeT, uint64_t>; 429 430 public: 431 ExtTSPImpl(size_t NumNodes, const std::vector<uint64_t> &NodeSizes, 432 const std::vector<uint64_t> &NodeCounts, 433 const EdgeCountMap &EdgeCounts) 434 : NumNodes(NumNodes) { 435 initialize(NodeSizes, NodeCounts, EdgeCounts); 436 } 437 438 /// Run the algorithm and return an optimized ordering of blocks. 439 void run(std::vector<uint64_t> &Result) { 440 // Pass 1: Merge blocks with their mutually forced successors 441 mergeForcedPairs(); 442 443 // Pass 2: Merge pairs of chains while improving the ExtTSP objective 444 mergeChainPairs(); 445 446 // Pass 3: Merge cold blocks to reduce code size 447 mergeColdChains(); 448 449 // Collect blocks from all chains 450 concatChains(Result); 451 } 452 453 private: 454 /// Initialize the algorithm's data structures. 455 void initialize(const std::vector<uint64_t> &NodeSizes, 456 const std::vector<uint64_t> &NodeCounts, 457 const EdgeCountMap &EdgeCounts) { 458 // Initialize blocks 459 AllBlocks.reserve(NumNodes); 460 for (uint64_t Node = 0; Node < NumNodes; Node++) { 461 uint64_t Size = std::max<uint64_t>(NodeSizes[Node], 1ULL); 462 uint64_t ExecutionCount = NodeCounts[Node]; 463 // The execution count of the entry block is set to at least 1 464 if (Node == 0 && ExecutionCount == 0) 465 ExecutionCount = 1; 466 AllBlocks.emplace_back(Node, Size, ExecutionCount); 467 } 468 469 // Initialize jumps between blocks 470 SuccNodes = std::vector<std::vector<uint64_t>>(NumNodes); 471 PredNodes = std::vector<std::vector<uint64_t>>(NumNodes); 472 AllJumps.reserve(EdgeCounts.size()); 473 for (auto It : EdgeCounts) { 474 auto Pred = It.first.first; 475 auto Succ = It.first.second; 476 // Ignore self-edges 477 if (Pred == Succ) 478 continue; 479 480 SuccNodes[Pred].push_back(Succ); 481 PredNodes[Succ].push_back(Pred); 482 auto ExecutionCount = It.second; 483 if (ExecutionCount > 0) { 484 auto &Block = AllBlocks[Pred]; 485 auto &SuccBlock = AllBlocks[Succ]; 486 AllJumps.emplace_back(&Block, &SuccBlock, ExecutionCount); 487 SuccBlock.InJumps.push_back(&AllJumps.back()); 488 Block.OutJumps.push_back(&AllJumps.back()); 489 } 490 } 491 492 // Initialize chains 493 AllChains.reserve(NumNodes); 494 HotChains.reserve(NumNodes); 495 for (auto &Block : AllBlocks) { 496 AllChains.emplace_back(Block.Index, &Block); 497 Block.CurChain = &AllChains.back(); 498 if (Block.ExecutionCount > 0) { 499 HotChains.push_back(&AllChains.back()); 500 } 501 } 502 503 // Initialize chain edges 504 AllEdges.reserve(AllJumps.size()); 505 for (auto &Block : AllBlocks) { 506 for (auto &Jump : Block.OutJumps) { 507 const auto SuccBlock = Jump->Target; 508 auto CurEdge = Block.CurChain->getEdge(SuccBlock->CurChain); 509 // this edge is already present in the graph 510 if (CurEdge != nullptr) { 511 assert(SuccBlock->CurChain->getEdge(Block.CurChain) != nullptr); 512 CurEdge->appendJump(Jump); 513 continue; 514 } 515 // this is a new edge 516 AllEdges.emplace_back(Jump); 517 Block.CurChain->addEdge(SuccBlock->CurChain, &AllEdges.back()); 518 SuccBlock->CurChain->addEdge(Block.CurChain, &AllEdges.back()); 519 } 520 } 521 } 522 523 /// For a pair of blocks, A and B, block B is the forced successor of A, 524 /// if (i) all jumps (based on profile) from A goes to B and (ii) all jumps 525 /// to B are from A. Such blocks should be adjacent in the optimal ordering; 526 /// the method finds and merges such pairs of blocks. 527 void mergeForcedPairs() { 528 // Find fallthroughs based on edge weights 529 for (auto &Block : AllBlocks) { 530 if (SuccNodes[Block.Index].size() == 1 && 531 PredNodes[SuccNodes[Block.Index][0]].size() == 1 && 532 SuccNodes[Block.Index][0] != 0) { 533 size_t SuccIndex = SuccNodes[Block.Index][0]; 534 Block.ForcedSucc = &AllBlocks[SuccIndex]; 535 AllBlocks[SuccIndex].ForcedPred = &Block; 536 } 537 } 538 539 // There might be 'cycles' in the forced dependencies, since profile 540 // data isn't 100% accurate. Typically this is observed in loops, when the 541 // loop edges are the hottest successors for the basic blocks of the loop. 542 // Break the cycles by choosing the block with the smallest index as the 543 // head. This helps to keep the original order of the loops, which likely 544 // have already been rotated in the optimized manner. 545 for (auto &Block : AllBlocks) { 546 if (Block.ForcedSucc == nullptr || Block.ForcedPred == nullptr) 547 continue; 548 549 auto SuccBlock = Block.ForcedSucc; 550 while (SuccBlock != nullptr && SuccBlock != &Block) { 551 SuccBlock = SuccBlock->ForcedSucc; 552 } 553 if (SuccBlock == nullptr) 554 continue; 555 // Break the cycle 556 AllBlocks[Block.ForcedPred->Index].ForcedSucc = nullptr; 557 Block.ForcedPred = nullptr; 558 } 559 560 // Merge blocks with their fallthrough successors 561 for (auto &Block : AllBlocks) { 562 if (Block.ForcedPred == nullptr && Block.ForcedSucc != nullptr) { 563 auto CurBlock = &Block; 564 while (CurBlock->ForcedSucc != nullptr) { 565 const auto NextBlock = CurBlock->ForcedSucc; 566 mergeChains(Block.CurChain, NextBlock->CurChain, 0, MergeTypeTy::X_Y); 567 CurBlock = NextBlock; 568 } 569 } 570 } 571 } 572 573 /// Merge pairs of chains while improving the ExtTSP objective. 574 void mergeChainPairs() { 575 /// Deterministically compare pairs of chains 576 auto compareChainPairs = [](const Chain *A1, const Chain *B1, 577 const Chain *A2, const Chain *B2) { 578 if (A1 != A2) 579 return A1->id() < A2->id(); 580 return B1->id() < B2->id(); 581 }; 582 583 while (HotChains.size() > 1) { 584 Chain *BestChainPred = nullptr; 585 Chain *BestChainSucc = nullptr; 586 auto BestGain = MergeGainTy(); 587 // Iterate over all pairs of chains 588 for (auto ChainPred : HotChains) { 589 // Get candidates for merging with the current chain 590 for (auto EdgeIter : ChainPred->edges()) { 591 auto ChainSucc = EdgeIter.first; 592 auto ChainEdge = EdgeIter.second; 593 // Ignore loop edges 594 if (ChainPred == ChainSucc) 595 continue; 596 597 // Compute the gain of merging the two chains 598 auto CurGain = getBestMergeGain(ChainPred, ChainSucc, ChainEdge); 599 if (CurGain.score() <= EPS) 600 continue; 601 602 if (BestGain < CurGain || 603 (std::abs(CurGain.score() - BestGain.score()) < EPS && 604 compareChainPairs(ChainPred, ChainSucc, BestChainPred, 605 BestChainSucc))) { 606 BestGain = CurGain; 607 BestChainPred = ChainPred; 608 BestChainSucc = ChainSucc; 609 } 610 } 611 } 612 613 // Stop merging when there is no improvement 614 if (BestGain.score() <= EPS) 615 break; 616 617 // Merge the best pair of chains 618 mergeChains(BestChainPred, BestChainSucc, BestGain.mergeOffset(), 619 BestGain.mergeType()); 620 } 621 } 622 623 /// Merge cold blocks to reduce code size. 624 void mergeColdChains() { 625 for (size_t SrcBB = 0; SrcBB < NumNodes; SrcBB++) { 626 // Iterating over neighbors in the reverse order to make sure original 627 // fallthrough jumps are merged first 628 size_t NumSuccs = SuccNodes[SrcBB].size(); 629 for (size_t Idx = 0; Idx < NumSuccs; Idx++) { 630 auto DstBB = SuccNodes[SrcBB][NumSuccs - Idx - 1]; 631 auto SrcChain = AllBlocks[SrcBB].CurChain; 632 auto DstChain = AllBlocks[DstBB].CurChain; 633 if (SrcChain != DstChain && !DstChain->isEntry() && 634 SrcChain->blocks().back()->Index == SrcBB && 635 DstChain->blocks().front()->Index == DstBB) { 636 mergeChains(SrcChain, DstChain, 0, MergeTypeTy::X_Y); 637 } 638 } 639 } 640 } 641 642 /// Compute the Ext-TSP score for a given block order and a list of jumps. 643 double extTSPScore(const MergedChain &MergedBlocks, 644 const std::vector<Jump *> &Jumps) const { 645 if (Jumps.empty()) 646 return 0.0; 647 uint64_t CurAddr = 0; 648 MergedBlocks.forEach([&](const Block *BB) { 649 BB->EstimatedAddr = CurAddr; 650 CurAddr += BB->Size; 651 }); 652 653 double Score = 0; 654 for (auto &Jump : Jumps) { 655 const auto SrcBlock = Jump->Source; 656 const auto DstBlock = Jump->Target; 657 Score += ::extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size, 658 DstBlock->EstimatedAddr, Jump->ExecutionCount); 659 } 660 return Score; 661 } 662 663 /// Compute the gain of merging two chains. 664 /// 665 /// The function considers all possible ways of merging two chains and 666 /// computes the one having the largest increase in ExtTSP objective. The 667 /// result is a pair with the first element being the gain and the second 668 /// element being the corresponding merging type. 669 MergeGainTy getBestMergeGain(Chain *ChainPred, Chain *ChainSucc, 670 ChainEdge *Edge) const { 671 if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) { 672 return Edge->getCachedMergeGain(ChainPred, ChainSucc); 673 } 674 675 // Precompute jumps between ChainPred and ChainSucc 676 auto Jumps = Edge->jumps(); 677 auto EdgePP = ChainPred->getEdge(ChainPred); 678 if (EdgePP != nullptr) { 679 Jumps.insert(Jumps.end(), EdgePP->jumps().begin(), EdgePP->jumps().end()); 680 } 681 assert(!Jumps.empty() && "trying to merge chains w/o jumps"); 682 683 // The object holds the best currently chosen gain of merging the two chains 684 MergeGainTy Gain = MergeGainTy(); 685 686 /// Given a merge offset and a list of merge types, try to merge two chains 687 /// and update Gain with a better alternative 688 auto tryChainMerging = [&](size_t Offset, 689 const std::vector<MergeTypeTy> &MergeTypes) { 690 // Skip merging corresponding to concatenation w/o splitting 691 if (Offset == 0 || Offset == ChainPred->blocks().size()) 692 return; 693 // Skip merging if it breaks Forced successors 694 auto BB = ChainPred->blocks()[Offset - 1]; 695 if (BB->ForcedSucc != nullptr) 696 return; 697 // Apply the merge, compute the corresponding gain, and update the best 698 // value, if the merge is beneficial 699 for (auto &MergeType : MergeTypes) { 700 Gain.updateIfLessThan( 701 computeMergeGain(ChainPred, ChainSucc, Jumps, Offset, MergeType)); 702 } 703 }; 704 705 // Try to concatenate two chains w/o splitting 706 Gain.updateIfLessThan( 707 computeMergeGain(ChainPred, ChainSucc, Jumps, 0, MergeTypeTy::X_Y)); 708 709 if (EnableChainSplitAlongJumps) { 710 // Attach (a part of) ChainPred before the first block of ChainSucc 711 for (auto &Jump : ChainSucc->blocks().front()->InJumps) { 712 const auto SrcBlock = Jump->Source; 713 if (SrcBlock->CurChain != ChainPred) 714 continue; 715 size_t Offset = SrcBlock->CurIndex + 1; 716 tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::X2_X1_Y}); 717 } 718 719 // Attach (a part of) ChainPred after the last block of ChainSucc 720 for (auto &Jump : ChainSucc->blocks().back()->OutJumps) { 721 const auto DstBlock = Jump->Source; 722 if (DstBlock->CurChain != ChainPred) 723 continue; 724 size_t Offset = DstBlock->CurIndex; 725 tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::Y_X2_X1}); 726 } 727 } 728 729 // Try to break ChainPred in various ways and concatenate with ChainSucc 730 if (ChainPred->blocks().size() <= ChainSplitThreshold) { 731 for (size_t Offset = 1; Offset < ChainPred->blocks().size(); Offset++) { 732 // Try to split the chain in different ways. In practice, applying 733 // X2_Y_X1 merging is almost never provides benefits; thus, we exclude 734 // it from consideration to reduce the search space 735 tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::Y_X2_X1, 736 MergeTypeTy::X2_X1_Y}); 737 } 738 } 739 Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain); 740 return Gain; 741 } 742 743 /// Compute the score gain of merging two chains, respecting a given 744 /// merge 'type' and 'offset'. 745 /// 746 /// The two chains are not modified in the method. 747 MergeGainTy computeMergeGain(const Chain *ChainPred, const Chain *ChainSucc, 748 const std::vector<Jump *> &Jumps, 749 size_t MergeOffset, 750 MergeTypeTy MergeType) const { 751 auto MergedBlocks = mergeBlocks(ChainPred->blocks(), ChainSucc->blocks(), 752 MergeOffset, MergeType); 753 754 // Do not allow a merge that does not preserve the original entry block 755 if ((ChainPred->isEntry() || ChainSucc->isEntry()) && 756 !MergedBlocks.getFirstBlock()->isEntry()) 757 return MergeGainTy(); 758 759 // The gain for the new chain 760 auto NewGainScore = extTSPScore(MergedBlocks, Jumps) - ChainPred->score(); 761 return MergeGainTy(NewGainScore, MergeOffset, MergeType); 762 } 763 764 /// Merge two chains of blocks respecting a given merge 'type' and 'offset'. 765 /// 766 /// If MergeType == 0, then the result is a concatentation of two chains. 767 /// Otherwise, the first chain is cut into two sub-chains at the offset, 768 /// and merged using all possible ways of concatenating three chains. 769 MergedChain mergeBlocks(const std::vector<Block *> &X, 770 const std::vector<Block *> &Y, size_t MergeOffset, 771 MergeTypeTy MergeType) const { 772 // Split the first chain, X, into X1 and X2 773 BlockIter BeginX1 = X.begin(); 774 BlockIter EndX1 = X.begin() + MergeOffset; 775 BlockIter BeginX2 = X.begin() + MergeOffset; 776 BlockIter EndX2 = X.end(); 777 BlockIter BeginY = Y.begin(); 778 BlockIter EndY = Y.end(); 779 780 // Construct a new chain from the three existing ones 781 switch (MergeType) { 782 case MergeTypeTy::X_Y: 783 return MergedChain(BeginX1, EndX2, BeginY, EndY); 784 case MergeTypeTy::X1_Y_X2: 785 return MergedChain(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2); 786 case MergeTypeTy::Y_X2_X1: 787 return MergedChain(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1); 788 case MergeTypeTy::X2_X1_Y: 789 return MergedChain(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY); 790 } 791 llvm_unreachable("unexpected chain merge type"); 792 } 793 794 /// Merge chain From into chain Into, update the list of active chains, 795 /// adjacency information, and the corresponding cached values. 796 void mergeChains(Chain *Into, Chain *From, size_t MergeOffset, 797 MergeTypeTy MergeType) { 798 assert(Into != From && "a chain cannot be merged with itself"); 799 800 // Merge the blocks 801 auto MergedBlocks = 802 mergeBlocks(Into->blocks(), From->blocks(), MergeOffset, MergeType); 803 Into->merge(From, MergedBlocks.getBlocks()); 804 Into->mergeEdges(From); 805 From->clear(); 806 807 // Update cached ext-tsp score for the new chain 808 auto SelfEdge = Into->getEdge(Into); 809 if (SelfEdge != nullptr) { 810 MergedBlocks = MergedChain(Into->blocks().begin(), Into->blocks().end()); 811 Into->setScore(extTSPScore(MergedBlocks, SelfEdge->jumps())); 812 } 813 814 // Remove chain From from the list of active chains 815 auto Iter = std::remove(HotChains.begin(), HotChains.end(), From); 816 HotChains.erase(Iter, HotChains.end()); 817 818 // Invalidate caches 819 for (auto EdgeIter : Into->edges()) { 820 EdgeIter.second->invalidateCache(); 821 } 822 } 823 824 /// Concatenate all chains into a final order of blocks. 825 void concatChains(std::vector<uint64_t> &Order) { 826 // Collect chains and calculate some stats for their sorting 827 std::vector<Chain *> SortedChains; 828 DenseMap<const Chain *, double> ChainDensity; 829 for (auto &Chain : AllChains) { 830 if (!Chain.blocks().empty()) { 831 SortedChains.push_back(&Chain); 832 // Using doubles to avoid overflow of ExecutionCount 833 double Size = 0; 834 double ExecutionCount = 0; 835 for (auto Block : Chain.blocks()) { 836 Size += static_cast<double>(Block->Size); 837 ExecutionCount += static_cast<double>(Block->ExecutionCount); 838 } 839 assert(Size > 0 && "a chain of zero size"); 840 ChainDensity[&Chain] = ExecutionCount / Size; 841 } 842 } 843 844 // Sorting chains by density in the decreasing order 845 std::stable_sort(SortedChains.begin(), SortedChains.end(), 846 [&](const Chain *C1, const Chain *C2) { 847 // Makre sure the original entry block is at the 848 // beginning of the order 849 if (C1->isEntry() != C2->isEntry()) { 850 return C1->isEntry(); 851 } 852 853 const double D1 = ChainDensity[C1]; 854 const double D2 = ChainDensity[C2]; 855 // Compare by density and break ties by chain identifiers 856 return (D1 != D2) ? (D1 > D2) : (C1->id() < C2->id()); 857 }); 858 859 // Collect the blocks in the order specified by their chains 860 Order.reserve(NumNodes); 861 for (auto Chain : SortedChains) { 862 for (auto Block : Chain->blocks()) { 863 Order.push_back(Block->Index); 864 } 865 } 866 } 867 868 private: 869 /// The number of nodes in the graph. 870 const size_t NumNodes; 871 872 /// Successors of each node. 873 std::vector<std::vector<uint64_t>> SuccNodes; 874 875 /// Predecessors of each node. 876 std::vector<std::vector<uint64_t>> PredNodes; 877 878 /// All basic blocks. 879 std::vector<Block> AllBlocks; 880 881 /// All jumps between blocks. 882 std::vector<Jump> AllJumps; 883 884 /// All chains of basic blocks. 885 std::vector<Chain> AllChains; 886 887 /// All edges between chains. 888 std::vector<ChainEdge> AllEdges; 889 890 /// Active chains. The vector gets updated at runtime when chains are merged. 891 std::vector<Chain *> HotChains; 892 }; 893 894 } // end of anonymous namespace 895 896 std::vector<uint64_t> llvm::applyExtTspLayout( 897 const std::vector<uint64_t> &NodeSizes, 898 const std::vector<uint64_t> &NodeCounts, 899 const DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> &EdgeCounts) { 900 size_t NumNodes = NodeSizes.size(); 901 902 // Verify correctness of the input data. 903 assert(NodeCounts.size() == NodeSizes.size() && "Incorrect input"); 904 assert(NumNodes > 2 && "Incorrect input"); 905 906 // Apply the reordering algorithm. 907 auto Alg = ExtTSPImpl(NumNodes, NodeSizes, NodeCounts, EdgeCounts); 908 std::vector<uint64_t> Result; 909 Alg.run(Result); 910 911 // Verify correctness of the output. 912 assert(Result.front() == 0 && "Original entry point is not preserved"); 913 assert(Result.size() == NumNodes && "Incorrect size of reordered layout"); 914 return Result; 915 } 916 917 double llvm::calcExtTspScore( 918 const std::vector<uint64_t> &Order, const std::vector<uint64_t> &NodeSizes, 919 const std::vector<uint64_t> &NodeCounts, 920 const DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> &EdgeCounts) { 921 // Estimate addresses of the blocks in memory 922 auto Addr = std::vector<uint64_t>(NodeSizes.size(), 0); 923 for (size_t Idx = 1; Idx < Order.size(); Idx++) { 924 Addr[Order[Idx]] = Addr[Order[Idx - 1]] + NodeSizes[Order[Idx - 1]]; 925 } 926 927 // Increase the score for each jump 928 double Score = 0; 929 for (auto It : EdgeCounts) { 930 auto Pred = It.first.first; 931 auto Succ = It.first.second; 932 uint64_t Count = It.second; 933 Score += extTSPScore(Addr[Pred], NodeSizes[Pred], Addr[Succ], Count); 934 } 935 return Score; 936 } 937 938 double llvm::calcExtTspScore( 939 const std::vector<uint64_t> &NodeSizes, 940 const std::vector<uint64_t> &NodeCounts, 941 const DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> &EdgeCounts) { 942 auto Order = std::vector<uint64_t>(NodeSizes.size()); 943 for (size_t Idx = 0; Idx < NodeSizes.size(); Idx++) { 944 Order[Idx] = Idx; 945 } 946 return calcExtTspScore(Order, NodeSizes, NodeCounts, EdgeCounts); 947 } 948