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