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