MachineOutliner.cpp 57 KB

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