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 // The file implements "cache-aware" layout algorithms of basic blocks and 10 // functions in a binary. 11 // 12 // The algorithm tries to find a layout of nodes (basic blocks) of a given CFG 13 // optimizing jump locality and thus processor I-cache utilization. This is 14 // achieved via increasing the number of fall-through jumps and co-locating 15 // frequently executed nodes together. The name follows the underlying 16 // optimization problem, Extended-TSP, which is a generalization of classical 17 // (maximum) Traveling Salesmen Problem. 18 // 19 // The algorithm is a greedy heuristic that works with chains (ordered lists) 20 // of basic blocks. Initially all chains are isolated basic blocks. On every 21 // iteration, we pick a pair of chains whose merging yields the biggest increase 22 // in the ExtTSP score, which models how i-cache "friendly" a specific chain is. 23 // A pair of chains giving the maximum gain is merged into a new chain. The 24 // procedure stops when there is only one chain left, or when merging does not 25 // increase ExtTSP. In the latter case, the remaining chains are sorted by 26 // density in the decreasing order. 27 // 28 // An important aspect is the way two chains are merged. Unlike earlier 29 // algorithms (e.g., based on the approach of Pettis-Hansen), two 30 // chains, X and Y, are first split into three, X1, X2, and Y. Then we 31 // consider all possible ways of gluing the three chains (e.g., X1YX2, X1X2Y, 32 // X2X1Y, X2YX1, YX1X2, YX2X1) and choose the one producing the largest score. 33 // This improves the quality of the final result (the search space is larger) 34 // while keeping the implementation sufficiently fast. 35 // 36 // Reference: 37 // * A. Newell and S. Pupyrev, Improved Basic Block Reordering, 38 // IEEE Transactions on Computers, 2020 39 // https://arxiv.org/abs/1809.04676 40 // 41 //===----------------------------------------------------------------------===// 42 43 #include "llvm/Transforms/Utils/CodeLayout.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Debug.h" 46 47 #include <cmath> 48 #include <set> 49 50 using namespace llvm; 51 using namespace llvm::codelayout; 52 53 #define DEBUG_TYPE "code-layout" 54 55 namespace llvm { 56 cl::opt<bool> EnableExtTspBlockPlacement( 57 "enable-ext-tsp-block-placement", cl::Hidden, cl::init(false), 58 cl::desc("Enable machine block placement based on the ext-tsp model, " 59 "optimizing I-cache utilization.")); 60 61 cl::opt<bool> ApplyExtTspWithoutProfile( 62 "ext-tsp-apply-without-profile", 63 cl::desc("Whether to apply ext-tsp placement for instances w/o profile"), 64 cl::init(true), cl::Hidden); 65 } // namespace llvm 66 67 // Algorithm-specific params for Ext-TSP. The values are tuned for the best 68 // performance of large-scale front-end bound binaries. 69 static cl::opt<double> ForwardWeightCond( 70 "ext-tsp-forward-weight-cond", cl::ReallyHidden, cl::init(0.1), 71 cl::desc("The weight of conditional forward jumps for ExtTSP value")); 72 73 static cl::opt<double> ForwardWeightUncond( 74 "ext-tsp-forward-weight-uncond", cl::ReallyHidden, cl::init(0.1), 75 cl::desc("The weight of unconditional forward jumps for ExtTSP value")); 76 77 static cl::opt<double> BackwardWeightCond( 78 "ext-tsp-backward-weight-cond", cl::ReallyHidden, cl::init(0.1), 79 cl::desc("The weight of conditional backward jumps for ExtTSP value")); 80 81 static cl::opt<double> BackwardWeightUncond( 82 "ext-tsp-backward-weight-uncond", cl::ReallyHidden, cl::init(0.1), 83 cl::desc("The weight of unconditional backward jumps for ExtTSP value")); 84 85 static cl::opt<double> FallthroughWeightCond( 86 "ext-tsp-fallthrough-weight-cond", cl::ReallyHidden, cl::init(1.0), 87 cl::desc("The weight of conditional fallthrough jumps for ExtTSP value")); 88 89 static cl::opt<double> FallthroughWeightUncond( 90 "ext-tsp-fallthrough-weight-uncond", cl::ReallyHidden, cl::init(1.05), 91 cl::desc("The weight of unconditional fallthrough jumps for ExtTSP value")); 92 93 static cl::opt<unsigned> ForwardDistance( 94 "ext-tsp-forward-distance", cl::ReallyHidden, cl::init(1024), 95 cl::desc("The maximum distance (in bytes) of a forward jump for ExtTSP")); 96 97 static cl::opt<unsigned> BackwardDistance( 98 "ext-tsp-backward-distance", cl::ReallyHidden, cl::init(640), 99 cl::desc("The maximum distance (in bytes) of a backward jump for ExtTSP")); 100 101 // The maximum size of a chain created by the algorithm. The size is bounded 102 // so that the algorithm can efficiently process extremely large instances. 103 static cl::opt<unsigned> 104 MaxChainSize("ext-tsp-max-chain-size", cl::ReallyHidden, cl::init(4096), 105 cl::desc("The maximum size of a chain to create.")); 106 107 // The maximum size of a chain for splitting. Larger values of the threshold 108 // may yield better quality at the cost of worsen run-time. 109 static cl::opt<unsigned> ChainSplitThreshold( 110 "ext-tsp-chain-split-threshold", cl::ReallyHidden, cl::init(128), 111 cl::desc("The maximum size of a chain to apply splitting")); 112 113 // The option enables splitting (large) chains along in-coming and out-going 114 // jumps. This typically results in a better quality. 115 static cl::opt<bool> EnableChainSplitAlongJumps( 116 "ext-tsp-enable-chain-split-along-jumps", cl::ReallyHidden, cl::init(true), 117 cl::desc("The maximum size of a chain to apply splitting")); 118 119 // Algorithm-specific options for CDS. 120 static cl::opt<unsigned> CacheEntries("cds-cache-entries", cl::ReallyHidden, 121 cl::desc("The size of the cache")); 122 123 static cl::opt<unsigned> CacheSize("cds-cache-size", cl::ReallyHidden, 124 cl::desc("The size of a line in the cache")); 125 126 static cl::opt<double> DistancePower( 127 "cds-distance-power", cl::ReallyHidden, 128 cl::desc("The power exponent for the distance-based locality")); 129 130 static cl::opt<double> FrequencyScale( 131 "cds-frequency-scale", cl::ReallyHidden, 132 cl::desc("The scale factor for the frequency-based locality")); 133 134 namespace { 135 136 // Epsilon for comparison of doubles. 137 constexpr double EPS = 1e-8; 138 139 // Compute the Ext-TSP score for a given jump. 140 double jumpExtTSPScore(uint64_t JumpDist, uint64_t JumpMaxDist, uint64_t Count, 141 double Weight) { 142 if (JumpDist > JumpMaxDist) 143 return 0; 144 double Prob = 1.0 - static_cast<double>(JumpDist) / JumpMaxDist; 145 return Weight * Prob * Count; 146 } 147 148 // Compute the Ext-TSP score for a jump between a given pair of blocks, 149 // using their sizes, (estimated) addresses and the jump execution count. 150 double extTSPScore(uint64_t SrcAddr, uint64_t SrcSize, uint64_t DstAddr, 151 uint64_t Count, bool IsConditional) { 152 // Fallthrough 153 if (SrcAddr + SrcSize == DstAddr) { 154 return jumpExtTSPScore(0, 1, Count, 155 IsConditional ? FallthroughWeightCond 156 : FallthroughWeightUncond); 157 } 158 // Forward 159 if (SrcAddr + SrcSize < DstAddr) { 160 const uint64_t Dist = DstAddr - (SrcAddr + SrcSize); 161 return jumpExtTSPScore(Dist, ForwardDistance, Count, 162 IsConditional ? ForwardWeightCond 163 : ForwardWeightUncond); 164 } 165 // Backward 166 const uint64_t Dist = SrcAddr + SrcSize - DstAddr; 167 return jumpExtTSPScore(Dist, BackwardDistance, Count, 168 IsConditional ? BackwardWeightCond 169 : BackwardWeightUncond); 170 } 171 172 /// A type of merging two chains, X and Y. The former chain is split into 173 /// X1 and X2 and then concatenated with Y in the order specified by the type. 174 enum class MergeTypeT : int { X_Y, Y_X, X1_Y_X2, Y_X2_X1, X2_X1_Y }; 175 176 /// The gain of merging two chains, that is, the Ext-TSP score of the merge 177 /// together with the corresponding merge 'type' and 'offset'. 178 struct MergeGainT { 179 explicit MergeGainT() = default; 180 explicit MergeGainT(double Score, size_t MergeOffset, MergeTypeT MergeType) 181 : Score(Score), MergeOffset(MergeOffset), MergeType(MergeType) {} 182 183 double score() const { return Score; } 184 185 size_t mergeOffset() const { return MergeOffset; } 186 187 MergeTypeT mergeType() const { return MergeType; } 188 189 void setMergeType(MergeTypeT Ty) { MergeType = Ty; } 190 191 // Returns 'true' iff Other is preferred over this. 192 bool operator<(const MergeGainT &Other) const { 193 return (Other.Score > EPS && Other.Score > Score + EPS); 194 } 195 196 // Update the current gain if Other is preferred over this. 197 void updateIfLessThan(const MergeGainT &Other) { 198 if (*this < Other) 199 *this = Other; 200 } 201 202 private: 203 double Score{-1.0}; 204 size_t MergeOffset{0}; 205 MergeTypeT MergeType{MergeTypeT::X_Y}; 206 }; 207 208 struct JumpT; 209 struct ChainT; 210 struct ChainEdge; 211 212 /// A node in the graph, typically corresponding to a basic block in the CFG or 213 /// a function in the call graph. 214 struct NodeT { 215 NodeT(const NodeT &) = delete; 216 NodeT(NodeT &&) = default; 217 NodeT &operator=(const NodeT &) = delete; 218 NodeT &operator=(NodeT &&) = default; 219 220 explicit NodeT(size_t Index, uint64_t Size, uint64_t Count) 221 : Index(Index), Size(Size), ExecutionCount(Count) {} 222 223 bool isEntry() const { return Index == 0; } 224 225 // The total execution count of outgoing jumps. 226 uint64_t outCount() const; 227 228 // The total execution count of incoming jumps. 229 uint64_t inCount() const; 230 231 // The original index of the node in graph. 232 size_t Index{0}; 233 // The index of the node in the current chain. 234 size_t CurIndex{0}; 235 // The size of the node in the binary. 236 uint64_t Size{0}; 237 // The execution count of the node in the profile data. 238 uint64_t ExecutionCount{0}; 239 // The current chain of the node. 240 ChainT *CurChain{nullptr}; 241 // The offset of the node in the current chain. 242 mutable uint64_t EstimatedAddr{0}; 243 // Forced successor of the node in the graph. 244 NodeT *ForcedSucc{nullptr}; 245 // Forced predecessor of the node in the graph. 246 NodeT *ForcedPred{nullptr}; 247 // Outgoing jumps from the node. 248 std::vector<JumpT *> OutJumps; 249 // Incoming jumps to the node. 250 std::vector<JumpT *> InJumps; 251 }; 252 253 /// An arc in the graph, typically corresponding to a jump between two nodes. 254 struct JumpT { 255 JumpT(const JumpT &) = delete; 256 JumpT(JumpT &&) = default; 257 JumpT &operator=(const JumpT &) = delete; 258 JumpT &operator=(JumpT &&) = default; 259 260 explicit JumpT(NodeT *Source, NodeT *Target, uint64_t ExecutionCount) 261 : Source(Source), Target(Target), ExecutionCount(ExecutionCount) {} 262 263 // Source node of the jump. 264 NodeT *Source; 265 // Target node of the jump. 266 NodeT *Target; 267 // Execution count of the arc in the profile data. 268 uint64_t ExecutionCount{0}; 269 // Whether the jump corresponds to a conditional branch. 270 bool IsConditional{false}; 271 // The offset of the jump from the source node. 272 uint64_t Offset{0}; 273 }; 274 275 /// A chain (ordered sequence) of nodes in the graph. 276 struct ChainT { 277 ChainT(const ChainT &) = delete; 278 ChainT(ChainT &&) = default; 279 ChainT &operator=(const ChainT &) = delete; 280 ChainT &operator=(ChainT &&) = default; 281 282 explicit ChainT(uint64_t Id, NodeT *Node) 283 : Id(Id), ExecutionCount(Node->ExecutionCount), Size(Node->Size), 284 Nodes(1, Node) {} 285 286 size_t numBlocks() const { return Nodes.size(); } 287 288 double density() const { return static_cast<double>(ExecutionCount) / Size; } 289 290 bool isEntry() const { return Nodes[0]->Index == 0; } 291 292 bool isCold() const { 293 for (NodeT *Node : Nodes) { 294 if (Node->ExecutionCount > 0) 295 return false; 296 } 297 return true; 298 } 299 300 ChainEdge *getEdge(ChainT *Other) const { 301 for (const auto &[Chain, ChainEdge] : Edges) { 302 if (Chain == Other) 303 return ChainEdge; 304 } 305 return nullptr; 306 } 307 308 void removeEdge(ChainT *Other) { 309 auto It = Edges.begin(); 310 while (It != Edges.end()) { 311 if (It->first == Other) { 312 Edges.erase(It); 313 return; 314 } 315 It++; 316 } 317 } 318 319 void addEdge(ChainT *Other, ChainEdge *Edge) { 320 Edges.push_back(std::make_pair(Other, Edge)); 321 } 322 323 void merge(ChainT *Other, std::vector<NodeT *> MergedBlocks) { 324 Nodes = std::move(MergedBlocks); 325 // Update the chain's data. 326 ExecutionCount += Other->ExecutionCount; 327 Size += Other->Size; 328 Id = Nodes[0]->Index; 329 // Update the node's data. 330 for (size_t Idx = 0; Idx < Nodes.size(); Idx++) { 331 Nodes[Idx]->CurChain = this; 332 Nodes[Idx]->CurIndex = Idx; 333 } 334 } 335 336 void mergeEdges(ChainT *Other); 337 338 void clear() { 339 Nodes.clear(); 340 Nodes.shrink_to_fit(); 341 Edges.clear(); 342 Edges.shrink_to_fit(); 343 } 344 345 // Unique chain identifier. 346 uint64_t Id; 347 // Cached ext-tsp score for the chain. 348 double Score{0}; 349 // The total execution count of the chain. 350 uint64_t ExecutionCount{0}; 351 // The total size of the chain. 352 uint64_t Size{0}; 353 // Nodes of the chain. 354 std::vector<NodeT *> Nodes; 355 // Adjacent chains and corresponding edges (lists of jumps). 356 std::vector<std::pair<ChainT *, ChainEdge *>> Edges; 357 }; 358 359 /// An edge in the graph representing jumps between two chains. 360 /// When nodes are merged into chains, the edges are combined too so that 361 /// there is always at most one edge between a pair of chains. 362 struct ChainEdge { 363 ChainEdge(const ChainEdge &) = delete; 364 ChainEdge(ChainEdge &&) = default; 365 ChainEdge &operator=(const ChainEdge &) = delete; 366 ChainEdge &operator=(ChainEdge &&) = delete; 367 368 explicit ChainEdge(JumpT *Jump) 369 : SrcChain(Jump->Source->CurChain), DstChain(Jump->Target->CurChain), 370 Jumps(1, Jump) {} 371 372 ChainT *srcChain() const { return SrcChain; } 373 374 ChainT *dstChain() const { return DstChain; } 375 376 bool isSelfEdge() const { return SrcChain == DstChain; } 377 378 const std::vector<JumpT *> &jumps() const { return Jumps; } 379 380 void appendJump(JumpT *Jump) { Jumps.push_back(Jump); } 381 382 void moveJumps(ChainEdge *Other) { 383 Jumps.insert(Jumps.end(), Other->Jumps.begin(), Other->Jumps.end()); 384 Other->Jumps.clear(); 385 Other->Jumps.shrink_to_fit(); 386 } 387 388 void changeEndpoint(ChainT *From, ChainT *To) { 389 if (From == SrcChain) 390 SrcChain = To; 391 if (From == DstChain) 392 DstChain = To; 393 } 394 395 bool hasCachedMergeGain(ChainT *Src, ChainT *Dst) const { 396 return Src == SrcChain ? CacheValidForward : CacheValidBackward; 397 } 398 399 MergeGainT getCachedMergeGain(ChainT *Src, ChainT *Dst) const { 400 return Src == SrcChain ? CachedGainForward : CachedGainBackward; 401 } 402 403 void setCachedMergeGain(ChainT *Src, ChainT *Dst, MergeGainT MergeGain) { 404 if (Src == SrcChain) { 405 CachedGainForward = MergeGain; 406 CacheValidForward = true; 407 } else { 408 CachedGainBackward = MergeGain; 409 CacheValidBackward = true; 410 } 411 } 412 413 void invalidateCache() { 414 CacheValidForward = false; 415 CacheValidBackward = false; 416 } 417 418 void setMergeGain(MergeGainT Gain) { CachedGain = Gain; } 419 420 MergeGainT getMergeGain() const { return CachedGain; } 421 422 double gain() const { return CachedGain.score(); } 423 424 private: 425 // Source chain. 426 ChainT *SrcChain{nullptr}; 427 // Destination chain. 428 ChainT *DstChain{nullptr}; 429 // Original jumps in the binary with corresponding execution counts. 430 std::vector<JumpT *> Jumps; 431 // Cached gain value for merging the pair of chains. 432 MergeGainT CachedGain; 433 434 // Cached gain values for merging the pair of chains. Since the gain of 435 // merging (Src, Dst) and (Dst, Src) might be different, we store both values 436 // here and a flag indicating which of the options results in a higher gain. 437 // Cached gain values. 438 MergeGainT CachedGainForward; 439 MergeGainT CachedGainBackward; 440 // Whether the cached value must be recomputed. 441 bool CacheValidForward{false}; 442 bool CacheValidBackward{false}; 443 }; 444 445 uint64_t NodeT::outCount() const { 446 uint64_t Count = 0; 447 for (JumpT *Jump : OutJumps) 448 Count += Jump->ExecutionCount; 449 return Count; 450 } 451 452 uint64_t NodeT::inCount() const { 453 uint64_t Count = 0; 454 for (JumpT *Jump : InJumps) 455 Count += Jump->ExecutionCount; 456 return Count; 457 } 458 459 void ChainT::mergeEdges(ChainT *Other) { 460 // Update edges adjacent to chain Other. 461 for (const auto &[DstChain, DstEdge] : Other->Edges) { 462 ChainT *TargetChain = DstChain == Other ? this : DstChain; 463 ChainEdge *CurEdge = getEdge(TargetChain); 464 if (CurEdge == nullptr) { 465 DstEdge->changeEndpoint(Other, this); 466 this->addEdge(TargetChain, DstEdge); 467 if (DstChain != this && DstChain != Other) 468 DstChain->addEdge(this, DstEdge); 469 } else { 470 CurEdge->moveJumps(DstEdge); 471 } 472 // Cleanup leftover edge. 473 if (DstChain != Other) 474 DstChain->removeEdge(Other); 475 } 476 } 477 478 using NodeIter = std::vector<NodeT *>::const_iterator; 479 static std::vector<NodeT *> EmptyList; 480 481 /// A wrapper around three concatenated vectors (chains) of nodes; it is used 482 /// to avoid extra instantiation of the vectors. 483 struct MergedNodesT { 484 MergedNodesT(NodeIter Begin1, NodeIter End1, 485 NodeIter Begin2 = EmptyList.begin(), 486 NodeIter End2 = EmptyList.end(), 487 NodeIter Begin3 = EmptyList.begin(), 488 NodeIter End3 = EmptyList.end()) 489 : Begin1(Begin1), End1(End1), Begin2(Begin2), End2(End2), Begin3(Begin3), 490 End3(End3) {} 491 492 template <typename F> void forEach(const F &Func) const { 493 for (auto It = Begin1; It != End1; It++) 494 Func(*It); 495 for (auto It = Begin2; It != End2; It++) 496 Func(*It); 497 for (auto It = Begin3; It != End3; It++) 498 Func(*It); 499 } 500 501 std::vector<NodeT *> getNodes() const { 502 std::vector<NodeT *> Result; 503 Result.reserve(std::distance(Begin1, End1) + std::distance(Begin2, End2) + 504 std::distance(Begin3, End3)); 505 Result.insert(Result.end(), Begin1, End1); 506 Result.insert(Result.end(), Begin2, End2); 507 Result.insert(Result.end(), Begin3, End3); 508 return Result; 509 } 510 511 const NodeT *getFirstNode() const { return *Begin1; } 512 513 bool empty() const { return Begin1 == End1; } 514 515 private: 516 NodeIter Begin1; 517 NodeIter End1; 518 NodeIter Begin2; 519 NodeIter End2; 520 NodeIter Begin3; 521 NodeIter End3; 522 }; 523 524 /// A wrapper around two concatenated vectors (chains) of jumps. 525 struct MergedJumpsT { 526 MergedJumpsT(const std::vector<JumpT *> *Jumps1, 527 const std::vector<JumpT *> *Jumps2 = nullptr) { 528 assert(!Jumps1->empty() && "cannot merge empty jump list"); 529 JumpArray[0] = Jumps1; 530 JumpArray[1] = Jumps2; 531 } 532 533 template <typename F> void forEach(const F &Func) const { 534 for (auto Jumps : JumpArray) 535 if (Jumps != nullptr) 536 for (JumpT *Jump : *Jumps) 537 Func(Jump); 538 } 539 540 private: 541 std::array<const std::vector<JumpT *> *, 2> JumpArray{nullptr, nullptr}; 542 }; 543 544 /// Merge two chains of nodes respecting a given 'type' and 'offset'. 545 /// 546 /// If MergeType == 0, then the result is a concatenation of two chains. 547 /// Otherwise, the first chain is cut into two sub-chains at the offset, 548 /// and merged using all possible ways of concatenating three chains. 549 MergedNodesT mergeNodes(const std::vector<NodeT *> &X, 550 const std::vector<NodeT *> &Y, size_t MergeOffset, 551 MergeTypeT MergeType) { 552 // Split the first chain, X, into X1 and X2. 553 NodeIter BeginX1 = X.begin(); 554 NodeIter EndX1 = X.begin() + MergeOffset; 555 NodeIter BeginX2 = X.begin() + MergeOffset; 556 NodeIter EndX2 = X.end(); 557 NodeIter BeginY = Y.begin(); 558 NodeIter EndY = Y.end(); 559 560 // Construct a new chain from the three existing ones. 561 switch (MergeType) { 562 case MergeTypeT::X_Y: 563 return MergedNodesT(BeginX1, EndX2, BeginY, EndY); 564 case MergeTypeT::Y_X: 565 return MergedNodesT(BeginY, EndY, BeginX1, EndX2); 566 case MergeTypeT::X1_Y_X2: 567 return MergedNodesT(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2); 568 case MergeTypeT::Y_X2_X1: 569 return MergedNodesT(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1); 570 case MergeTypeT::X2_X1_Y: 571 return MergedNodesT(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY); 572 } 573 llvm_unreachable("unexpected chain merge type"); 574 } 575 576 /// The implementation of the ExtTSP algorithm. 577 class ExtTSPImpl { 578 public: 579 ExtTSPImpl(ArrayRef<uint64_t> NodeSizes, ArrayRef<uint64_t> NodeCounts, 580 ArrayRef<EdgeCount> EdgeCounts) 581 : NumNodes(NodeSizes.size()) { 582 initialize(NodeSizes, NodeCounts, EdgeCounts); 583 } 584 585 /// Run the algorithm and return an optimized ordering of nodes. 586 std::vector<uint64_t> run() { 587 // Pass 1: Merge nodes with their mutually forced successors 588 mergeForcedPairs(); 589 590 // Pass 2: Merge pairs of chains while improving the ExtTSP objective 591 mergeChainPairs(); 592 593 // Pass 3: Merge cold nodes to reduce code size 594 mergeColdChains(); 595 596 // Collect nodes from all chains 597 return concatChains(); 598 } 599 600 private: 601 /// Initialize the algorithm's data structures. 602 void initialize(const ArrayRef<uint64_t> &NodeSizes, 603 const ArrayRef<uint64_t> &NodeCounts, 604 const ArrayRef<EdgeCount> &EdgeCounts) { 605 // Initialize nodes 606 AllNodes.reserve(NumNodes); 607 for (uint64_t Idx = 0; Idx < NumNodes; Idx++) { 608 uint64_t Size = std::max<uint64_t>(NodeSizes[Idx], 1ULL); 609 uint64_t ExecutionCount = NodeCounts[Idx]; 610 // The execution count of the entry node is set to at least one. 611 if (Idx == 0 && ExecutionCount == 0) 612 ExecutionCount = 1; 613 AllNodes.emplace_back(Idx, Size, ExecutionCount); 614 } 615 616 // Initialize jumps between nodes 617 SuccNodes.resize(NumNodes); 618 PredNodes.resize(NumNodes); 619 std::vector<uint64_t> OutDegree(NumNodes, 0); 620 AllJumps.reserve(EdgeCounts.size()); 621 for (auto Edge : EdgeCounts) { 622 ++OutDegree[Edge.src]; 623 // Ignore self-edges. 624 if (Edge.src == Edge.dst) 625 continue; 626 627 SuccNodes[Edge.src].push_back(Edge.dst); 628 PredNodes[Edge.dst].push_back(Edge.src); 629 if (Edge.count > 0) { 630 NodeT &PredNode = AllNodes[Edge.src]; 631 NodeT &SuccNode = AllNodes[Edge.dst]; 632 AllJumps.emplace_back(&PredNode, &SuccNode, Edge.count); 633 SuccNode.InJumps.push_back(&AllJumps.back()); 634 PredNode.OutJumps.push_back(&AllJumps.back()); 635 } 636 } 637 for (JumpT &Jump : AllJumps) { 638 assert(OutDegree[Jump.Source->Index] > 0); 639 Jump.IsConditional = OutDegree[Jump.Source->Index] > 1; 640 } 641 642 // Initialize chains. 643 AllChains.reserve(NumNodes); 644 HotChains.reserve(NumNodes); 645 for (NodeT &Node : AllNodes) { 646 // Create a chain. 647 AllChains.emplace_back(Node.Index, &Node); 648 Node.CurChain = &AllChains.back(); 649 if (Node.ExecutionCount > 0) 650 HotChains.push_back(&AllChains.back()); 651 } 652 653 // Initialize chain edges. 654 AllEdges.reserve(AllJumps.size()); 655 for (NodeT &PredNode : AllNodes) { 656 for (JumpT *Jump : PredNode.OutJumps) { 657 NodeT *SuccNode = Jump->Target; 658 ChainEdge *CurEdge = PredNode.CurChain->getEdge(SuccNode->CurChain); 659 // This edge is already present in the graph. 660 if (CurEdge != nullptr) { 661 assert(SuccNode->CurChain->getEdge(PredNode.CurChain) != nullptr); 662 CurEdge->appendJump(Jump); 663 continue; 664 } 665 // This is a new edge. 666 AllEdges.emplace_back(Jump); 667 PredNode.CurChain->addEdge(SuccNode->CurChain, &AllEdges.back()); 668 SuccNode->CurChain->addEdge(PredNode.CurChain, &AllEdges.back()); 669 } 670 } 671 } 672 673 /// For a pair of nodes, A and B, node B is the forced successor of A, 674 /// if (i) all jumps (based on profile) from A goes to B and (ii) all jumps 675 /// to B are from A. Such nodes should be adjacent in the optimal ordering; 676 /// the method finds and merges such pairs of nodes. 677 void mergeForcedPairs() { 678 // Find forced pairs of blocks. 679 for (NodeT &Node : AllNodes) { 680 if (SuccNodes[Node.Index].size() == 1 && 681 PredNodes[SuccNodes[Node.Index][0]].size() == 1 && 682 SuccNodes[Node.Index][0] != 0) { 683 size_t SuccIndex = SuccNodes[Node.Index][0]; 684 Node.ForcedSucc = &AllNodes[SuccIndex]; 685 AllNodes[SuccIndex].ForcedPred = &Node; 686 } 687 } 688 689 // There might be 'cycles' in the forced dependencies, since profile 690 // data isn't 100% accurate. Typically this is observed in loops, when the 691 // loop edges are the hottest successors for the basic blocks of the loop. 692 // Break the cycles by choosing the node with the smallest index as the 693 // head. This helps to keep the original order of the loops, which likely 694 // have already been rotated in the optimized manner. 695 for (NodeT &Node : AllNodes) { 696 if (Node.ForcedSucc == nullptr || Node.ForcedPred == nullptr) 697 continue; 698 699 NodeT *SuccNode = Node.ForcedSucc; 700 while (SuccNode != nullptr && SuccNode != &Node) { 701 SuccNode = SuccNode->ForcedSucc; 702 } 703 if (SuccNode == nullptr) 704 continue; 705 // Break the cycle. 706 AllNodes[Node.ForcedPred->Index].ForcedSucc = nullptr; 707 Node.ForcedPred = nullptr; 708 } 709 710 // Merge nodes with their fallthrough successors. 711 for (NodeT &Node : AllNodes) { 712 if (Node.ForcedPred == nullptr && Node.ForcedSucc != nullptr) { 713 const NodeT *CurBlock = &Node; 714 while (CurBlock->ForcedSucc != nullptr) { 715 const NodeT *NextBlock = CurBlock->ForcedSucc; 716 mergeChains(Node.CurChain, NextBlock->CurChain, 0, MergeTypeT::X_Y); 717 CurBlock = NextBlock; 718 } 719 } 720 } 721 } 722 723 /// Merge pairs of chains while improving the ExtTSP objective. 724 void mergeChainPairs() { 725 /// Deterministically compare pairs of chains. 726 auto compareChainPairs = [](const ChainT *A1, const ChainT *B1, 727 const ChainT *A2, const ChainT *B2) { 728 return std::make_tuple(A1->Id, B1->Id) < std::make_tuple(A2->Id, B2->Id); 729 }; 730 731 while (HotChains.size() > 1) { 732 ChainT *BestChainPred = nullptr; 733 ChainT *BestChainSucc = nullptr; 734 MergeGainT BestGain; 735 // Iterate over all pairs of chains. 736 for (ChainT *ChainPred : HotChains) { 737 // Get candidates for merging with the current chain. 738 for (const auto &[ChainSucc, Edge] : ChainPred->Edges) { 739 // Ignore loop edges. 740 if (ChainPred == ChainSucc) 741 continue; 742 743 // Stop early if the combined chain violates the maximum allowed size. 744 if (ChainPred->numBlocks() + ChainSucc->numBlocks() >= MaxChainSize) 745 continue; 746 747 // Compute the gain of merging the two chains. 748 MergeGainT CurGain = getBestMergeGain(ChainPred, ChainSucc, Edge); 749 if (CurGain.score() <= EPS) 750 continue; 751 752 if (BestGain < CurGain || 753 (std::abs(CurGain.score() - BestGain.score()) < EPS && 754 compareChainPairs(ChainPred, ChainSucc, BestChainPred, 755 BestChainSucc))) { 756 BestGain = CurGain; 757 BestChainPred = ChainPred; 758 BestChainSucc = ChainSucc; 759 } 760 } 761 } 762 763 // Stop merging when there is no improvement. 764 if (BestGain.score() <= EPS) 765 break; 766 767 // Merge the best pair of chains. 768 mergeChains(BestChainPred, BestChainSucc, BestGain.mergeOffset(), 769 BestGain.mergeType()); 770 } 771 } 772 773 /// Merge remaining nodes into chains w/o taking jump counts into 774 /// consideration. This allows to maintain the original node order in the 775 /// absence of profile data. 776 void mergeColdChains() { 777 for (size_t SrcBB = 0; SrcBB < NumNodes; SrcBB++) { 778 // Iterating in reverse order to make sure original fallthrough jumps are 779 // merged first; this might be beneficial for code size. 780 size_t NumSuccs = SuccNodes[SrcBB].size(); 781 for (size_t Idx = 0; Idx < NumSuccs; Idx++) { 782 size_t DstBB = SuccNodes[SrcBB][NumSuccs - Idx - 1]; 783 ChainT *SrcChain = AllNodes[SrcBB].CurChain; 784 ChainT *DstChain = AllNodes[DstBB].CurChain; 785 if (SrcChain != DstChain && !DstChain->isEntry() && 786 SrcChain->Nodes.back()->Index == SrcBB && 787 DstChain->Nodes.front()->Index == DstBB && 788 SrcChain->isCold() == DstChain->isCold()) { 789 mergeChains(SrcChain, DstChain, 0, MergeTypeT::X_Y); 790 } 791 } 792 } 793 } 794 795 /// Compute the Ext-TSP score for a given node order and a list of jumps. 796 double extTSPScore(const MergedNodesT &Nodes, 797 const MergedJumpsT &Jumps) const { 798 uint64_t CurAddr = 0; 799 Nodes.forEach([&](const NodeT *Node) { 800 Node->EstimatedAddr = CurAddr; 801 CurAddr += Node->Size; 802 }); 803 804 double Score = 0; 805 Jumps.forEach([&](const JumpT *Jump) { 806 const NodeT *SrcBlock = Jump->Source; 807 const NodeT *DstBlock = Jump->Target; 808 Score += ::extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size, 809 DstBlock->EstimatedAddr, Jump->ExecutionCount, 810 Jump->IsConditional); 811 }); 812 return Score; 813 } 814 815 /// Compute the gain of merging two chains. 816 /// 817 /// The function considers all possible ways of merging two chains and 818 /// computes the one having the largest increase in ExtTSP objective. The 819 /// result is a pair with the first element being the gain and the second 820 /// element being the corresponding merging type. 821 MergeGainT getBestMergeGain(ChainT *ChainPred, ChainT *ChainSucc, 822 ChainEdge *Edge) const { 823 if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) 824 return Edge->getCachedMergeGain(ChainPred, ChainSucc); 825 826 assert(!Edge->jumps().empty() && "trying to merge chains w/o jumps"); 827 // Precompute jumps between ChainPred and ChainSucc. 828 ChainEdge *EdgePP = ChainPred->getEdge(ChainPred); 829 MergedJumpsT Jumps(&Edge->jumps(), EdgePP ? &EdgePP->jumps() : nullptr); 830 831 // This object holds the best chosen gain of merging two chains. 832 MergeGainT Gain = MergeGainT(); 833 834 /// Given a merge offset and a list of merge types, try to merge two chains 835 /// and update Gain with a better alternative. 836 auto tryChainMerging = [&](size_t Offset, 837 const std::vector<MergeTypeT> &MergeTypes) { 838 // Skip merging corresponding to concatenation w/o splitting. 839 if (Offset == 0 || Offset == ChainPred->Nodes.size()) 840 return; 841 // Skip merging if it breaks Forced successors. 842 NodeT *Node = ChainPred->Nodes[Offset - 1]; 843 if (Node->ForcedSucc != nullptr) 844 return; 845 // Apply the merge, compute the corresponding gain, and update the best 846 // value, if the merge is beneficial. 847 for (const MergeTypeT &MergeType : MergeTypes) { 848 Gain.updateIfLessThan( 849 computeMergeGain(ChainPred, ChainSucc, Jumps, Offset, MergeType)); 850 } 851 }; 852 853 // Try to concatenate two chains w/o splitting. 854 Gain.updateIfLessThan( 855 computeMergeGain(ChainPred, ChainSucc, Jumps, 0, MergeTypeT::X_Y)); 856 857 if (EnableChainSplitAlongJumps) { 858 // Attach (a part of) ChainPred before the first node of ChainSucc. 859 for (JumpT *Jump : ChainSucc->Nodes.front()->InJumps) { 860 const NodeT *SrcBlock = Jump->Source; 861 if (SrcBlock->CurChain != ChainPred) 862 continue; 863 size_t Offset = SrcBlock->CurIndex + 1; 864 tryChainMerging(Offset, {MergeTypeT::X1_Y_X2, MergeTypeT::X2_X1_Y}); 865 } 866 867 // Attach (a part of) ChainPred after the last node of ChainSucc. 868 for (JumpT *Jump : ChainSucc->Nodes.back()->OutJumps) { 869 const NodeT *DstBlock = Jump->Target; 870 if (DstBlock->CurChain != ChainPred) 871 continue; 872 size_t Offset = DstBlock->CurIndex; 873 tryChainMerging(Offset, {MergeTypeT::X1_Y_X2, MergeTypeT::Y_X2_X1}); 874 } 875 } 876 877 // Try to break ChainPred in various ways and concatenate with ChainSucc. 878 if (ChainPred->Nodes.size() <= ChainSplitThreshold) { 879 for (size_t Offset = 1; Offset < ChainPred->Nodes.size(); Offset++) { 880 // Try to split the chain in different ways. In practice, applying 881 // X2_Y_X1 merging is almost never provides benefits; thus, we exclude 882 // it from consideration to reduce the search space. 883 tryChainMerging(Offset, {MergeTypeT::X1_Y_X2, MergeTypeT::Y_X2_X1, 884 MergeTypeT::X2_X1_Y}); 885 } 886 } 887 Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain); 888 return Gain; 889 } 890 891 /// Compute the score gain of merging two chains, respecting a given 892 /// merge 'type' and 'offset'. 893 /// 894 /// The two chains are not modified in the method. 895 MergeGainT computeMergeGain(const ChainT *ChainPred, const ChainT *ChainSucc, 896 const MergedJumpsT &Jumps, size_t MergeOffset, 897 MergeTypeT MergeType) const { 898 MergedNodesT MergedNodes = 899 mergeNodes(ChainPred->Nodes, ChainSucc->Nodes, MergeOffset, MergeType); 900 901 // Do not allow a merge that does not preserve the original entry point. 902 if ((ChainPred->isEntry() || ChainSucc->isEntry()) && 903 !MergedNodes.getFirstNode()->isEntry()) 904 return MergeGainT(); 905 906 // The gain for the new chain. 907 double NewScore = extTSPScore(MergedNodes, Jumps); 908 double CurScore = ChainPred->Score; 909 return MergeGainT(NewScore - CurScore, MergeOffset, MergeType); 910 } 911 912 /// Merge chain From into chain Into, update the list of active chains, 913 /// adjacency information, and the corresponding cached values. 914 void mergeChains(ChainT *Into, ChainT *From, size_t MergeOffset, 915 MergeTypeT MergeType) { 916 assert(Into != From && "a chain cannot be merged with itself"); 917 918 // Merge the nodes. 919 MergedNodesT MergedNodes = 920 mergeNodes(Into->Nodes, From->Nodes, MergeOffset, MergeType); 921 Into->merge(From, MergedNodes.getNodes()); 922 923 // Merge the edges. 924 Into->mergeEdges(From); 925 From->clear(); 926 927 // Update cached ext-tsp score for the new chain. 928 ChainEdge *SelfEdge = Into->getEdge(Into); 929 if (SelfEdge != nullptr) { 930 MergedNodes = MergedNodesT(Into->Nodes.begin(), Into->Nodes.end()); 931 MergedJumpsT MergedJumps(&SelfEdge->jumps()); 932 Into->Score = extTSPScore(MergedNodes, MergedJumps); 933 } 934 935 // Remove the chain from the list of active chains. 936 llvm::erase_value(HotChains, From); 937 938 // Invalidate caches. 939 for (auto EdgeIt : Into->Edges) 940 EdgeIt.second->invalidateCache(); 941 } 942 943 /// Concatenate all chains into the final order. 944 std::vector<uint64_t> concatChains() { 945 // Collect chains and calculate density stats for their sorting. 946 std::vector<const ChainT *> SortedChains; 947 DenseMap<const ChainT *, double> ChainDensity; 948 for (ChainT &Chain : AllChains) { 949 if (!Chain.Nodes.empty()) { 950 SortedChains.push_back(&Chain); 951 // Using doubles to avoid overflow of ExecutionCounts. 952 double Size = 0; 953 double ExecutionCount = 0; 954 for (NodeT *Node : Chain.Nodes) { 955 Size += static_cast<double>(Node->Size); 956 ExecutionCount += static_cast<double>(Node->ExecutionCount); 957 } 958 assert(Size > 0 && "a chain of zero size"); 959 ChainDensity[&Chain] = ExecutionCount / Size; 960 } 961 } 962 963 // Sorting chains by density in the decreasing order. 964 std::sort(SortedChains.begin(), SortedChains.end(), 965 [&](const ChainT *L, const ChainT *R) { 966 // Place the entry point at the beginning of the order. 967 if (L->isEntry() != R->isEntry()) 968 return L->isEntry(); 969 970 const double DL = ChainDensity[L]; 971 const double DR = ChainDensity[R]; 972 // Compare by density and break ties by chain identifiers. 973 return std::make_tuple(-DL, L->Id) < 974 std::make_tuple(-DR, R->Id); 975 }); 976 977 // Collect the nodes in the order specified by their chains. 978 std::vector<uint64_t> Order; 979 Order.reserve(NumNodes); 980 for (const ChainT *Chain : SortedChains) 981 for (NodeT *Node : Chain->Nodes) 982 Order.push_back(Node->Index); 983 return Order; 984 } 985 986 private: 987 /// The number of nodes in the graph. 988 const size_t NumNodes; 989 990 /// Successors of each node. 991 std::vector<std::vector<uint64_t>> SuccNodes; 992 993 /// Predecessors of each node. 994 std::vector<std::vector<uint64_t>> PredNodes; 995 996 /// All nodes (basic blocks) in the graph. 997 std::vector<NodeT> AllNodes; 998 999 /// All jumps between the nodes. 1000 std::vector<JumpT> AllJumps; 1001 1002 /// All chains of nodes. 1003 std::vector<ChainT> AllChains; 1004 1005 /// All edges between the chains. 1006 std::vector<ChainEdge> AllEdges; 1007 1008 /// Active chains. The vector gets updated at runtime when chains are merged. 1009 std::vector<ChainT *> HotChains; 1010 }; 1011 1012 /// The implementation of the Cache-Directed Sort (CDS) algorithm for ordering 1013 /// functions represented by a call graph. 1014 class CDSortImpl { 1015 public: 1016 CDSortImpl(const CDSortConfig &Config, ArrayRef<uint64_t> NodeSizes, 1017 ArrayRef<uint64_t> NodeCounts, ArrayRef<EdgeCount> EdgeCounts, 1018 ArrayRef<uint64_t> EdgeOffsets) 1019 : Config(Config), NumNodes(NodeSizes.size()) { 1020 initialize(NodeSizes, NodeCounts, EdgeCounts, EdgeOffsets); 1021 } 1022 1023 /// Run the algorithm and return an ordered set of function clusters. 1024 std::vector<uint64_t> run() { 1025 // Merge pairs of chains while improving the objective. 1026 mergeChainPairs(); 1027 1028 LLVM_DEBUG(dbgs() << "Cache-directed function sorting reduced the number" 1029 << " of chains from " << NumNodes << " to " 1030 << HotChains.size() << "\n"); 1031 1032 // Collect nodes from all the chains. 1033 return concatChains(); 1034 } 1035 1036 private: 1037 /// Initialize the algorithm's data structures. 1038 void initialize(const ArrayRef<uint64_t> &NodeSizes, 1039 const ArrayRef<uint64_t> &NodeCounts, 1040 const ArrayRef<EdgeCount> &EdgeCounts, 1041 const ArrayRef<uint64_t> &EdgeOffsets) { 1042 // Initialize nodes. 1043 AllNodes.reserve(NumNodes); 1044 for (uint64_t Node = 0; Node < NumNodes; Node++) { 1045 uint64_t Size = std::max<uint64_t>(NodeSizes[Node], 1ULL); 1046 uint64_t ExecutionCount = NodeCounts[Node]; 1047 AllNodes.emplace_back(Node, Size, ExecutionCount); 1048 TotalSamples += ExecutionCount; 1049 if (ExecutionCount > 0) 1050 TotalSize += Size; 1051 } 1052 1053 // Initialize jumps between the nodes. 1054 SuccNodes.resize(NumNodes); 1055 PredNodes.resize(NumNodes); 1056 AllJumps.reserve(EdgeCounts.size()); 1057 for (size_t I = 0; I < EdgeCounts.size(); I++) { 1058 auto [Pred, Succ, Count] = EdgeCounts[I]; 1059 // Ignore recursive calls. 1060 if (Pred == Succ) 1061 continue; 1062 1063 SuccNodes[Pred].push_back(Succ); 1064 PredNodes[Succ].push_back(Pred); 1065 if (Count > 0) { 1066 NodeT &PredNode = AllNodes[Pred]; 1067 NodeT &SuccNode = AllNodes[Succ]; 1068 AllJumps.emplace_back(&PredNode, &SuccNode, Count); 1069 AllJumps.back().Offset = EdgeOffsets[I]; 1070 SuccNode.InJumps.push_back(&AllJumps.back()); 1071 PredNode.OutJumps.push_back(&AllJumps.back()); 1072 } 1073 } 1074 1075 // Initialize chains. 1076 AllChains.reserve(NumNodes); 1077 HotChains.reserve(NumNodes); 1078 for (NodeT &Node : AllNodes) { 1079 // Adjust execution counts. 1080 Node.ExecutionCount = std::max(Node.ExecutionCount, Node.inCount()); 1081 Node.ExecutionCount = std::max(Node.ExecutionCount, Node.outCount()); 1082 // Create chain. 1083 AllChains.emplace_back(Node.Index, &Node); 1084 Node.CurChain = &AllChains.back(); 1085 if (Node.ExecutionCount > 0) 1086 HotChains.push_back(&AllChains.back()); 1087 } 1088 1089 // Initialize chain edges. 1090 AllEdges.reserve(AllJumps.size()); 1091 for (NodeT &PredNode : AllNodes) { 1092 for (JumpT *Jump : PredNode.OutJumps) { 1093 NodeT *SuccNode = Jump->Target; 1094 ChainEdge *CurEdge = PredNode.CurChain->getEdge(SuccNode->CurChain); 1095 // this edge is already present in the graph. 1096 if (CurEdge != nullptr) { 1097 assert(SuccNode->CurChain->getEdge(PredNode.CurChain) != nullptr); 1098 CurEdge->appendJump(Jump); 1099 continue; 1100 } 1101 // this is a new edge. 1102 AllEdges.emplace_back(Jump); 1103 PredNode.CurChain->addEdge(SuccNode->CurChain, &AllEdges.back()); 1104 SuccNode->CurChain->addEdge(PredNode.CurChain, &AllEdges.back()); 1105 } 1106 } 1107 } 1108 1109 /// Merge pairs of chains while there is an improvement in the objective. 1110 void mergeChainPairs() { 1111 // Create a priority queue containing all edges ordered by the merge gain. 1112 auto GainComparator = [](ChainEdge *L, ChainEdge *R) { 1113 return std::make_tuple(-L->gain(), L->srcChain()->Id, L->dstChain()->Id) < 1114 std::make_tuple(-R->gain(), R->srcChain()->Id, R->dstChain()->Id); 1115 }; 1116 std::set<ChainEdge *, decltype(GainComparator)> Queue(GainComparator); 1117 1118 // Insert the edges into the queue. 1119 for (ChainT *ChainPred : HotChains) { 1120 for (const auto &[_, Edge] : ChainPred->Edges) { 1121 // Ignore self-edges. 1122 if (Edge->isSelfEdge()) 1123 continue; 1124 // Ignore already processed edges. 1125 if (Edge->gain() != -1.0) 1126 continue; 1127 1128 // Compute the gain of merging the two chains. 1129 MergeGainT Gain = getBestMergeGain(Edge); 1130 Edge->setMergeGain(Gain); 1131 1132 if (Edge->gain() > EPS) 1133 Queue.insert(Edge); 1134 } 1135 } 1136 1137 // Merge the chains while the gain of merging is positive. 1138 while (!Queue.empty()) { 1139 // Extract the best (top) edge for merging. 1140 ChainEdge *BestEdge = *Queue.begin(); 1141 Queue.erase(Queue.begin()); 1142 // Ignore self-edges. 1143 if (BestEdge->isSelfEdge()) 1144 continue; 1145 // Ignore edges with non-positive gains. 1146 if (BestEdge->gain() <= EPS) 1147 continue; 1148 1149 ChainT *BestSrcChain = BestEdge->srcChain(); 1150 ChainT *BestDstChain = BestEdge->dstChain(); 1151 1152 // Remove outdated edges from the queue. 1153 for (const auto &[_, ChainEdge] : BestSrcChain->Edges) 1154 Queue.erase(ChainEdge); 1155 for (const auto &[_, ChainEdge] : BestDstChain->Edges) 1156 Queue.erase(ChainEdge); 1157 1158 // Merge the best pair of chains. 1159 MergeGainT BestGain = BestEdge->getMergeGain(); 1160 mergeChains(BestSrcChain, BestDstChain, BestGain.mergeOffset(), 1161 BestGain.mergeType()); 1162 1163 // Insert newly created edges into the queue. 1164 for (const auto &[_, Edge] : BestSrcChain->Edges) { 1165 // Ignore loop edges. 1166 if (Edge->isSelfEdge()) 1167 continue; 1168 1169 // Compute the gain of merging the two chains. 1170 MergeGainT Gain = getBestMergeGain(Edge); 1171 Edge->setMergeGain(Gain); 1172 1173 if (Edge->gain() > EPS) 1174 Queue.insert(Edge); 1175 } 1176 } 1177 } 1178 1179 /// Compute the gain of merging two chains. 1180 /// 1181 /// The function considers all possible ways of merging two chains and 1182 /// computes the one having the largest increase in ExtTSP objective. The 1183 /// result is a pair with the first element being the gain and the second 1184 /// element being the corresponding merging type. 1185 MergeGainT getBestMergeGain(ChainEdge *Edge) const { 1186 assert(!Edge->jumps().empty() && "trying to merge chains w/o jumps"); 1187 // Precompute jumps between ChainPred and ChainSucc. 1188 MergedJumpsT Jumps(&Edge->jumps()); 1189 ChainT *SrcChain = Edge->srcChain(); 1190 ChainT *DstChain = Edge->dstChain(); 1191 1192 // This object holds the best currently chosen gain of merging two chains. 1193 MergeGainT Gain = MergeGainT(); 1194 1195 /// Given a list of merge types, try to merge two chains and update Gain 1196 /// with a better alternative. 1197 auto tryChainMerging = [&](const std::vector<MergeTypeT> &MergeTypes) { 1198 // Apply the merge, compute the corresponding gain, and update the best 1199 // value, if the merge is beneficial. 1200 for (const MergeTypeT &MergeType : MergeTypes) { 1201 MergeGainT NewGain = 1202 computeMergeGain(SrcChain, DstChain, Jumps, MergeType); 1203 1204 // When forward and backward gains are the same, prioritize merging that 1205 // preserves the original order of the functions in the binary. 1206 if (std::abs(Gain.score() - NewGain.score()) < EPS) { 1207 if ((MergeType == MergeTypeT::X_Y && SrcChain->Id < DstChain->Id) || 1208 (MergeType == MergeTypeT::Y_X && SrcChain->Id > DstChain->Id)) { 1209 Gain = NewGain; 1210 } 1211 } else if (NewGain.score() > Gain.score() + EPS) { 1212 Gain = NewGain; 1213 } 1214 } 1215 }; 1216 1217 // Try to concatenate two chains w/o splitting. 1218 tryChainMerging({MergeTypeT::X_Y, MergeTypeT::Y_X}); 1219 1220 return Gain; 1221 } 1222 1223 /// Compute the score gain of merging two chains, respecting a given type. 1224 /// 1225 /// The two chains are not modified in the method. 1226 MergeGainT computeMergeGain(ChainT *ChainPred, ChainT *ChainSucc, 1227 const MergedJumpsT &Jumps, 1228 MergeTypeT MergeType) const { 1229 // This doesn't depend on the ordering of the nodes 1230 double FreqGain = freqBasedLocalityGain(ChainPred, ChainSucc); 1231 1232 // Merge offset is always 0, as the chains are not split. 1233 size_t MergeOffset = 0; 1234 auto MergedBlocks = 1235 mergeNodes(ChainPred->Nodes, ChainSucc->Nodes, MergeOffset, MergeType); 1236 double DistGain = distBasedLocalityGain(MergedBlocks, Jumps); 1237 1238 double GainScore = DistGain + Config.FrequencyScale * FreqGain; 1239 // Scale the result to increase the importance of merging short chains. 1240 if (GainScore >= 0.0) 1241 GainScore /= std::min(ChainPred->Size, ChainSucc->Size); 1242 1243 return MergeGainT(GainScore, MergeOffset, MergeType); 1244 } 1245 1246 /// Compute the change of the frequency locality after merging the chains. 1247 double freqBasedLocalityGain(ChainT *ChainPred, ChainT *ChainSucc) const { 1248 auto missProbability = [&](double ChainDensity) { 1249 double PageSamples = ChainDensity * Config.CacheSize; 1250 if (PageSamples >= TotalSamples) 1251 return 0.0; 1252 double P = PageSamples / TotalSamples; 1253 return pow(1.0 - P, static_cast<double>(Config.CacheEntries)); 1254 }; 1255 1256 // Cache misses on the chains before merging. 1257 double CurScore = 1258 ChainPred->ExecutionCount * missProbability(ChainPred->density()) + 1259 ChainSucc->ExecutionCount * missProbability(ChainSucc->density()); 1260 1261 // Cache misses on the merged chain 1262 double MergedCounts = ChainPred->ExecutionCount + ChainSucc->ExecutionCount; 1263 double MergedSize = ChainPred->Size + ChainSucc->Size; 1264 double MergedDensity = static_cast<double>(MergedCounts) / MergedSize; 1265 double NewScore = MergedCounts * missProbability(MergedDensity); 1266 1267 return CurScore - NewScore; 1268 } 1269 1270 /// Compute the distance locality for a jump / call. 1271 double distScore(uint64_t SrcAddr, uint64_t DstAddr, uint64_t Count) const { 1272 uint64_t Dist = SrcAddr <= DstAddr ? DstAddr - SrcAddr : SrcAddr - DstAddr; 1273 double D = Dist == 0 ? 0.1 : static_cast<double>(Dist); 1274 return static_cast<double>(Count) * std::pow(D, -Config.DistancePower); 1275 } 1276 1277 /// Compute the change of the distance locality after merging the chains. 1278 double distBasedLocalityGain(const MergedNodesT &Nodes, 1279 const MergedJumpsT &Jumps) const { 1280 uint64_t CurAddr = 0; 1281 Nodes.forEach([&](const NodeT *Node) { 1282 Node->EstimatedAddr = CurAddr; 1283 CurAddr += Node->Size; 1284 }); 1285 1286 double CurScore = 0; 1287 double NewScore = 0; 1288 Jumps.forEach([&](const JumpT *Jump) { 1289 uint64_t SrcAddr = Jump->Source->EstimatedAddr + Jump->Offset; 1290 uint64_t DstAddr = Jump->Target->EstimatedAddr; 1291 NewScore += distScore(SrcAddr, DstAddr, Jump->ExecutionCount); 1292 CurScore += distScore(0, TotalSize, Jump->ExecutionCount); 1293 }); 1294 return NewScore - CurScore; 1295 } 1296 1297 /// Merge chain From into chain Into, update the list of active chains, 1298 /// adjacency information, and the corresponding cached values. 1299 void mergeChains(ChainT *Into, ChainT *From, size_t MergeOffset, 1300 MergeTypeT MergeType) { 1301 assert(Into != From && "a chain cannot be merged with itself"); 1302 1303 // Merge the nodes. 1304 MergedNodesT MergedNodes = 1305 mergeNodes(Into->Nodes, From->Nodes, MergeOffset, MergeType); 1306 Into->merge(From, MergedNodes.getNodes()); 1307 1308 // Merge the edges. 1309 Into->mergeEdges(From); 1310 From->clear(); 1311 1312 // Remove the chain from the list of active chains. 1313 llvm::erase_value(HotChains, From); 1314 } 1315 1316 /// Concatenate all chains into the final order. 1317 std::vector<uint64_t> concatChains() { 1318 // Collect chains and calculate density stats for their sorting. 1319 std::vector<const ChainT *> SortedChains; 1320 DenseMap<const ChainT *, double> ChainDensity; 1321 for (ChainT &Chain : AllChains) { 1322 if (!Chain.Nodes.empty()) { 1323 SortedChains.push_back(&Chain); 1324 // Using doubles to avoid overflow of ExecutionCounts. 1325 double Size = 0; 1326 double ExecutionCount = 0; 1327 for (NodeT *Node : Chain.Nodes) { 1328 Size += static_cast<double>(Node->Size); 1329 ExecutionCount += static_cast<double>(Node->ExecutionCount); 1330 } 1331 assert(Size > 0 && "a chain of zero size"); 1332 ChainDensity[&Chain] = ExecutionCount / Size; 1333 } 1334 } 1335 1336 // Sort chains by density in the decreasing order. 1337 std::sort(SortedChains.begin(), SortedChains.end(), 1338 [&](const ChainT *L, const ChainT *R) { 1339 const double DL = ChainDensity[L]; 1340 const double DR = ChainDensity[R]; 1341 // Compare by density and break ties by chain identifiers. 1342 return std::make_tuple(-DL, L->Id) < 1343 std::make_tuple(-DR, R->Id); 1344 }); 1345 1346 // Collect the nodes in the order specified by their chains. 1347 std::vector<uint64_t> Order; 1348 Order.reserve(NumNodes); 1349 for (const ChainT *Chain : SortedChains) 1350 for (NodeT *Node : Chain->Nodes) 1351 Order.push_back(Node->Index); 1352 return Order; 1353 } 1354 1355 private: 1356 /// Config for the algorithm. 1357 const CDSortConfig Config; 1358 1359 /// The number of nodes in the graph. 1360 const size_t NumNodes; 1361 1362 /// Successors of each node. 1363 std::vector<std::vector<uint64_t>> SuccNodes; 1364 1365 /// Predecessors of each node. 1366 std::vector<std::vector<uint64_t>> PredNodes; 1367 1368 /// All nodes (functions) in the graph. 1369 std::vector<NodeT> AllNodes; 1370 1371 /// All jumps (function calls) between the nodes. 1372 std::vector<JumpT> AllJumps; 1373 1374 /// All chains of nodes. 1375 std::vector<ChainT> AllChains; 1376 1377 /// All edges between the chains. 1378 std::vector<ChainEdge> AllEdges; 1379 1380 /// Active chains. The vector gets updated at runtime when chains are merged. 1381 std::vector<ChainT *> HotChains; 1382 1383 /// The total number of samples in the graph. 1384 uint64_t TotalSamples{0}; 1385 1386 /// The total size of the nodes in the graph. 1387 uint64_t TotalSize{0}; 1388 }; 1389 1390 } // end of anonymous namespace 1391 1392 std::vector<uint64_t> 1393 codelayout::computeExtTspLayout(ArrayRef<uint64_t> NodeSizes, 1394 ArrayRef<uint64_t> NodeCounts, 1395 ArrayRef<EdgeCount> EdgeCounts) { 1396 // Verify correctness of the input data. 1397 assert(NodeCounts.size() == NodeSizes.size() && "Incorrect input"); 1398 assert(NodeSizes.size() > 2 && "Incorrect input"); 1399 1400 // Apply the reordering algorithm. 1401 ExtTSPImpl Alg(NodeSizes, NodeCounts, EdgeCounts); 1402 std::vector<uint64_t> Result = Alg.run(); 1403 1404 // Verify correctness of the output. 1405 assert(Result.front() == 0 && "Original entry point is not preserved"); 1406 assert(Result.size() == NodeSizes.size() && "Incorrect size of layout"); 1407 return Result; 1408 } 1409 1410 double codelayout::calcExtTspScore(ArrayRef<uint64_t> Order, 1411 ArrayRef<uint64_t> NodeSizes, 1412 ArrayRef<uint64_t> NodeCounts, 1413 ArrayRef<EdgeCount> EdgeCounts) { 1414 // Estimate addresses of the blocks in memory. 1415 std::vector<uint64_t> Addr(NodeSizes.size(), 0); 1416 for (size_t Idx = 1; Idx < Order.size(); Idx++) { 1417 Addr[Order[Idx]] = Addr[Order[Idx - 1]] + NodeSizes[Order[Idx - 1]]; 1418 } 1419 std::vector<uint64_t> OutDegree(NodeSizes.size(), 0); 1420 for (auto Edge : EdgeCounts) 1421 ++OutDegree[Edge.src]; 1422 1423 // Increase the score for each jump. 1424 double Score = 0; 1425 for (auto Edge : EdgeCounts) { 1426 bool IsConditional = OutDegree[Edge.src] > 1; 1427 Score += ::extTSPScore(Addr[Edge.src], NodeSizes[Edge.src], Addr[Edge.dst], 1428 Edge.count, IsConditional); 1429 } 1430 return Score; 1431 } 1432 1433 double codelayout::calcExtTspScore(ArrayRef<uint64_t> NodeSizes, 1434 ArrayRef<uint64_t> NodeCounts, 1435 ArrayRef<EdgeCount> EdgeCounts) { 1436 std::vector<uint64_t> Order(NodeSizes.size()); 1437 for (size_t Idx = 0; Idx < NodeSizes.size(); Idx++) { 1438 Order[Idx] = Idx; 1439 } 1440 return calcExtTspScore(Order, NodeSizes, NodeCounts, EdgeCounts); 1441 } 1442 1443 std::vector<uint64_t> codelayout::computeCacheDirectedLayout( 1444 const CDSortConfig &Config, ArrayRef<uint64_t> FuncSizes, 1445 ArrayRef<uint64_t> FuncCounts, ArrayRef<EdgeCount> CallCounts, 1446 ArrayRef<uint64_t> CallOffsets) { 1447 // Verify correctness of the input data. 1448 assert(FuncCounts.size() == FuncSizes.size() && "Incorrect input"); 1449 1450 // Apply the reordering algorithm. 1451 CDSortImpl Alg(Config, FuncSizes, FuncCounts, CallCounts, CallOffsets); 1452 std::vector<uint64_t> Result = Alg.run(); 1453 assert(Result.size() == FuncSizes.size() && "Incorrect size of layout"); 1454 return Result; 1455 } 1456 1457 std::vector<uint64_t> codelayout::computeCacheDirectedLayout( 1458 ArrayRef<uint64_t> FuncSizes, ArrayRef<uint64_t> FuncCounts, 1459 ArrayRef<EdgeCount> CallCounts, ArrayRef<uint64_t> CallOffsets) { 1460 CDSortConfig Config; 1461 // Populate the config from the command-line options. 1462 if (CacheEntries.getNumOccurrences() > 0) 1463 Config.CacheEntries = CacheEntries; 1464 if (CacheSize.getNumOccurrences() > 0) 1465 Config.CacheSize = CacheSize; 1466 if (DistancePower.getNumOccurrences() > 0) 1467 Config.DistancePower = DistancePower; 1468 if (FrequencyScale.getNumOccurrences() > 0) 1469 Config.FrequencyScale = FrequencyScale; 1470 return computeCacheDirectedLayout(Config, FuncSizes, FuncCounts, CallCounts, 1471 CallOffsets); 1472 } 1473