xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/CodeLayout.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
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
38*bdd1243dSDimitry Andric //     https://arxiv.org/abs/1809.04676
390eae32dcSDimitry Andric //
400eae32dcSDimitry Andric //===----------------------------------------------------------------------===//
410eae32dcSDimitry Andric 
420eae32dcSDimitry Andric #include "llvm/Transforms/Utils/CodeLayout.h"
430eae32dcSDimitry Andric #include "llvm/Support/CommandLine.h"
440eae32dcSDimitry Andric 
45*bdd1243dSDimitry Andric #include <cmath>
46*bdd1243dSDimitry Andric 
470eae32dcSDimitry Andric using namespace llvm;
480eae32dcSDimitry Andric #define DEBUG_TYPE "code-layout"
490eae32dcSDimitry Andric 
5081ad6265SDimitry Andric cl::opt<bool> EnableExtTspBlockPlacement(
5181ad6265SDimitry Andric     "enable-ext-tsp-block-placement", cl::Hidden, cl::init(false),
5281ad6265SDimitry Andric     cl::desc("Enable machine block placement based on the ext-tsp model, "
5381ad6265SDimitry Andric              "optimizing I-cache utilization."));
5481ad6265SDimitry Andric 
5581ad6265SDimitry Andric cl::opt<bool> ApplyExtTspWithoutProfile(
5681ad6265SDimitry Andric     "ext-tsp-apply-without-profile",
5781ad6265SDimitry Andric     cl::desc("Whether to apply ext-tsp placement for instances w/o profile"),
5881ad6265SDimitry Andric     cl::init(true), cl::Hidden);
5981ad6265SDimitry Andric 
60*bdd1243dSDimitry Andric // Algorithm-specific params. The values are tuned for the best performance
610eae32dcSDimitry Andric // of large-scale front-end bound binaries.
62*bdd1243dSDimitry Andric static cl::opt<double> ForwardWeightCond(
63*bdd1243dSDimitry Andric     "ext-tsp-forward-weight-cond", cl::ReallyHidden, cl::init(0.1),
64*bdd1243dSDimitry Andric     cl::desc("The weight of conditional forward jumps for ExtTSP value"));
650eae32dcSDimitry Andric 
66*bdd1243dSDimitry Andric static cl::opt<double> ForwardWeightUncond(
67*bdd1243dSDimitry Andric     "ext-tsp-forward-weight-uncond", cl::ReallyHidden, cl::init(0.1),
68*bdd1243dSDimitry Andric     cl::desc("The weight of unconditional forward jumps for ExtTSP value"));
69*bdd1243dSDimitry Andric 
70*bdd1243dSDimitry Andric static cl::opt<double> BackwardWeightCond(
71*bdd1243dSDimitry Andric     "ext-tsp-backward-weight-cond", cl::ReallyHidden, cl::init(0.1),
72*bdd1243dSDimitry Andric     cl::desc("The weight of conditonal backward jumps for ExtTSP value"));
73*bdd1243dSDimitry Andric 
74*bdd1243dSDimitry Andric static cl::opt<double> BackwardWeightUncond(
75*bdd1243dSDimitry Andric     "ext-tsp-backward-weight-uncond", cl::ReallyHidden, cl::init(0.1),
76*bdd1243dSDimitry Andric     cl::desc("The weight of unconditonal backward jumps for ExtTSP value"));
77*bdd1243dSDimitry Andric 
78*bdd1243dSDimitry Andric static cl::opt<double> FallthroughWeightCond(
79*bdd1243dSDimitry Andric     "ext-tsp-fallthrough-weight-cond", cl::ReallyHidden, cl::init(1.0),
80*bdd1243dSDimitry Andric     cl::desc("The weight of conditional fallthrough jumps for ExtTSP value"));
81*bdd1243dSDimitry Andric 
82*bdd1243dSDimitry Andric static cl::opt<double> FallthroughWeightUncond(
83*bdd1243dSDimitry Andric     "ext-tsp-fallthrough-weight-uncond", cl::ReallyHidden, cl::init(1.05),
84*bdd1243dSDimitry Andric     cl::desc("The weight of unconditional fallthrough jumps for ExtTSP value"));
850eae32dcSDimitry Andric 
860eae32dcSDimitry Andric static cl::opt<unsigned> ForwardDistance(
87*bdd1243dSDimitry Andric     "ext-tsp-forward-distance", cl::ReallyHidden, cl::init(1024),
880eae32dcSDimitry Andric     cl::desc("The maximum distance (in bytes) of a forward jump for ExtTSP"));
890eae32dcSDimitry Andric 
900eae32dcSDimitry Andric static cl::opt<unsigned> BackwardDistance(
91*bdd1243dSDimitry Andric     "ext-tsp-backward-distance", cl::ReallyHidden, cl::init(640),
920eae32dcSDimitry Andric     cl::desc("The maximum distance (in bytes) of a backward jump for ExtTSP"));
930eae32dcSDimitry Andric 
9481ad6265SDimitry Andric // The maximum size of a chain created by the algorithm. The size is bounded
9581ad6265SDimitry Andric // so that the algorithm can efficiently process extremely large instance.
9681ad6265SDimitry Andric static cl::opt<unsigned>
97*bdd1243dSDimitry Andric     MaxChainSize("ext-tsp-max-chain-size", cl::ReallyHidden, cl::init(4096),
9881ad6265SDimitry Andric                  cl::desc("The maximum size of a chain to create."));
9981ad6265SDimitry Andric 
1000eae32dcSDimitry Andric // The maximum size of a chain for splitting. Larger values of the threshold
1010eae32dcSDimitry Andric // may yield better quality at the cost of worsen run-time.
1020eae32dcSDimitry Andric static cl::opt<unsigned> ChainSplitThreshold(
103*bdd1243dSDimitry Andric     "ext-tsp-chain-split-threshold", cl::ReallyHidden, cl::init(128),
1040eae32dcSDimitry Andric     cl::desc("The maximum size of a chain to apply splitting"));
1050eae32dcSDimitry Andric 
1060eae32dcSDimitry Andric // The option enables splitting (large) chains along in-coming and out-going
1070eae32dcSDimitry Andric // jumps. This typically results in a better quality.
1080eae32dcSDimitry Andric static cl::opt<bool> EnableChainSplitAlongJumps(
109*bdd1243dSDimitry Andric     "ext-tsp-enable-chain-split-along-jumps", cl::ReallyHidden, cl::init(true),
1100eae32dcSDimitry Andric     cl::desc("The maximum size of a chain to apply splitting"));
1110eae32dcSDimitry Andric 
1120eae32dcSDimitry Andric namespace {
1130eae32dcSDimitry Andric 
1140eae32dcSDimitry Andric // Epsilon for comparison of doubles.
1150eae32dcSDimitry Andric constexpr double EPS = 1e-8;
1160eae32dcSDimitry Andric 
117*bdd1243dSDimitry Andric // Compute the Ext-TSP score for a given jump.
118*bdd1243dSDimitry Andric double jumpExtTSPScore(uint64_t JumpDist, uint64_t JumpMaxDist, uint64_t Count,
119*bdd1243dSDimitry Andric                        double Weight) {
120*bdd1243dSDimitry Andric   if (JumpDist > JumpMaxDist)
121*bdd1243dSDimitry Andric     return 0;
122*bdd1243dSDimitry Andric   double Prob = 1.0 - static_cast<double>(JumpDist) / JumpMaxDist;
123*bdd1243dSDimitry Andric   return Weight * Prob * Count;
124*bdd1243dSDimitry Andric }
125*bdd1243dSDimitry Andric 
1260eae32dcSDimitry Andric // Compute the Ext-TSP score for a jump between a given pair of blocks,
1270eae32dcSDimitry Andric // using their sizes, (estimated) addresses and the jump execution count.
1280eae32dcSDimitry Andric double extTSPScore(uint64_t SrcAddr, uint64_t SrcSize, uint64_t DstAddr,
129*bdd1243dSDimitry Andric                    uint64_t Count, bool IsConditional) {
1300eae32dcSDimitry Andric   // Fallthrough
1310eae32dcSDimitry Andric   if (SrcAddr + SrcSize == DstAddr) {
132*bdd1243dSDimitry Andric     return jumpExtTSPScore(0, 1, Count,
133*bdd1243dSDimitry Andric                            IsConditional ? FallthroughWeightCond
134*bdd1243dSDimitry Andric                                          : FallthroughWeightUncond);
1350eae32dcSDimitry Andric   }
1360eae32dcSDimitry Andric   // Forward
1370eae32dcSDimitry Andric   if (SrcAddr + SrcSize < DstAddr) {
138*bdd1243dSDimitry Andric     const uint64_t Dist = DstAddr - (SrcAddr + SrcSize);
139*bdd1243dSDimitry Andric     return jumpExtTSPScore(Dist, ForwardDistance, Count,
140*bdd1243dSDimitry Andric                            IsConditional ? ForwardWeightCond
141*bdd1243dSDimitry Andric                                          : ForwardWeightUncond);
1420eae32dcSDimitry Andric   }
1430eae32dcSDimitry Andric   // Backward
144*bdd1243dSDimitry Andric   const uint64_t Dist = SrcAddr + SrcSize - DstAddr;
145*bdd1243dSDimitry Andric   return jumpExtTSPScore(Dist, BackwardDistance, Count,
146*bdd1243dSDimitry Andric                          IsConditional ? BackwardWeightCond
147*bdd1243dSDimitry Andric                                        : BackwardWeightUncond);
1480eae32dcSDimitry Andric }
1490eae32dcSDimitry Andric 
1500eae32dcSDimitry Andric /// A type of merging two chains, X and Y. The former chain is split into
1510eae32dcSDimitry Andric /// X1 and X2 and then concatenated with Y in the order specified by the type.
1520eae32dcSDimitry Andric enum class MergeTypeTy : int { X_Y, X1_Y_X2, Y_X2_X1, X2_X1_Y };
1530eae32dcSDimitry Andric 
1540eae32dcSDimitry Andric /// The gain of merging two chains, that is, the Ext-TSP score of the merge
1550eae32dcSDimitry Andric /// together with the corresponfiding merge 'type' and 'offset'.
1560eae32dcSDimitry Andric class MergeGainTy {
1570eae32dcSDimitry Andric public:
15881ad6265SDimitry Andric   explicit MergeGainTy() = default;
1590eae32dcSDimitry Andric   explicit MergeGainTy(double Score, size_t MergeOffset, MergeTypeTy MergeType)
1600eae32dcSDimitry Andric       : Score(Score), MergeOffset(MergeOffset), MergeType(MergeType) {}
1610eae32dcSDimitry Andric 
1620eae32dcSDimitry Andric   double score() const { return Score; }
1630eae32dcSDimitry Andric 
1640eae32dcSDimitry Andric   size_t mergeOffset() const { return MergeOffset; }
1650eae32dcSDimitry Andric 
1660eae32dcSDimitry Andric   MergeTypeTy mergeType() const { return MergeType; }
1670eae32dcSDimitry Andric 
1680eae32dcSDimitry Andric   // Returns 'true' iff Other is preferred over this.
1690eae32dcSDimitry Andric   bool operator<(const MergeGainTy &Other) const {
1700eae32dcSDimitry Andric     return (Other.Score > EPS && Other.Score > Score + EPS);
1710eae32dcSDimitry Andric   }
1720eae32dcSDimitry Andric 
1730eae32dcSDimitry Andric   // Update the current gain if Other is preferred over this.
1740eae32dcSDimitry Andric   void updateIfLessThan(const MergeGainTy &Other) {
1750eae32dcSDimitry Andric     if (*this < Other)
1760eae32dcSDimitry Andric       *this = Other;
1770eae32dcSDimitry Andric   }
1780eae32dcSDimitry Andric 
1790eae32dcSDimitry Andric private:
1800eae32dcSDimitry Andric   double Score{-1.0};
1810eae32dcSDimitry Andric   size_t MergeOffset{0};
1820eae32dcSDimitry Andric   MergeTypeTy MergeType{MergeTypeTy::X_Y};
1830eae32dcSDimitry Andric };
1840eae32dcSDimitry Andric 
1850eae32dcSDimitry Andric class Jump;
1860eae32dcSDimitry Andric class Chain;
1870eae32dcSDimitry Andric class ChainEdge;
1880eae32dcSDimitry Andric 
1890eae32dcSDimitry Andric /// A node in the graph, typically corresponding to a basic block in CFG.
1900eae32dcSDimitry Andric class Block {
1910eae32dcSDimitry Andric public:
1920eae32dcSDimitry Andric   Block(const Block &) = delete;
1930eae32dcSDimitry Andric   Block(Block &&) = default;
1940eae32dcSDimitry Andric   Block &operator=(const Block &) = delete;
1950eae32dcSDimitry Andric   Block &operator=(Block &&) = default;
1960eae32dcSDimitry Andric 
1970eae32dcSDimitry Andric   // The original index of the block in CFG.
1980eae32dcSDimitry Andric   size_t Index{0};
1990eae32dcSDimitry Andric   // The index of the block in the current chain.
2000eae32dcSDimitry Andric   size_t CurIndex{0};
2010eae32dcSDimitry Andric   // Size of the block in the binary.
2020eae32dcSDimitry Andric   uint64_t Size{0};
2030eae32dcSDimitry Andric   // Execution count of the block in the profile data.
2040eae32dcSDimitry Andric   uint64_t ExecutionCount{0};
2050eae32dcSDimitry Andric   // Current chain of the node.
2060eae32dcSDimitry Andric   Chain *CurChain{nullptr};
2070eae32dcSDimitry Andric   // An offset of the block in the current chain.
2080eae32dcSDimitry Andric   mutable uint64_t EstimatedAddr{0};
2090eae32dcSDimitry Andric   // Forced successor of the block in CFG.
2100eae32dcSDimitry Andric   Block *ForcedSucc{nullptr};
2110eae32dcSDimitry Andric   // Forced predecessor of the block in CFG.
2120eae32dcSDimitry Andric   Block *ForcedPred{nullptr};
2130eae32dcSDimitry Andric   // Outgoing jumps from the block.
2140eae32dcSDimitry Andric   std::vector<Jump *> OutJumps;
2150eae32dcSDimitry Andric   // Incoming jumps to the block.
2160eae32dcSDimitry Andric   std::vector<Jump *> InJumps;
2170eae32dcSDimitry Andric 
2180eae32dcSDimitry Andric public:
219*bdd1243dSDimitry Andric   explicit Block(size_t Index, uint64_t Size, uint64_t EC)
220*bdd1243dSDimitry Andric       : Index(Index), Size(Size), ExecutionCount(EC) {}
2210eae32dcSDimitry Andric   bool isEntry() const { return Index == 0; }
2220eae32dcSDimitry Andric };
2230eae32dcSDimitry Andric 
2240eae32dcSDimitry Andric /// An arc in the graph, typically corresponding to a jump between two blocks.
2250eae32dcSDimitry Andric class Jump {
2260eae32dcSDimitry Andric public:
2270eae32dcSDimitry Andric   Jump(const Jump &) = delete;
2280eae32dcSDimitry Andric   Jump(Jump &&) = default;
2290eae32dcSDimitry Andric   Jump &operator=(const Jump &) = delete;
2300eae32dcSDimitry Andric   Jump &operator=(Jump &&) = default;
2310eae32dcSDimitry Andric 
2320eae32dcSDimitry Andric   // Source block of the jump.
2330eae32dcSDimitry Andric   Block *Source;
2340eae32dcSDimitry Andric   // Target block of the jump.
2350eae32dcSDimitry Andric   Block *Target;
2360eae32dcSDimitry Andric   // Execution count of the arc in the profile data.
2370eae32dcSDimitry Andric   uint64_t ExecutionCount{0};
238*bdd1243dSDimitry Andric   // Whether the jump corresponds to a conditional branch.
239*bdd1243dSDimitry Andric   bool IsConditional{false};
2400eae32dcSDimitry Andric 
2410eae32dcSDimitry Andric public:
2420eae32dcSDimitry Andric   explicit Jump(Block *Source, Block *Target, uint64_t ExecutionCount)
2430eae32dcSDimitry Andric       : Source(Source), Target(Target), ExecutionCount(ExecutionCount) {}
2440eae32dcSDimitry Andric };
2450eae32dcSDimitry Andric 
2460eae32dcSDimitry Andric /// A chain (ordered sequence) of blocks.
2470eae32dcSDimitry Andric class Chain {
2480eae32dcSDimitry Andric public:
2490eae32dcSDimitry Andric   Chain(const Chain &) = delete;
2500eae32dcSDimitry Andric   Chain(Chain &&) = default;
2510eae32dcSDimitry Andric   Chain &operator=(const Chain &) = delete;
2520eae32dcSDimitry Andric   Chain &operator=(Chain &&) = default;
2530eae32dcSDimitry Andric 
2540eae32dcSDimitry Andric   explicit Chain(uint64_t Id, Block *Block)
2550eae32dcSDimitry Andric       : Id(Id), Score(0), Blocks(1, Block) {}
2560eae32dcSDimitry Andric 
2570eae32dcSDimitry Andric   uint64_t id() const { return Id; }
2580eae32dcSDimitry Andric 
2590eae32dcSDimitry Andric   bool isEntry() const { return Blocks[0]->Index == 0; }
2600eae32dcSDimitry Andric 
261*bdd1243dSDimitry Andric   bool isCold() const {
262*bdd1243dSDimitry Andric     for (auto *Block : Blocks) {
263*bdd1243dSDimitry Andric       if (Block->ExecutionCount > 0)
264*bdd1243dSDimitry Andric         return false;
265*bdd1243dSDimitry Andric     }
266*bdd1243dSDimitry Andric     return true;
267*bdd1243dSDimitry Andric   }
268*bdd1243dSDimitry Andric 
2690eae32dcSDimitry Andric   double score() const { return Score; }
2700eae32dcSDimitry Andric 
2710eae32dcSDimitry Andric   void setScore(double NewScore) { Score = NewScore; }
2720eae32dcSDimitry Andric 
2730eae32dcSDimitry Andric   const std::vector<Block *> &blocks() const { return Blocks; }
2740eae32dcSDimitry Andric 
27581ad6265SDimitry Andric   size_t numBlocks() const { return Blocks.size(); }
27681ad6265SDimitry Andric 
2770eae32dcSDimitry Andric   const std::vector<std::pair<Chain *, ChainEdge *>> &edges() const {
2780eae32dcSDimitry Andric     return Edges;
2790eae32dcSDimitry Andric   }
2800eae32dcSDimitry Andric 
2810eae32dcSDimitry Andric   ChainEdge *getEdge(Chain *Other) const {
2820eae32dcSDimitry Andric     for (auto It : Edges) {
2830eae32dcSDimitry Andric       if (It.first == Other)
2840eae32dcSDimitry Andric         return It.second;
2850eae32dcSDimitry Andric     }
2860eae32dcSDimitry Andric     return nullptr;
2870eae32dcSDimitry Andric   }
2880eae32dcSDimitry Andric 
2890eae32dcSDimitry Andric   void removeEdge(Chain *Other) {
2900eae32dcSDimitry Andric     auto It = Edges.begin();
2910eae32dcSDimitry Andric     while (It != Edges.end()) {
2920eae32dcSDimitry Andric       if (It->first == Other) {
2930eae32dcSDimitry Andric         Edges.erase(It);
2940eae32dcSDimitry Andric         return;
2950eae32dcSDimitry Andric       }
2960eae32dcSDimitry Andric       It++;
2970eae32dcSDimitry Andric     }
2980eae32dcSDimitry Andric   }
2990eae32dcSDimitry Andric 
3000eae32dcSDimitry Andric   void addEdge(Chain *Other, ChainEdge *Edge) {
3010eae32dcSDimitry Andric     Edges.push_back(std::make_pair(Other, Edge));
3020eae32dcSDimitry Andric   }
3030eae32dcSDimitry Andric 
3040eae32dcSDimitry Andric   void merge(Chain *Other, const std::vector<Block *> &MergedBlocks) {
3050eae32dcSDimitry Andric     Blocks = MergedBlocks;
3060eae32dcSDimitry Andric     // Update the block's chains
3070eae32dcSDimitry Andric     for (size_t Idx = 0; Idx < Blocks.size(); Idx++) {
3080eae32dcSDimitry Andric       Blocks[Idx]->CurChain = this;
3090eae32dcSDimitry Andric       Blocks[Idx]->CurIndex = Idx;
3100eae32dcSDimitry Andric     }
3110eae32dcSDimitry Andric   }
3120eae32dcSDimitry Andric 
3130eae32dcSDimitry Andric   void mergeEdges(Chain *Other);
3140eae32dcSDimitry Andric 
3150eae32dcSDimitry Andric   void clear() {
3160eae32dcSDimitry Andric     Blocks.clear();
3170eae32dcSDimitry Andric     Blocks.shrink_to_fit();
3180eae32dcSDimitry Andric     Edges.clear();
3190eae32dcSDimitry Andric     Edges.shrink_to_fit();
3200eae32dcSDimitry Andric   }
3210eae32dcSDimitry Andric 
3220eae32dcSDimitry Andric private:
3230eae32dcSDimitry Andric   // Unique chain identifier.
3240eae32dcSDimitry Andric   uint64_t Id;
3250eae32dcSDimitry Andric   // Cached ext-tsp score for the chain.
3260eae32dcSDimitry Andric   double Score;
3270eae32dcSDimitry Andric   // Blocks of the chain.
3280eae32dcSDimitry Andric   std::vector<Block *> Blocks;
3290eae32dcSDimitry Andric   // Adjacent chains and corresponding edges (lists of jumps).
3300eae32dcSDimitry Andric   std::vector<std::pair<Chain *, ChainEdge *>> Edges;
3310eae32dcSDimitry Andric };
3320eae32dcSDimitry Andric 
3330eae32dcSDimitry Andric /// An edge in CFG representing jumps between two chains.
3340eae32dcSDimitry Andric /// When blocks are merged into chains, the edges are combined too so that
3350eae32dcSDimitry Andric /// there is always at most one edge between a pair of chains
3360eae32dcSDimitry Andric class ChainEdge {
3370eae32dcSDimitry Andric public:
3380eae32dcSDimitry Andric   ChainEdge(const ChainEdge &) = delete;
3390eae32dcSDimitry Andric   ChainEdge(ChainEdge &&) = default;
3400eae32dcSDimitry Andric   ChainEdge &operator=(const ChainEdge &) = delete;
3410eae32dcSDimitry Andric   ChainEdge &operator=(ChainEdge &&) = default;
3420eae32dcSDimitry Andric 
3430eae32dcSDimitry Andric   explicit ChainEdge(Jump *Jump)
3440eae32dcSDimitry Andric       : SrcChain(Jump->Source->CurChain), DstChain(Jump->Target->CurChain),
3450eae32dcSDimitry Andric         Jumps(1, Jump) {}
3460eae32dcSDimitry Andric 
3470eae32dcSDimitry Andric   const std::vector<Jump *> &jumps() const { return Jumps; }
3480eae32dcSDimitry Andric 
3490eae32dcSDimitry Andric   void changeEndpoint(Chain *From, Chain *To) {
3500eae32dcSDimitry Andric     if (From == SrcChain)
3510eae32dcSDimitry Andric       SrcChain = To;
3520eae32dcSDimitry Andric     if (From == DstChain)
3530eae32dcSDimitry Andric       DstChain = To;
3540eae32dcSDimitry Andric   }
3550eae32dcSDimitry Andric 
3560eae32dcSDimitry Andric   void appendJump(Jump *Jump) { Jumps.push_back(Jump); }
3570eae32dcSDimitry Andric 
3580eae32dcSDimitry Andric   void moveJumps(ChainEdge *Other) {
3590eae32dcSDimitry Andric     Jumps.insert(Jumps.end(), Other->Jumps.begin(), Other->Jumps.end());
3600eae32dcSDimitry Andric     Other->Jumps.clear();
3610eae32dcSDimitry Andric     Other->Jumps.shrink_to_fit();
3620eae32dcSDimitry Andric   }
3630eae32dcSDimitry Andric 
3640eae32dcSDimitry Andric   bool hasCachedMergeGain(Chain *Src, Chain *Dst) const {
3650eae32dcSDimitry Andric     return Src == SrcChain ? CacheValidForward : CacheValidBackward;
3660eae32dcSDimitry Andric   }
3670eae32dcSDimitry Andric 
3680eae32dcSDimitry Andric   MergeGainTy getCachedMergeGain(Chain *Src, Chain *Dst) const {
3690eae32dcSDimitry Andric     return Src == SrcChain ? CachedGainForward : CachedGainBackward;
3700eae32dcSDimitry Andric   }
3710eae32dcSDimitry Andric 
3720eae32dcSDimitry Andric   void setCachedMergeGain(Chain *Src, Chain *Dst, MergeGainTy MergeGain) {
3730eae32dcSDimitry Andric     if (Src == SrcChain) {
3740eae32dcSDimitry Andric       CachedGainForward = MergeGain;
3750eae32dcSDimitry Andric       CacheValidForward = true;
3760eae32dcSDimitry Andric     } else {
3770eae32dcSDimitry Andric       CachedGainBackward = MergeGain;
3780eae32dcSDimitry Andric       CacheValidBackward = true;
3790eae32dcSDimitry Andric     }
3800eae32dcSDimitry Andric   }
3810eae32dcSDimitry Andric 
3820eae32dcSDimitry Andric   void invalidateCache() {
3830eae32dcSDimitry Andric     CacheValidForward = false;
3840eae32dcSDimitry Andric     CacheValidBackward = false;
3850eae32dcSDimitry Andric   }
3860eae32dcSDimitry Andric 
3870eae32dcSDimitry Andric private:
3880eae32dcSDimitry Andric   // Source chain.
3890eae32dcSDimitry Andric   Chain *SrcChain{nullptr};
3900eae32dcSDimitry Andric   // Destination chain.
3910eae32dcSDimitry Andric   Chain *DstChain{nullptr};
3920eae32dcSDimitry Andric   // Original jumps in the binary with correspinding execution counts.
3930eae32dcSDimitry Andric   std::vector<Jump *> Jumps;
3940eae32dcSDimitry Andric   // Cached ext-tsp value for merging the pair of chains.
3950eae32dcSDimitry Andric   // Since the gain of merging (Src, Dst) and (Dst, Src) might be different,
3960eae32dcSDimitry Andric   // we store both values here.
3970eae32dcSDimitry Andric   MergeGainTy CachedGainForward;
3980eae32dcSDimitry Andric   MergeGainTy CachedGainBackward;
3990eae32dcSDimitry Andric   // Whether the cached value must be recomputed.
4000eae32dcSDimitry Andric   bool CacheValidForward{false};
4010eae32dcSDimitry Andric   bool CacheValidBackward{false};
4020eae32dcSDimitry Andric };
4030eae32dcSDimitry Andric 
4040eae32dcSDimitry Andric void Chain::mergeEdges(Chain *Other) {
4050eae32dcSDimitry Andric   assert(this != Other && "cannot merge a chain with itself");
4060eae32dcSDimitry Andric 
4070eae32dcSDimitry Andric   // Update edges adjacent to chain Other
4080eae32dcSDimitry Andric   for (auto EdgeIt : Other->Edges) {
409*bdd1243dSDimitry Andric     Chain *DstChain = EdgeIt.first;
410*bdd1243dSDimitry Andric     ChainEdge *DstEdge = EdgeIt.second;
411*bdd1243dSDimitry Andric     Chain *TargetChain = DstChain == Other ? this : DstChain;
412*bdd1243dSDimitry Andric     ChainEdge *CurEdge = getEdge(TargetChain);
4130eae32dcSDimitry Andric     if (CurEdge == nullptr) {
4140eae32dcSDimitry Andric       DstEdge->changeEndpoint(Other, this);
4150eae32dcSDimitry Andric       this->addEdge(TargetChain, DstEdge);
4160eae32dcSDimitry Andric       if (DstChain != this && DstChain != Other) {
4170eae32dcSDimitry Andric         DstChain->addEdge(this, DstEdge);
4180eae32dcSDimitry Andric       }
4190eae32dcSDimitry Andric     } else {
4200eae32dcSDimitry Andric       CurEdge->moveJumps(DstEdge);
4210eae32dcSDimitry Andric     }
4220eae32dcSDimitry Andric     // Cleanup leftover edge
4230eae32dcSDimitry Andric     if (DstChain != Other) {
4240eae32dcSDimitry Andric       DstChain->removeEdge(Other);
4250eae32dcSDimitry Andric     }
4260eae32dcSDimitry Andric   }
4270eae32dcSDimitry Andric }
4280eae32dcSDimitry Andric 
4290eae32dcSDimitry Andric using BlockIter = std::vector<Block *>::const_iterator;
4300eae32dcSDimitry Andric 
4310eae32dcSDimitry Andric /// A wrapper around three chains of blocks; it is used to avoid extra
4320eae32dcSDimitry Andric /// instantiation of the vectors.
4330eae32dcSDimitry Andric class MergedChain {
4340eae32dcSDimitry Andric public:
4350eae32dcSDimitry Andric   MergedChain(BlockIter Begin1, BlockIter End1, BlockIter Begin2 = BlockIter(),
4360eae32dcSDimitry Andric               BlockIter End2 = BlockIter(), BlockIter Begin3 = BlockIter(),
4370eae32dcSDimitry Andric               BlockIter End3 = BlockIter())
4380eae32dcSDimitry Andric       : Begin1(Begin1), End1(End1), Begin2(Begin2), End2(End2), Begin3(Begin3),
4390eae32dcSDimitry Andric         End3(End3) {}
4400eae32dcSDimitry Andric 
4410eae32dcSDimitry Andric   template <typename F> void forEach(const F &Func) const {
4420eae32dcSDimitry Andric     for (auto It = Begin1; It != End1; It++)
4430eae32dcSDimitry Andric       Func(*It);
4440eae32dcSDimitry Andric     for (auto It = Begin2; It != End2; It++)
4450eae32dcSDimitry Andric       Func(*It);
4460eae32dcSDimitry Andric     for (auto It = Begin3; It != End3; It++)
4470eae32dcSDimitry Andric       Func(*It);
4480eae32dcSDimitry Andric   }
4490eae32dcSDimitry Andric 
4500eae32dcSDimitry Andric   std::vector<Block *> getBlocks() const {
4510eae32dcSDimitry Andric     std::vector<Block *> Result;
4520eae32dcSDimitry Andric     Result.reserve(std::distance(Begin1, End1) + std::distance(Begin2, End2) +
4530eae32dcSDimitry Andric                    std::distance(Begin3, End3));
4540eae32dcSDimitry Andric     Result.insert(Result.end(), Begin1, End1);
4550eae32dcSDimitry Andric     Result.insert(Result.end(), Begin2, End2);
4560eae32dcSDimitry Andric     Result.insert(Result.end(), Begin3, End3);
4570eae32dcSDimitry Andric     return Result;
4580eae32dcSDimitry Andric   }
4590eae32dcSDimitry Andric 
4600eae32dcSDimitry Andric   const Block *getFirstBlock() const { return *Begin1; }
4610eae32dcSDimitry Andric 
4620eae32dcSDimitry Andric private:
4630eae32dcSDimitry Andric   BlockIter Begin1;
4640eae32dcSDimitry Andric   BlockIter End1;
4650eae32dcSDimitry Andric   BlockIter Begin2;
4660eae32dcSDimitry Andric   BlockIter End2;
4670eae32dcSDimitry Andric   BlockIter Begin3;
4680eae32dcSDimitry Andric   BlockIter End3;
4690eae32dcSDimitry Andric };
4700eae32dcSDimitry Andric 
4710eae32dcSDimitry Andric /// The implementation of the ExtTSP algorithm.
4720eae32dcSDimitry Andric class ExtTSPImpl {
4730eae32dcSDimitry Andric   using EdgeT = std::pair<uint64_t, uint64_t>;
474*bdd1243dSDimitry Andric   using EdgeCountMap = std::vector<std::pair<EdgeT, uint64_t>>;
4750eae32dcSDimitry Andric 
4760eae32dcSDimitry Andric public:
4770eae32dcSDimitry Andric   ExtTSPImpl(size_t NumNodes, const std::vector<uint64_t> &NodeSizes,
4780eae32dcSDimitry Andric              const std::vector<uint64_t> &NodeCounts,
4790eae32dcSDimitry Andric              const EdgeCountMap &EdgeCounts)
4800eae32dcSDimitry Andric       : NumNodes(NumNodes) {
4810eae32dcSDimitry Andric     initialize(NodeSizes, NodeCounts, EdgeCounts);
4820eae32dcSDimitry Andric   }
4830eae32dcSDimitry Andric 
4840eae32dcSDimitry Andric   /// Run the algorithm and return an optimized ordering of blocks.
4850eae32dcSDimitry Andric   void run(std::vector<uint64_t> &Result) {
4860eae32dcSDimitry Andric     // Pass 1: Merge blocks with their mutually forced successors
4870eae32dcSDimitry Andric     mergeForcedPairs();
4880eae32dcSDimitry Andric 
4890eae32dcSDimitry Andric     // Pass 2: Merge pairs of chains while improving the ExtTSP objective
4900eae32dcSDimitry Andric     mergeChainPairs();
4910eae32dcSDimitry Andric 
4920eae32dcSDimitry Andric     // Pass 3: Merge cold blocks to reduce code size
4930eae32dcSDimitry Andric     mergeColdChains();
4940eae32dcSDimitry Andric 
4950eae32dcSDimitry Andric     // Collect blocks from all chains
4960eae32dcSDimitry Andric     concatChains(Result);
4970eae32dcSDimitry Andric   }
4980eae32dcSDimitry Andric 
4990eae32dcSDimitry Andric private:
5000eae32dcSDimitry Andric   /// Initialize the algorithm's data structures.
5010eae32dcSDimitry Andric   void initialize(const std::vector<uint64_t> &NodeSizes,
5020eae32dcSDimitry Andric                   const std::vector<uint64_t> &NodeCounts,
5030eae32dcSDimitry Andric                   const EdgeCountMap &EdgeCounts) {
5040eae32dcSDimitry Andric     // Initialize blocks
5050eae32dcSDimitry Andric     AllBlocks.reserve(NumNodes);
5060eae32dcSDimitry Andric     for (uint64_t Node = 0; Node < NumNodes; Node++) {
5070eae32dcSDimitry Andric       uint64_t Size = std::max<uint64_t>(NodeSizes[Node], 1ULL);
5080eae32dcSDimitry Andric       uint64_t ExecutionCount = NodeCounts[Node];
5090eae32dcSDimitry Andric       // The execution count of the entry block is set to at least 1
5100eae32dcSDimitry Andric       if (Node == 0 && ExecutionCount == 0)
5110eae32dcSDimitry Andric         ExecutionCount = 1;
5120eae32dcSDimitry Andric       AllBlocks.emplace_back(Node, Size, ExecutionCount);
5130eae32dcSDimitry Andric     }
5140eae32dcSDimitry Andric 
5150eae32dcSDimitry Andric     // Initialize jumps between blocks
516*bdd1243dSDimitry Andric     SuccNodes.resize(NumNodes);
517*bdd1243dSDimitry Andric     PredNodes.resize(NumNodes);
518*bdd1243dSDimitry Andric     std::vector<uint64_t> OutDegree(NumNodes, 0);
5190eae32dcSDimitry Andric     AllJumps.reserve(EdgeCounts.size());
5200eae32dcSDimitry Andric     for (auto It : EdgeCounts) {
5210eae32dcSDimitry Andric       auto Pred = It.first.first;
5220eae32dcSDimitry Andric       auto Succ = It.first.second;
523*bdd1243dSDimitry Andric       OutDegree[Pred]++;
5240eae32dcSDimitry Andric       // Ignore self-edges
5250eae32dcSDimitry Andric       if (Pred == Succ)
5260eae32dcSDimitry Andric         continue;
5270eae32dcSDimitry Andric 
5280eae32dcSDimitry Andric       SuccNodes[Pred].push_back(Succ);
5290eae32dcSDimitry Andric       PredNodes[Succ].push_back(Pred);
5300eae32dcSDimitry Andric       auto ExecutionCount = It.second;
5310eae32dcSDimitry Andric       if (ExecutionCount > 0) {
5320eae32dcSDimitry Andric         auto &Block = AllBlocks[Pred];
5330eae32dcSDimitry Andric         auto &SuccBlock = AllBlocks[Succ];
5340eae32dcSDimitry Andric         AllJumps.emplace_back(&Block, &SuccBlock, ExecutionCount);
5350eae32dcSDimitry Andric         SuccBlock.InJumps.push_back(&AllJumps.back());
5360eae32dcSDimitry Andric         Block.OutJumps.push_back(&AllJumps.back());
5370eae32dcSDimitry Andric       }
5380eae32dcSDimitry Andric     }
539*bdd1243dSDimitry Andric     for (auto &Jump : AllJumps) {
540*bdd1243dSDimitry Andric       assert(OutDegree[Jump.Source->Index] > 0);
541*bdd1243dSDimitry Andric       Jump.IsConditional = OutDegree[Jump.Source->Index] > 1;
542*bdd1243dSDimitry Andric     }
5430eae32dcSDimitry Andric 
5440eae32dcSDimitry Andric     // Initialize chains
5450eae32dcSDimitry Andric     AllChains.reserve(NumNodes);
5460eae32dcSDimitry Andric     HotChains.reserve(NumNodes);
547*bdd1243dSDimitry Andric     for (Block &Block : AllBlocks) {
5480eae32dcSDimitry Andric       AllChains.emplace_back(Block.Index, &Block);
5490eae32dcSDimitry Andric       Block.CurChain = &AllChains.back();
5500eae32dcSDimitry Andric       if (Block.ExecutionCount > 0) {
5510eae32dcSDimitry Andric         HotChains.push_back(&AllChains.back());
5520eae32dcSDimitry Andric       }
5530eae32dcSDimitry Andric     }
5540eae32dcSDimitry Andric 
5550eae32dcSDimitry Andric     // Initialize chain edges
5560eae32dcSDimitry Andric     AllEdges.reserve(AllJumps.size());
557*bdd1243dSDimitry Andric     for (Block &Block : AllBlocks) {
5580eae32dcSDimitry Andric       for (auto &Jump : Block.OutJumps) {
55981ad6265SDimitry Andric         auto SuccBlock = Jump->Target;
560*bdd1243dSDimitry Andric         ChainEdge *CurEdge = Block.CurChain->getEdge(SuccBlock->CurChain);
5610eae32dcSDimitry Andric         // this edge is already present in the graph
5620eae32dcSDimitry Andric         if (CurEdge != nullptr) {
5630eae32dcSDimitry Andric           assert(SuccBlock->CurChain->getEdge(Block.CurChain) != nullptr);
5640eae32dcSDimitry Andric           CurEdge->appendJump(Jump);
5650eae32dcSDimitry Andric           continue;
5660eae32dcSDimitry Andric         }
5670eae32dcSDimitry Andric         // this is a new edge
5680eae32dcSDimitry Andric         AllEdges.emplace_back(Jump);
5690eae32dcSDimitry Andric         Block.CurChain->addEdge(SuccBlock->CurChain, &AllEdges.back());
5700eae32dcSDimitry Andric         SuccBlock->CurChain->addEdge(Block.CurChain, &AllEdges.back());
5710eae32dcSDimitry Andric       }
5720eae32dcSDimitry Andric     }
5730eae32dcSDimitry Andric   }
5740eae32dcSDimitry Andric 
5750eae32dcSDimitry Andric   /// For a pair of blocks, A and B, block B is the forced successor of A,
5760eae32dcSDimitry Andric   /// if (i) all jumps (based on profile) from A goes to B and (ii) all jumps
5770eae32dcSDimitry Andric   /// to B are from A. Such blocks should be adjacent in the optimal ordering;
5780eae32dcSDimitry Andric   /// the method finds and merges such pairs of blocks.
5790eae32dcSDimitry Andric   void mergeForcedPairs() {
5800eae32dcSDimitry Andric     // Find fallthroughs based on edge weights
5810eae32dcSDimitry Andric     for (auto &Block : AllBlocks) {
5820eae32dcSDimitry Andric       if (SuccNodes[Block.Index].size() == 1 &&
5830eae32dcSDimitry Andric           PredNodes[SuccNodes[Block.Index][0]].size() == 1 &&
5840eae32dcSDimitry Andric           SuccNodes[Block.Index][0] != 0) {
5850eae32dcSDimitry Andric         size_t SuccIndex = SuccNodes[Block.Index][0];
5860eae32dcSDimitry Andric         Block.ForcedSucc = &AllBlocks[SuccIndex];
5870eae32dcSDimitry Andric         AllBlocks[SuccIndex].ForcedPred = &Block;
5880eae32dcSDimitry Andric       }
5890eae32dcSDimitry Andric     }
5900eae32dcSDimitry Andric 
5910eae32dcSDimitry Andric     // There might be 'cycles' in the forced dependencies, since profile
5920eae32dcSDimitry Andric     // data isn't 100% accurate. Typically this is observed in loops, when the
5930eae32dcSDimitry Andric     // loop edges are the hottest successors for the basic blocks of the loop.
5940eae32dcSDimitry Andric     // Break the cycles by choosing the block with the smallest index as the
5950eae32dcSDimitry Andric     // head. This helps to keep the original order of the loops, which likely
5960eae32dcSDimitry Andric     // have already been rotated in the optimized manner.
5970eae32dcSDimitry Andric     for (auto &Block : AllBlocks) {
5980eae32dcSDimitry Andric       if (Block.ForcedSucc == nullptr || Block.ForcedPred == nullptr)
5990eae32dcSDimitry Andric         continue;
6000eae32dcSDimitry Andric 
6010eae32dcSDimitry Andric       auto SuccBlock = Block.ForcedSucc;
6020eae32dcSDimitry Andric       while (SuccBlock != nullptr && SuccBlock != &Block) {
6030eae32dcSDimitry Andric         SuccBlock = SuccBlock->ForcedSucc;
6040eae32dcSDimitry Andric       }
6050eae32dcSDimitry Andric       if (SuccBlock == nullptr)
6060eae32dcSDimitry Andric         continue;
6070eae32dcSDimitry Andric       // Break the cycle
6080eae32dcSDimitry Andric       AllBlocks[Block.ForcedPred->Index].ForcedSucc = nullptr;
6090eae32dcSDimitry Andric       Block.ForcedPred = nullptr;
6100eae32dcSDimitry Andric     }
6110eae32dcSDimitry Andric 
6120eae32dcSDimitry Andric     // Merge blocks with their fallthrough successors
6130eae32dcSDimitry Andric     for (auto &Block : AllBlocks) {
6140eae32dcSDimitry Andric       if (Block.ForcedPred == nullptr && Block.ForcedSucc != nullptr) {
6150eae32dcSDimitry Andric         auto CurBlock = &Block;
6160eae32dcSDimitry Andric         while (CurBlock->ForcedSucc != nullptr) {
6170eae32dcSDimitry Andric           const auto NextBlock = CurBlock->ForcedSucc;
6180eae32dcSDimitry Andric           mergeChains(Block.CurChain, NextBlock->CurChain, 0, MergeTypeTy::X_Y);
6190eae32dcSDimitry Andric           CurBlock = NextBlock;
6200eae32dcSDimitry Andric         }
6210eae32dcSDimitry Andric       }
6220eae32dcSDimitry Andric     }
6230eae32dcSDimitry Andric   }
6240eae32dcSDimitry Andric 
6250eae32dcSDimitry Andric   /// Merge pairs of chains while improving the ExtTSP objective.
6260eae32dcSDimitry Andric   void mergeChainPairs() {
6270eae32dcSDimitry Andric     /// Deterministically compare pairs of chains
6280eae32dcSDimitry Andric     auto compareChainPairs = [](const Chain *A1, const Chain *B1,
6290eae32dcSDimitry Andric                                 const Chain *A2, const Chain *B2) {
6300eae32dcSDimitry Andric       if (A1 != A2)
6310eae32dcSDimitry Andric         return A1->id() < A2->id();
6320eae32dcSDimitry Andric       return B1->id() < B2->id();
6330eae32dcSDimitry Andric     };
6340eae32dcSDimitry Andric 
6350eae32dcSDimitry Andric     while (HotChains.size() > 1) {
6360eae32dcSDimitry Andric       Chain *BestChainPred = nullptr;
6370eae32dcSDimitry Andric       Chain *BestChainSucc = nullptr;
6380eae32dcSDimitry Andric       auto BestGain = MergeGainTy();
6390eae32dcSDimitry Andric       // Iterate over all pairs of chains
640*bdd1243dSDimitry Andric       for (Chain *ChainPred : HotChains) {
6410eae32dcSDimitry Andric         // Get candidates for merging with the current chain
6420eae32dcSDimitry Andric         for (auto EdgeIter : ChainPred->edges()) {
643*bdd1243dSDimitry Andric           Chain *ChainSucc = EdgeIter.first;
644*bdd1243dSDimitry Andric           class ChainEdge *ChainEdge = EdgeIter.second;
6450eae32dcSDimitry Andric           // Ignore loop edges
6460eae32dcSDimitry Andric           if (ChainPred == ChainSucc)
6470eae32dcSDimitry Andric             continue;
6480eae32dcSDimitry Andric 
64981ad6265SDimitry Andric           // Stop early if the combined chain violates the maximum allowed size
65081ad6265SDimitry Andric           if (ChainPred->numBlocks() + ChainSucc->numBlocks() >= MaxChainSize)
65181ad6265SDimitry Andric             continue;
65281ad6265SDimitry Andric 
6530eae32dcSDimitry Andric           // Compute the gain of merging the two chains
654*bdd1243dSDimitry Andric           MergeGainTy CurGain =
655*bdd1243dSDimitry Andric               getBestMergeGain(ChainPred, ChainSucc, ChainEdge);
6560eae32dcSDimitry Andric           if (CurGain.score() <= EPS)
6570eae32dcSDimitry Andric             continue;
6580eae32dcSDimitry Andric 
6590eae32dcSDimitry Andric           if (BestGain < CurGain ||
6600eae32dcSDimitry Andric               (std::abs(CurGain.score() - BestGain.score()) < EPS &&
6610eae32dcSDimitry Andric                compareChainPairs(ChainPred, ChainSucc, BestChainPred,
6620eae32dcSDimitry Andric                                  BestChainSucc))) {
6630eae32dcSDimitry Andric             BestGain = CurGain;
6640eae32dcSDimitry Andric             BestChainPred = ChainPred;
6650eae32dcSDimitry Andric             BestChainSucc = ChainSucc;
6660eae32dcSDimitry Andric           }
6670eae32dcSDimitry Andric         }
6680eae32dcSDimitry Andric       }
6690eae32dcSDimitry Andric 
6700eae32dcSDimitry Andric       // Stop merging when there is no improvement
6710eae32dcSDimitry Andric       if (BestGain.score() <= EPS)
6720eae32dcSDimitry Andric         break;
6730eae32dcSDimitry Andric 
6740eae32dcSDimitry Andric       // Merge the best pair of chains
6750eae32dcSDimitry Andric       mergeChains(BestChainPred, BestChainSucc, BestGain.mergeOffset(),
6760eae32dcSDimitry Andric                   BestGain.mergeType());
6770eae32dcSDimitry Andric     }
6780eae32dcSDimitry Andric   }
6790eae32dcSDimitry Andric 
680*bdd1243dSDimitry Andric   /// Merge remaining blocks into chains w/o taking jump counts into
681*bdd1243dSDimitry Andric   /// consideration. This allows to maintain the original block order in the
682*bdd1243dSDimitry Andric   /// absense of profile data
6830eae32dcSDimitry Andric   void mergeColdChains() {
6840eae32dcSDimitry Andric     for (size_t SrcBB = 0; SrcBB < NumNodes; SrcBB++) {
685*bdd1243dSDimitry Andric       // Iterating in reverse order to make sure original fallthrough jumps are
686*bdd1243dSDimitry Andric       // merged first; this might be beneficial for code size.
6870eae32dcSDimitry Andric       size_t NumSuccs = SuccNodes[SrcBB].size();
6880eae32dcSDimitry Andric       for (size_t Idx = 0; Idx < NumSuccs; Idx++) {
6890eae32dcSDimitry Andric         auto DstBB = SuccNodes[SrcBB][NumSuccs - Idx - 1];
6900eae32dcSDimitry Andric         auto SrcChain = AllBlocks[SrcBB].CurChain;
6910eae32dcSDimitry Andric         auto DstChain = AllBlocks[DstBB].CurChain;
6920eae32dcSDimitry Andric         if (SrcChain != DstChain && !DstChain->isEntry() &&
6930eae32dcSDimitry Andric             SrcChain->blocks().back()->Index == SrcBB &&
694*bdd1243dSDimitry Andric             DstChain->blocks().front()->Index == DstBB &&
695*bdd1243dSDimitry Andric             SrcChain->isCold() == DstChain->isCold()) {
6960eae32dcSDimitry Andric           mergeChains(SrcChain, DstChain, 0, MergeTypeTy::X_Y);
6970eae32dcSDimitry Andric         }
6980eae32dcSDimitry Andric       }
6990eae32dcSDimitry Andric     }
7000eae32dcSDimitry Andric   }
7010eae32dcSDimitry Andric 
7020eae32dcSDimitry Andric   /// Compute the Ext-TSP score for a given block order and a list of jumps.
7030eae32dcSDimitry Andric   double extTSPScore(const MergedChain &MergedBlocks,
7040eae32dcSDimitry Andric                      const std::vector<Jump *> &Jumps) const {
7050eae32dcSDimitry Andric     if (Jumps.empty())
7060eae32dcSDimitry Andric       return 0.0;
7070eae32dcSDimitry Andric     uint64_t CurAddr = 0;
7080eae32dcSDimitry Andric     MergedBlocks.forEach([&](const Block *BB) {
7090eae32dcSDimitry Andric       BB->EstimatedAddr = CurAddr;
7100eae32dcSDimitry Andric       CurAddr += BB->Size;
7110eae32dcSDimitry Andric     });
7120eae32dcSDimitry Andric 
7130eae32dcSDimitry Andric     double Score = 0;
7140eae32dcSDimitry Andric     for (auto &Jump : Jumps) {
715*bdd1243dSDimitry Andric       const Block *SrcBlock = Jump->Source;
716*bdd1243dSDimitry Andric       const Block *DstBlock = Jump->Target;
7170eae32dcSDimitry Andric       Score += ::extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size,
718*bdd1243dSDimitry Andric                              DstBlock->EstimatedAddr, Jump->ExecutionCount,
719*bdd1243dSDimitry Andric                              Jump->IsConditional);
7200eae32dcSDimitry Andric     }
7210eae32dcSDimitry Andric     return Score;
7220eae32dcSDimitry Andric   }
7230eae32dcSDimitry Andric 
7240eae32dcSDimitry Andric   /// Compute the gain of merging two chains.
7250eae32dcSDimitry Andric   ///
7260eae32dcSDimitry Andric   /// The function considers all possible ways of merging two chains and
7270eae32dcSDimitry Andric   /// computes the one having the largest increase in ExtTSP objective. The
7280eae32dcSDimitry Andric   /// result is a pair with the first element being the gain and the second
7290eae32dcSDimitry Andric   /// element being the corresponding merging type.
7300eae32dcSDimitry Andric   MergeGainTy getBestMergeGain(Chain *ChainPred, Chain *ChainSucc,
7310eae32dcSDimitry Andric                                ChainEdge *Edge) const {
7320eae32dcSDimitry Andric     if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) {
7330eae32dcSDimitry Andric       return Edge->getCachedMergeGain(ChainPred, ChainSucc);
7340eae32dcSDimitry Andric     }
7350eae32dcSDimitry Andric 
7360eae32dcSDimitry Andric     // Precompute jumps between ChainPred and ChainSucc
7370eae32dcSDimitry Andric     auto Jumps = Edge->jumps();
738*bdd1243dSDimitry Andric     ChainEdge *EdgePP = ChainPred->getEdge(ChainPred);
7390eae32dcSDimitry Andric     if (EdgePP != nullptr) {
7400eae32dcSDimitry Andric       Jumps.insert(Jumps.end(), EdgePP->jumps().begin(), EdgePP->jumps().end());
7410eae32dcSDimitry Andric     }
7420eae32dcSDimitry Andric     assert(!Jumps.empty() && "trying to merge chains w/o jumps");
7430eae32dcSDimitry Andric 
7440eae32dcSDimitry Andric     // The object holds the best currently chosen gain of merging the two chains
7450eae32dcSDimitry Andric     MergeGainTy Gain = MergeGainTy();
7460eae32dcSDimitry Andric 
7470eae32dcSDimitry Andric     /// Given a merge offset and a list of merge types, try to merge two chains
7480eae32dcSDimitry Andric     /// and update Gain with a better alternative
7490eae32dcSDimitry Andric     auto tryChainMerging = [&](size_t Offset,
7500eae32dcSDimitry Andric                                const std::vector<MergeTypeTy> &MergeTypes) {
7510eae32dcSDimitry Andric       // Skip merging corresponding to concatenation w/o splitting
7520eae32dcSDimitry Andric       if (Offset == 0 || Offset == ChainPred->blocks().size())
7530eae32dcSDimitry Andric         return;
7540eae32dcSDimitry Andric       // Skip merging if it breaks Forced successors
7550eae32dcSDimitry Andric       auto BB = ChainPred->blocks()[Offset - 1];
7560eae32dcSDimitry Andric       if (BB->ForcedSucc != nullptr)
7570eae32dcSDimitry Andric         return;
7580eae32dcSDimitry Andric       // Apply the merge, compute the corresponding gain, and update the best
7590eae32dcSDimitry Andric       // value, if the merge is beneficial
760*bdd1243dSDimitry Andric       for (const auto &MergeType : MergeTypes) {
7610eae32dcSDimitry Andric         Gain.updateIfLessThan(
7620eae32dcSDimitry Andric             computeMergeGain(ChainPred, ChainSucc, Jumps, Offset, MergeType));
7630eae32dcSDimitry Andric       }
7640eae32dcSDimitry Andric     };
7650eae32dcSDimitry Andric 
7660eae32dcSDimitry Andric     // Try to concatenate two chains w/o splitting
7670eae32dcSDimitry Andric     Gain.updateIfLessThan(
7680eae32dcSDimitry Andric         computeMergeGain(ChainPred, ChainSucc, Jumps, 0, MergeTypeTy::X_Y));
7690eae32dcSDimitry Andric 
7700eae32dcSDimitry Andric     if (EnableChainSplitAlongJumps) {
7710eae32dcSDimitry Andric       // Attach (a part of) ChainPred before the first block of ChainSucc
7720eae32dcSDimitry Andric       for (auto &Jump : ChainSucc->blocks().front()->InJumps) {
7730eae32dcSDimitry Andric         const auto SrcBlock = Jump->Source;
7740eae32dcSDimitry Andric         if (SrcBlock->CurChain != ChainPred)
7750eae32dcSDimitry Andric           continue;
7760eae32dcSDimitry Andric         size_t Offset = SrcBlock->CurIndex + 1;
7770eae32dcSDimitry Andric         tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::X2_X1_Y});
7780eae32dcSDimitry Andric       }
7790eae32dcSDimitry Andric 
7800eae32dcSDimitry Andric       // Attach (a part of) ChainPred after the last block of ChainSucc
7810eae32dcSDimitry Andric       for (auto &Jump : ChainSucc->blocks().back()->OutJumps) {
7820eae32dcSDimitry Andric         const auto DstBlock = Jump->Source;
7830eae32dcSDimitry Andric         if (DstBlock->CurChain != ChainPred)
7840eae32dcSDimitry Andric           continue;
7850eae32dcSDimitry Andric         size_t Offset = DstBlock->CurIndex;
7860eae32dcSDimitry Andric         tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::Y_X2_X1});
7870eae32dcSDimitry Andric       }
7880eae32dcSDimitry Andric     }
7890eae32dcSDimitry Andric 
7900eae32dcSDimitry Andric     // Try to break ChainPred in various ways and concatenate with ChainSucc
7910eae32dcSDimitry Andric     if (ChainPred->blocks().size() <= ChainSplitThreshold) {
7920eae32dcSDimitry Andric       for (size_t Offset = 1; Offset < ChainPred->blocks().size(); Offset++) {
7930eae32dcSDimitry Andric         // Try to split the chain in different ways. In practice, applying
7940eae32dcSDimitry Andric         // X2_Y_X1 merging is almost never provides benefits; thus, we exclude
7950eae32dcSDimitry Andric         // it from consideration to reduce the search space
7960eae32dcSDimitry Andric         tryChainMerging(Offset, {MergeTypeTy::X1_Y_X2, MergeTypeTy::Y_X2_X1,
7970eae32dcSDimitry Andric                                  MergeTypeTy::X2_X1_Y});
7980eae32dcSDimitry Andric       }
7990eae32dcSDimitry Andric     }
8000eae32dcSDimitry Andric     Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain);
8010eae32dcSDimitry Andric     return Gain;
8020eae32dcSDimitry Andric   }
8030eae32dcSDimitry Andric 
8040eae32dcSDimitry Andric   /// Compute the score gain of merging two chains, respecting a given
8050eae32dcSDimitry Andric   /// merge 'type' and 'offset'.
8060eae32dcSDimitry Andric   ///
8070eae32dcSDimitry Andric   /// The two chains are not modified in the method.
8080eae32dcSDimitry Andric   MergeGainTy computeMergeGain(const Chain *ChainPred, const Chain *ChainSucc,
8090eae32dcSDimitry Andric                                const std::vector<Jump *> &Jumps,
8100eae32dcSDimitry Andric                                size_t MergeOffset,
8110eae32dcSDimitry Andric                                MergeTypeTy MergeType) const {
8120eae32dcSDimitry Andric     auto MergedBlocks = mergeBlocks(ChainPred->blocks(), ChainSucc->blocks(),
8130eae32dcSDimitry Andric                                     MergeOffset, MergeType);
8140eae32dcSDimitry Andric 
8150eae32dcSDimitry Andric     // Do not allow a merge that does not preserve the original entry block
8160eae32dcSDimitry Andric     if ((ChainPred->isEntry() || ChainSucc->isEntry()) &&
8170eae32dcSDimitry Andric         !MergedBlocks.getFirstBlock()->isEntry())
8180eae32dcSDimitry Andric       return MergeGainTy();
8190eae32dcSDimitry Andric 
8200eae32dcSDimitry Andric     // The gain for the new chain
8210eae32dcSDimitry Andric     auto NewGainScore = extTSPScore(MergedBlocks, Jumps) - ChainPred->score();
8220eae32dcSDimitry Andric     return MergeGainTy(NewGainScore, MergeOffset, MergeType);
8230eae32dcSDimitry Andric   }
8240eae32dcSDimitry Andric 
8250eae32dcSDimitry Andric   /// Merge two chains of blocks respecting a given merge 'type' and 'offset'.
8260eae32dcSDimitry Andric   ///
827*bdd1243dSDimitry Andric   /// If MergeType == 0, then the result is a concatenation of two chains.
8280eae32dcSDimitry Andric   /// Otherwise, the first chain is cut into two sub-chains at the offset,
8290eae32dcSDimitry Andric   /// and merged using all possible ways of concatenating three chains.
8300eae32dcSDimitry Andric   MergedChain mergeBlocks(const std::vector<Block *> &X,
8310eae32dcSDimitry Andric                           const std::vector<Block *> &Y, size_t MergeOffset,
8320eae32dcSDimitry Andric                           MergeTypeTy MergeType) const {
8330eae32dcSDimitry Andric     // Split the first chain, X, into X1 and X2
8340eae32dcSDimitry Andric     BlockIter BeginX1 = X.begin();
8350eae32dcSDimitry Andric     BlockIter EndX1 = X.begin() + MergeOffset;
8360eae32dcSDimitry Andric     BlockIter BeginX2 = X.begin() + MergeOffset;
8370eae32dcSDimitry Andric     BlockIter EndX2 = X.end();
8380eae32dcSDimitry Andric     BlockIter BeginY = Y.begin();
8390eae32dcSDimitry Andric     BlockIter EndY = Y.end();
8400eae32dcSDimitry Andric 
8410eae32dcSDimitry Andric     // Construct a new chain from the three existing ones
8420eae32dcSDimitry Andric     switch (MergeType) {
8430eae32dcSDimitry Andric     case MergeTypeTy::X_Y:
8440eae32dcSDimitry Andric       return MergedChain(BeginX1, EndX2, BeginY, EndY);
8450eae32dcSDimitry Andric     case MergeTypeTy::X1_Y_X2:
8460eae32dcSDimitry Andric       return MergedChain(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2);
8470eae32dcSDimitry Andric     case MergeTypeTy::Y_X2_X1:
8480eae32dcSDimitry Andric       return MergedChain(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1);
8490eae32dcSDimitry Andric     case MergeTypeTy::X2_X1_Y:
8500eae32dcSDimitry Andric       return MergedChain(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY);
8510eae32dcSDimitry Andric     }
8520eae32dcSDimitry Andric     llvm_unreachable("unexpected chain merge type");
8530eae32dcSDimitry Andric   }
8540eae32dcSDimitry Andric 
8550eae32dcSDimitry Andric   /// Merge chain From into chain Into, update the list of active chains,
8560eae32dcSDimitry Andric   /// adjacency information, and the corresponding cached values.
8570eae32dcSDimitry Andric   void mergeChains(Chain *Into, Chain *From, size_t MergeOffset,
8580eae32dcSDimitry Andric                    MergeTypeTy MergeType) {
8590eae32dcSDimitry Andric     assert(Into != From && "a chain cannot be merged with itself");
8600eae32dcSDimitry Andric 
8610eae32dcSDimitry Andric     // Merge the blocks
862*bdd1243dSDimitry Andric     MergedChain MergedBlocks =
8630eae32dcSDimitry Andric         mergeBlocks(Into->blocks(), From->blocks(), MergeOffset, MergeType);
8640eae32dcSDimitry Andric     Into->merge(From, MergedBlocks.getBlocks());
8650eae32dcSDimitry Andric     Into->mergeEdges(From);
8660eae32dcSDimitry Andric     From->clear();
8670eae32dcSDimitry Andric 
8680eae32dcSDimitry Andric     // Update cached ext-tsp score for the new chain
869*bdd1243dSDimitry Andric     ChainEdge *SelfEdge = Into->getEdge(Into);
8700eae32dcSDimitry Andric     if (SelfEdge != nullptr) {
8710eae32dcSDimitry Andric       MergedBlocks = MergedChain(Into->blocks().begin(), Into->blocks().end());
8720eae32dcSDimitry Andric       Into->setScore(extTSPScore(MergedBlocks, SelfEdge->jumps()));
8730eae32dcSDimitry Andric     }
8740eae32dcSDimitry Andric 
8750eae32dcSDimitry Andric     // Remove chain From from the list of active chains
876*bdd1243dSDimitry Andric     llvm::erase_value(HotChains, From);
8770eae32dcSDimitry Andric 
8780eae32dcSDimitry Andric     // Invalidate caches
8790eae32dcSDimitry Andric     for (auto EdgeIter : Into->edges()) {
8800eae32dcSDimitry Andric       EdgeIter.second->invalidateCache();
8810eae32dcSDimitry Andric     }
8820eae32dcSDimitry Andric   }
8830eae32dcSDimitry Andric 
8840eae32dcSDimitry Andric   /// Concatenate all chains into a final order of blocks.
8850eae32dcSDimitry Andric   void concatChains(std::vector<uint64_t> &Order) {
8860eae32dcSDimitry Andric     // Collect chains and calculate some stats for their sorting
8870eae32dcSDimitry Andric     std::vector<Chain *> SortedChains;
8880eae32dcSDimitry Andric     DenseMap<const Chain *, double> ChainDensity;
8890eae32dcSDimitry Andric     for (auto &Chain : AllChains) {
8900eae32dcSDimitry Andric       if (!Chain.blocks().empty()) {
8910eae32dcSDimitry Andric         SortedChains.push_back(&Chain);
8920eae32dcSDimitry Andric         // Using doubles to avoid overflow of ExecutionCount
8930eae32dcSDimitry Andric         double Size = 0;
8940eae32dcSDimitry Andric         double ExecutionCount = 0;
895*bdd1243dSDimitry Andric         for (auto *Block : Chain.blocks()) {
8960eae32dcSDimitry Andric           Size += static_cast<double>(Block->Size);
8970eae32dcSDimitry Andric           ExecutionCount += static_cast<double>(Block->ExecutionCount);
8980eae32dcSDimitry Andric         }
8990eae32dcSDimitry Andric         assert(Size > 0 && "a chain of zero size");
9000eae32dcSDimitry Andric         ChainDensity[&Chain] = ExecutionCount / Size;
9010eae32dcSDimitry Andric       }
9020eae32dcSDimitry Andric     }
9030eae32dcSDimitry Andric 
9040eae32dcSDimitry Andric     // Sorting chains by density in the decreasing order
9050eae32dcSDimitry Andric     std::stable_sort(SortedChains.begin(), SortedChains.end(),
9060eae32dcSDimitry Andric                      [&](const Chain *C1, const Chain *C2) {
907*bdd1243dSDimitry Andric                        // Make sure the original entry block is at the
9080eae32dcSDimitry Andric                        // beginning of the order
9090eae32dcSDimitry Andric                        if (C1->isEntry() != C2->isEntry()) {
9100eae32dcSDimitry Andric                          return C1->isEntry();
9110eae32dcSDimitry Andric                        }
9120eae32dcSDimitry Andric 
9130eae32dcSDimitry Andric                        const double D1 = ChainDensity[C1];
9140eae32dcSDimitry Andric                        const double D2 = ChainDensity[C2];
9150eae32dcSDimitry Andric                        // Compare by density and break ties by chain identifiers
9160eae32dcSDimitry Andric                        return (D1 != D2) ? (D1 > D2) : (C1->id() < C2->id());
9170eae32dcSDimitry Andric                      });
9180eae32dcSDimitry Andric 
9190eae32dcSDimitry Andric     // Collect the blocks in the order specified by their chains
9200eae32dcSDimitry Andric     Order.reserve(NumNodes);
921*bdd1243dSDimitry Andric     for (Chain *Chain : SortedChains) {
922*bdd1243dSDimitry Andric       for (Block *Block : Chain->blocks()) {
9230eae32dcSDimitry Andric         Order.push_back(Block->Index);
9240eae32dcSDimitry Andric       }
9250eae32dcSDimitry Andric     }
9260eae32dcSDimitry Andric   }
9270eae32dcSDimitry Andric 
9280eae32dcSDimitry Andric private:
9290eae32dcSDimitry Andric   /// The number of nodes in the graph.
9300eae32dcSDimitry Andric   const size_t NumNodes;
9310eae32dcSDimitry Andric 
9320eae32dcSDimitry Andric   /// Successors of each node.
9330eae32dcSDimitry Andric   std::vector<std::vector<uint64_t>> SuccNodes;
9340eae32dcSDimitry Andric 
9350eae32dcSDimitry Andric   /// Predecessors of each node.
9360eae32dcSDimitry Andric   std::vector<std::vector<uint64_t>> PredNodes;
9370eae32dcSDimitry Andric 
9380eae32dcSDimitry Andric   /// All basic blocks.
9390eae32dcSDimitry Andric   std::vector<Block> AllBlocks;
9400eae32dcSDimitry Andric 
9410eae32dcSDimitry Andric   /// All jumps between blocks.
9420eae32dcSDimitry Andric   std::vector<Jump> AllJumps;
9430eae32dcSDimitry Andric 
9440eae32dcSDimitry Andric   /// All chains of basic blocks.
9450eae32dcSDimitry Andric   std::vector<Chain> AllChains;
9460eae32dcSDimitry Andric 
9470eae32dcSDimitry Andric   /// All edges between chains.
9480eae32dcSDimitry Andric   std::vector<ChainEdge> AllEdges;
9490eae32dcSDimitry Andric 
9500eae32dcSDimitry Andric   /// Active chains. The vector gets updated at runtime when chains are merged.
9510eae32dcSDimitry Andric   std::vector<Chain *> HotChains;
9520eae32dcSDimitry Andric };
9530eae32dcSDimitry Andric 
9540eae32dcSDimitry Andric } // end of anonymous namespace
9550eae32dcSDimitry Andric 
9560eae32dcSDimitry Andric std::vector<uint64_t> llvm::applyExtTspLayout(
9570eae32dcSDimitry Andric     const std::vector<uint64_t> &NodeSizes,
9580eae32dcSDimitry Andric     const std::vector<uint64_t> &NodeCounts,
959*bdd1243dSDimitry Andric     const std::vector<std::pair<EdgeT, uint64_t>> &EdgeCounts) {
9600eae32dcSDimitry Andric   size_t NumNodes = NodeSizes.size();
9610eae32dcSDimitry Andric 
9620eae32dcSDimitry Andric   // Verify correctness of the input data.
9630eae32dcSDimitry Andric   assert(NodeCounts.size() == NodeSizes.size() && "Incorrect input");
9640eae32dcSDimitry Andric   assert(NumNodes > 2 && "Incorrect input");
9650eae32dcSDimitry Andric 
9660eae32dcSDimitry Andric   // Apply the reordering algorithm.
9670eae32dcSDimitry Andric   auto Alg = ExtTSPImpl(NumNodes, NodeSizes, NodeCounts, EdgeCounts);
9680eae32dcSDimitry Andric   std::vector<uint64_t> Result;
9690eae32dcSDimitry Andric   Alg.run(Result);
9700eae32dcSDimitry Andric 
9710eae32dcSDimitry Andric   // Verify correctness of the output.
9720eae32dcSDimitry Andric   assert(Result.front() == 0 && "Original entry point is not preserved");
9730eae32dcSDimitry Andric   assert(Result.size() == NumNodes && "Incorrect size of reordered layout");
9740eae32dcSDimitry Andric   return Result;
9750eae32dcSDimitry Andric }
9760eae32dcSDimitry Andric 
9770eae32dcSDimitry Andric double llvm::calcExtTspScore(
9780eae32dcSDimitry Andric     const std::vector<uint64_t> &Order, const std::vector<uint64_t> &NodeSizes,
9790eae32dcSDimitry Andric     const std::vector<uint64_t> &NodeCounts,
980*bdd1243dSDimitry Andric     const std::vector<std::pair<EdgeT, uint64_t>> &EdgeCounts) {
9810eae32dcSDimitry Andric   // Estimate addresses of the blocks in memory
982*bdd1243dSDimitry Andric   std::vector<uint64_t> Addr(NodeSizes.size(), 0);
9830eae32dcSDimitry Andric   for (size_t Idx = 1; Idx < Order.size(); Idx++) {
9840eae32dcSDimitry Andric     Addr[Order[Idx]] = Addr[Order[Idx - 1]] + NodeSizes[Order[Idx - 1]];
9850eae32dcSDimitry Andric   }
986*bdd1243dSDimitry Andric   std::vector<uint64_t> OutDegree(NodeSizes.size(), 0);
987*bdd1243dSDimitry Andric   for (auto It : EdgeCounts) {
988*bdd1243dSDimitry Andric     auto Pred = It.first.first;
989*bdd1243dSDimitry Andric     OutDegree[Pred]++;
990*bdd1243dSDimitry Andric   }
9910eae32dcSDimitry Andric 
9920eae32dcSDimitry Andric   // Increase the score for each jump
9930eae32dcSDimitry Andric   double Score = 0;
9940eae32dcSDimitry Andric   for (auto It : EdgeCounts) {
9950eae32dcSDimitry Andric     auto Pred = It.first.first;
9960eae32dcSDimitry Andric     auto Succ = It.first.second;
9970eae32dcSDimitry Andric     uint64_t Count = It.second;
998*bdd1243dSDimitry Andric     bool IsConditional = OutDegree[Pred] > 1;
999*bdd1243dSDimitry Andric     Score += ::extTSPScore(Addr[Pred], NodeSizes[Pred], Addr[Succ], Count,
1000*bdd1243dSDimitry Andric                            IsConditional);
10010eae32dcSDimitry Andric   }
10020eae32dcSDimitry Andric   return Score;
10030eae32dcSDimitry Andric }
10040eae32dcSDimitry Andric 
10050eae32dcSDimitry Andric double llvm::calcExtTspScore(
10060eae32dcSDimitry Andric     const std::vector<uint64_t> &NodeSizes,
10070eae32dcSDimitry Andric     const std::vector<uint64_t> &NodeCounts,
1008*bdd1243dSDimitry Andric     const std::vector<std::pair<EdgeT, uint64_t>> &EdgeCounts) {
1009*bdd1243dSDimitry Andric   std::vector<uint64_t> Order(NodeSizes.size());
10100eae32dcSDimitry Andric   for (size_t Idx = 0; Idx < NodeSizes.size(); Idx++) {
10110eae32dcSDimitry Andric     Order[Idx] = Idx;
10120eae32dcSDimitry Andric   }
10130eae32dcSDimitry Andric   return calcExtTspScore(Order, NodeSizes, NodeCounts, EdgeCounts);
10140eae32dcSDimitry Andric }
1015