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