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 480 /// A wrapper around three concatenated vectors (chains) of nodes; it is used 481 /// to avoid extra instantiation of the vectors. 482 struct MergedNodesT { 483 MergedNodesT(NodeIter Begin1, NodeIter End1, NodeIter Begin2 = NodeIter(), 484 NodeIter End2 = NodeIter(), NodeIter Begin3 = NodeIter(), 485 NodeIter End3 = NodeIter()) 486 : Begin1(Begin1), End1(End1), Begin2(Begin2), End2(End2), Begin3(Begin3), 487 End3(End3) {} 488 489 template <typename F> void forEach(const F &Func) const { 490 for (auto It = Begin1; It != End1; It++) 491 Func(*It); 492 for (auto It = Begin2; It != End2; It++) 493 Func(*It); 494 for (auto It = Begin3; It != End3; It++) 495 Func(*It); 496 } 497 498 std::vector<NodeT *> getNodes() const { 499 std::vector<NodeT *> Result; 500 Result.reserve(std::distance(Begin1, End1) + std::distance(Begin2, End2) + 501 std::distance(Begin3, End3)); 502 Result.insert(Result.end(), Begin1, End1); 503 Result.insert(Result.end(), Begin2, End2); 504 Result.insert(Result.end(), Begin3, End3); 505 return Result; 506 } 507 508 const NodeT *getFirstNode() const { return *Begin1; } 509 510 bool empty() const { return Begin1 == End1; } 511 512 private: 513 NodeIter Begin1; 514 NodeIter End1; 515 NodeIter Begin2; 516 NodeIter End2; 517 NodeIter Begin3; 518 NodeIter End3; 519 }; 520 521 /// A wrapper around two concatenated vectors (chains) of jumps. 522 struct MergedJumpsT { 523 MergedJumpsT(const std::vector<JumpT *> *Jumps1, 524 const std::vector<JumpT *> *Jumps2 = nullptr) { 525 assert(!Jumps1->empty() && "cannot merge empty jump list"); 526 JumpArray[0] = Jumps1; 527 JumpArray[1] = Jumps2; 528 } 529 530 template <typename F> void forEach(const F &Func) const { 531 for (auto Jumps : JumpArray) 532 if (Jumps != nullptr) 533 for (JumpT *Jump : *Jumps) 534 Func(Jump); 535 } 536 537 private: 538 std::array<const std::vector<JumpT *> *, 2> JumpArray{nullptr, nullptr}; 539 }; 540 541 /// Merge two chains of nodes respecting a given 'type' and 'offset'. 542 /// 543 /// If MergeType == 0, then the result is a concatenation of two chains. 544 /// Otherwise, the first chain is cut into two sub-chains at the offset, 545 /// and merged using all possible ways of concatenating three chains. 546 MergedNodesT mergeNodes(const std::vector<NodeT *> &X, 547 const std::vector<NodeT *> &Y, size_t MergeOffset, 548 MergeTypeT MergeType) { 549 // Split the first chain, X, into X1 and X2. 550 NodeIter BeginX1 = X.begin(); 551 NodeIter EndX1 = X.begin() + MergeOffset; 552 NodeIter BeginX2 = X.begin() + MergeOffset; 553 NodeIter EndX2 = X.end(); 554 NodeIter BeginY = Y.begin(); 555 NodeIter EndY = Y.end(); 556 557 // Construct a new chain from the three existing ones. 558 switch (MergeType) { 559 case MergeTypeT::X_Y: 560 return MergedNodesT(BeginX1, EndX2, BeginY, EndY); 561 case MergeTypeT::Y_X: 562 return MergedNodesT(BeginY, EndY, BeginX1, EndX2); 563 case MergeTypeT::X1_Y_X2: 564 return MergedNodesT(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2); 565 case MergeTypeT::Y_X2_X1: 566 return MergedNodesT(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1); 567 case MergeTypeT::X2_X1_Y: 568 return MergedNodesT(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY); 569 } 570 llvm_unreachable("unexpected chain merge type"); 571 } 572 573 /// The implementation of the ExtTSP algorithm. 574 class ExtTSPImpl { 575 public: 576 ExtTSPImpl(ArrayRef<uint64_t> NodeSizes, ArrayRef<uint64_t> NodeCounts, 577 ArrayRef<EdgeCount> EdgeCounts) 578 : NumNodes(NodeSizes.size()) { 579 initialize(NodeSizes, NodeCounts, EdgeCounts); 580 } 581 582 /// Run the algorithm and return an optimized ordering of nodes. 583 std::vector<uint64_t> run() { 584 // Pass 1: Merge nodes with their mutually forced successors 585 mergeForcedPairs(); 586 587 // Pass 2: Merge pairs of chains while improving the ExtTSP objective 588 mergeChainPairs(); 589 590 // Pass 3: Merge cold nodes to reduce code size 591 mergeColdChains(); 592 593 // Collect nodes from all chains 594 return concatChains(); 595 } 596 597 private: 598 /// Initialize the algorithm's data structures. 599 void initialize(const ArrayRef<uint64_t> &NodeSizes, 600 const ArrayRef<uint64_t> &NodeCounts, 601 const ArrayRef<EdgeCount> &EdgeCounts) { 602 // Initialize nodes 603 AllNodes.reserve(NumNodes); 604 for (uint64_t Idx = 0; Idx < NumNodes; Idx++) { 605 uint64_t Size = std::max<uint64_t>(NodeSizes[Idx], 1ULL); 606 uint64_t ExecutionCount = NodeCounts[Idx]; 607 // The execution count of the entry node is set to at least one. 608 if (Idx == 0 && ExecutionCount == 0) 609 ExecutionCount = 1; 610 AllNodes.emplace_back(Idx, Size, ExecutionCount); 611 } 612 613 // Initialize jumps between nodes 614 SuccNodes.resize(NumNodes); 615 PredNodes.resize(NumNodes); 616 std::vector<uint64_t> OutDegree(NumNodes, 0); 617 AllJumps.reserve(EdgeCounts.size()); 618 for (auto Edge : EdgeCounts) { 619 ++OutDegree[Edge.src]; 620 // Ignore self-edges. 621 if (Edge.src == Edge.dst) 622 continue; 623 624 SuccNodes[Edge.src].push_back(Edge.dst); 625 PredNodes[Edge.dst].push_back(Edge.src); 626 if (Edge.count > 0) { 627 NodeT &PredNode = AllNodes[Edge.src]; 628 NodeT &SuccNode = AllNodes[Edge.dst]; 629 AllJumps.emplace_back(&PredNode, &SuccNode, Edge.count); 630 SuccNode.InJumps.push_back(&AllJumps.back()); 631 PredNode.OutJumps.push_back(&AllJumps.back()); 632 } 633 } 634 for (JumpT &Jump : AllJumps) { 635 assert(OutDegree[Jump.Source->Index] > 0); 636 Jump.IsConditional = OutDegree[Jump.Source->Index] > 1; 637 } 638 639 // Initialize chains. 640 AllChains.reserve(NumNodes); 641 HotChains.reserve(NumNodes); 642 for (NodeT &Node : AllNodes) { 643 // Create a chain. 644 AllChains.emplace_back(Node.Index, &Node); 645 Node.CurChain = &AllChains.back(); 646 if (Node.ExecutionCount > 0) 647 HotChains.push_back(&AllChains.back()); 648 } 649 650 // Initialize chain edges. 651 AllEdges.reserve(AllJumps.size()); 652 for (NodeT &PredNode : AllNodes) { 653 for (JumpT *Jump : PredNode.OutJumps) { 654 NodeT *SuccNode = Jump->Target; 655 ChainEdge *CurEdge = PredNode.CurChain->getEdge(SuccNode->CurChain); 656 // This edge is already present in the graph. 657 if (CurEdge != nullptr) { 658 assert(SuccNode->CurChain->getEdge(PredNode.CurChain) != nullptr); 659 CurEdge->appendJump(Jump); 660 continue; 661 } 662 // This is a new edge. 663 AllEdges.emplace_back(Jump); 664 PredNode.CurChain->addEdge(SuccNode->CurChain, &AllEdges.back()); 665 SuccNode->CurChain->addEdge(PredNode.CurChain, &AllEdges.back()); 666 } 667 } 668 } 669 670 /// For a pair of nodes, A and B, node B is the forced successor of A, 671 /// if (i) all jumps (based on profile) from A goes to B and (ii) all jumps 672 /// to B are from A. Such nodes should be adjacent in the optimal ordering; 673 /// the method finds and merges such pairs of nodes. 674 void mergeForcedPairs() { 675 // Find forced pairs of blocks. 676 for (NodeT &Node : AllNodes) { 677 if (SuccNodes[Node.Index].size() == 1 && 678 PredNodes[SuccNodes[Node.Index][0]].size() == 1 && 679 SuccNodes[Node.Index][0] != 0) { 680 size_t SuccIndex = SuccNodes[Node.Index][0]; 681 Node.ForcedSucc = &AllNodes[SuccIndex]; 682 AllNodes[SuccIndex].ForcedPred = &Node; 683 } 684 } 685 686 // There might be 'cycles' in the forced dependencies, since profile 687 // data isn't 100% accurate. Typically this is observed in loops, when the 688 // loop edges are the hottest successors for the basic blocks of the loop. 689 // Break the cycles by choosing the node with the smallest index as the 690 // head. This helps to keep the original order of the loops, which likely 691 // have already been rotated in the optimized manner. 692 for (NodeT &Node : AllNodes) { 693 if (Node.ForcedSucc == nullptr || Node.ForcedPred == nullptr) 694 continue; 695 696 NodeT *SuccNode = Node.ForcedSucc; 697 while (SuccNode != nullptr && SuccNode != &Node) { 698 SuccNode = SuccNode->ForcedSucc; 699 } 700 if (SuccNode == nullptr) 701 continue; 702 // Break the cycle. 703 AllNodes[Node.ForcedPred->Index].ForcedSucc = nullptr; 704 Node.ForcedPred = nullptr; 705 } 706 707 // Merge nodes with their fallthrough successors. 708 for (NodeT &Node : AllNodes) { 709 if (Node.ForcedPred == nullptr && Node.ForcedSucc != nullptr) { 710 const NodeT *CurBlock = &Node; 711 while (CurBlock->ForcedSucc != nullptr) { 712 const NodeT *NextBlock = CurBlock->ForcedSucc; 713 mergeChains(Node.CurChain, NextBlock->CurChain, 0, MergeTypeT::X_Y); 714 CurBlock = NextBlock; 715 } 716 } 717 } 718 } 719 720 /// Merge pairs of chains while improving the ExtTSP objective. 721 void mergeChainPairs() { 722 /// Deterministically compare pairs of chains. 723 auto compareChainPairs = [](const ChainT *A1, const ChainT *B1, 724 const ChainT *A2, const ChainT *B2) { 725 return std::make_tuple(A1->Id, B1->Id) < std::make_tuple(A2->Id, B2->Id); 726 }; 727 728 while (HotChains.size() > 1) { 729 ChainT *BestChainPred = nullptr; 730 ChainT *BestChainSucc = nullptr; 731 MergeGainT BestGain; 732 // Iterate over all pairs of chains. 733 for (ChainT *ChainPred : HotChains) { 734 // Get candidates for merging with the current chain. 735 for (const auto &[ChainSucc, Edge] : ChainPred->Edges) { 736 // Ignore loop edges. 737 if (ChainPred == ChainSucc) 738 continue; 739 740 // Stop early if the combined chain violates the maximum allowed size. 741 if (ChainPred->numBlocks() + ChainSucc->numBlocks() >= MaxChainSize) 742 continue; 743 744 // Compute the gain of merging the two chains. 745 MergeGainT CurGain = getBestMergeGain(ChainPred, ChainSucc, Edge); 746 if (CurGain.score() <= EPS) 747 continue; 748 749 if (BestGain < CurGain || 750 (std::abs(CurGain.score() - BestGain.score()) < EPS && 751 compareChainPairs(ChainPred, ChainSucc, BestChainPred, 752 BestChainSucc))) { 753 BestGain = CurGain; 754 BestChainPred = ChainPred; 755 BestChainSucc = ChainSucc; 756 } 757 } 758 } 759 760 // Stop merging when there is no improvement. 761 if (BestGain.score() <= EPS) 762 break; 763 764 // Merge the best pair of chains. 765 mergeChains(BestChainPred, BestChainSucc, BestGain.mergeOffset(), 766 BestGain.mergeType()); 767 } 768 } 769 770 /// Merge remaining nodes into chains w/o taking jump counts into 771 /// consideration. This allows to maintain the original node order in the 772 /// absence of profile data. 773 void mergeColdChains() { 774 for (size_t SrcBB = 0; SrcBB < NumNodes; SrcBB++) { 775 // Iterating in reverse order to make sure original fallthrough jumps are 776 // merged first; this might be beneficial for code size. 777 size_t NumSuccs = SuccNodes[SrcBB].size(); 778 for (size_t Idx = 0; Idx < NumSuccs; Idx++) { 779 size_t DstBB = SuccNodes[SrcBB][NumSuccs - Idx - 1]; 780 ChainT *SrcChain = AllNodes[SrcBB].CurChain; 781 ChainT *DstChain = AllNodes[DstBB].CurChain; 782 if (SrcChain != DstChain && !DstChain->isEntry() && 783 SrcChain->Nodes.back()->Index == SrcBB && 784 DstChain->Nodes.front()->Index == DstBB && 785 SrcChain->isCold() == DstChain->isCold()) { 786 mergeChains(SrcChain, DstChain, 0, MergeTypeT::X_Y); 787 } 788 } 789 } 790 } 791 792 /// Compute the Ext-TSP score for a given node order and a list of jumps. 793 double extTSPScore(const MergedNodesT &Nodes, 794 const MergedJumpsT &Jumps) const { 795 uint64_t CurAddr = 0; 796 Nodes.forEach([&](const NodeT *Node) { 797 Node->EstimatedAddr = CurAddr; 798 CurAddr += Node->Size; 799 }); 800 801 double Score = 0; 802 Jumps.forEach([&](const JumpT *Jump) { 803 const NodeT *SrcBlock = Jump->Source; 804 const NodeT *DstBlock = Jump->Target; 805 Score += ::extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size, 806 DstBlock->EstimatedAddr, Jump->ExecutionCount, 807 Jump->IsConditional); 808 }); 809 return Score; 810 } 811 812 /// Compute the gain of merging two chains. 813 /// 814 /// The function considers all possible ways of merging two chains and 815 /// computes the one having the largest increase in ExtTSP objective. The 816 /// result is a pair with the first element being the gain and the second 817 /// element being the corresponding merging type. 818 MergeGainT getBestMergeGain(ChainT *ChainPred, ChainT *ChainSucc, 819 ChainEdge *Edge) const { 820 if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) 821 return Edge->getCachedMergeGain(ChainPred, ChainSucc); 822 823 assert(!Edge->jumps().empty() && "trying to merge chains w/o jumps"); 824 // Precompute jumps between ChainPred and ChainSucc. 825 ChainEdge *EdgePP = ChainPred->getEdge(ChainPred); 826 MergedJumpsT Jumps(&Edge->jumps(), EdgePP ? &EdgePP->jumps() : nullptr); 827 828 // This object holds the best chosen gain of merging two chains. 829 MergeGainT Gain = MergeGainT(); 830 831 /// Given a merge offset and a list of merge types, try to merge two chains 832 /// and update Gain with a better alternative. 833 auto tryChainMerging = [&](size_t Offset, 834 const std::vector<MergeTypeT> &MergeTypes) { 835 // Skip merging corresponding to concatenation w/o splitting. 836 if (Offset == 0 || Offset == ChainPred->Nodes.size()) 837 return; 838 // Skip merging if it breaks Forced successors. 839 NodeT *Node = ChainPred->Nodes[Offset - 1]; 840 if (Node->ForcedSucc != nullptr) 841 return; 842 // Apply the merge, compute the corresponding gain, and update the best 843 // value, if the merge is beneficial. 844 for (const MergeTypeT &MergeType : MergeTypes) { 845 Gain.updateIfLessThan( 846 computeMergeGain(ChainPred, ChainSucc, Jumps, Offset, MergeType)); 847 } 848 }; 849 850 // Try to concatenate two chains w/o splitting. 851 Gain.updateIfLessThan( 852 computeMergeGain(ChainPred, ChainSucc, Jumps, 0, MergeTypeT::X_Y)); 853 854 if (EnableChainSplitAlongJumps) { 855 // Attach (a part of) ChainPred before the first node of ChainSucc. 856 for (JumpT *Jump : ChainSucc->Nodes.front()->InJumps) { 857 const NodeT *SrcBlock = Jump->Source; 858 if (SrcBlock->CurChain != ChainPred) 859 continue; 860 size_t Offset = SrcBlock->CurIndex + 1; 861 tryChainMerging(Offset, {MergeTypeT::X1_Y_X2, MergeTypeT::X2_X1_Y}); 862 } 863 864 // Attach (a part of) ChainPred after the last node of ChainSucc. 865 for (JumpT *Jump : ChainSucc->Nodes.back()->OutJumps) { 866 const NodeT *DstBlock = Jump->Target; 867 if (DstBlock->CurChain != ChainPred) 868 continue; 869 size_t Offset = DstBlock->CurIndex; 870 tryChainMerging(Offset, {MergeTypeT::X1_Y_X2, MergeTypeT::Y_X2_X1}); 871 } 872 } 873 874 // Try to break ChainPred in various ways and concatenate with ChainSucc. 875 if (ChainPred->Nodes.size() <= ChainSplitThreshold) { 876 for (size_t Offset = 1; Offset < ChainPred->Nodes.size(); Offset++) { 877 // Try to split the chain in different ways. In practice, applying 878 // X2_Y_X1 merging is almost never provides benefits; thus, we exclude 879 // it from consideration to reduce the search space. 880 tryChainMerging(Offset, {MergeTypeT::X1_Y_X2, MergeTypeT::Y_X2_X1, 881 MergeTypeT::X2_X1_Y}); 882 } 883 } 884 Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain); 885 return Gain; 886 } 887 888 /// Compute the score gain of merging two chains, respecting a given 889 /// merge 'type' and 'offset'. 890 /// 891 /// The two chains are not modified in the method. 892 MergeGainT computeMergeGain(const ChainT *ChainPred, const ChainT *ChainSucc, 893 const MergedJumpsT &Jumps, size_t MergeOffset, 894 MergeTypeT MergeType) const { 895 MergedNodesT MergedNodes = 896 mergeNodes(ChainPred->Nodes, ChainSucc->Nodes, MergeOffset, MergeType); 897 898 // Do not allow a merge that does not preserve the original entry point. 899 if ((ChainPred->isEntry() || ChainSucc->isEntry()) && 900 !MergedNodes.getFirstNode()->isEntry()) 901 return MergeGainT(); 902 903 // The gain for the new chain. 904 double NewScore = extTSPScore(MergedNodes, Jumps); 905 double CurScore = ChainPred->Score; 906 return MergeGainT(NewScore - CurScore, MergeOffset, MergeType); 907 } 908 909 /// Merge chain From into chain Into, update the list of active chains, 910 /// adjacency information, and the corresponding cached values. 911 void mergeChains(ChainT *Into, ChainT *From, size_t MergeOffset, 912 MergeTypeT MergeType) { 913 assert(Into != From && "a chain cannot be merged with itself"); 914 915 // Merge the nodes. 916 MergedNodesT MergedNodes = 917 mergeNodes(Into->Nodes, From->Nodes, MergeOffset, MergeType); 918 Into->merge(From, MergedNodes.getNodes()); 919 920 // Merge the edges. 921 Into->mergeEdges(From); 922 From->clear(); 923 924 // Update cached ext-tsp score for the new chain. 925 ChainEdge *SelfEdge = Into->getEdge(Into); 926 if (SelfEdge != nullptr) { 927 MergedNodes = MergedNodesT(Into->Nodes.begin(), Into->Nodes.end()); 928 MergedJumpsT MergedJumps(&SelfEdge->jumps()); 929 Into->Score = extTSPScore(MergedNodes, MergedJumps); 930 } 931 932 // Remove the chain from the list of active chains. 933 llvm::erase_value(HotChains, From); 934 935 // Invalidate caches. 936 for (auto EdgeIt : Into->Edges) 937 EdgeIt.second->invalidateCache(); 938 } 939 940 /// Concatenate all chains into the final order. 941 std::vector<uint64_t> concatChains() { 942 // Collect chains and calculate density stats for their sorting. 943 std::vector<const ChainT *> SortedChains; 944 DenseMap<const ChainT *, double> ChainDensity; 945 for (ChainT &Chain : AllChains) { 946 if (!Chain.Nodes.empty()) { 947 SortedChains.push_back(&Chain); 948 // Using doubles to avoid overflow of ExecutionCounts. 949 double Size = 0; 950 double ExecutionCount = 0; 951 for (NodeT *Node : Chain.Nodes) { 952 Size += static_cast<double>(Node->Size); 953 ExecutionCount += static_cast<double>(Node->ExecutionCount); 954 } 955 assert(Size > 0 && "a chain of zero size"); 956 ChainDensity[&Chain] = ExecutionCount / Size; 957 } 958 } 959 960 // Sorting chains by density in the decreasing order. 961 std::sort(SortedChains.begin(), SortedChains.end(), 962 [&](const ChainT *L, const ChainT *R) { 963 // Place the entry point at the beginning of the order. 964 if (L->isEntry() != R->isEntry()) 965 return L->isEntry(); 966 967 const double DL = ChainDensity[L]; 968 const double DR = ChainDensity[R]; 969 // Compare by density and break ties by chain identifiers. 970 return std::make_tuple(-DL, L->Id) < 971 std::make_tuple(-DR, R->Id); 972 }); 973 974 // Collect the nodes in the order specified by their chains. 975 std::vector<uint64_t> Order; 976 Order.reserve(NumNodes); 977 for (const ChainT *Chain : SortedChains) 978 for (NodeT *Node : Chain->Nodes) 979 Order.push_back(Node->Index); 980 return Order; 981 } 982 983 private: 984 /// The number of nodes in the graph. 985 const size_t NumNodes; 986 987 /// Successors of each node. 988 std::vector<std::vector<uint64_t>> SuccNodes; 989 990 /// Predecessors of each node. 991 std::vector<std::vector<uint64_t>> PredNodes; 992 993 /// All nodes (basic blocks) in the graph. 994 std::vector<NodeT> AllNodes; 995 996 /// All jumps between the nodes. 997 std::vector<JumpT> AllJumps; 998 999 /// All chains of nodes. 1000 std::vector<ChainT> AllChains; 1001 1002 /// All edges between the chains. 1003 std::vector<ChainEdge> AllEdges; 1004 1005 /// Active chains. The vector gets updated at runtime when chains are merged. 1006 std::vector<ChainT *> HotChains; 1007 }; 1008 1009 /// The implementation of the Cache-Directed Sort (CDS) algorithm for ordering 1010 /// functions represented by a call graph. 1011 class CDSortImpl { 1012 public: 1013 CDSortImpl(const CDSortConfig &Config, ArrayRef<uint64_t> NodeSizes, 1014 ArrayRef<uint64_t> NodeCounts, ArrayRef<EdgeCount> EdgeCounts, 1015 ArrayRef<uint64_t> EdgeOffsets) 1016 : Config(Config), NumNodes(NodeSizes.size()) { 1017 initialize(NodeSizes, NodeCounts, EdgeCounts, EdgeOffsets); 1018 } 1019 1020 /// Run the algorithm and return an ordered set of function clusters. 1021 std::vector<uint64_t> run() { 1022 // Merge pairs of chains while improving the objective. 1023 mergeChainPairs(); 1024 1025 LLVM_DEBUG(dbgs() << "Cache-directed function sorting reduced the number" 1026 << " of chains from " << NumNodes << " to " 1027 << HotChains.size() << "\n"); 1028 1029 // Collect nodes from all the chains. 1030 return concatChains(); 1031 } 1032 1033 private: 1034 /// Initialize the algorithm's data structures. 1035 void initialize(const ArrayRef<uint64_t> &NodeSizes, 1036 const ArrayRef<uint64_t> &NodeCounts, 1037 const ArrayRef<EdgeCount> &EdgeCounts, 1038 const ArrayRef<uint64_t> &EdgeOffsets) { 1039 // Initialize nodes. 1040 AllNodes.reserve(NumNodes); 1041 for (uint64_t Node = 0; Node < NumNodes; Node++) { 1042 uint64_t Size = std::max<uint64_t>(NodeSizes[Node], 1ULL); 1043 uint64_t ExecutionCount = NodeCounts[Node]; 1044 AllNodes.emplace_back(Node, Size, ExecutionCount); 1045 TotalSamples += ExecutionCount; 1046 if (ExecutionCount > 0) 1047 TotalSize += Size; 1048 } 1049 1050 // Initialize jumps between the nodes. 1051 SuccNodes.resize(NumNodes); 1052 PredNodes.resize(NumNodes); 1053 AllJumps.reserve(EdgeCounts.size()); 1054 for (size_t I = 0; I < EdgeCounts.size(); I++) { 1055 auto [Pred, Succ, Count] = EdgeCounts[I]; 1056 // Ignore recursive calls. 1057 if (Pred == Succ) 1058 continue; 1059 1060 SuccNodes[Pred].push_back(Succ); 1061 PredNodes[Succ].push_back(Pred); 1062 if (Count > 0) { 1063 NodeT &PredNode = AllNodes[Pred]; 1064 NodeT &SuccNode = AllNodes[Succ]; 1065 AllJumps.emplace_back(&PredNode, &SuccNode, Count); 1066 AllJumps.back().Offset = EdgeOffsets[I]; 1067 SuccNode.InJumps.push_back(&AllJumps.back()); 1068 PredNode.OutJumps.push_back(&AllJumps.back()); 1069 } 1070 } 1071 1072 // Initialize chains. 1073 AllChains.reserve(NumNodes); 1074 HotChains.reserve(NumNodes); 1075 for (NodeT &Node : AllNodes) { 1076 // Adjust execution counts. 1077 Node.ExecutionCount = std::max(Node.ExecutionCount, Node.inCount()); 1078 Node.ExecutionCount = std::max(Node.ExecutionCount, Node.outCount()); 1079 // Create chain. 1080 AllChains.emplace_back(Node.Index, &Node); 1081 Node.CurChain = &AllChains.back(); 1082 if (Node.ExecutionCount > 0) 1083 HotChains.push_back(&AllChains.back()); 1084 } 1085 1086 // Initialize chain edges. 1087 AllEdges.reserve(AllJumps.size()); 1088 for (NodeT &PredNode : AllNodes) { 1089 for (JumpT *Jump : PredNode.OutJumps) { 1090 NodeT *SuccNode = Jump->Target; 1091 ChainEdge *CurEdge = PredNode.CurChain->getEdge(SuccNode->CurChain); 1092 // this edge is already present in the graph. 1093 if (CurEdge != nullptr) { 1094 assert(SuccNode->CurChain->getEdge(PredNode.CurChain) != nullptr); 1095 CurEdge->appendJump(Jump); 1096 continue; 1097 } 1098 // this is a new edge. 1099 AllEdges.emplace_back(Jump); 1100 PredNode.CurChain->addEdge(SuccNode->CurChain, &AllEdges.back()); 1101 SuccNode->CurChain->addEdge(PredNode.CurChain, &AllEdges.back()); 1102 } 1103 } 1104 } 1105 1106 /// Merge pairs of chains while there is an improvement in the objective. 1107 void mergeChainPairs() { 1108 // Create a priority queue containing all edges ordered by the merge gain. 1109 auto GainComparator = [](ChainEdge *L, ChainEdge *R) { 1110 return std::make_tuple(-L->gain(), L->srcChain()->Id, L->dstChain()->Id) < 1111 std::make_tuple(-R->gain(), R->srcChain()->Id, R->dstChain()->Id); 1112 }; 1113 std::set<ChainEdge *, decltype(GainComparator)> Queue(GainComparator); 1114 1115 // Insert the edges into the queue. 1116 for (ChainT *ChainPred : HotChains) { 1117 for (const auto &[_, Edge] : ChainPred->Edges) { 1118 // Ignore self-edges. 1119 if (Edge->isSelfEdge()) 1120 continue; 1121 // Ignore already processed edges. 1122 if (Edge->gain() != -1.0) 1123 continue; 1124 1125 // Compute the gain of merging the two chains. 1126 MergeGainT Gain = getBestMergeGain(Edge); 1127 Edge->setMergeGain(Gain); 1128 1129 if (Edge->gain() > EPS) 1130 Queue.insert(Edge); 1131 } 1132 } 1133 1134 // Merge the chains while the gain of merging is positive. 1135 while (!Queue.empty()) { 1136 // Extract the best (top) edge for merging. 1137 ChainEdge *BestEdge = *Queue.begin(); 1138 Queue.erase(Queue.begin()); 1139 // Ignore self-edges. 1140 if (BestEdge->isSelfEdge()) 1141 continue; 1142 // Ignore edges with non-positive gains. 1143 if (BestEdge->gain() <= EPS) 1144 continue; 1145 1146 ChainT *BestSrcChain = BestEdge->srcChain(); 1147 ChainT *BestDstChain = BestEdge->dstChain(); 1148 1149 // Remove outdated edges from the queue. 1150 for (const auto &[_, ChainEdge] : BestSrcChain->Edges) 1151 Queue.erase(ChainEdge); 1152 for (const auto &[_, ChainEdge] : BestDstChain->Edges) 1153 Queue.erase(ChainEdge); 1154 1155 // Merge the best pair of chains. 1156 MergeGainT BestGain = BestEdge->getMergeGain(); 1157 mergeChains(BestSrcChain, BestDstChain, BestGain.mergeOffset(), 1158 BestGain.mergeType()); 1159 1160 // Insert newly created edges into the queue. 1161 for (const auto &[_, Edge] : BestSrcChain->Edges) { 1162 // Ignore loop edges. 1163 if (Edge->isSelfEdge()) 1164 continue; 1165 1166 // Compute the gain of merging the two chains. 1167 MergeGainT Gain = getBestMergeGain(Edge); 1168 Edge->setMergeGain(Gain); 1169 1170 if (Edge->gain() > EPS) 1171 Queue.insert(Edge); 1172 } 1173 } 1174 } 1175 1176 /// Compute the gain of merging two chains. 1177 /// 1178 /// The function considers all possible ways of merging two chains and 1179 /// computes the one having the largest increase in ExtTSP objective. The 1180 /// result is a pair with the first element being the gain and the second 1181 /// element being the corresponding merging type. 1182 MergeGainT getBestMergeGain(ChainEdge *Edge) const { 1183 assert(!Edge->jumps().empty() && "trying to merge chains w/o jumps"); 1184 // Precompute jumps between ChainPred and ChainSucc. 1185 MergedJumpsT Jumps(&Edge->jumps()); 1186 ChainT *SrcChain = Edge->srcChain(); 1187 ChainT *DstChain = Edge->dstChain(); 1188 1189 // This object holds the best currently chosen gain of merging two chains. 1190 MergeGainT Gain = MergeGainT(); 1191 1192 /// Given a list of merge types, try to merge two chains and update Gain 1193 /// with a better alternative. 1194 auto tryChainMerging = [&](const std::vector<MergeTypeT> &MergeTypes) { 1195 // Apply the merge, compute the corresponding gain, and update the best 1196 // value, if the merge is beneficial. 1197 for (const MergeTypeT &MergeType : MergeTypes) { 1198 MergeGainT NewGain = 1199 computeMergeGain(SrcChain, DstChain, Jumps, MergeType); 1200 1201 // When forward and backward gains are the same, prioritize merging that 1202 // preserves the original order of the functions in the binary. 1203 if (std::abs(Gain.score() - NewGain.score()) < EPS) { 1204 if ((MergeType == MergeTypeT::X_Y && SrcChain->Id < DstChain->Id) || 1205 (MergeType == MergeTypeT::Y_X && SrcChain->Id > DstChain->Id)) { 1206 Gain = NewGain; 1207 } 1208 } else if (NewGain.score() > Gain.score() + EPS) { 1209 Gain = NewGain; 1210 } 1211 } 1212 }; 1213 1214 // Try to concatenate two chains w/o splitting. 1215 tryChainMerging({MergeTypeT::X_Y, MergeTypeT::Y_X}); 1216 1217 return Gain; 1218 } 1219 1220 /// Compute the score gain of merging two chains, respecting a given type. 1221 /// 1222 /// The two chains are not modified in the method. 1223 MergeGainT computeMergeGain(ChainT *ChainPred, ChainT *ChainSucc, 1224 const MergedJumpsT &Jumps, 1225 MergeTypeT MergeType) const { 1226 // This doesn't depend on the ordering of the nodes 1227 double FreqGain = freqBasedLocalityGain(ChainPred, ChainSucc); 1228 1229 // Merge offset is always 0, as the chains are not split. 1230 size_t MergeOffset = 0; 1231 auto MergedBlocks = 1232 mergeNodes(ChainPred->Nodes, ChainSucc->Nodes, MergeOffset, MergeType); 1233 double DistGain = distBasedLocalityGain(MergedBlocks, Jumps); 1234 1235 double GainScore = DistGain + Config.FrequencyScale * FreqGain; 1236 // Scale the result to increase the importance of merging short chains. 1237 if (GainScore >= 0.0) 1238 GainScore /= std::min(ChainPred->Size, ChainSucc->Size); 1239 1240 return MergeGainT(GainScore, MergeOffset, MergeType); 1241 } 1242 1243 /// Compute the change of the frequency locality after merging the chains. 1244 double freqBasedLocalityGain(ChainT *ChainPred, ChainT *ChainSucc) const { 1245 auto missProbability = [&](double ChainDensity) { 1246 double PageSamples = ChainDensity * Config.CacheSize; 1247 if (PageSamples >= TotalSamples) 1248 return 0.0; 1249 double P = PageSamples / TotalSamples; 1250 return pow(1.0 - P, static_cast<double>(Config.CacheEntries)); 1251 }; 1252 1253 // Cache misses on the chains before merging. 1254 double CurScore = 1255 ChainPred->ExecutionCount * missProbability(ChainPred->density()) + 1256 ChainSucc->ExecutionCount * missProbability(ChainSucc->density()); 1257 1258 // Cache misses on the merged chain 1259 double MergedCounts = ChainPred->ExecutionCount + ChainSucc->ExecutionCount; 1260 double MergedSize = ChainPred->Size + ChainSucc->Size; 1261 double MergedDensity = static_cast<double>(MergedCounts) / MergedSize; 1262 double NewScore = MergedCounts * missProbability(MergedDensity); 1263 1264 return CurScore - NewScore; 1265 } 1266 1267 /// Compute the distance locality for a jump / call. 1268 double distScore(uint64_t SrcAddr, uint64_t DstAddr, uint64_t Count) const { 1269 uint64_t Dist = SrcAddr <= DstAddr ? DstAddr - SrcAddr : SrcAddr - DstAddr; 1270 double D = Dist == 0 ? 0.1 : static_cast<double>(Dist); 1271 return static_cast<double>(Count) * std::pow(D, -Config.DistancePower); 1272 } 1273 1274 /// Compute the change of the distance locality after merging the chains. 1275 double distBasedLocalityGain(const MergedNodesT &Nodes, 1276 const MergedJumpsT &Jumps) const { 1277 uint64_t CurAddr = 0; 1278 Nodes.forEach([&](const NodeT *Node) { 1279 Node->EstimatedAddr = CurAddr; 1280 CurAddr += Node->Size; 1281 }); 1282 1283 double CurScore = 0; 1284 double NewScore = 0; 1285 Jumps.forEach([&](const JumpT *Jump) { 1286 uint64_t SrcAddr = Jump->Source->EstimatedAddr + Jump->Offset; 1287 uint64_t DstAddr = Jump->Target->EstimatedAddr; 1288 NewScore += distScore(SrcAddr, DstAddr, Jump->ExecutionCount); 1289 CurScore += distScore(0, TotalSize, Jump->ExecutionCount); 1290 }); 1291 return NewScore - CurScore; 1292 } 1293 1294 /// Merge chain From into chain Into, update the list of active chains, 1295 /// adjacency information, and the corresponding cached values. 1296 void mergeChains(ChainT *Into, ChainT *From, size_t MergeOffset, 1297 MergeTypeT MergeType) { 1298 assert(Into != From && "a chain cannot be merged with itself"); 1299 1300 // Merge the nodes. 1301 MergedNodesT MergedNodes = 1302 mergeNodes(Into->Nodes, From->Nodes, MergeOffset, MergeType); 1303 Into->merge(From, MergedNodes.getNodes()); 1304 1305 // Merge the edges. 1306 Into->mergeEdges(From); 1307 From->clear(); 1308 1309 // Remove the chain from the list of active chains. 1310 llvm::erase_value(HotChains, From); 1311 } 1312 1313 /// Concatenate all chains into the final order. 1314 std::vector<uint64_t> concatChains() { 1315 // Collect chains and calculate density stats for their sorting. 1316 std::vector<const ChainT *> SortedChains; 1317 DenseMap<const ChainT *, double> ChainDensity; 1318 for (ChainT &Chain : AllChains) { 1319 if (!Chain.Nodes.empty()) { 1320 SortedChains.push_back(&Chain); 1321 // Using doubles to avoid overflow of ExecutionCounts. 1322 double Size = 0; 1323 double ExecutionCount = 0; 1324 for (NodeT *Node : Chain.Nodes) { 1325 Size += static_cast<double>(Node->Size); 1326 ExecutionCount += static_cast<double>(Node->ExecutionCount); 1327 } 1328 assert(Size > 0 && "a chain of zero size"); 1329 ChainDensity[&Chain] = ExecutionCount / Size; 1330 } 1331 } 1332 1333 // Sort chains by density in the decreasing order. 1334 std::sort(SortedChains.begin(), SortedChains.end(), 1335 [&](const ChainT *L, const ChainT *R) { 1336 const double DL = ChainDensity[L]; 1337 const double DR = ChainDensity[R]; 1338 // Compare by density and break ties by chain identifiers. 1339 return std::make_tuple(-DL, L->Id) < 1340 std::make_tuple(-DR, R->Id); 1341 }); 1342 1343 // Collect the nodes in the order specified by their chains. 1344 std::vector<uint64_t> Order; 1345 Order.reserve(NumNodes); 1346 for (const ChainT *Chain : SortedChains) 1347 for (NodeT *Node : Chain->Nodes) 1348 Order.push_back(Node->Index); 1349 return Order; 1350 } 1351 1352 private: 1353 /// Config for the algorithm. 1354 const CDSortConfig Config; 1355 1356 /// The number of nodes in the graph. 1357 const size_t NumNodes; 1358 1359 /// Successors of each node. 1360 std::vector<std::vector<uint64_t>> SuccNodes; 1361 1362 /// Predecessors of each node. 1363 std::vector<std::vector<uint64_t>> PredNodes; 1364 1365 /// All nodes (functions) in the graph. 1366 std::vector<NodeT> AllNodes; 1367 1368 /// All jumps (function calls) between the nodes. 1369 std::vector<JumpT> AllJumps; 1370 1371 /// All chains of nodes. 1372 std::vector<ChainT> AllChains; 1373 1374 /// All edges between the chains. 1375 std::vector<ChainEdge> AllEdges; 1376 1377 /// Active chains. The vector gets updated at runtime when chains are merged. 1378 std::vector<ChainT *> HotChains; 1379 1380 /// The total number of samples in the graph. 1381 uint64_t TotalSamples{0}; 1382 1383 /// The total size of the nodes in the graph. 1384 uint64_t TotalSize{0}; 1385 }; 1386 1387 } // end of anonymous namespace 1388 1389 std::vector<uint64_t> 1390 codelayout::computeExtTspLayout(ArrayRef<uint64_t> NodeSizes, 1391 ArrayRef<uint64_t> NodeCounts, 1392 ArrayRef<EdgeCount> EdgeCounts) { 1393 // Verify correctness of the input data. 1394 assert(NodeCounts.size() == NodeSizes.size() && "Incorrect input"); 1395 assert(NodeSizes.size() > 2 && "Incorrect input"); 1396 1397 // Apply the reordering algorithm. 1398 ExtTSPImpl Alg(NodeSizes, NodeCounts, EdgeCounts); 1399 std::vector<uint64_t> Result = Alg.run(); 1400 1401 // Verify correctness of the output. 1402 assert(Result.front() == 0 && "Original entry point is not preserved"); 1403 assert(Result.size() == NodeSizes.size() && "Incorrect size of layout"); 1404 return Result; 1405 } 1406 1407 double codelayout::calcExtTspScore(ArrayRef<uint64_t> Order, 1408 ArrayRef<uint64_t> NodeSizes, 1409 ArrayRef<uint64_t> NodeCounts, 1410 ArrayRef<EdgeCount> EdgeCounts) { 1411 // Estimate addresses of the blocks in memory. 1412 std::vector<uint64_t> Addr(NodeSizes.size(), 0); 1413 for (size_t Idx = 1; Idx < Order.size(); Idx++) { 1414 Addr[Order[Idx]] = Addr[Order[Idx - 1]] + NodeSizes[Order[Idx - 1]]; 1415 } 1416 std::vector<uint64_t> OutDegree(NodeSizes.size(), 0); 1417 for (auto Edge : EdgeCounts) 1418 ++OutDegree[Edge.src]; 1419 1420 // Increase the score for each jump. 1421 double Score = 0; 1422 for (auto Edge : EdgeCounts) { 1423 bool IsConditional = OutDegree[Edge.src] > 1; 1424 Score += ::extTSPScore(Addr[Edge.src], NodeSizes[Edge.src], Addr[Edge.dst], 1425 Edge.count, IsConditional); 1426 } 1427 return Score; 1428 } 1429 1430 double codelayout::calcExtTspScore(ArrayRef<uint64_t> NodeSizes, 1431 ArrayRef<uint64_t> NodeCounts, 1432 ArrayRef<EdgeCount> EdgeCounts) { 1433 std::vector<uint64_t> Order(NodeSizes.size()); 1434 for (size_t Idx = 0; Idx < NodeSizes.size(); Idx++) { 1435 Order[Idx] = Idx; 1436 } 1437 return calcExtTspScore(Order, NodeSizes, NodeCounts, EdgeCounts); 1438 } 1439 1440 std::vector<uint64_t> codelayout::computeCacheDirectedLayout( 1441 const CDSortConfig &Config, ArrayRef<uint64_t> FuncSizes, 1442 ArrayRef<uint64_t> FuncCounts, ArrayRef<EdgeCount> CallCounts, 1443 ArrayRef<uint64_t> CallOffsets) { 1444 // Verify correctness of the input data. 1445 assert(FuncCounts.size() == FuncSizes.size() && "Incorrect input"); 1446 1447 // Apply the reordering algorithm. 1448 CDSortImpl Alg(Config, FuncSizes, FuncCounts, CallCounts, CallOffsets); 1449 std::vector<uint64_t> Result = Alg.run(); 1450 assert(Result.size() == FuncSizes.size() && "Incorrect size of layout"); 1451 return Result; 1452 } 1453 1454 std::vector<uint64_t> codelayout::computeCacheDirectedLayout( 1455 ArrayRef<uint64_t> FuncSizes, ArrayRef<uint64_t> FuncCounts, 1456 ArrayRef<EdgeCount> CallCounts, ArrayRef<uint64_t> CallOffsets) { 1457 CDSortConfig Config; 1458 // Populate the config from the command-line options. 1459 if (CacheEntries.getNumOccurrences() > 0) 1460 Config.CacheEntries = CacheEntries; 1461 if (CacheSize.getNumOccurrences() > 0) 1462 Config.CacheSize = CacheSize; 1463 if (DistancePower.getNumOccurrences() > 0) 1464 Config.DistancePower = DistancePower; 1465 if (FrequencyScale.getNumOccurrences() > 0) 1466 Config.FrequencyScale = FrequencyScale; 1467 return computeCacheDirectedLayout(Config, FuncSizes, FuncCounts, CallCounts, 1468 CallOffsets); 1469 } 1470