MachineOutliner.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
  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. /// \file
  10. /// Replaces repeated sequences of instructions with function calls.
  11. ///
  12. /// This works by placing every instruction from every basic block in a
  13. /// suffix tree, and repeatedly querying that tree for repeated sequences of
  14. /// instructions. If a sequence of instructions appears often, then it ought
  15. /// to be beneficial to pull out into a function.
  16. ///
  17. /// The MachineOutliner communicates with a given target using hooks defined in
  18. /// TargetInstrInfo.h. The target supplies the outliner with information on how
  19. /// a specific sequence of instructions should be outlined. This information
  20. /// is used to deduce the number of instructions necessary to
  21. ///
  22. /// * Create an outlined function
  23. /// * Call that outlined function
  24. ///
  25. /// Targets must implement
  26. /// * getOutliningCandidateInfo
  27. /// * buildOutlinedFrame
  28. /// * insertOutlinedCall
  29. /// * isFunctionSafeToOutlineFrom
  30. ///
  31. /// in order to make use of the MachineOutliner.
  32. ///
  33. /// This was originally presented at the 2016 LLVM Developers' Meeting in the
  34. /// talk "Reducing Code Size Using Outlining". For a high-level overview of
  35. /// how this pass works, the talk is available on YouTube at
  36. ///
  37. /// https://www.youtube.com/watch?v=yorld-WSOeU
  38. ///
  39. /// The slides for the talk are available at
  40. ///
  41. /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
  42. ///
  43. /// The talk provides an overview of how the outliner finds candidates and
  44. /// ultimately outlines them. It describes how the main data structure for this
  45. /// pass, the suffix tree, is queried and purged for candidates. It also gives
  46. /// a simplified suffix tree construction algorithm for suffix trees based off
  47. /// of the algorithm actually used here, Ukkonen's algorithm.
  48. ///
  49. /// For the original RFC for this pass, please see
  50. ///
  51. /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
  52. ///
  53. /// For more information on the suffix tree data structure, please see
  54. /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
  55. ///
  56. //===----------------------------------------------------------------------===//
  57. #include "llvm/CodeGen/MachineOutliner.h"
  58. #include "llvm/ADT/DenseMap.h"
  59. #include "llvm/ADT/Statistic.h"
  60. #include "llvm/ADT/Twine.h"
  61. #include "llvm/CodeGen/MachineFunction.h"
  62. #include "llvm/CodeGen/MachineModuleInfo.h"
  63. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  64. #include "llvm/CodeGen/MachineRegisterInfo.h"
  65. #include "llvm/CodeGen/Passes.h"
  66. #include "llvm/CodeGen/TargetInstrInfo.h"
  67. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  68. #include "llvm/IR/DIBuilder.h"
  69. #include "llvm/IR/IRBuilder.h"
  70. #include "llvm/IR/Mangler.h"
  71. #include "llvm/Support/Allocator.h"
  72. #include "llvm/Support/CommandLine.h"
  73. #include "llvm/Support/Debug.h"
  74. #include "llvm/Support/raw_ostream.h"
  75. #include <functional>
  76. #include <tuple>
  77. #include <vector>
  78. #define DEBUG_TYPE "machine-outliner"
  79. using namespace llvm;
  80. using namespace ore;
  81. using namespace outliner;
  82. STATISTIC(NumOutlined, "Number of candidates outlined");
  83. STATISTIC(FunctionsCreated, "Number of functions created");
  84. // Set to true if the user wants the outliner to run on linkonceodr linkage
  85. // functions. This is false by default because the linker can dedupe linkonceodr
  86. // functions. Since the outliner is confined to a single module (modulo LTO),
  87. // this is off by default. It should, however, be the default behaviour in
  88. // LTO.
  89. static cl::opt<bool> EnableLinkOnceODROutlining(
  90. "enable-linkonceodr-outlining",
  91. cl::Hidden,
  92. cl::desc("Enable the machine outliner on linkonceodr functions"),
  93. cl::init(false));
  94. namespace {
  95. /// Represents an undefined index in the suffix tree.
  96. const unsigned EmptyIdx = -1;
  97. /// A node in a suffix tree which represents a substring or suffix.
  98. ///
  99. /// Each node has either no children or at least two children, with the root
  100. /// being a exception in the empty tree.
  101. ///
  102. /// Children are represented as a map between unsigned integers and nodes. If
  103. /// a node N has a child M on unsigned integer k, then the mapping represented
  104. /// by N is a proper prefix of the mapping represented by M. Note that this,
  105. /// although similar to a trie is somewhat different: each node stores a full
  106. /// substring of the full mapping rather than a single character state.
  107. ///
  108. /// Each internal node contains a pointer to the internal node representing
  109. /// the same string, but with the first character chopped off. This is stored
  110. /// in \p Link. Each leaf node stores the start index of its respective
  111. /// suffix in \p SuffixIdx.
  112. struct SuffixTreeNode {
  113. /// The children of this node.
  114. ///
  115. /// A child existing on an unsigned integer implies that from the mapping
  116. /// represented by the current node, there is a way to reach another
  117. /// mapping by tacking that character on the end of the current string.
  118. DenseMap<unsigned, SuffixTreeNode *> Children;
  119. /// The start index of this node's substring in the main string.
  120. unsigned StartIdx = EmptyIdx;
  121. /// The end index of this node's substring in the main string.
  122. ///
  123. /// Every leaf node must have its \p EndIdx incremented at the end of every
  124. /// step in the construction algorithm. To avoid having to update O(N)
  125. /// nodes individually at the end of every step, the end index is stored
  126. /// as a pointer.
  127. unsigned *EndIdx = nullptr;
  128. /// For leaves, the start index of the suffix represented by this node.
  129. ///
  130. /// For all other nodes, this is ignored.
  131. unsigned SuffixIdx = EmptyIdx;
  132. /// For internal nodes, a pointer to the internal node representing
  133. /// the same sequence with the first character chopped off.
  134. ///
  135. /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
  136. /// Ukkonen's algorithm does to achieve linear-time construction is
  137. /// keep track of which node the next insert should be at. This makes each
  138. /// insert O(1), and there are a total of O(N) inserts. The suffix link
  139. /// helps with inserting children of internal nodes.
  140. ///
  141. /// Say we add a child to an internal node with associated mapping S. The
  142. /// next insertion must be at the node representing S - its first character.
  143. /// This is given by the way that we iteratively build the tree in Ukkonen's
  144. /// algorithm. The main idea is to look at the suffixes of each prefix in the
  145. /// string, starting with the longest suffix of the prefix, and ending with
  146. /// the shortest. Therefore, if we keep pointers between such nodes, we can
  147. /// move to the next insertion point in O(1) time. If we don't, then we'd
  148. /// have to query from the root, which takes O(N) time. This would make the
  149. /// construction algorithm O(N^2) rather than O(N).
  150. SuffixTreeNode *Link = nullptr;
  151. /// The length of the string formed by concatenating the edge labels from the
  152. /// root to this node.
  153. unsigned ConcatLen = 0;
  154. /// Returns true if this node is a leaf.
  155. bool isLeaf() const { return SuffixIdx != EmptyIdx; }
  156. /// Returns true if this node is the root of its owning \p SuffixTree.
  157. bool isRoot() const { return StartIdx == EmptyIdx; }
  158. /// Return the number of elements in the substring associated with this node.
  159. size_t size() const {
  160. // Is it the root? If so, it's the empty string so return 0.
  161. if (isRoot())
  162. return 0;
  163. assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
  164. // Size = the number of elements in the string.
  165. // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
  166. return *EndIdx - StartIdx + 1;
  167. }
  168. SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
  169. : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
  170. SuffixTreeNode() {}
  171. };
  172. /// A data structure for fast substring queries.
  173. ///
  174. /// Suffix trees represent the suffixes of their input strings in their leaves.
  175. /// A suffix tree is a type of compressed trie structure where each node
  176. /// represents an entire substring rather than a single character. Each leaf
  177. /// of the tree is a suffix.
  178. ///
  179. /// A suffix tree can be seen as a type of state machine where each state is a
  180. /// substring of the full string. The tree is structured so that, for a string
  181. /// of length N, there are exactly N leaves in the tree. This structure allows
  182. /// us to quickly find repeated substrings of the input string.
  183. ///
  184. /// In this implementation, a "string" is a vector of unsigned integers.
  185. /// These integers may result from hashing some data type. A suffix tree can
  186. /// contain 1 or many strings, which can then be queried as one large string.
  187. ///
  188. /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
  189. /// suffix tree construction. Ukkonen's algorithm is explained in more detail
  190. /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
  191. /// paper is available at
  192. ///
  193. /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
  194. class SuffixTree {
  195. public:
  196. /// Each element is an integer representing an instruction in the module.
  197. ArrayRef<unsigned> Str;
  198. /// A repeated substring in the tree.
  199. struct RepeatedSubstring {
  200. /// The length of the string.
  201. unsigned Length;
  202. /// The start indices of each occurrence.
  203. std::vector<unsigned> StartIndices;
  204. };
  205. private:
  206. /// Maintains each node in the tree.
  207. SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
  208. /// The root of the suffix tree.
  209. ///
  210. /// The root represents the empty string. It is maintained by the
  211. /// \p NodeAllocator like every other node in the tree.
  212. SuffixTreeNode *Root = nullptr;
  213. /// Maintains the end indices of the internal nodes in the tree.
  214. ///
  215. /// Each internal node is guaranteed to never have its end index change
  216. /// during the construction algorithm; however, leaves must be updated at
  217. /// every step. Therefore, we need to store leaf end indices by reference
  218. /// to avoid updating O(N) leaves at every step of construction. Thus,
  219. /// every internal node must be allocated its own end index.
  220. BumpPtrAllocator InternalEndIdxAllocator;
  221. /// The end index of each leaf in the tree.
  222. unsigned LeafEndIdx = -1;
  223. /// Helper struct which keeps track of the next insertion point in
  224. /// Ukkonen's algorithm.
  225. struct ActiveState {
  226. /// The next node to insert at.
  227. SuffixTreeNode *Node;
  228. /// The index of the first character in the substring currently being added.
  229. unsigned Idx = EmptyIdx;
  230. /// The length of the substring we have to add at the current step.
  231. unsigned Len = 0;
  232. };
  233. /// The point the next insertion will take place at in the
  234. /// construction algorithm.
  235. ActiveState Active;
  236. /// Allocate a leaf node and add it to the tree.
  237. ///
  238. /// \param Parent The parent of this node.
  239. /// \param StartIdx The start index of this node's associated string.
  240. /// \param Edge The label on the edge leaving \p Parent to this node.
  241. ///
  242. /// \returns A pointer to the allocated leaf node.
  243. SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
  244. unsigned Edge) {
  245. assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
  246. SuffixTreeNode *N = new (NodeAllocator.Allocate())
  247. SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
  248. Parent.Children[Edge] = N;
  249. return N;
  250. }
  251. /// Allocate an internal node and add it to the tree.
  252. ///
  253. /// \param Parent The parent of this node. Only null when allocating the root.
  254. /// \param StartIdx The start index of this node's associated string.
  255. /// \param EndIdx The end index of this node's associated string.
  256. /// \param Edge The label on the edge leaving \p Parent to this node.
  257. ///
  258. /// \returns A pointer to the allocated internal node.
  259. SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
  260. unsigned EndIdx, unsigned Edge) {
  261. assert(StartIdx <= EndIdx && "String can't start after it ends!");
  262. assert(!(!Parent && StartIdx != EmptyIdx) &&
  263. "Non-root internal nodes must have parents!");
  264. unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
  265. SuffixTreeNode *N = new (NodeAllocator.Allocate())
  266. SuffixTreeNode(StartIdx, E, Root);
  267. if (Parent)
  268. Parent->Children[Edge] = N;
  269. return N;
  270. }
  271. /// Set the suffix indices of the leaves to the start indices of their
  272. /// respective suffixes.
  273. ///
  274. /// \param[in] CurrNode The node currently being visited.
  275. /// \param CurrNodeLen The concatenation of all node sizes from the root to
  276. /// this node. Used to produce suffix indices.
  277. void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrNodeLen) {
  278. bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
  279. // Store the concatenation of lengths down from the root.
  280. CurrNode.ConcatLen = CurrNodeLen;
  281. // Traverse the tree depth-first.
  282. for (auto &ChildPair : CurrNode.Children) {
  283. assert(ChildPair.second && "Node had a null child!");
  284. setSuffixIndices(*ChildPair.second,
  285. CurrNodeLen + ChildPair.second->size());
  286. }
  287. // Is this node a leaf? If it is, give it a suffix index.
  288. if (IsLeaf)
  289. CurrNode.SuffixIdx = Str.size() - CurrNodeLen;
  290. }
  291. /// Construct the suffix tree for the prefix of the input ending at
  292. /// \p EndIdx.
  293. ///
  294. /// Used to construct the full suffix tree iteratively. At the end of each
  295. /// step, the constructed suffix tree is either a valid suffix tree, or a
  296. /// suffix tree with implicit suffixes. At the end of the final step, the
  297. /// suffix tree is a valid tree.
  298. ///
  299. /// \param EndIdx The end index of the current prefix in the main string.
  300. /// \param SuffixesToAdd The number of suffixes that must be added
  301. /// to complete the suffix tree at the current phase.
  302. ///
  303. /// \returns The number of suffixes that have not been added at the end of
  304. /// this step.
  305. unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
  306. SuffixTreeNode *NeedsLink = nullptr;
  307. while (SuffixesToAdd > 0) {
  308. // Are we waiting to add anything other than just the last character?
  309. if (Active.Len == 0) {
  310. // If not, then say the active index is the end index.
  311. Active.Idx = EndIdx;
  312. }
  313. assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
  314. // The first character in the current substring we're looking at.
  315. unsigned FirstChar = Str[Active.Idx];
  316. // Have we inserted anything starting with FirstChar at the current node?
  317. if (Active.Node->Children.count(FirstChar) == 0) {
  318. // If not, then we can just insert a leaf and move too the next step.
  319. insertLeaf(*Active.Node, EndIdx, FirstChar);
  320. // The active node is an internal node, and we visited it, so it must
  321. // need a link if it doesn't have one.
  322. if (NeedsLink) {
  323. NeedsLink->Link = Active.Node;
  324. NeedsLink = nullptr;
  325. }
  326. } else {
  327. // There's a match with FirstChar, so look for the point in the tree to
  328. // insert a new node.
  329. SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
  330. unsigned SubstringLen = NextNode->size();
  331. // Is the current suffix we're trying to insert longer than the size of
  332. // the child we want to move to?
  333. if (Active.Len >= SubstringLen) {
  334. // If yes, then consume the characters we've seen and move to the next
  335. // node.
  336. Active.Idx += SubstringLen;
  337. Active.Len -= SubstringLen;
  338. Active.Node = NextNode;
  339. continue;
  340. }
  341. // Otherwise, the suffix we're trying to insert must be contained in the
  342. // next node we want to move to.
  343. unsigned LastChar = Str[EndIdx];
  344. // Is the string we're trying to insert a substring of the next node?
  345. if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
  346. // If yes, then we're done for this step. Remember our insertion point
  347. // and move to the next end index. At this point, we have an implicit
  348. // suffix tree.
  349. if (NeedsLink && !Active.Node->isRoot()) {
  350. NeedsLink->Link = Active.Node;
  351. NeedsLink = nullptr;
  352. }
  353. Active.Len++;
  354. break;
  355. }
  356. // The string we're trying to insert isn't a substring of the next node,
  357. // but matches up to a point. Split the node.
  358. //
  359. // For example, say we ended our search at a node n and we're trying to
  360. // insert ABD. Then we'll create a new node s for AB, reduce n to just
  361. // representing C, and insert a new leaf node l to represent d. This
  362. // allows us to ensure that if n was a leaf, it remains a leaf.
  363. //
  364. // | ABC ---split---> | AB
  365. // n s
  366. // C / \ D
  367. // n l
  368. // The node s from the diagram
  369. SuffixTreeNode *SplitNode =
  370. insertInternalNode(Active.Node, NextNode->StartIdx,
  371. NextNode->StartIdx + Active.Len - 1, FirstChar);
  372. // Insert the new node representing the new substring into the tree as
  373. // a child of the split node. This is the node l from the diagram.
  374. insertLeaf(*SplitNode, EndIdx, LastChar);
  375. // Make the old node a child of the split node and update its start
  376. // index. This is the node n from the diagram.
  377. NextNode->StartIdx += Active.Len;
  378. SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
  379. // SplitNode is an internal node, update the suffix link.
  380. if (NeedsLink)
  381. NeedsLink->Link = SplitNode;
  382. NeedsLink = SplitNode;
  383. }
  384. // We've added something new to the tree, so there's one less suffix to
  385. // add.
  386. SuffixesToAdd--;
  387. if (Active.Node->isRoot()) {
  388. if (Active.Len > 0) {
  389. Active.Len--;
  390. Active.Idx = EndIdx - SuffixesToAdd + 1;
  391. }
  392. } else {
  393. // Start the next phase at the next smallest suffix.
  394. Active.Node = Active.Node->Link;
  395. }
  396. }
  397. return SuffixesToAdd;
  398. }
  399. public:
  400. /// Construct a suffix tree from a sequence of unsigned integers.
  401. ///
  402. /// \param Str The string to construct the suffix tree for.
  403. SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
  404. Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
  405. Active.Node = Root;
  406. // Keep track of the number of suffixes we have to add of the current
  407. // prefix.
  408. unsigned SuffixesToAdd = 0;
  409. Active.Node = Root;
  410. // Construct the suffix tree iteratively on each prefix of the string.
  411. // PfxEndIdx is the end index of the current prefix.
  412. // End is one past the last element in the string.
  413. for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
  414. PfxEndIdx++) {
  415. SuffixesToAdd++;
  416. LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
  417. SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
  418. }
  419. // Set the suffix indices of each leaf.
  420. assert(Root && "Root node can't be nullptr!");
  421. setSuffixIndices(*Root, 0);
  422. }
  423. /// Iterator for finding all repeated substrings in the suffix tree.
  424. struct RepeatedSubstringIterator {
  425. private:
  426. /// The current node we're visiting.
  427. SuffixTreeNode *N = nullptr;
  428. /// The repeated substring associated with this node.
  429. RepeatedSubstring RS;
  430. /// The nodes left to visit.
  431. std::vector<SuffixTreeNode *> ToVisit;
  432. /// The minimum length of a repeated substring to find.
  433. /// Since we're outlining, we want at least two instructions in the range.
  434. /// FIXME: This may not be true for targets like X86 which support many
  435. /// instruction lengths.
  436. const unsigned MinLength = 2;
  437. /// Move the iterator to the next repeated substring.
  438. void advance() {
  439. // Clear the current state. If we're at the end of the range, then this
  440. // is the state we want to be in.
  441. RS = RepeatedSubstring();
  442. N = nullptr;
  443. // Each leaf node represents a repeat of a string.
  444. std::vector<SuffixTreeNode *> LeafChildren;
  445. // Continue visiting nodes until we find one which repeats more than once.
  446. while (!ToVisit.empty()) {
  447. SuffixTreeNode *Curr = ToVisit.back();
  448. ToVisit.pop_back();
  449. LeafChildren.clear();
  450. // Keep track of the length of the string associated with the node. If
  451. // it's too short, we'll quit.
  452. unsigned Length = Curr->ConcatLen;
  453. // Iterate over each child, saving internal nodes for visiting, and
  454. // leaf nodes in LeafChildren. Internal nodes represent individual
  455. // strings, which may repeat.
  456. for (auto &ChildPair : Curr->Children) {
  457. // Save all of this node's children for processing.
  458. if (!ChildPair.second->isLeaf())
  459. ToVisit.push_back(ChildPair.second);
  460. // It's not an internal node, so it must be a leaf. If we have a
  461. // long enough string, then save the leaf children.
  462. else if (Length >= MinLength)
  463. LeafChildren.push_back(ChildPair.second);
  464. }
  465. // The root never represents a repeated substring. If we're looking at
  466. // that, then skip it.
  467. if (Curr->isRoot())
  468. continue;
  469. // Do we have any repeated substrings?
  470. if (LeafChildren.size() >= 2) {
  471. // Yes. Update the state to reflect this, and then bail out.
  472. N = Curr;
  473. RS.Length = Length;
  474. for (SuffixTreeNode *Leaf : LeafChildren)
  475. RS.StartIndices.push_back(Leaf->SuffixIdx);
  476. break;
  477. }
  478. }
  479. // At this point, either NewRS is an empty RepeatedSubstring, or it was
  480. // set in the above loop. Similarly, N is either nullptr, or the node
  481. // associated with NewRS.
  482. }
  483. public:
  484. /// Return the current repeated substring.
  485. RepeatedSubstring &operator*() { return RS; }
  486. RepeatedSubstringIterator &operator++() {
  487. advance();
  488. return *this;
  489. }
  490. RepeatedSubstringIterator operator++(int I) {
  491. RepeatedSubstringIterator It(*this);
  492. advance();
  493. return It;
  494. }
  495. bool operator==(const RepeatedSubstringIterator &Other) {
  496. return N == Other.N;
  497. }
  498. bool operator!=(const RepeatedSubstringIterator &Other) {
  499. return !(*this == Other);
  500. }
  501. RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
  502. // Do we have a non-null node?
  503. if (N) {
  504. // Yes. At the first step, we need to visit all of N's children.
  505. // Note: This means that we visit N last.
  506. ToVisit.push_back(N);
  507. advance();
  508. }
  509. }
  510. };
  511. typedef RepeatedSubstringIterator iterator;
  512. iterator begin() { return iterator(Root); }
  513. iterator end() { return iterator(nullptr); }
  514. };
  515. /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
  516. struct InstructionMapper {
  517. /// The next available integer to assign to a \p MachineInstr that
  518. /// cannot be outlined.
  519. ///
  520. /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
  521. unsigned IllegalInstrNumber = -3;
  522. /// The next available integer to assign to a \p MachineInstr that can
  523. /// be outlined.
  524. unsigned LegalInstrNumber = 0;
  525. /// Correspondence from \p MachineInstrs to unsigned integers.
  526. DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
  527. InstructionIntegerMap;
  528. /// Correspondence between \p MachineBasicBlocks and target-defined flags.
  529. DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
  530. /// The vector of unsigned integers that the module is mapped to.
  531. std::vector<unsigned> UnsignedVec;
  532. /// Stores the location of the instruction associated with the integer
  533. /// at index i in \p UnsignedVec for each index i.
  534. std::vector<MachineBasicBlock::iterator> InstrList;
  535. // Set if we added an illegal number in the previous step.
  536. // Since each illegal number is unique, we only need one of them between
  537. // each range of legal numbers. This lets us make sure we don't add more
  538. // than one illegal number per range.
  539. bool AddedIllegalLastTime = false;
  540. /// Maps \p *It to a legal integer.
  541. ///
  542. /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
  543. /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
  544. ///
  545. /// \returns The integer that \p *It was mapped to.
  546. unsigned mapToLegalUnsigned(
  547. MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
  548. bool &HaveLegalRange, unsigned &NumLegalInBlock,
  549. std::vector<unsigned> &UnsignedVecForMBB,
  550. std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
  551. // We added something legal, so we should unset the AddedLegalLastTime
  552. // flag.
  553. AddedIllegalLastTime = false;
  554. // If we have at least two adjacent legal instructions (which may have
  555. // invisible instructions in between), remember that.
  556. if (CanOutlineWithPrevInstr)
  557. HaveLegalRange = true;
  558. CanOutlineWithPrevInstr = true;
  559. // Keep track of the number of legal instructions we insert.
  560. NumLegalInBlock++;
  561. // Get the integer for this instruction or give it the current
  562. // LegalInstrNumber.
  563. InstrListForMBB.push_back(It);
  564. MachineInstr &MI = *It;
  565. bool WasInserted;
  566. DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
  567. ResultIt;
  568. std::tie(ResultIt, WasInserted) =
  569. InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
  570. unsigned MINumber = ResultIt->second;
  571. // There was an insertion.
  572. if (WasInserted)
  573. LegalInstrNumber++;
  574. UnsignedVecForMBB.push_back(MINumber);
  575. // Make sure we don't overflow or use any integers reserved by the DenseMap.
  576. if (LegalInstrNumber >= IllegalInstrNumber)
  577. report_fatal_error("Instruction mapping overflow!");
  578. assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
  579. "Tried to assign DenseMap tombstone or empty key to instruction.");
  580. assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
  581. "Tried to assign DenseMap tombstone or empty key to instruction.");
  582. return MINumber;
  583. }
  584. /// Maps \p *It to an illegal integer.
  585. ///
  586. /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
  587. /// IllegalInstrNumber.
  588. ///
  589. /// \returns The integer that \p *It was mapped to.
  590. unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It,
  591. bool &CanOutlineWithPrevInstr, std::vector<unsigned> &UnsignedVecForMBB,
  592. std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
  593. // Can't outline an illegal instruction. Set the flag.
  594. CanOutlineWithPrevInstr = false;
  595. // Only add one illegal number per range of legal numbers.
  596. if (AddedIllegalLastTime)
  597. return IllegalInstrNumber;
  598. // Remember that we added an illegal number last time.
  599. AddedIllegalLastTime = true;
  600. unsigned MINumber = IllegalInstrNumber;
  601. InstrListForMBB.push_back(It);
  602. UnsignedVecForMBB.push_back(IllegalInstrNumber);
  603. IllegalInstrNumber--;
  604. assert(LegalInstrNumber < IllegalInstrNumber &&
  605. "Instruction mapping overflow!");
  606. assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
  607. "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
  608. assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
  609. "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
  610. return MINumber;
  611. }
  612. /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
  613. /// and appends it to \p UnsignedVec and \p InstrList.
  614. ///
  615. /// Two instructions are assigned the same integer if they are identical.
  616. /// If an instruction is deemed unsafe to outline, then it will be assigned an
  617. /// unique integer. The resulting mapping is placed into a suffix tree and
  618. /// queried for candidates.
  619. ///
  620. /// \param MBB The \p MachineBasicBlock to be translated into integers.
  621. /// \param TII \p TargetInstrInfo for the function.
  622. void convertToUnsignedVec(MachineBasicBlock &MBB,
  623. const TargetInstrInfo &TII) {
  624. unsigned Flags = 0;
  625. // Don't even map in this case.
  626. if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
  627. return;
  628. // Store info for the MBB for later outlining.
  629. MBBFlagsMap[&MBB] = Flags;
  630. MachineBasicBlock::iterator It = MBB.begin();
  631. // The number of instructions in this block that will be considered for
  632. // outlining.
  633. unsigned NumLegalInBlock = 0;
  634. // True if we have at least two legal instructions which aren't separated
  635. // by an illegal instruction.
  636. bool HaveLegalRange = false;
  637. // True if we can perform outlining given the last mapped (non-invisible)
  638. // instruction. This lets us know if we have a legal range.
  639. bool CanOutlineWithPrevInstr = false;
  640. // FIXME: Should this all just be handled in the target, rather than using
  641. // repeated calls to getOutliningType?
  642. std::vector<unsigned> UnsignedVecForMBB;
  643. std::vector<MachineBasicBlock::iterator> InstrListForMBB;
  644. for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; It++) {
  645. // Keep track of where this instruction is in the module.
  646. switch (TII.getOutliningType(It, Flags)) {
  647. case InstrType::Illegal:
  648. mapToIllegalUnsigned(It, CanOutlineWithPrevInstr,
  649. UnsignedVecForMBB, InstrListForMBB);
  650. break;
  651. case InstrType::Legal:
  652. mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
  653. NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
  654. break;
  655. case InstrType::LegalTerminator:
  656. mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
  657. NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
  658. // The instruction also acts as a terminator, so we have to record that
  659. // in the string.
  660. mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
  661. InstrListForMBB);
  662. break;
  663. case InstrType::Invisible:
  664. // Normally this is set by mapTo(Blah)Unsigned, but we just want to
  665. // skip this instruction. So, unset the flag here.
  666. AddedIllegalLastTime = false;
  667. break;
  668. }
  669. }
  670. // Are there enough legal instructions in the block for outlining to be
  671. // possible?
  672. if (HaveLegalRange) {
  673. // After we're done every insertion, uniquely terminate this part of the
  674. // "string". This makes sure we won't match across basic block or function
  675. // boundaries since the "end" is encoded uniquely and thus appears in no
  676. // repeated substring.
  677. mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
  678. InstrListForMBB);
  679. InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
  680. InstrListForMBB.end());
  681. UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
  682. UnsignedVecForMBB.end());
  683. }
  684. }
  685. InstructionMapper() {
  686. // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
  687. // changed.
  688. assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
  689. "DenseMapInfo<unsigned>'s empty key isn't -1!");
  690. assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
  691. "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
  692. }
  693. };
  694. /// An interprocedural pass which finds repeated sequences of
  695. /// instructions and replaces them with calls to functions.
  696. ///
  697. /// Each instruction is mapped to an unsigned integer and placed in a string.
  698. /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
  699. /// is then repeatedly queried for repeated sequences of instructions. Each
  700. /// non-overlapping repeated sequence is then placed in its own
  701. /// \p MachineFunction and each instance is then replaced with a call to that
  702. /// function.
  703. struct MachineOutliner : public ModulePass {
  704. static char ID;
  705. /// Set to true if the outliner should consider functions with
  706. /// linkonceodr linkage.
  707. bool OutlineFromLinkOnceODRs = false;
  708. /// Set to true if the outliner should run on all functions in the module
  709. /// considered safe for outlining.
  710. /// Set to true by default for compatibility with llc's -run-pass option.
  711. /// Set when the pass is constructed in TargetPassConfig.
  712. bool RunOnAllFunctions = true;
  713. StringRef getPassName() const override { return "Machine Outliner"; }
  714. void getAnalysisUsage(AnalysisUsage &AU) const override {
  715. AU.addRequired<MachineModuleInfo>();
  716. AU.addPreserved<MachineModuleInfo>();
  717. AU.setPreservesAll();
  718. ModulePass::getAnalysisUsage(AU);
  719. }
  720. MachineOutliner() : ModulePass(ID) {
  721. initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
  722. }
  723. /// Remark output explaining that not outlining a set of candidates would be
  724. /// better than outlining that set.
  725. void emitNotOutliningCheaperRemark(
  726. unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
  727. OutlinedFunction &OF);
  728. /// Remark output explaining that a function was outlined.
  729. void emitOutlinedFunctionRemark(OutlinedFunction &OF);
  730. /// Find all repeated substrings that satisfy the outlining cost model by
  731. /// constructing a suffix tree.
  732. ///
  733. /// If a substring appears at least twice, then it must be represented by
  734. /// an internal node which appears in at least two suffixes. Each suffix
  735. /// is represented by a leaf node. To do this, we visit each internal node
  736. /// in the tree, using the leaf children of each internal node. If an
  737. /// internal node represents a beneficial substring, then we use each of
  738. /// its leaf children to find the locations of its substring.
  739. ///
  740. /// \param Mapper Contains outlining mapping information.
  741. /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
  742. /// each type of candidate.
  743. void findCandidates(InstructionMapper &Mapper,
  744. std::vector<OutlinedFunction> &FunctionList);
  745. /// Replace the sequences of instructions represented by \p OutlinedFunctions
  746. /// with calls to functions.
  747. ///
  748. /// \param M The module we are outlining from.
  749. /// \param FunctionList A list of functions to be inserted into the module.
  750. /// \param Mapper Contains the instruction mappings for the module.
  751. bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
  752. InstructionMapper &Mapper);
  753. /// Creates a function for \p OF and inserts it into the module.
  754. MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
  755. InstructionMapper &Mapper,
  756. unsigned Name);
  757. /// Construct a suffix tree on the instructions in \p M and outline repeated
  758. /// strings from that tree.
  759. bool runOnModule(Module &M) override;
  760. /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
  761. /// function for remark emission.
  762. DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
  763. DISubprogram *SP;
  764. for (const Candidate &C : OF.Candidates)
  765. if (C.getMF() && (SP = C.getMF()->getFunction().getSubprogram()))
  766. return SP;
  767. return nullptr;
  768. }
  769. /// Populate and \p InstructionMapper with instruction-to-integer mappings.
  770. /// These are used to construct a suffix tree.
  771. void populateMapper(InstructionMapper &Mapper, Module &M,
  772. MachineModuleInfo &MMI);
  773. /// Initialize information necessary to output a size remark.
  774. /// FIXME: This should be handled by the pass manager, not the outliner.
  775. /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
  776. /// pass manager.
  777. void initSizeRemarkInfo(
  778. const Module &M, const MachineModuleInfo &MMI,
  779. StringMap<unsigned> &FunctionToInstrCount);
  780. /// Emit the remark.
  781. // FIXME: This should be handled by the pass manager, not the outliner.
  782. void emitInstrCountChangedRemark(
  783. const Module &M, const MachineModuleInfo &MMI,
  784. const StringMap<unsigned> &FunctionToInstrCount);
  785. };
  786. } // Anonymous namespace.
  787. char MachineOutliner::ID = 0;
  788. namespace llvm {
  789. ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
  790. MachineOutliner *OL = new MachineOutliner();
  791. OL->RunOnAllFunctions = RunOnAllFunctions;
  792. return OL;
  793. }
  794. } // namespace llvm
  795. INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
  796. false)
  797. void MachineOutliner::emitNotOutliningCheaperRemark(
  798. unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
  799. OutlinedFunction &OF) {
  800. // FIXME: Right now, we arbitrarily choose some Candidate from the
  801. // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
  802. // We should probably sort these by function name or something to make sure
  803. // the remarks are stable.
  804. Candidate &C = CandidatesForRepeatedSeq.front();
  805. MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
  806. MORE.emit([&]() {
  807. MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
  808. C.front()->getDebugLoc(), C.getMBB());
  809. R << "Did not outline " << NV("Length", StringLen) << " instructions"
  810. << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
  811. << " locations."
  812. << " Bytes from outlining all occurrences ("
  813. << NV("OutliningCost", OF.getOutliningCost()) << ")"
  814. << " >= Unoutlined instruction bytes ("
  815. << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
  816. << " (Also found at: ";
  817. // Tell the user the other places the candidate was found.
  818. for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
  819. R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
  820. CandidatesForRepeatedSeq[i].front()->getDebugLoc());
  821. if (i != e - 1)
  822. R << ", ";
  823. }
  824. R << ")";
  825. return R;
  826. });
  827. }
  828. void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
  829. MachineBasicBlock *MBB = &*OF.MF->begin();
  830. MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
  831. MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
  832. MBB->findDebugLoc(MBB->begin()), MBB);
  833. R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
  834. << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
  835. << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
  836. << " locations. "
  837. << "(Found at: ";
  838. // Tell the user the other places the candidate was found.
  839. for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
  840. R << NV((Twine("StartLoc") + Twine(i)).str(),
  841. OF.Candidates[i].front()->getDebugLoc());
  842. if (i != e - 1)
  843. R << ", ";
  844. }
  845. R << ")";
  846. MORE.emit(R);
  847. }
  848. void
  849. MachineOutliner::findCandidates(InstructionMapper &Mapper,
  850. std::vector<OutlinedFunction> &FunctionList) {
  851. FunctionList.clear();
  852. SuffixTree ST(Mapper.UnsignedVec);
  853. // First, find dall of the repeated substrings in the tree of minimum length
  854. // 2.
  855. std::vector<Candidate> CandidatesForRepeatedSeq;
  856. for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
  857. CandidatesForRepeatedSeq.clear();
  858. SuffixTree::RepeatedSubstring RS = *It;
  859. unsigned StringLen = RS.Length;
  860. for (const unsigned &StartIdx : RS.StartIndices) {
  861. unsigned EndIdx = StartIdx + StringLen - 1;
  862. // Trick: Discard some candidates that would be incompatible with the
  863. // ones we've already found for this sequence. This will save us some
  864. // work in candidate selection.
  865. //
  866. // If two candidates overlap, then we can't outline them both. This
  867. // happens when we have candidates that look like, say
  868. //
  869. // AA (where each "A" is an instruction).
  870. //
  871. // We might have some portion of the module that looks like this:
  872. // AAAAAA (6 A's)
  873. //
  874. // In this case, there are 5 different copies of "AA" in this range, but
  875. // at most 3 can be outlined. If only outlining 3 of these is going to
  876. // be unbeneficial, then we ought to not bother.
  877. //
  878. // Note that two things DON'T overlap when they look like this:
  879. // start1...end1 .... start2...end2
  880. // That is, one must either
  881. // * End before the other starts
  882. // * Start after the other ends
  883. if (std::all_of(
  884. CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
  885. [&StartIdx, &EndIdx](const Candidate &C) {
  886. return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
  887. })) {
  888. // It doesn't overlap with anything, so we can outline it.
  889. // Each sequence is over [StartIt, EndIt].
  890. // Save the candidate and its location.
  891. MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
  892. MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
  893. MachineBasicBlock *MBB = StartIt->getParent();
  894. CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
  895. EndIt, MBB, FunctionList.size(),
  896. Mapper.MBBFlagsMap[MBB]);
  897. }
  898. }
  899. // We've found something we might want to outline.
  900. // Create an OutlinedFunction to store it and check if it'd be beneficial
  901. // to outline.
  902. if (CandidatesForRepeatedSeq.size() < 2)
  903. continue;
  904. // Arbitrarily choose a TII from the first candidate.
  905. // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
  906. const TargetInstrInfo *TII =
  907. CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
  908. OutlinedFunction OF =
  909. TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
  910. // If we deleted too many candidates, then there's nothing worth outlining.
  911. // FIXME: This should take target-specified instruction sizes into account.
  912. if (OF.Candidates.size() < 2)
  913. continue;
  914. // Is it better to outline this candidate than not?
  915. if (OF.getBenefit() < 1) {
  916. emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
  917. continue;
  918. }
  919. FunctionList.push_back(OF);
  920. }
  921. }
  922. MachineFunction *
  923. MachineOutliner::createOutlinedFunction(Module &M, OutlinedFunction &OF,
  924. InstructionMapper &Mapper,
  925. unsigned Name) {
  926. // Create the function name. This should be unique.
  927. // FIXME: We should have a better naming scheme. This should be stable,
  928. // regardless of changes to the outliner's cost model/traversal order.
  929. std::string FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str();
  930. // Create the function using an IR-level function.
  931. LLVMContext &C = M.getContext();
  932. Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
  933. Function::ExternalLinkage, FunctionName, M);
  934. // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
  935. // which gives us better results when we outline from linkonceodr functions.
  936. F->setLinkage(GlobalValue::InternalLinkage);
  937. F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
  938. // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
  939. // necessary.
  940. // Set optsize/minsize, so we don't insert padding between outlined
  941. // functions.
  942. F->addFnAttr(Attribute::OptimizeForSize);
  943. F->addFnAttr(Attribute::MinSize);
  944. // Include target features from an arbitrary candidate for the outlined
  945. // function. This makes sure the outlined function knows what kinds of
  946. // instructions are going into it. This is fine, since all parent functions
  947. // must necessarily support the instructions that are in the outlined region.
  948. Candidate &FirstCand = OF.Candidates.front();
  949. const Function &ParentFn = FirstCand.getMF()->getFunction();
  950. if (ParentFn.hasFnAttribute("target-features"))
  951. F->addFnAttr(ParentFn.getFnAttribute("target-features"));
  952. BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
  953. IRBuilder<> Builder(EntryBB);
  954. Builder.CreateRetVoid();
  955. MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
  956. MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
  957. MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
  958. const TargetSubtargetInfo &STI = MF.getSubtarget();
  959. const TargetInstrInfo &TII = *STI.getInstrInfo();
  960. // Insert the new function into the module.
  961. MF.insert(MF.begin(), &MBB);
  962. for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
  963. ++I) {
  964. MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
  965. NewMI->dropMemRefs(MF);
  966. // Don't keep debug information for outlined instructions.
  967. NewMI->setDebugLoc(DebugLoc());
  968. MBB.insert(MBB.end(), NewMI);
  969. }
  970. TII.buildOutlinedFrame(MBB, MF, OF);
  971. // Outlined functions shouldn't preserve liveness.
  972. MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
  973. MF.getRegInfo().freezeReservedRegs(MF);
  974. // If there's a DISubprogram associated with this outlined function, then
  975. // emit debug info for the outlined function.
  976. if (DISubprogram *SP = getSubprogramOrNull(OF)) {
  977. // We have a DISubprogram. Get its DICompileUnit.
  978. DICompileUnit *CU = SP->getUnit();
  979. DIBuilder DB(M, true, CU);
  980. DIFile *Unit = SP->getFile();
  981. Mangler Mg;
  982. // Get the mangled name of the function for the linkage name.
  983. std::string Dummy;
  984. llvm::raw_string_ostream MangledNameStream(Dummy);
  985. Mg.getNameWithPrefix(MangledNameStream, F, false);
  986. DISubprogram *OutlinedSP = DB.createFunction(
  987. Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
  988. Unit /* File */,
  989. 0 /* Line 0 is reserved for compiler-generated code. */,
  990. DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
  991. 0, /* Line 0 is reserved for compiler-generated code. */
  992. DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
  993. /* Outlined code is optimized code by definition. */
  994. DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
  995. // Don't add any new variables to the subprogram.
  996. DB.finalizeSubprogram(OutlinedSP);
  997. // Attach subprogram to the function.
  998. F->setSubprogram(OutlinedSP);
  999. // We're done with the DIBuilder.
  1000. DB.finalize();
  1001. }
  1002. return &MF;
  1003. }
  1004. bool MachineOutliner::outline(Module &M,
  1005. std::vector<OutlinedFunction> &FunctionList,
  1006. InstructionMapper &Mapper) {
  1007. bool OutlinedSomething = false;
  1008. // Number to append to the current outlined function.
  1009. unsigned OutlinedFunctionNum = 0;
  1010. // Sort by benefit. The most beneficial functions should be outlined first.
  1011. llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
  1012. const OutlinedFunction &RHS) {
  1013. return LHS.getBenefit() > RHS.getBenefit();
  1014. });
  1015. // Walk over each function, outlining them as we go along. Functions are
  1016. // outlined greedily, based off the sort above.
  1017. for (OutlinedFunction &OF : FunctionList) {
  1018. // If we outlined something that overlapped with a candidate in a previous
  1019. // step, then we can't outline from it.
  1020. erase_if(OF.Candidates, [&Mapper](Candidate &C) {
  1021. return std::any_of(
  1022. Mapper.UnsignedVec.begin() + C.getStartIdx(),
  1023. Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
  1024. [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
  1025. });
  1026. // If we made it unbeneficial to outline this function, skip it.
  1027. if (OF.getBenefit() < 1)
  1028. continue;
  1029. // It's beneficial. Create the function and outline its sequence's
  1030. // occurrences.
  1031. OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
  1032. emitOutlinedFunctionRemark(OF);
  1033. FunctionsCreated++;
  1034. OutlinedFunctionNum++; // Created a function, move to the next name.
  1035. MachineFunction *MF = OF.MF;
  1036. const TargetSubtargetInfo &STI = MF->getSubtarget();
  1037. const TargetInstrInfo &TII = *STI.getInstrInfo();
  1038. // Replace occurrences of the sequence with calls to the new function.
  1039. for (Candidate &C : OF.Candidates) {
  1040. MachineBasicBlock &MBB = *C.getMBB();
  1041. MachineBasicBlock::iterator StartIt = C.front();
  1042. MachineBasicBlock::iterator EndIt = C.back();
  1043. // Insert the call.
  1044. auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
  1045. // If the caller tracks liveness, then we need to make sure that
  1046. // anything we outline doesn't break liveness assumptions. The outlined
  1047. // functions themselves currently don't track liveness, but we should
  1048. // make sure that the ranges we yank things out of aren't wrong.
  1049. if (MBB.getParent()->getProperties().hasProperty(
  1050. MachineFunctionProperties::Property::TracksLiveness)) {
  1051. // Helper lambda for adding implicit def operands to the call
  1052. // instruction. It also updates call site information for moved
  1053. // code.
  1054. auto CopyDefsAndUpdateCalls = [&CallInst](MachineInstr &MI) {
  1055. for (MachineOperand &MOP : MI.operands()) {
  1056. // Skip over anything that isn't a register.
  1057. if (!MOP.isReg())
  1058. continue;
  1059. // If it's a def, add it to the call instruction.
  1060. if (MOP.isDef())
  1061. CallInst->addOperand(MachineOperand::CreateReg(
  1062. MOP.getReg(), true, /* isDef = true */
  1063. true /* isImp = true */));
  1064. }
  1065. if (MI.isCall())
  1066. MI.getMF()->updateCallSiteInfo(&MI);
  1067. };
  1068. // Copy over the defs in the outlined range.
  1069. // First inst in outlined range <-- Anything that's defined in this
  1070. // ... .. range has to be added as an
  1071. // implicit Last inst in outlined range <-- def to the call
  1072. // instruction. Also remove call site information for outlined block
  1073. // of code.
  1074. std::for_each(CallInst, std::next(EndIt), CopyDefsAndUpdateCalls);
  1075. }
  1076. // Erase from the point after where the call was inserted up to, and
  1077. // including, the final instruction in the sequence.
  1078. // Erase needs one past the end, so we need std::next there too.
  1079. MBB.erase(std::next(StartIt), std::next(EndIt));
  1080. // Keep track of what we removed by marking them all as -1.
  1081. std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
  1082. Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
  1083. [](unsigned &I) { I = static_cast<unsigned>(-1); });
  1084. OutlinedSomething = true;
  1085. // Statistics.
  1086. NumOutlined++;
  1087. }
  1088. }
  1089. LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
  1090. return OutlinedSomething;
  1091. }
  1092. void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
  1093. MachineModuleInfo &MMI) {
  1094. // Build instruction mappings for each function in the module. Start by
  1095. // iterating over each Function in M.
  1096. for (Function &F : M) {
  1097. // If there's nothing in F, then there's no reason to try and outline from
  1098. // it.
  1099. if (F.empty())
  1100. continue;
  1101. // There's something in F. Check if it has a MachineFunction associated with
  1102. // it.
  1103. MachineFunction *MF = MMI.getMachineFunction(F);
  1104. // If it doesn't, then there's nothing to outline from. Move to the next
  1105. // Function.
  1106. if (!MF)
  1107. continue;
  1108. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1109. if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
  1110. continue;
  1111. // We have a MachineFunction. Ask the target if it's suitable for outlining.
  1112. // If it isn't, then move on to the next Function in the module.
  1113. if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
  1114. continue;
  1115. // We have a function suitable for outlining. Iterate over every
  1116. // MachineBasicBlock in MF and try to map its instructions to a list of
  1117. // unsigned integers.
  1118. for (MachineBasicBlock &MBB : *MF) {
  1119. // If there isn't anything in MBB, then there's no point in outlining from
  1120. // it.
  1121. // If there are fewer than 2 instructions in the MBB, then it can't ever
  1122. // contain something worth outlining.
  1123. // FIXME: This should be based off of the maximum size in B of an outlined
  1124. // call versus the size in B of the MBB.
  1125. if (MBB.empty() || MBB.size() < 2)
  1126. continue;
  1127. // Check if MBB could be the target of an indirect branch. If it is, then
  1128. // we don't want to outline from it.
  1129. if (MBB.hasAddressTaken())
  1130. continue;
  1131. // MBB is suitable for outlining. Map it to a list of unsigneds.
  1132. Mapper.convertToUnsignedVec(MBB, *TII);
  1133. }
  1134. }
  1135. }
  1136. void MachineOutliner::initSizeRemarkInfo(
  1137. const Module &M, const MachineModuleInfo &MMI,
  1138. StringMap<unsigned> &FunctionToInstrCount) {
  1139. // Collect instruction counts for every function. We'll use this to emit
  1140. // per-function size remarks later.
  1141. for (const Function &F : M) {
  1142. MachineFunction *MF = MMI.getMachineFunction(F);
  1143. // We only care about MI counts here. If there's no MachineFunction at this
  1144. // point, then there won't be after the outliner runs, so let's move on.
  1145. if (!MF)
  1146. continue;
  1147. FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
  1148. }
  1149. }
  1150. void MachineOutliner::emitInstrCountChangedRemark(
  1151. const Module &M, const MachineModuleInfo &MMI,
  1152. const StringMap<unsigned> &FunctionToInstrCount) {
  1153. // Iterate over each function in the module and emit remarks.
  1154. // Note that we won't miss anything by doing this, because the outliner never
  1155. // deletes functions.
  1156. for (const Function &F : M) {
  1157. MachineFunction *MF = MMI.getMachineFunction(F);
  1158. // The outliner never deletes functions. If we don't have a MF here, then we
  1159. // didn't have one prior to outlining either.
  1160. if (!MF)
  1161. continue;
  1162. std::string Fname = F.getName();
  1163. unsigned FnCountAfter = MF->getInstructionCount();
  1164. unsigned FnCountBefore = 0;
  1165. // Check if the function was recorded before.
  1166. auto It = FunctionToInstrCount.find(Fname);
  1167. // Did we have a previously-recorded size? If yes, then set FnCountBefore
  1168. // to that.
  1169. if (It != FunctionToInstrCount.end())
  1170. FnCountBefore = It->second;
  1171. // Compute the delta and emit a remark if there was a change.
  1172. int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
  1173. static_cast<int64_t>(FnCountBefore);
  1174. if (FnDelta == 0)
  1175. continue;
  1176. MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
  1177. MORE.emit([&]() {
  1178. MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
  1179. DiagnosticLocation(),
  1180. &MF->front());
  1181. R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
  1182. << ": Function: "
  1183. << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
  1184. << ": MI instruction count changed from "
  1185. << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
  1186. FnCountBefore)
  1187. << " to "
  1188. << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
  1189. FnCountAfter)
  1190. << "; Delta: "
  1191. << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
  1192. return R;
  1193. });
  1194. }
  1195. }
  1196. bool MachineOutliner::runOnModule(Module &M) {
  1197. // Check if there's anything in the module. If it's empty, then there's
  1198. // nothing to outline.
  1199. if (M.empty())
  1200. return false;
  1201. MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
  1202. // If the user passed -enable-machine-outliner=always or
  1203. // -enable-machine-outliner, the pass will run on all functions in the module.
  1204. // Otherwise, if the target supports default outlining, it will run on all
  1205. // functions deemed by the target to be worth outlining from by default. Tell
  1206. // the user how the outliner is running.
  1207. LLVM_DEBUG(
  1208. dbgs() << "Machine Outliner: Running on ";
  1209. if (RunOnAllFunctions)
  1210. dbgs() << "all functions";
  1211. else
  1212. dbgs() << "target-default functions";
  1213. dbgs() << "\n"
  1214. );
  1215. // If the user specifies that they want to outline from linkonceodrs, set
  1216. // it here.
  1217. OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
  1218. InstructionMapper Mapper;
  1219. // Prepare instruction mappings for the suffix tree.
  1220. populateMapper(Mapper, M, MMI);
  1221. std::vector<OutlinedFunction> FunctionList;
  1222. // Find all of the outlining candidates.
  1223. findCandidates(Mapper, FunctionList);
  1224. // If we've requested size remarks, then collect the MI counts of every
  1225. // function before outlining, and the MI counts after outlining.
  1226. // FIXME: This shouldn't be in the outliner at all; it should ultimately be
  1227. // the pass manager's responsibility.
  1228. // This could pretty easily be placed in outline instead, but because we
  1229. // really ultimately *don't* want this here, it's done like this for now
  1230. // instead.
  1231. // Check if we want size remarks.
  1232. bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
  1233. StringMap<unsigned> FunctionToInstrCount;
  1234. if (ShouldEmitSizeRemarks)
  1235. initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
  1236. // Outline each of the candidates and return true if something was outlined.
  1237. bool OutlinedSomething = outline(M, FunctionList, Mapper);
  1238. // If we outlined something, we definitely changed the MI count of the
  1239. // module. If we've asked for size remarks, then output them.
  1240. // FIXME: This should be in the pass manager.
  1241. if (ShouldEmitSizeRemarks && OutlinedSomething)
  1242. emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
  1243. return OutlinedSomething;
  1244. }