MachineOutliner.cpp 58 KB

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