CodeLayout.cpp 36 KB

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