10eae32dcSDimitry Andric //===- CodeLayout.cpp - Implementation of code layout algorithms ----------===// 20eae32dcSDimitry Andric // 30eae32dcSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40eae32dcSDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50eae32dcSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60eae32dcSDimitry Andric // 70eae32dcSDimitry Andric //===----------------------------------------------------------------------===// 80eae32dcSDimitry Andric // 90eae32dcSDimitry Andric // ExtTSP - layout of basic blocks with i-cache optimization. 100eae32dcSDimitry Andric // 110eae32dcSDimitry Andric // The algorithm tries to find a layout of nodes (basic blocks) of a given CFG 120eae32dcSDimitry Andric // optimizing jump locality and thus processor I-cache utilization. This is 130eae32dcSDimitry Andric // achieved via increasing the number of fall-through jumps and co-locating 140eae32dcSDimitry Andric // frequently executed nodes together. The name follows the underlying 150eae32dcSDimitry Andric // optimization problem, Extended-TSP, which is a generalization of classical 160eae32dcSDimitry Andric // (maximum) Traveling Salesmen Problem. 170eae32dcSDimitry Andric // 180eae32dcSDimitry Andric // The algorithm is a greedy heuristic that works with chains (ordered lists) 190eae32dcSDimitry Andric // of basic blocks. Initially all chains are isolated basic blocks. On every 200eae32dcSDimitry Andric // iteration, we pick a pair of chains whose merging yields the biggest increase 210eae32dcSDimitry Andric // in the ExtTSP score, which models how i-cache "friendly" a specific chain is. 220eae32dcSDimitry Andric // A pair of chains giving the maximum gain is merged into a new chain. The 230eae32dcSDimitry Andric // procedure stops when there is only one chain left, or when merging does not 240eae32dcSDimitry Andric // increase ExtTSP. In the latter case, the remaining chains are sorted by 250eae32dcSDimitry Andric // density in the decreasing order. 260eae32dcSDimitry Andric // 270eae32dcSDimitry Andric // An important aspect is the way two chains are merged. Unlike earlier 280eae32dcSDimitry Andric // algorithms (e.g., based on the approach of Pettis-Hansen), two 290eae32dcSDimitry Andric // chains, X and Y, are first split into three, X1, X2, and Y. Then we 300eae32dcSDimitry Andric // consider all possible ways of gluing the three chains (e.g., X1YX2, X1X2Y, 310eae32dcSDimitry Andric // X2X1Y, X2YX1, YX1X2, YX2X1) and choose the one producing the largest score. 320eae32dcSDimitry Andric // This improves the quality of the final result (the search space is larger) 330eae32dcSDimitry Andric // while keeping the implementation sufficiently fast. 340eae32dcSDimitry Andric // 350eae32dcSDimitry Andric // Reference: 360eae32dcSDimitry Andric // * A. Newell and S. Pupyrev, Improved Basic Block Reordering, 370eae32dcSDimitry Andric // IEEE Transactions on Computers, 2020 380eae32dcSDimitry Andric // 390eae32dcSDimitry Andric //===----------------------------------------------------------------------===// 400eae32dcSDimitry Andric 410eae32dcSDimitry Andric #include "llvm/Transforms/Utils/CodeLayout.h" 420eae32dcSDimitry Andric #include "llvm/Support/CommandLine.h" 430eae32dcSDimitry Andric 440eae32dcSDimitry Andric using namespace llvm; 450eae32dcSDimitry Andric #define DEBUG_TYPE "code-layout" 460eae32dcSDimitry Andric 47*81ad6265SDimitry Andric cl::opt<bool> EnableExtTspBlockPlacement( 48*81ad6265SDimitry Andric "enable-ext-tsp-block-placement", cl::Hidden, cl::init(false), 49*81ad6265SDimitry Andric cl::desc("Enable machine block placement based on the ext-tsp model, " 50*81ad6265SDimitry Andric "optimizing I-cache utilization.")); 51*81ad6265SDimitry Andric 52*81ad6265SDimitry Andric cl::opt<bool> ApplyExtTspWithoutProfile( 53*81ad6265SDimitry Andric "ext-tsp-apply-without-profile", 54*81ad6265SDimitry Andric cl::desc("Whether to apply ext-tsp placement for instances w/o profile"), 55*81ad6265SDimitry Andric cl::init(true), cl::Hidden); 56*81ad6265SDimitry Andric 570eae32dcSDimitry Andric // Algorithm-specific constants. The values are tuned for the best performance 580eae32dcSDimitry Andric // of large-scale front-end bound binaries. 590eae32dcSDimitry Andric static cl::opt<double> 600eae32dcSDimitry Andric ForwardWeight("ext-tsp-forward-weight", cl::Hidden, cl::init(0.1), 610eae32dcSDimitry Andric cl::desc("The weight of forward jumps for ExtTSP value")); 620eae32dcSDimitry Andric 630eae32dcSDimitry Andric static cl::opt<double> 640eae32dcSDimitry Andric BackwardWeight("ext-tsp-backward-weight", cl::Hidden, cl::init(0.1), 650eae32dcSDimitry Andric cl::desc("The weight of backward jumps for ExtTSP value")); 660eae32dcSDimitry Andric 670eae32dcSDimitry Andric static cl::opt<unsigned> ForwardDistance( 680eae32dcSDimitry Andric "ext-tsp-forward-distance", cl::Hidden, cl::init(1024), 690eae32dcSDimitry Andric cl::desc("The maximum distance (in bytes) of a forward jump for ExtTSP")); 700eae32dcSDimitry Andric 710eae32dcSDimitry Andric static cl::opt<unsigned> BackwardDistance( 720eae32dcSDimitry Andric "ext-tsp-backward-distance", cl::Hidden, cl::init(640), 730eae32dcSDimitry Andric cl::desc("The maximum distance (in bytes) of a backward jump for ExtTSP")); 740eae32dcSDimitry Andric 75*81ad6265SDimitry Andric // The maximum size of a chain created by the algorithm. The size is bounded 76*81ad6265SDimitry Andric // so that the algorithm can efficiently process extremely large instance. 77*81ad6265SDimitry Andric static cl::opt<unsigned> 78*81ad6265SDimitry Andric MaxChainSize("ext-tsp-max-chain-size", cl::Hidden, cl::init(4096), 79*81ad6265SDimitry Andric cl::desc("The maximum size of a chain to create.")); 80*81ad6265SDimitry Andric 810eae32dcSDimitry Andric // The maximum size of a chain for splitting. Larger values of the threshold 820eae32dcSDimitry Andric // may yield better quality at the cost of worsen run-time. 830eae32dcSDimitry Andric static cl::opt<unsigned> ChainSplitThreshold( 840eae32dcSDimitry Andric "ext-tsp-chain-split-threshold", cl::Hidden, cl::init(128), 850eae32dcSDimitry Andric cl::desc("The maximum size of a chain to apply splitting")); 860eae32dcSDimitry Andric 870eae32dcSDimitry Andric // The option enables splitting (large) chains along in-coming and out-going 880eae32dcSDimitry Andric // jumps. This typically results in a better quality. 890eae32dcSDimitry Andric static cl::opt<bool> EnableChainSplitAlongJumps( 900eae32dcSDimitry Andric "ext-tsp-enable-chain-split-along-jumps", cl::Hidden, cl::init(true), 910eae32dcSDimitry Andric cl::desc("The maximum size of a chain to apply splitting")); 920eae32dcSDimitry Andric 930eae32dcSDimitry Andric namespace { 940eae32dcSDimitry Andric 950eae32dcSDimitry Andric // Epsilon for comparison of doubles. 960eae32dcSDimitry Andric constexpr double EPS = 1e-8; 970eae32dcSDimitry Andric 980eae32dcSDimitry Andric // Compute the Ext-TSP score for a jump between a given pair of blocks, 990eae32dcSDimitry Andric // using their sizes, (estimated) addresses and the jump execution count. 1000eae32dcSDimitry Andric double extTSPScore(uint64_t SrcAddr, uint64_t SrcSize, uint64_t DstAddr, 1010eae32dcSDimitry Andric uint64_t Count) { 1020eae32dcSDimitry Andric // Fallthrough 1030eae32dcSDimitry Andric if (SrcAddr + SrcSize == DstAddr) { 1040eae32dcSDimitry Andric // Assume that FallthroughWeight = 1.0 after normalization 1050eae32dcSDimitry Andric return static_cast<double>(Count); 1060eae32dcSDimitry Andric } 1070eae32dcSDimitry Andric // Forward 1080eae32dcSDimitry Andric if (SrcAddr + SrcSize < DstAddr) { 1090eae32dcSDimitry Andric const auto Dist = DstAddr - (SrcAddr + SrcSize); 1100eae32dcSDimitry Andric if (Dist <= ForwardDistance) { 1110eae32dcSDimitry Andric double Prob = 1.0 - static_cast<double>(Dist) / ForwardDistance; 1120eae32dcSDimitry Andric return ForwardWeight * Prob * Count; 1130eae32dcSDimitry Andric } 1140eae32dcSDimitry Andric return 0; 1150eae32dcSDimitry Andric } 1160eae32dcSDimitry Andric // Backward 1170eae32dcSDimitry Andric const auto Dist = SrcAddr + SrcSize - DstAddr; 1180eae32dcSDimitry Andric if (Dist <= BackwardDistance) { 1190eae32dcSDimitry Andric double Prob = 1.0 - static_cast<double>(Dist) / BackwardDistance; 1200eae32dcSDimitry Andric return BackwardWeight * Prob * Count; 1210eae32dcSDimitry Andric } 1220eae32dcSDimitry Andric return 0; 1230eae32dcSDimitry Andric } 1240eae32dcSDimitry Andric 1250eae32dcSDimitry Andric /// A type of merging two chains, X and Y. The former chain is split into 1260eae32dcSDimitry Andric /// X1 and X2 and then concatenated with Y in the order specified by the type. 1270eae32dcSDimitry Andric enum class MergeTypeTy : int { X_Y, X1_Y_X2, Y_X2_X1, X2_X1_Y }; 1280eae32dcSDimitry Andric 1290eae32dcSDimitry Andric /// The gain of merging two chains, that is, the Ext-TSP score of the merge 1300eae32dcSDimitry Andric /// together with the corresponfiding merge 'type' and 'offset'. 1310eae32dcSDimitry Andric class MergeGainTy { 1320eae32dcSDimitry Andric public: 133*81ad6265SDimitry Andric explicit MergeGainTy() = default; 1340eae32dcSDimitry Andric explicit MergeGainTy(double Score, size_t MergeOffset, MergeTypeTy MergeType) 1350eae32dcSDimitry Andric : Score(Score), MergeOffset(MergeOffset), MergeType(MergeType) {} 1360eae32dcSDimitry Andric 1370eae32dcSDimitry Andric double score() const { return Score; } 1380eae32dcSDimitry Andric 1390eae32dcSDimitry Andric size_t mergeOffset() const { return MergeOffset; } 1400eae32dcSDimitry Andric 1410eae32dcSDimitry Andric MergeTypeTy mergeType() const { return MergeType; } 1420eae32dcSDimitry Andric 1430eae32dcSDimitry Andric // Returns 'true' iff Other is preferred over this. 1440eae32dcSDimitry Andric bool operator<(const MergeGainTy &Other) const { 1450eae32dcSDimitry Andric return (Other.Score > EPS && Other.Score > Score + EPS); 1460eae32dcSDimitry Andric } 1470eae32dcSDimitry Andric 1480eae32dcSDimitry Andric // Update the current gain if Other is preferred over this. 1490eae32dcSDimitry Andric void updateIfLessThan(const MergeGainTy &Other) { 1500eae32dcSDimitry Andric if (*this < Other) 1510eae32dcSDimitry Andric *this = Other; 1520eae32dcSDimitry Andric } 1530eae32dcSDimitry Andric 1540eae32dcSDimitry Andric private: 1550eae32dcSDimitry Andric double Score{-1.0}; 1560eae32dcSDimitry Andric size_t MergeOffset{0}; 1570eae32dcSDimitry Andric MergeTypeTy MergeType{MergeTypeTy::X_Y}; 1580eae32dcSDimitry Andric }; 1590eae32dcSDimitry Andric 1600eae32dcSDimitry Andric class Jump; 1610eae32dcSDimitry Andric class Chain; 1620eae32dcSDimitry Andric class ChainEdge; 1630eae32dcSDimitry Andric 1640eae32dcSDimitry Andric /// A node in the graph, typically corresponding to a basic block in CFG. 1650eae32dcSDimitry Andric class Block { 1660eae32dcSDimitry Andric public: 1670eae32dcSDimitry Andric Block(const Block &) = delete; 1680eae32dcSDimitry Andric Block(Block &&) = default; 1690eae32dcSDimitry Andric Block &operator=(const Block &) = delete; 1700eae32dcSDimitry Andric Block &operator=(Block &&) = default; 1710eae32dcSDimitry Andric 1720eae32dcSDimitry Andric // The original index of the block in CFG. 1730eae32dcSDimitry Andric size_t Index{0}; 1740eae32dcSDimitry Andric // The index of the block in the current chain. 1750eae32dcSDimitry Andric size_t CurIndex{0}; 1760eae32dcSDimitry Andric // Size of the block in the binary. 1770eae32dcSDimitry Andric uint64_t Size{0}; 1780eae32dcSDimitry Andric // Execution count of the block in the profile data. 1790eae32dcSDimitry Andric uint64_t ExecutionCount{0}; 1800eae32dcSDimitry Andric // Current chain of the node. 1810eae32dcSDimitry Andric Chain *CurChain{nullptr}; 1820eae32dcSDimitry Andric // An offset of the block in the current chain. 1830eae32dcSDimitry Andric mutable uint64_t EstimatedAddr{0}; 1840eae32dcSDimitry Andric // Forced successor of the block in CFG. 1850eae32dcSDimitry Andric Block *ForcedSucc{nullptr}; 1860eae32dcSDimitry Andric // Forced predecessor of the block in CFG. 1870eae32dcSDimitry Andric Block *ForcedPred{nullptr}; 1880eae32dcSDimitry Andric // Outgoing jumps from the block. 1890eae32dcSDimitry Andric std::vector<Jump *> OutJumps; 1900eae32dcSDimitry Andric // Incoming jumps to the block. 1910eae32dcSDimitry Andric std::vector<Jump *> InJumps; 1920eae32dcSDimitry Andric 1930eae32dcSDimitry Andric public: 1940eae32dcSDimitry Andric explicit Block(size_t Index, uint64_t Size_, uint64_t EC) 1950eae32dcSDimitry Andric : Index(Index), Size(Size_), ExecutionCount(EC) {} 1960eae32dcSDimitry Andric bool isEntry() const { return Index == 0; } 1970eae32dcSDimitry Andric }; 1980eae32dcSDimitry Andric 1990eae32dcSDimitry Andric /// An arc in the graph, typically corresponding to a jump between two blocks. 2000eae32dcSDimitry Andric class Jump { 2010eae32dcSDimitry Andric public: 2020eae32dcSDimitry Andric Jump(const Jump &) = delete; 2030eae32dcSDimitry Andric Jump(Jump &&) = default; 2040eae32dcSDimitry Andric Jump &operator=(const Jump &) = delete; 2050eae32dcSDimitry Andric Jump &operator=(Jump &&) = default; 2060eae32dcSDimitry Andric 2070eae32dcSDimitry Andric // Source block of the jump. 2080eae32dcSDimitry Andric Block *Source; 2090eae32dcSDimitry Andric // Target block of the jump. 2100eae32dcSDimitry Andric Block *Target; 2110eae32dcSDimitry Andric // Execution count of the arc in the profile data. 2120eae32dcSDimitry Andric uint64_t ExecutionCount{0}; 2130eae32dcSDimitry Andric 2140eae32dcSDimitry Andric public: 2150eae32dcSDimitry Andric explicit Jump(Block *Source, Block *Target, uint64_t ExecutionCount) 2160eae32dcSDimitry Andric : Source(Source), Target(Target), ExecutionCount(ExecutionCount) {} 2170eae32dcSDimitry Andric }; 2180eae32dcSDimitry Andric 2190eae32dcSDimitry Andric /// A chain (ordered sequence) of blocks. 2200eae32dcSDimitry Andric class Chain { 2210eae32dcSDimitry Andric public: 2220eae32dcSDimitry Andric Chain(const Chain &) = delete; 2230eae32dcSDimitry Andric Chain(Chain &&) = default; 2240eae32dcSDimitry Andric Chain &operator=(const Chain &) = delete; 2250eae32dcSDimitry Andric Chain &operator=(Chain &&) = default; 2260eae32dcSDimitry Andric 2270eae32dcSDimitry Andric explicit Chain(uint64_t Id, Block *Block) 2280eae32dcSDimitry Andric : Id(Id), Score(0), Blocks(1, Block) {} 2290eae32dcSDimitry Andric 2300eae32dcSDimitry Andric uint64_t id() const { return Id; } 2310eae32dcSDimitry Andric 2320eae32dcSDimitry Andric bool isEntry() const { return Blocks[0]->Index == 0; } 2330eae32dcSDimitry Andric 2340eae32dcSDimitry Andric double score() const { return Score; } 2350eae32dcSDimitry Andric 2360eae32dcSDimitry Andric void setScore(double NewScore) { Score = NewScore; } 2370eae32dcSDimitry Andric 2380eae32dcSDimitry Andric const std::vector<Block *> &blocks() const { return Blocks; } 2390eae32dcSDimitry Andric 240*81ad6265SDimitry Andric size_t numBlocks() const { return Blocks.size(); } 241*81ad6265SDimitry Andric 2420eae32dcSDimitry Andric const std::vector<std::pair<Chain *, ChainEdge *>> &edges() const { 2430eae32dcSDimitry Andric return Edges; 2440eae32dcSDimitry Andric } 2450eae32dcSDimitry Andric 2460eae32dcSDimitry Andric ChainEdge *getEdge(Chain *Other) const { 2470eae32dcSDimitry Andric for (auto It : Edges) { 2480eae32dcSDimitry Andric if (It.first == Other) 2490eae32dcSDimitry Andric return It.second; 2500eae32dcSDimitry Andric } 2510eae32dcSDimitry Andric return nullptr; 2520eae32dcSDimitry Andric } 2530eae32dcSDimitry Andric 2540eae32dcSDimitry Andric void removeEdge(Chain *Other) { 2550eae32dcSDimitry Andric auto It = Edges.begin(); 2560eae32dcSDimitry Andric while (It != Edges.end()) { 2570eae32dcSDimitry Andric if (It->first == Other) { 2580eae32dcSDimitry Andric Edges.erase(It); 2590eae32dcSDimitry Andric return; 2600eae32dcSDimitry Andric } 2610eae32dcSDimitry Andric It++; 2620eae32dcSDimitry Andric } 2630eae32dcSDimitry Andric } 2640eae32dcSDimitry Andric 2650eae32dcSDimitry Andric void addEdge(Chain *Other, ChainEdge *Edge) { 2660eae32dcSDimitry Andric Edges.push_back(std::make_pair(Other, Edge)); 2670eae32dcSDimitry Andric } 2680eae32dcSDimitry Andric 2690eae32dcSDimitry Andric void merge(Chain *Other, const std::vector<Block *> &MergedBlocks) { 2700eae32dcSDimitry Andric Blocks = MergedBlocks; 2710eae32dcSDimitry Andric // Update the block's chains 2720eae32dcSDimitry Andric for (size_t Idx = 0; Idx < Blocks.size(); Idx++) { 2730eae32dcSDimitry Andric Blocks[Idx]->CurChain = this; 2740eae32dcSDimitry Andric Blocks[Idx]->CurIndex = Idx; 2750eae32dcSDimitry Andric } 2760eae32dcSDimitry Andric } 2770eae32dcSDimitry Andric 2780eae32dcSDimitry Andric void mergeEdges(Chain *Other); 2790eae32dcSDimitry Andric 2800eae32dcSDimitry Andric void clear() { 2810eae32dcSDimitry Andric Blocks.clear(); 2820eae32dcSDimitry Andric Blocks.shrink_to_fit(); 2830eae32dcSDimitry Andric Edges.clear(); 2840eae32dcSDimitry Andric Edges.shrink_to_fit(); 2850eae32dcSDimitry Andric } 2860eae32dcSDimitry Andric 2870eae32dcSDimitry Andric private: 2880eae32dcSDimitry Andric // Unique chain identifier. 2890eae32dcSDimitry Andric uint64_t Id; 2900eae32dcSDimitry Andric // Cached ext-tsp score for the chain. 2910eae32dcSDimitry Andric double Score; 2920eae32dcSDimitry Andric // Blocks of the chain. 2930eae32dcSDimitry Andric std::vector<Block *> Blocks; 2940eae32dcSDimitry Andric // Adjacent chains and corresponding edges (lists of jumps). 2950eae32dcSDimitry Andric std::vector<std::pair<Chain *, ChainEdge *>> Edges; 2960eae32dcSDimitry Andric }; 2970eae32dcSDimitry Andric 2980eae32dcSDimitry Andric /// An edge in CFG representing jumps between two chains. 2990eae32dcSDimitry Andric /// When blocks are merged into chains, the edges are combined too so that 3000eae32dcSDimitry Andric /// there is always at most one edge between a pair of chains 3010eae32dcSDimitry Andric class ChainEdge { 3020eae32dcSDimitry Andric public: 3030eae32dcSDimitry Andric ChainEdge(const ChainEdge &) = delete; 3040eae32dcSDimitry Andric ChainEdge(ChainEdge &&) = default; 3050eae32dcSDimitry Andric ChainEdge &operator=(const ChainEdge &) = delete; 3060eae32dcSDimitry Andric ChainEdge &operator=(ChainEdge &&) = default; 3070eae32dcSDimitry Andric 3080eae32dcSDimitry Andric explicit ChainEdge(Jump *Jump) 3090eae32dcSDimitry Andric : SrcChain(Jump->Source->CurChain), DstChain(Jump->Target->CurChain), 3100eae32dcSDimitry Andric Jumps(1, Jump) {} 3110eae32dcSDimitry Andric 3120eae32dcSDimitry Andric const std::vector<Jump *> &jumps() const { return Jumps; } 3130eae32dcSDimitry Andric 3140eae32dcSDimitry Andric void changeEndpoint(Chain *From, Chain *To) { 3150eae32dcSDimitry Andric if (From == SrcChain) 3160eae32dcSDimitry Andric SrcChain = To; 3170eae32dcSDimitry Andric if (From == DstChain) 3180eae32dcSDimitry Andric DstChain = To; 3190eae32dcSDimitry Andric } 3200eae32dcSDimitry Andric 3210eae32dcSDimitry Andric void appendJump(Jump *Jump) { Jumps.push_back(Jump); } 3220eae32dcSDimitry Andric 3230eae32dcSDimitry Andric void moveJumps(ChainEdge *Other) { 3240eae32dcSDimitry Andric Jumps.insert(Jumps.end(), Other->Jumps.begin(), Other->Jumps.end()); 3250eae32dcSDimitry Andric Other->Jumps.clear(); 3260eae32dcSDimitry Andric Other->Jumps.shrink_to_fit(); 3270eae32dcSDimitry Andric } 3280eae32dcSDimitry Andric 3290eae32dcSDimitry Andric bool hasCachedMergeGain(Chain *Src, Chain *Dst) const { 3300eae32dcSDimitry Andric return Src == SrcChain ? CacheValidForward : CacheValidBackward; 3310eae32dcSDimitry Andric } 3320eae32dcSDimitry Andric 3330eae32dcSDimitry Andric MergeGainTy getCachedMergeGain(Chain *Src, Chain *Dst) const { 3340eae32dcSDimitry Andric return Src == SrcChain ? CachedGainForward : CachedGainBackward; 3350eae32dcSDimitry Andric } 3360eae32dcSDimitry Andric 3370eae32dcSDimitry Andric void setCachedMergeGain(Chain *Src, Chain *Dst, MergeGainTy MergeGain) { 3380eae32dcSDimitry Andric if (Src == SrcChain) { 3390eae32dcSDimitry Andric CachedGainForward = MergeGain; 3400eae32dcSDimitry Andric CacheValidForward = true; 3410eae32dcSDimitry Andric } else { 3420eae32dcSDimitry Andric CachedGainBackward = MergeGain; 3430eae32dcSDimitry Andric CacheValidBackward = true; 3440eae32dcSDimitry Andric } 3450eae32dcSDimitry Andric } 3460eae32dcSDimitry Andric 3470eae32dcSDimitry Andric void invalidateCache() { 3480eae32dcSDimitry Andric CacheValidForward = false; 3490eae32dcSDimitry Andric CacheValidBackward = false; 3500eae32dcSDimitry Andric } 3510eae32dcSDimitry Andric 3520eae32dcSDimitry Andric private: 3530eae32dcSDimitry Andric // Source chain. 3540eae32dcSDimitry Andric Chain *SrcChain{nullptr}; 3550eae32dcSDimitry Andric // Destination chain. 3560eae32dcSDimitry Andric Chain *DstChain{nullptr}; 3570eae32dcSDimitry Andric // Original jumps in the binary with correspinding execution counts. 3580eae32dcSDimitry Andric std::vector<Jump *> Jumps; 3590eae32dcSDimitry Andric // Cached ext-tsp value for merging the pair of chains. 3600eae32dcSDimitry Andric // Since the gain of merging (Src, Dst) and (Dst, Src) might be different, 3610eae32dcSDimitry Andric // we store both values here. 3620eae32dcSDimitry Andric MergeGainTy CachedGainForward; 3630eae32dcSDimitry Andric MergeGainTy CachedGainBackward; 3640eae32dcSDimitry Andric // Whether the cached value must be recomputed. 3650eae32dcSDimitry Andric bool CacheValidForward{false}; 3660eae32dcSDimitry Andric bool CacheValidBackward{false}; 3670eae32dcSDimitry Andric }; 3680eae32dcSDimitry Andric 3690eae32dcSDimitry Andric void Chain::mergeEdges(Chain *Other) { 3700eae32dcSDimitry Andric assert(this != Other && "cannot merge a chain with itself"); 3710eae32dcSDimitry Andric 3720eae32dcSDimitry Andric // Update edges adjacent to chain Other 3730eae32dcSDimitry Andric for (auto EdgeIt : Other->Edges) { 3740eae32dcSDimitry Andric const auto DstChain = EdgeIt.first; 3750eae32dcSDimitry Andric const auto DstEdge = EdgeIt.second; 3760eae32dcSDimitry Andric const auto TargetChain = DstChain == Other ? this : DstChain; 3770eae32dcSDimitry Andric auto CurEdge = getEdge(TargetChain); 3780eae32dcSDimitry Andric if (CurEdge == nullptr) { 3790eae32dcSDimitry Andric DstEdge->changeEndpoint(Other, this); 3800eae32dcSDimitry Andric this->addEdge(TargetChain, DstEdge); 3810eae32dcSDimitry Andric if (DstChain != this && DstChain != Other) { 3820eae32dcSDimitry Andric DstChain->addEdge(this, DstEdge); 3830eae32dcSDimitry Andric } 3840eae32dcSDimitry Andric } else { 3850eae32dcSDimitry Andric CurEdge->moveJumps(DstEdge); 3860eae32dcSDimitry Andric } 3870eae32dcSDimitry Andric // Cleanup leftover edge 3880eae32dcSDimitry Andric if (DstChain != Other) { 3890eae32dcSDimitry Andric DstChain->removeEdge(Other); 3900eae32dcSDimitry Andric } 3910eae32dcSDimitry Andric } 3920eae32dcSDimitry Andric } 3930eae32dcSDimitry Andric 3940eae32dcSDimitry Andric using BlockIter = std::vector<Block *>::const_iterator; 3950eae32dcSDimitry Andric 3960eae32dcSDimitry Andric /// A wrapper around three chains of blocks; it is used to avoid extra 3970eae32dcSDimitry Andric /// instantiation of the vectors. 3980eae32dcSDimitry Andric class MergedChain { 3990eae32dcSDimitry Andric public: 4000eae32dcSDimitry Andric MergedChain(BlockIter Begin1, BlockIter End1, BlockIter Begin2 = BlockIter(), 4010eae32dcSDimitry Andric BlockIter End2 = BlockIter(), BlockIter Begin3 = BlockIter(), 4020eae32dcSDimitry Andric BlockIter End3 = BlockIter()) 4030eae32dcSDimitry Andric : Begin1(Begin1), End1(End1), Begin2(Begin2), End2(End2), Begin3(Begin3), 4040eae32dcSDimitry Andric End3(End3) {} 4050eae32dcSDimitry Andric 4060eae32dcSDimitry Andric template <typename F> void forEach(const F &Func) const { 4070eae32dcSDimitry Andric for (auto It = Begin1; It != End1; It++) 4080eae32dcSDimitry Andric Func(*It); 4090eae32dcSDimitry Andric for (auto It = Begin2; It != End2; It++) 4100eae32dcSDimitry Andric Func(*It); 4110eae32dcSDimitry Andric for (auto It = Begin3; It != End3; It++) 4120eae32dcSDimitry Andric Func(*It); 4130eae32dcSDimitry Andric } 4140eae32dcSDimitry Andric 4150eae32dcSDimitry Andric std::vector<Block *> getBlocks() const { 4160eae32dcSDimitry Andric std::vector<Block *> Result; 4170eae32dcSDimitry Andric Result.reserve(std::distance(Begin1, End1) + std::distance(Begin2, End2) + 4180eae32dcSDimitry Andric std::distance(Begin3, End3)); 4190eae32dcSDimitry Andric Result.insert(Result.end(), Begin1, End1); 4200eae32dcSDimitry Andric Result.insert(Result.end(), Begin2, End2); 4210eae32dcSDimitry Andric Result.insert(Result.end(), Begin3, End3); 4220eae32dcSDimitry Andric return Result; 4230eae32dcSDimitry Andric } 4240eae32dcSDimitry Andric 4250eae32dcSDimitry Andric const Block *getFirstBlock() const { return *Begin1; } 4260eae32dcSDimitry Andric 4270eae32dcSDimitry Andric private: 4280eae32dcSDimitry Andric BlockIter Begin1; 4290eae32dcSDimitry Andric BlockIter End1; 4300eae32dcSDimitry Andric BlockIter Begin2; 4310eae32dcSDimitry Andric BlockIter End2; 4320eae32dcSDimitry Andric BlockIter Begin3; 4330eae32dcSDimitry Andric BlockIter End3; 4340eae32dcSDimitry Andric }; 4350eae32dcSDimitry Andric 4360eae32dcSDimitry Andric /// The implementation of the ExtTSP algorithm. 4370eae32dcSDimitry Andric class ExtTSPImpl { 4380eae32dcSDimitry Andric using EdgeT = std::pair<uint64_t, uint64_t>; 4390eae32dcSDimitry Andric using EdgeCountMap = DenseMap<EdgeT, uint64_t>; 4400eae32dcSDimitry Andric 4410eae32dcSDimitry Andric public: 4420eae32dcSDimitry Andric ExtTSPImpl(size_t NumNodes, const std::vector<uint64_t> &NodeSizes, 4430eae32dcSDimitry Andric const std::vector<uint64_t> &NodeCounts, 4440eae32dcSDimitry Andric const EdgeCountMap &EdgeCounts) 4450eae32dcSDimitry Andric : NumNodes(NumNodes) { 4460eae32dcSDimitry Andric initialize(NodeSizes, NodeCounts, EdgeCounts); 4470eae32dcSDimitry Andric } 4480eae32dcSDimitry Andric 4490eae32dcSDimitry Andric /// Run the algorithm and return an optimized ordering of blocks. 4500eae32dcSDimitry Andric void run(std::vector<uint64_t> &Result) { 4510eae32dcSDimitry Andric // Pass 1: Merge blocks with their mutually forced successors 4520eae32dcSDimitry Andric mergeForcedPairs(); 4530eae32dcSDimitry Andric 4540eae32dcSDimitry Andric // Pass 2: Merge pairs of chains while improving the ExtTSP objective 4550eae32dcSDimitry Andric mergeChainPairs(); 4560eae32dcSDimitry Andric 4570eae32dcSDimitry Andric // Pass 3: Merge cold blocks to reduce code size 4580eae32dcSDimitry Andric mergeColdChains(); 4590eae32dcSDimitry Andric 4600eae32dcSDimitry Andric // Collect blocks from all chains 4610eae32dcSDimitry Andric concatChains(Result); 4620eae32dcSDimitry Andric } 4630eae32dcSDimitry Andric 4640eae32dcSDimitry Andric private: 4650eae32dcSDimitry Andric /// Initialize the algorithm's data structures. 4660eae32dcSDimitry Andric void initialize(const std::vector<uint64_t> &NodeSizes, 4670eae32dcSDimitry Andric const std::vector<uint64_t> &NodeCounts, 4680eae32dcSDimitry Andric const EdgeCountMap &EdgeCounts) { 4690eae32dcSDimitry Andric // Initialize blocks 4700eae32dcSDimitry Andric AllBlocks.reserve(NumNodes); 4710eae32dcSDimitry Andric for (uint64_t Node = 0; Node < NumNodes; Node++) { 4720eae32dcSDimitry Andric uint64_t Size = std::max<uint64_t>(NodeSizes[Node], 1ULL); 4730eae32dcSDimitry Andric uint64_t ExecutionCount = NodeCounts[Node]; 4740eae32dcSDimitry Andric // The execution count of the entry block is set to at least 1 4750eae32dcSDimitry Andric if (Node == 0 && ExecutionCount == 0) 4760eae32dcSDimitry Andric ExecutionCount = 1; 4770eae32dcSDimitry Andric AllBlocks.emplace_back(Node, Size, ExecutionCount); 4780eae32dcSDimitry Andric } 4790eae32dcSDimitry Andric 4800eae32dcSDimitry Andric // Initialize jumps between blocks 4810eae32dcSDimitry Andric SuccNodes = std::vector<std::vector<uint64_t>>(NumNodes); 4820eae32dcSDimitry Andric PredNodes = std::vector<std::vector<uint64_t>>(NumNodes); 4830eae32dcSDimitry Andric AllJumps.reserve(EdgeCounts.size()); 4840eae32dcSDimitry Andric for (auto It : EdgeCounts) { 4850eae32dcSDimitry Andric auto Pred = It.first.first; 4860eae32dcSDimitry Andric auto Succ = It.first.second; 4870eae32dcSDimitry Andric // Ignore self-edges 4880eae32dcSDimitry Andric if (Pred == Succ) 4890eae32dcSDimitry Andric continue; 4900eae32dcSDimitry Andric 4910eae32dcSDimitry Andric SuccNodes[Pred].push_back(Succ); 4920eae32dcSDimitry Andric PredNodes[Succ].push_back(Pred); 4930eae32dcSDimitry Andric auto ExecutionCount = It.second; 4940eae32dcSDimitry Andric if (ExecutionCount > 0) { 4950eae32dcSDimitry Andric auto &Block = AllBlocks[Pred]; 4960eae32dcSDimitry Andric auto &SuccBlock = AllBlocks[Succ]; 4970eae32dcSDimitry Andric AllJumps.emplace_back(&Block, &SuccBlock, ExecutionCount); 4980eae32dcSDimitry Andric SuccBlock.InJumps.push_back(&AllJumps.back()); 4990eae32dcSDimitry Andric Block.OutJumps.push_back(&AllJumps.back()); 5000eae32dcSDimitry Andric } 5010eae32dcSDimitry Andric } 5020eae32dcSDimitry Andric 5030eae32dcSDimitry Andric // Initialize chains 5040eae32dcSDimitry Andric AllChains.reserve(NumNodes); 5050eae32dcSDimitry Andric HotChains.reserve(NumNodes); 5060eae32dcSDimitry Andric for (auto &Block : AllBlocks) { 5070eae32dcSDimitry Andric AllChains.emplace_back(Block.Index, &Block); 5080eae32dcSDimitry Andric Block.CurChain = &AllChains.back(); 5090eae32dcSDimitry Andric if (Block.ExecutionCount > 0) { 5100eae32dcSDimitry Andric HotChains.push_back(&AllChains.back()); 5110eae32dcSDimitry Andric } 5120eae32dcSDimitry Andric } 5130eae32dcSDimitry Andric 5140eae32dcSDimitry Andric // Initialize chain edges 5150eae32dcSDimitry Andric AllEdges.reserve(AllJumps.size()); 5160eae32dcSDimitry Andric for (auto &Block : AllBlocks) { 5170eae32dcSDimitry Andric for (auto &Jump : Block.OutJumps) { 518*81ad6265SDimitry Andric auto SuccBlock = Jump->Target; 5190eae32dcSDimitry Andric auto CurEdge = Block.CurChain->getEdge(SuccBlock->CurChain); 5200eae32dcSDimitry Andric // this edge is already present in the graph 5210eae32dcSDimitry Andric if (CurEdge != nullptr) { 5220eae32dcSDimitry Andric assert(SuccBlock->CurChain->getEdge(Block.CurChain) != nullptr); 5230eae32dcSDimitry Andric CurEdge->appendJump(Jump); 5240eae32dcSDimitry Andric continue; 5250eae32dcSDimitry Andric } 5260eae32dcSDimitry Andric // this is a new edge 5270eae32dcSDimitry Andric AllEdges.emplace_back(Jump); 5280eae32dcSDimitry Andric Block.CurChain->addEdge(SuccBlock->CurChain, &AllEdges.back()); 5290eae32dcSDimitry Andric SuccBlock->CurChain->addEdge(Block.CurChain, &AllEdges.back()); 5300eae32dcSDimitry Andric } 5310eae32dcSDimitry Andric } 5320eae32dcSDimitry Andric } 5330eae32dcSDimitry Andric 5340eae32dcSDimitry Andric /// For a pair of blocks, A and B, block B is the forced successor of A, 5350eae32dcSDimitry Andric /// if (i) all jumps (based on profile) from A goes to B and (ii) all jumps 5360eae32dcSDimitry Andric /// to B are from A. Such blocks should be adjacent in the optimal ordering; 5370eae32dcSDimitry Andric /// the method finds and merges such pairs of blocks. 5380eae32dcSDimitry Andric void mergeForcedPairs() { 5390eae32dcSDimitry Andric // Find fallthroughs based on edge weights 5400eae32dcSDimitry Andric for (auto &Block : AllBlocks) { 5410eae32dcSDimitry Andric if (SuccNodes[Block.Index].size() == 1 && 5420eae32dcSDimitry Andric PredNodes[SuccNodes[Block.Index][0]].size() == 1 && 5430eae32dcSDimitry Andric SuccNodes[Block.Index][0] != 0) { 5440eae32dcSDimitry Andric size_t SuccIndex = SuccNodes[Block.Index][0]; 5450eae32dcSDimitry Andric Block.ForcedSucc = &AllBlocks[SuccIndex]; 5460eae32dcSDimitry Andric AllBlocks[SuccIndex].ForcedPred = &Block; 5470eae32dcSDimitry Andric } 5480eae32dcSDimitry Andric } 5490eae32dcSDimitry Andric 5500eae32dcSDimitry Andric // There might be 'cycles' in the forced dependencies, since profile 5510eae32dcSDimitry Andric // data isn't 100% accurate. Typically this is observed in loops, when the 5520eae32dcSDimitry Andric // loop edges are the hottest successors for the basic blocks of the loop. 5530eae32dcSDimitry Andric // Break the cycles by choosing the block with the smallest index as the 5540eae32dcSDimitry Andric // head. This helps to keep the original order of the loops, which likely 5550eae32dcSDimitry Andric // have already been rotated in the optimized manner. 5560eae32dcSDimitry Andric for (auto &Block : AllBlocks) { 5570eae32dcSDimitry Andric if (Block.ForcedSucc == nullptr || Block.ForcedPred == nullptr) 5580eae32dcSDimitry Andric continue; 5590eae32dcSDimitry Andric 5600eae32dcSDimitry Andric auto SuccBlock = Block.ForcedSucc; 5610eae32dcSDimitry Andric while (SuccBlock != nullptr && SuccBlock != &Block) { 5620eae32dcSDimitry Andric SuccBlock = SuccBlock->ForcedSucc; 5630eae32dcSDimitry Andric } 5640eae32dcSDimitry Andric if (SuccBlock == nullptr) 5650eae32dcSDimitry Andric continue; 5660eae32dcSDimitry Andric // Break the cycle 5670eae32dcSDimitry Andric AllBlocks[Block.ForcedPred->Index].ForcedSucc = nullptr; 5680eae32dcSDimitry Andric Block.ForcedPred = nullptr; 5690eae32dcSDimitry Andric } 5700eae32dcSDimitry Andric 5710eae32dcSDimitry Andric // Merge blocks with their fallthrough successors 5720eae32dcSDimitry Andric for (auto &Block : AllBlocks) { 5730eae32dcSDimitry Andric if (Block.ForcedPred == nullptr && Block.ForcedSucc != nullptr) { 5740eae32dcSDimitry Andric auto CurBlock = &Block; 5750eae32dcSDimitry Andric while (CurBlock->ForcedSucc != nullptr) { 5760eae32dcSDimitry Andric const auto NextBlock = CurBlock->ForcedSucc; 5770eae32dcSDimitry Andric mergeChains(Block.CurChain, NextBlock->CurChain, 0, MergeTypeTy::X_Y); 5780eae32dcSDimitry Andric CurBlock = NextBlock; 5790eae32dcSDimitry Andric } 5800eae32dcSDimitry Andric } 5810eae32dcSDimitry Andric } 5820eae32dcSDimitry Andric } 5830eae32dcSDimitry Andric 5840eae32dcSDimitry Andric /// Merge pairs of chains while improving the ExtTSP objective. 5850eae32dcSDimitry Andric void mergeChainPairs() { 5860eae32dcSDimitry Andric /// Deterministically compare pairs of chains 5870eae32dcSDimitry Andric auto compareChainPairs = [](const Chain *A1, const Chain *B1, 5880eae32dcSDimitry Andric const Chain *A2, const Chain *B2) { 5890eae32dcSDimitry Andric if (A1 != A2) 5900eae32dcSDimitry Andric return A1->id() < A2->id(); 5910eae32dcSDimitry Andric return B1->id() < B2->id(); 5920eae32dcSDimitry Andric }; 5930eae32dcSDimitry Andric 5940eae32dcSDimitry Andric while (HotChains.size() > 1) { 5950eae32dcSDimitry Andric Chain *BestChainPred = nullptr; 5960eae32dcSDimitry Andric Chain *BestChainSucc = nullptr; 5970eae32dcSDimitry Andric auto BestGain = MergeGainTy(); 5980eae32dcSDimitry Andric // Iterate over all pairs of chains 5990eae32dcSDimitry Andric for (auto ChainPred : HotChains) { 6000eae32dcSDimitry Andric // Get candidates for merging with the current chain 6010eae32dcSDimitry Andric for (auto EdgeIter : ChainPred->edges()) { 6020eae32dcSDimitry Andric auto ChainSucc = EdgeIter.first; 6030eae32dcSDimitry Andric auto ChainEdge = EdgeIter.second; 6040eae32dcSDimitry Andric // Ignore loop edges 6050eae32dcSDimitry Andric if (ChainPred == ChainSucc) 6060eae32dcSDimitry Andric continue; 6070eae32dcSDimitry Andric 608*81ad6265SDimitry Andric // Stop early if the combined chain violates the maximum allowed size 609*81ad6265SDimitry Andric if (ChainPred->numBlocks() + ChainSucc->numBlocks() >= MaxChainSize) 610*81ad6265SDimitry Andric continue; 611*81ad6265SDimitry Andric 6120eae32dcSDimitry Andric // Compute the gain of merging the two chains 6130eae32dcSDimitry Andric auto CurGain = getBestMergeGain(ChainPred, ChainSucc, ChainEdge); 6140eae32dcSDimitry Andric if (CurGain.score() <= EPS) 6150eae32dcSDimitry Andric continue; 6160eae32dcSDimitry Andric 6170eae32dcSDimitry Andric if (BestGain < CurGain || 6180eae32dcSDimitry Andric (std::abs(CurGain.score() - BestGain.score()) < EPS && 6190eae32dcSDimitry Andric compareChainPairs(ChainPred, ChainSucc, BestChainPred, 6200eae32dcSDimitry Andric BestChainSucc))) { 6210eae32dcSDimitry Andric BestGain = CurGain; 6220eae32dcSDimitry Andric BestChainPred = ChainPred; 6230eae32dcSDimitry Andric BestChainSucc = ChainSucc; 6240eae32dcSDimitry Andric } 6250eae32dcSDimitry Andric } 6260eae32dcSDimitry Andric } 6270eae32dcSDimitry Andric 6280eae32dcSDimitry Andric // Stop merging when there is no improvement 6290eae32dcSDimitry Andric if (BestGain.score() <= EPS) 6300eae32dcSDimitry Andric break; 6310eae32dcSDimitry Andric 6320eae32dcSDimitry Andric // Merge the best pair of chains 6330eae32dcSDimitry Andric mergeChains(BestChainPred, BestChainSucc, BestGain.mergeOffset(), 6340eae32dcSDimitry Andric BestGain.mergeType()); 6350eae32dcSDimitry Andric } 6360eae32dcSDimitry Andric } 6370eae32dcSDimitry Andric 6380eae32dcSDimitry Andric /// Merge cold blocks to reduce code size. 6390eae32dcSDimitry Andric void mergeColdChains() { 6400eae32dcSDimitry Andric for (size_t SrcBB = 0; SrcBB < NumNodes; SrcBB++) { 6410eae32dcSDimitry Andric // Iterating over neighbors in the reverse order to make sure original 6420eae32dcSDimitry Andric // fallthrough jumps are merged first 6430eae32dcSDimitry Andric size_t NumSuccs = SuccNodes[SrcBB].size(); 6440eae32dcSDimitry Andric for (size_t Idx = 0; Idx < NumSuccs; Idx++) { 6450eae32dcSDimitry Andric auto DstBB = SuccNodes[SrcBB][NumSuccs - Idx - 1]; 6460eae32dcSDimitry Andric auto SrcChain = AllBlocks[SrcBB].CurChain; 6470eae32dcSDimitry Andric auto DstChain = AllBlocks[DstBB].CurChain; 6480eae32dcSDimitry Andric if (SrcChain != DstChain && !DstChain->isEntry() && 6490eae32dcSDimitry Andric SrcChain->blocks().back()->Index == SrcBB && 6500eae32dcSDimitry Andric DstChain->blocks().front()->Index == DstBB) { 6510eae32dcSDimitry Andric mergeChains(SrcChain, DstChain, 0, MergeTypeTy::X_Y); 6520eae32dcSDimitry Andric } 6530eae32dcSDimitry Andric } 6540eae32dcSDimitry Andric } 6550eae32dcSDimitry Andric } 6560eae32dcSDimitry Andric 6570eae32dcSDimitry Andric /// Compute the Ext-TSP score for a given block order and a list of jumps. 6580eae32dcSDimitry Andric double extTSPScore(const MergedChain &MergedBlocks, 6590eae32dcSDimitry Andric const std::vector<Jump *> &Jumps) const { 6600eae32dcSDimitry Andric if (Jumps.empty()) 6610eae32dcSDimitry Andric return 0.0; 6620eae32dcSDimitry Andric uint64_t CurAddr = 0; 6630eae32dcSDimitry Andric MergedBlocks.forEach([&](const Block *BB) { 6640eae32dcSDimitry Andric BB->EstimatedAddr = CurAddr; 6650eae32dcSDimitry Andric CurAddr += BB->Size; 6660eae32dcSDimitry Andric }); 6670eae32dcSDimitry Andric 6680eae32dcSDimitry Andric double Score = 0; 6690eae32dcSDimitry Andric for (auto &Jump : Jumps) { 6700eae32dcSDimitry Andric const auto SrcBlock = Jump->Source; 6710eae32dcSDimitry Andric const auto DstBlock = Jump->Target; 6720eae32dcSDimitry Andric Score += ::extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size, 6730eae32dcSDimitry Andric DstBlock->EstimatedAddr, Jump->ExecutionCount); 6740eae32dcSDimitry Andric } 6750eae32dcSDimitry Andric return Score; 6760eae32dcSDimitry Andric } 6770eae32dcSDimitry Andric 6780eae32dcSDimitry Andric /// Compute the gain of merging two chains. 6790eae32dcSDimitry Andric /// 6800eae32dcSDimitry Andric /// The function considers all possible ways of merging two chains and 6810eae32dcSDimitry Andric /// computes the one having the largest increase in ExtTSP objective. The 6820eae32dcSDimitry Andric /// result is a pair with the first element being the gain and the second 6830eae32dcSDimitry Andric /// element being the corresponding merging type. 6840eae32dcSDimitry Andric MergeGainTy getBestMergeGain(Chain *ChainPred, Chain *ChainSucc, 6850eae32dcSDimitry Andric ChainEdge *Edge) const { 6860eae32dcSDimitry Andric if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) { 6870eae32dcSDimitry Andric return Edge->getCachedMergeGain(ChainPred, ChainSucc); 6880eae32dcSDimitry Andric } 6890eae32dcSDimitry Andric 6900eae32dcSDimitry Andric // Precompute jumps between ChainPred and ChainSucc 6910eae32dcSDimitry Andric auto Jumps = Edge->jumps(); 6920eae32dcSDimitry Andric auto EdgePP = ChainPred->getEdge(ChainPred); 6930eae32dcSDimitry Andric if (EdgePP != nullptr) { 6940eae32dcSDimitry Andric Jumps.insert(Jumps.end(), EdgePP->jumps().begin(), EdgePP->jumps().end()); 6950eae32dcSDimitry Andric } 6960eae32dcSDimitry Andric assert(!Jumps.empty() && "trying to merge chains w/o jumps"); 6970eae32dcSDimitry Andric 6980eae32dcSDimitry Andric // The object holds the best currently chosen gain of merging the two chains 6990eae32dcSDimitry Andric MergeGainTy Gain = MergeGainTy(); 7000eae32dcSDimitry Andric 7010eae32dcSDimitry Andric /// Given a merge offset and a list of merge types, try to merge two chains 7020eae32dcSDimitry Andric /// and update Gain with a better alternative 7030eae32dcSDimitry Andric auto tryChainMerging = [&](size_t Offset, 7040eae32dcSDimitry Andric const std::vector<MergeTypeTy> &MergeTypes) { 7050eae32dcSDimitry Andric // Skip merging corresponding to concatenation w/o splitting 7060eae32dcSDimitry Andric if (Offset == 0 || Offset == ChainPred->blocks().size()) 7070eae32dcSDimitry Andric return; 7080eae32dcSDimitry Andric // Skip merging if it breaks Forced successors 7090eae32dcSDimitry Andric auto BB = ChainPred->blocks()[Offset - 1]; 7100eae32dcSDimitry Andric if (BB->ForcedSucc != nullptr) 7110eae32dcSDimitry Andric return; 7120eae32dcSDimitry Andric // Apply the merge, compute the corresponding gain, and update the best 7130eae32dcSDimitry Andric // value, if the merge is beneficial 7140eae32dcSDimitry Andric for (auto &MergeType : MergeTypes) { 7150eae32dcSDimitry Andric Gain.updateIfLessThan( 7160eae32dcSDimitry Andric computeMergeGain(ChainPred, ChainSucc, Jumps, Offset, MergeType)); 7170eae32dcSDimitry Andric } 7180eae32dcSDimitry Andric }; 7190eae32dcSDimitry Andric 7200eae32dcSDimitry Andric // Try to concatenate two chains w/o splitting 7210eae32dcSDimitry Andric Gain.updateIfLessThan( 7220eae32dcSDimitry Andric computeMergeGain(ChainPred, ChainSucc, Jumps, 0, MergeTypeTy::X_Y)); 7230eae32dcSDimitry Andric 7240eae32dcSDimitry Andric if (EnableChainSplitAlongJumps) { 7250eae32dcSDimitry Andric // Attach (a part of) ChainPred before the first block of ChainSucc 7260eae32dcSDimitry Andric for (auto &Jump : ChainSucc->blocks().front()->InJumps) { 7270eae32dcSDimitry Andric const auto SrcBlock = Jump->Source; 7280eae32dcSDimitry Andric if (SrcBlock->CurChain != ChainPred) 7290eae32dcSDimitry Andric continue; 7300eae32dcSDimitry Andric size_t Offset = SrcBlock->CurIndex + 1; 7310eae32dcSDimitry Andric tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::X2_X1_Y}); 7320eae32dcSDimitry Andric } 7330eae32dcSDimitry Andric 7340eae32dcSDimitry Andric // Attach (a part of) ChainPred after the last block of ChainSucc 7350eae32dcSDimitry Andric for (auto &Jump : ChainSucc->blocks().back()->OutJumps) { 7360eae32dcSDimitry Andric const auto DstBlock = Jump->Source; 7370eae32dcSDimitry Andric if (DstBlock->CurChain != ChainPred) 7380eae32dcSDimitry Andric continue; 7390eae32dcSDimitry Andric size_t Offset = DstBlock->CurIndex; 7400eae32dcSDimitry Andric tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::Y_X2_X1}); 7410eae32dcSDimitry Andric } 7420eae32dcSDimitry Andric } 7430eae32dcSDimitry Andric 7440eae32dcSDimitry Andric // Try to break ChainPred in various ways and concatenate with ChainSucc 7450eae32dcSDimitry Andric if (ChainPred->blocks().size() <= ChainSplitThreshold) { 7460eae32dcSDimitry Andric for (size_t Offset = 1; Offset < ChainPred->blocks().size(); Offset++) { 7470eae32dcSDimitry Andric // Try to split the chain in different ways. In practice, applying 7480eae32dcSDimitry Andric // X2_Y_X1 merging is almost never provides benefits; thus, we exclude 7490eae32dcSDimitry Andric // it from consideration to reduce the search space 7500eae32dcSDimitry Andric tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::Y_X2_X1, 7510eae32dcSDimitry Andric MergeTypeTy::X2_X1_Y}); 7520eae32dcSDimitry Andric } 7530eae32dcSDimitry Andric } 7540eae32dcSDimitry Andric Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain); 7550eae32dcSDimitry Andric return Gain; 7560eae32dcSDimitry Andric } 7570eae32dcSDimitry Andric 7580eae32dcSDimitry Andric /// Compute the score gain of merging two chains, respecting a given 7590eae32dcSDimitry Andric /// merge 'type' and 'offset'. 7600eae32dcSDimitry Andric /// 7610eae32dcSDimitry Andric /// The two chains are not modified in the method. 7620eae32dcSDimitry Andric MergeGainTy computeMergeGain(const Chain *ChainPred, const Chain *ChainSucc, 7630eae32dcSDimitry Andric const std::vector<Jump *> &Jumps, 7640eae32dcSDimitry Andric size_t MergeOffset, 7650eae32dcSDimitry Andric MergeTypeTy MergeType) const { 7660eae32dcSDimitry Andric auto MergedBlocks = mergeBlocks(ChainPred->blocks(), ChainSucc->blocks(), 7670eae32dcSDimitry Andric MergeOffset, MergeType); 7680eae32dcSDimitry Andric 7690eae32dcSDimitry Andric // Do not allow a merge that does not preserve the original entry block 7700eae32dcSDimitry Andric if ((ChainPred->isEntry() || ChainSucc->isEntry()) && 7710eae32dcSDimitry Andric !MergedBlocks.getFirstBlock()->isEntry()) 7720eae32dcSDimitry Andric return MergeGainTy(); 7730eae32dcSDimitry Andric 7740eae32dcSDimitry Andric // The gain for the new chain 7750eae32dcSDimitry Andric auto NewGainScore = extTSPScore(MergedBlocks, Jumps) - ChainPred->score(); 7760eae32dcSDimitry Andric return MergeGainTy(NewGainScore, MergeOffset, MergeType); 7770eae32dcSDimitry Andric } 7780eae32dcSDimitry Andric 7790eae32dcSDimitry Andric /// Merge two chains of blocks respecting a given merge 'type' and 'offset'. 7800eae32dcSDimitry Andric /// 7810eae32dcSDimitry Andric /// If MergeType == 0, then the result is a concatentation of two chains. 7820eae32dcSDimitry Andric /// Otherwise, the first chain is cut into two sub-chains at the offset, 7830eae32dcSDimitry Andric /// and merged using all possible ways of concatenating three chains. 7840eae32dcSDimitry Andric MergedChain mergeBlocks(const std::vector<Block *> &X, 7850eae32dcSDimitry Andric const std::vector<Block *> &Y, size_t MergeOffset, 7860eae32dcSDimitry Andric MergeTypeTy MergeType) const { 7870eae32dcSDimitry Andric // Split the first chain, X, into X1 and X2 7880eae32dcSDimitry Andric BlockIter BeginX1 = X.begin(); 7890eae32dcSDimitry Andric BlockIter EndX1 = X.begin() + MergeOffset; 7900eae32dcSDimitry Andric BlockIter BeginX2 = X.begin() + MergeOffset; 7910eae32dcSDimitry Andric BlockIter EndX2 = X.end(); 7920eae32dcSDimitry Andric BlockIter BeginY = Y.begin(); 7930eae32dcSDimitry Andric BlockIter EndY = Y.end(); 7940eae32dcSDimitry Andric 7950eae32dcSDimitry Andric // Construct a new chain from the three existing ones 7960eae32dcSDimitry Andric switch (MergeType) { 7970eae32dcSDimitry Andric case MergeTypeTy::X_Y: 7980eae32dcSDimitry Andric return MergedChain(BeginX1, EndX2, BeginY, EndY); 7990eae32dcSDimitry Andric case MergeTypeTy::X1_Y_X2: 8000eae32dcSDimitry Andric return MergedChain(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2); 8010eae32dcSDimitry Andric case MergeTypeTy::Y_X2_X1: 8020eae32dcSDimitry Andric return MergedChain(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1); 8030eae32dcSDimitry Andric case MergeTypeTy::X2_X1_Y: 8040eae32dcSDimitry Andric return MergedChain(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY); 8050eae32dcSDimitry Andric } 8060eae32dcSDimitry Andric llvm_unreachable("unexpected chain merge type"); 8070eae32dcSDimitry Andric } 8080eae32dcSDimitry Andric 8090eae32dcSDimitry Andric /// Merge chain From into chain Into, update the list of active chains, 8100eae32dcSDimitry Andric /// adjacency information, and the corresponding cached values. 8110eae32dcSDimitry Andric void mergeChains(Chain *Into, Chain *From, size_t MergeOffset, 8120eae32dcSDimitry Andric MergeTypeTy MergeType) { 8130eae32dcSDimitry Andric assert(Into != From && "a chain cannot be merged with itself"); 8140eae32dcSDimitry Andric 8150eae32dcSDimitry Andric // Merge the blocks 8160eae32dcSDimitry Andric auto MergedBlocks = 8170eae32dcSDimitry Andric mergeBlocks(Into->blocks(), From->blocks(), MergeOffset, MergeType); 8180eae32dcSDimitry Andric Into->merge(From, MergedBlocks.getBlocks()); 8190eae32dcSDimitry Andric Into->mergeEdges(From); 8200eae32dcSDimitry Andric From->clear(); 8210eae32dcSDimitry Andric 8220eae32dcSDimitry Andric // Update cached ext-tsp score for the new chain 8230eae32dcSDimitry Andric auto SelfEdge = Into->getEdge(Into); 8240eae32dcSDimitry Andric if (SelfEdge != nullptr) { 8250eae32dcSDimitry Andric MergedBlocks = MergedChain(Into->blocks().begin(), Into->blocks().end()); 8260eae32dcSDimitry Andric Into->setScore(extTSPScore(MergedBlocks, SelfEdge->jumps())); 8270eae32dcSDimitry Andric } 8280eae32dcSDimitry Andric 8290eae32dcSDimitry Andric // Remove chain From from the list of active chains 8300eae32dcSDimitry Andric auto Iter = std::remove(HotChains.begin(), HotChains.end(), From); 8310eae32dcSDimitry Andric HotChains.erase(Iter, HotChains.end()); 8320eae32dcSDimitry Andric 8330eae32dcSDimitry Andric // Invalidate caches 8340eae32dcSDimitry Andric for (auto EdgeIter : Into->edges()) { 8350eae32dcSDimitry Andric EdgeIter.second->invalidateCache(); 8360eae32dcSDimitry Andric } 8370eae32dcSDimitry Andric } 8380eae32dcSDimitry Andric 8390eae32dcSDimitry Andric /// Concatenate all chains into a final order of blocks. 8400eae32dcSDimitry Andric void concatChains(std::vector<uint64_t> &Order) { 8410eae32dcSDimitry Andric // Collect chains and calculate some stats for their sorting 8420eae32dcSDimitry Andric std::vector<Chain *> SortedChains; 8430eae32dcSDimitry Andric DenseMap<const Chain *, double> ChainDensity; 8440eae32dcSDimitry Andric for (auto &Chain : AllChains) { 8450eae32dcSDimitry Andric if (!Chain.blocks().empty()) { 8460eae32dcSDimitry Andric SortedChains.push_back(&Chain); 8470eae32dcSDimitry Andric // Using doubles to avoid overflow of ExecutionCount 8480eae32dcSDimitry Andric double Size = 0; 8490eae32dcSDimitry Andric double ExecutionCount = 0; 8500eae32dcSDimitry Andric for (auto Block : Chain.blocks()) { 8510eae32dcSDimitry Andric Size += static_cast<double>(Block->Size); 8520eae32dcSDimitry Andric ExecutionCount += static_cast<double>(Block->ExecutionCount); 8530eae32dcSDimitry Andric } 8540eae32dcSDimitry Andric assert(Size > 0 && "a chain of zero size"); 8550eae32dcSDimitry Andric ChainDensity[&Chain] = ExecutionCount / Size; 8560eae32dcSDimitry Andric } 8570eae32dcSDimitry Andric } 8580eae32dcSDimitry Andric 8590eae32dcSDimitry Andric // Sorting chains by density in the decreasing order 8600eae32dcSDimitry Andric std::stable_sort(SortedChains.begin(), SortedChains.end(), 8610eae32dcSDimitry Andric [&](const Chain *C1, const Chain *C2) { 8620eae32dcSDimitry Andric // Makre sure the original entry block is at the 8630eae32dcSDimitry Andric // beginning of the order 8640eae32dcSDimitry Andric if (C1->isEntry() != C2->isEntry()) { 8650eae32dcSDimitry Andric return C1->isEntry(); 8660eae32dcSDimitry Andric } 8670eae32dcSDimitry Andric 8680eae32dcSDimitry Andric const double D1 = ChainDensity[C1]; 8690eae32dcSDimitry Andric const double D2 = ChainDensity[C2]; 8700eae32dcSDimitry Andric // Compare by density and break ties by chain identifiers 8710eae32dcSDimitry Andric return (D1 != D2) ? (D1 > D2) : (C1->id() < C2->id()); 8720eae32dcSDimitry Andric }); 8730eae32dcSDimitry Andric 8740eae32dcSDimitry Andric // Collect the blocks in the order specified by their chains 8750eae32dcSDimitry Andric Order.reserve(NumNodes); 8760eae32dcSDimitry Andric for (auto Chain : SortedChains) { 8770eae32dcSDimitry Andric for (auto Block : Chain->blocks()) { 8780eae32dcSDimitry Andric Order.push_back(Block->Index); 8790eae32dcSDimitry Andric } 8800eae32dcSDimitry Andric } 8810eae32dcSDimitry Andric } 8820eae32dcSDimitry Andric 8830eae32dcSDimitry Andric private: 8840eae32dcSDimitry Andric /// The number of nodes in the graph. 8850eae32dcSDimitry Andric const size_t NumNodes; 8860eae32dcSDimitry Andric 8870eae32dcSDimitry Andric /// Successors of each node. 8880eae32dcSDimitry Andric std::vector<std::vector<uint64_t>> SuccNodes; 8890eae32dcSDimitry Andric 8900eae32dcSDimitry Andric /// Predecessors of each node. 8910eae32dcSDimitry Andric std::vector<std::vector<uint64_t>> PredNodes; 8920eae32dcSDimitry Andric 8930eae32dcSDimitry Andric /// All basic blocks. 8940eae32dcSDimitry Andric std::vector<Block> AllBlocks; 8950eae32dcSDimitry Andric 8960eae32dcSDimitry Andric /// All jumps between blocks. 8970eae32dcSDimitry Andric std::vector<Jump> AllJumps; 8980eae32dcSDimitry Andric 8990eae32dcSDimitry Andric /// All chains of basic blocks. 9000eae32dcSDimitry Andric std::vector<Chain> AllChains; 9010eae32dcSDimitry Andric 9020eae32dcSDimitry Andric /// All edges between chains. 9030eae32dcSDimitry Andric std::vector<ChainEdge> AllEdges; 9040eae32dcSDimitry Andric 9050eae32dcSDimitry Andric /// Active chains. The vector gets updated at runtime when chains are merged. 9060eae32dcSDimitry Andric std::vector<Chain *> HotChains; 9070eae32dcSDimitry Andric }; 9080eae32dcSDimitry Andric 9090eae32dcSDimitry Andric } // end of anonymous namespace 9100eae32dcSDimitry Andric 9110eae32dcSDimitry Andric std::vector<uint64_t> llvm::applyExtTspLayout( 9120eae32dcSDimitry Andric const std::vector<uint64_t> &NodeSizes, 9130eae32dcSDimitry Andric const std::vector<uint64_t> &NodeCounts, 9140eae32dcSDimitry Andric const DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> &EdgeCounts) { 9150eae32dcSDimitry Andric size_t NumNodes = NodeSizes.size(); 9160eae32dcSDimitry Andric 9170eae32dcSDimitry Andric // Verify correctness of the input data. 9180eae32dcSDimitry Andric assert(NodeCounts.size() == NodeSizes.size() && "Incorrect input"); 9190eae32dcSDimitry Andric assert(NumNodes > 2 && "Incorrect input"); 9200eae32dcSDimitry Andric 9210eae32dcSDimitry Andric // Apply the reordering algorithm. 9220eae32dcSDimitry Andric auto Alg = ExtTSPImpl(NumNodes, NodeSizes, NodeCounts, EdgeCounts); 9230eae32dcSDimitry Andric std::vector<uint64_t> Result; 9240eae32dcSDimitry Andric Alg.run(Result); 9250eae32dcSDimitry Andric 9260eae32dcSDimitry Andric // Verify correctness of the output. 9270eae32dcSDimitry Andric assert(Result.front() == 0 && "Original entry point is not preserved"); 9280eae32dcSDimitry Andric assert(Result.size() == NumNodes && "Incorrect size of reordered layout"); 9290eae32dcSDimitry Andric return Result; 9300eae32dcSDimitry Andric } 9310eae32dcSDimitry Andric 9320eae32dcSDimitry Andric double llvm::calcExtTspScore( 9330eae32dcSDimitry Andric const std::vector<uint64_t> &Order, const std::vector<uint64_t> &NodeSizes, 9340eae32dcSDimitry Andric const std::vector<uint64_t> &NodeCounts, 9350eae32dcSDimitry Andric const DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> &EdgeCounts) { 9360eae32dcSDimitry Andric // Estimate addresses of the blocks in memory 9370eae32dcSDimitry Andric auto Addr = std::vector<uint64_t>(NodeSizes.size(), 0); 9380eae32dcSDimitry Andric for (size_t Idx = 1; Idx < Order.size(); Idx++) { 9390eae32dcSDimitry Andric Addr[Order[Idx]] = Addr[Order[Idx - 1]] + NodeSizes[Order[Idx - 1]]; 9400eae32dcSDimitry Andric } 9410eae32dcSDimitry Andric 9420eae32dcSDimitry Andric // Increase the score for each jump 9430eae32dcSDimitry Andric double Score = 0; 9440eae32dcSDimitry Andric for (auto It : EdgeCounts) { 9450eae32dcSDimitry Andric auto Pred = It.first.first; 9460eae32dcSDimitry Andric auto Succ = It.first.second; 9470eae32dcSDimitry Andric uint64_t Count = It.second; 9480eae32dcSDimitry Andric Score += extTSPScore(Addr[Pred], NodeSizes[Pred], Addr[Succ], Count); 9490eae32dcSDimitry Andric } 9500eae32dcSDimitry Andric return Score; 9510eae32dcSDimitry Andric } 9520eae32dcSDimitry Andric 9530eae32dcSDimitry Andric double llvm::calcExtTspScore( 9540eae32dcSDimitry Andric const std::vector<uint64_t> &NodeSizes, 9550eae32dcSDimitry Andric const std::vector<uint64_t> &NodeCounts, 9560eae32dcSDimitry Andric const DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> &EdgeCounts) { 9570eae32dcSDimitry Andric auto Order = std::vector<uint64_t>(NodeSizes.size()); 9580eae32dcSDimitry Andric for (size_t Idx = 0; Idx < NodeSizes.size(); Idx++) { 9590eae32dcSDimitry Andric Order[Idx] = Idx; 9600eae32dcSDimitry Andric } 9610eae32dcSDimitry Andric return calcExtTspScore(Order, NodeSizes, NodeCounts, EdgeCounts); 9620eae32dcSDimitry Andric } 963