MachineOutliner.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. /// This was originally presented at the 2016 LLVM Developers' Meeting in the
  19. /// talk "Reducing Code Size Using Outlining". For a high-level overview of
  20. /// how this pass works, the talk is available on YouTube at
  21. ///
  22. /// https://www.youtube.com/watch?v=yorld-WSOeU
  23. ///
  24. /// The slides for the talk are available at
  25. ///
  26. /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
  27. ///
  28. /// The talk provides an overview of how the outliner finds candidates and
  29. /// ultimately outlines them. It describes how the main data structure for this
  30. /// pass, the suffix tree, is queried and purged for candidates. It also gives
  31. /// a simplified suffix tree construction algorithm for suffix trees based off
  32. /// of the algorithm actually used here, Ukkonen's algorithm.
  33. ///
  34. /// For the original RFC for this pass, please see
  35. ///
  36. /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
  37. ///
  38. /// For more information on the suffix tree data structure, please see
  39. /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
  40. ///
  41. //===----------------------------------------------------------------------===//
  42. #include "llvm/ADT/DenseMap.h"
  43. #include "llvm/ADT/Statistic.h"
  44. #include "llvm/ADT/Twine.h"
  45. #include "llvm/CodeGen/MachineFrameInfo.h"
  46. #include "llvm/CodeGen/MachineFunction.h"
  47. #include "llvm/CodeGen/MachineInstrBuilder.h"
  48. #include "llvm/CodeGen/MachineModuleInfo.h"
  49. #include "llvm/CodeGen/Passes.h"
  50. #include "llvm/IR/IRBuilder.h"
  51. #include "llvm/Support/Allocator.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include "llvm/Target/TargetInstrInfo.h"
  55. #include "llvm/Target/TargetMachine.h"
  56. #include "llvm/Target/TargetRegisterInfo.h"
  57. #include "llvm/Target/TargetSubtargetInfo.h"
  58. #include <functional>
  59. #include <map>
  60. #include <sstream>
  61. #include <tuple>
  62. #include <vector>
  63. #define DEBUG_TYPE "machine-outliner"
  64. using namespace llvm;
  65. STATISTIC(NumOutlined, "Number of candidates outlined");
  66. STATISTIC(FunctionsCreated, "Number of functions created");
  67. namespace {
  68. /// \brief An individual sequence of instructions to be replaced with a call to
  69. /// an outlined function.
  70. struct Candidate {
  71. /// Set to false if the candidate overlapped with another candidate.
  72. bool InCandidateList = true;
  73. /// The start index of this \p Candidate.
  74. size_t StartIdx;
  75. /// The number of instructions in this \p Candidate.
  76. size_t Len;
  77. /// The index of this \p Candidate's \p OutlinedFunction in the list of
  78. /// \p OutlinedFunctions.
  79. size_t FunctionIdx;
  80. /// \brief The number of instructions that would be saved by outlining every
  81. /// candidate of this type.
  82. ///
  83. /// This is a fixed value which is not updated during the candidate pruning
  84. /// process. It is only used for deciding which candidate to keep if two
  85. /// candidates overlap. The true benefit is stored in the OutlinedFunction
  86. /// for some given candidate.
  87. unsigned Benefit = 0;
  88. Candidate(size_t StartIdx, size_t Len, size_t FunctionIdx)
  89. : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
  90. Candidate() {}
  91. /// \brief Used to ensure that \p Candidates are outlined in an order that
  92. /// preserves the start and end indices of other \p Candidates.
  93. bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; }
  94. };
  95. /// \brief The information necessary to create an outlined function for some
  96. /// class of candidate.
  97. struct OutlinedFunction {
  98. /// The actual outlined function created.
  99. /// This is initialized after we go through and create the actual function.
  100. MachineFunction *MF = nullptr;
  101. /// A number assigned to this function which appears at the end of its name.
  102. size_t Name;
  103. /// The number of candidates for this OutlinedFunction.
  104. size_t OccurrenceCount = 0;
  105. /// \brief The sequence of integers corresponding to the instructions in this
  106. /// function.
  107. std::vector<unsigned> Sequence;
  108. /// The number of instructions this function would save.
  109. unsigned Benefit = 0;
  110. /// \brief Set to true if candidates for this outlined function should be
  111. /// replaced with tail calls to this OutlinedFunction.
  112. bool IsTailCall = false;
  113. OutlinedFunction(size_t Name, size_t OccurrenceCount,
  114. const std::vector<unsigned> &Sequence,
  115. unsigned Benefit, bool IsTailCall)
  116. : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence),
  117. Benefit(Benefit), IsTailCall(IsTailCall)
  118. {}
  119. };
  120. /// Represents an undefined index in the suffix tree.
  121. const size_t EmptyIdx = -1;
  122. /// A node in a suffix tree which represents a substring or suffix.
  123. ///
  124. /// Each node has either no children or at least two children, with the root
  125. /// being a exception in the empty tree.
  126. ///
  127. /// Children are represented as a map between unsigned integers and nodes. If
  128. /// a node N has a child M on unsigned integer k, then the mapping represented
  129. /// by N is a proper prefix of the mapping represented by M. Note that this,
  130. /// although similar to a trie is somewhat different: each node stores a full
  131. /// substring of the full mapping rather than a single character state.
  132. ///
  133. /// Each internal node contains a pointer to the internal node representing
  134. /// the same string, but with the first character chopped off. This is stored
  135. /// in \p Link. Each leaf node stores the start index of its respective
  136. /// suffix in \p SuffixIdx.
  137. struct SuffixTreeNode {
  138. /// The children of this node.
  139. ///
  140. /// A child existing on an unsigned integer implies that from the mapping
  141. /// represented by the current node, there is a way to reach another
  142. /// mapping by tacking that character on the end of the current string.
  143. DenseMap<unsigned, SuffixTreeNode *> Children;
  144. /// A flag set to false if the node has been pruned from the tree.
  145. bool IsInTree = true;
  146. /// The start index of this node's substring in the main string.
  147. size_t StartIdx = EmptyIdx;
  148. /// The end index of this node's substring in the main string.
  149. ///
  150. /// Every leaf node must have its \p EndIdx incremented at the end of every
  151. /// step in the construction algorithm. To avoid having to update O(N)
  152. /// nodes individually at the end of every step, the end index is stored
  153. /// as a pointer.
  154. size_t *EndIdx = nullptr;
  155. /// For leaves, the start index of the suffix represented by this node.
  156. ///
  157. /// For all other nodes, this is ignored.
  158. size_t SuffixIdx = EmptyIdx;
  159. /// \brief For internal nodes, a pointer to the internal node representing
  160. /// the same sequence with the first character chopped off.
  161. ///
  162. /// This has two major purposes in the suffix tree. The first is as a
  163. /// shortcut in Ukkonen's construction algorithm. One of the things that
  164. /// Ukkonen's algorithm does to achieve linear-time construction is
  165. /// keep track of which node the next insert should be at. This makes each
  166. /// insert O(1), and there are a total of O(N) inserts. The suffix link
  167. /// helps with inserting children of internal nodes.
  168. ///
  169. /// Say we add a child to an internal node with associated mapping S. The
  170. /// next insertion must be at the node representing S - its first character.
  171. /// This is given by the way that we iteratively build the tree in Ukkonen's
  172. /// algorithm. The main idea is to look at the suffixes of each prefix in the
  173. /// string, starting with the longest suffix of the prefix, and ending with
  174. /// the shortest. Therefore, if we keep pointers between such nodes, we can
  175. /// move to the next insertion point in O(1) time. If we don't, then we'd
  176. /// have to query from the root, which takes O(N) time. This would make the
  177. /// construction algorithm O(N^2) rather than O(N).
  178. ///
  179. /// The suffix link is also used during the tree pruning process to let us
  180. /// quickly throw out a bunch of potential overlaps. Say we have a sequence
  181. /// S we want to outline. Then each of its suffixes contribute to at least
  182. /// one overlapping case. Therefore, we can follow the suffix links
  183. /// starting at the node associated with S to the root and "delete" those
  184. /// nodes, save for the root. For each candidate, this removes
  185. /// O(|candidate|) overlaps from the search space. We don't actually
  186. /// completely invalidate these nodes though; doing that is far too
  187. /// aggressive. Consider the following pathological string:
  188. ///
  189. /// 1 2 3 1 2 3 2 3 2 3 2 3 2 3 2 3 2 3
  190. ///
  191. /// If we, for the sake of example, outlined 1 2 3, then we would throw
  192. /// out all instances of 2 3. This isn't desirable. To get around this,
  193. /// when we visit a link node, we decrement its occurrence count by the
  194. /// number of sequences we outlined in the current step. In the pathological
  195. /// example, the 2 3 node would have an occurrence count of 8, while the
  196. /// 1 2 3 node would have an occurrence count of 2. Thus, the 2 3 node
  197. /// would survive to the next round allowing us to outline the extra
  198. /// instances of 2 3.
  199. SuffixTreeNode *Link = nullptr;
  200. /// The parent of this node. Every node except for the root has a parent.
  201. SuffixTreeNode *Parent = nullptr;
  202. /// The number of times this node's string appears in the tree.
  203. ///
  204. /// This is equal to the number of leaf children of the string. It represents
  205. /// the number of suffixes that the node's string is a prefix of.
  206. size_t OccurrenceCount = 0;
  207. /// The length of the string formed by concatenating the edge labels from the
  208. /// root to this node.
  209. size_t ConcatLen = 0;
  210. /// Returns true if this node is a leaf.
  211. bool isLeaf() const { return SuffixIdx != EmptyIdx; }
  212. /// Returns true if this node is the root of its owning \p SuffixTree.
  213. bool isRoot() const { return StartIdx == EmptyIdx; }
  214. /// Return the number of elements in the substring associated with this node.
  215. size_t size() const {
  216. // Is it the root? If so, it's the empty string so return 0.
  217. if (isRoot())
  218. return 0;
  219. assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
  220. // Size = the number of elements in the string.
  221. // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
  222. return *EndIdx - StartIdx + 1;
  223. }
  224. SuffixTreeNode(size_t StartIdx, size_t *EndIdx, SuffixTreeNode *Link,
  225. SuffixTreeNode *Parent)
  226. : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
  227. SuffixTreeNode() {}
  228. };
  229. /// A data structure for fast substring queries.
  230. ///
  231. /// Suffix trees represent the suffixes of their input strings in their leaves.
  232. /// A suffix tree is a type of compressed trie structure where each node
  233. /// represents an entire substring rather than a single character. Each leaf
  234. /// of the tree is a suffix.
  235. ///
  236. /// A suffix tree can be seen as a type of state machine where each state is a
  237. /// substring of the full string. The tree is structured so that, for a string
  238. /// of length N, there are exactly N leaves in the tree. This structure allows
  239. /// us to quickly find repeated substrings of the input string.
  240. ///
  241. /// In this implementation, a "string" is a vector of unsigned integers.
  242. /// These integers may result from hashing some data type. A suffix tree can
  243. /// contain 1 or many strings, which can then be queried as one large string.
  244. ///
  245. /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
  246. /// suffix tree construction. Ukkonen's algorithm is explained in more detail
  247. /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
  248. /// paper is available at
  249. ///
  250. /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
  251. class SuffixTree {
  252. private:
  253. /// Each element is an integer representing an instruction in the module.
  254. ArrayRef<unsigned> Str;
  255. /// Maintains each node in the tree.
  256. SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
  257. /// The root of the suffix tree.
  258. ///
  259. /// The root represents the empty string. It is maintained by the
  260. /// \p NodeAllocator like every other node in the tree.
  261. SuffixTreeNode *Root = nullptr;
  262. /// Stores each leaf node in the tree.
  263. ///
  264. /// This is used for finding outlining candidates.
  265. std::vector<SuffixTreeNode *> LeafVector;
  266. /// Maintains the end indices of the internal nodes in the tree.
  267. ///
  268. /// Each internal node is guaranteed to never have its end index change
  269. /// during the construction algorithm; however, leaves must be updated at
  270. /// every step. Therefore, we need to store leaf end indices by reference
  271. /// to avoid updating O(N) leaves at every step of construction. Thus,
  272. /// every internal node must be allocated its own end index.
  273. BumpPtrAllocator InternalEndIdxAllocator;
  274. /// The end index of each leaf in the tree.
  275. size_t LeafEndIdx = -1;
  276. /// \brief Helper struct which keeps track of the next insertion point in
  277. /// Ukkonen's algorithm.
  278. struct ActiveState {
  279. /// The next node to insert at.
  280. SuffixTreeNode *Node;
  281. /// The index of the first character in the substring currently being added.
  282. size_t Idx = EmptyIdx;
  283. /// The length of the substring we have to add at the current step.
  284. size_t Len = 0;
  285. };
  286. /// \brief The point the next insertion will take place at in the
  287. /// construction algorithm.
  288. ActiveState Active;
  289. /// Allocate a leaf node and add it to the tree.
  290. ///
  291. /// \param Parent The parent of this node.
  292. /// \param StartIdx The start index of this node's associated string.
  293. /// \param Edge The label on the edge leaving \p Parent to this node.
  294. ///
  295. /// \returns A pointer to the allocated leaf node.
  296. SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, size_t StartIdx,
  297. unsigned Edge) {
  298. assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
  299. SuffixTreeNode *N = new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx,
  300. &LeafEndIdx,
  301. nullptr,
  302. &Parent);
  303. Parent.Children[Edge] = N;
  304. return N;
  305. }
  306. /// Allocate an internal node and add it to the tree.
  307. ///
  308. /// \param Parent The parent of this node. Only null when allocating the root.
  309. /// \param StartIdx The start index of this node's associated string.
  310. /// \param EndIdx The end index of this node's associated string.
  311. /// \param Edge The label on the edge leaving \p Parent to this node.
  312. ///
  313. /// \returns A pointer to the allocated internal node.
  314. SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, size_t StartIdx,
  315. size_t EndIdx, unsigned Edge) {
  316. assert(StartIdx <= EndIdx && "String can't start after it ends!");
  317. assert(!(!Parent && StartIdx != EmptyIdx) &&
  318. "Non-root internal nodes must have parents!");
  319. size_t *E = new (InternalEndIdxAllocator) size_t(EndIdx);
  320. SuffixTreeNode *N = new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx,
  321. E,
  322. Root,
  323. Parent);
  324. if (Parent)
  325. Parent->Children[Edge] = N;
  326. return N;
  327. }
  328. /// \brief Set the suffix indices of the leaves to the start indices of their
  329. /// respective suffixes. Also stores each leaf in \p LeafVector at its
  330. /// respective suffix index.
  331. ///
  332. /// \param[in] CurrNode The node currently being visited.
  333. /// \param CurrIdx The current index of the string being visited.
  334. void setSuffixIndices(SuffixTreeNode &CurrNode, size_t CurrIdx) {
  335. bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
  336. // Store the length of the concatenation of all strings from the root to
  337. // this node.
  338. if (!CurrNode.isRoot()) {
  339. if (CurrNode.ConcatLen == 0)
  340. CurrNode.ConcatLen = CurrNode.size();
  341. if (CurrNode.Parent)
  342. CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
  343. }
  344. // Traverse the tree depth-first.
  345. for (auto &ChildPair : CurrNode.Children) {
  346. assert(ChildPair.second && "Node had a null child!");
  347. setSuffixIndices(*ChildPair.second,
  348. CurrIdx + ChildPair.second->size());
  349. }
  350. // Is this node a leaf?
  351. if (IsLeaf) {
  352. // If yes, give it a suffix index and bump its parent's occurrence count.
  353. CurrNode.SuffixIdx = Str.size() - CurrIdx;
  354. assert(CurrNode.Parent && "CurrNode had no parent!");
  355. CurrNode.Parent->OccurrenceCount++;
  356. // Store the leaf in the leaf vector for pruning later.
  357. LeafVector[CurrNode.SuffixIdx] = &CurrNode;
  358. }
  359. }
  360. /// \brief Construct the suffix tree for the prefix of the input ending at
  361. /// \p EndIdx.
  362. ///
  363. /// Used to construct the full suffix tree iteratively. At the end of each
  364. /// step, the constructed suffix tree is either a valid suffix tree, or a
  365. /// suffix tree with implicit suffixes. At the end of the final step, the
  366. /// suffix tree is a valid tree.
  367. ///
  368. /// \param EndIdx The end index of the current prefix in the main string.
  369. /// \param SuffixesToAdd The number of suffixes that must be added
  370. /// to complete the suffix tree at the current phase.
  371. ///
  372. /// \returns The number of suffixes that have not been added at the end of
  373. /// this step.
  374. unsigned extend(size_t EndIdx, size_t SuffixesToAdd) {
  375. SuffixTreeNode *NeedsLink = nullptr;
  376. while (SuffixesToAdd > 0) {
  377. // Are we waiting to add anything other than just the last character?
  378. if (Active.Len == 0) {
  379. // If not, then say the active index is the end index.
  380. Active.Idx = EndIdx;
  381. }
  382. assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
  383. // The first character in the current substring we're looking at.
  384. unsigned FirstChar = Str[Active.Idx];
  385. // Have we inserted anything starting with FirstChar at the current node?
  386. if (Active.Node->Children.count(FirstChar) == 0) {
  387. // If not, then we can just insert a leaf and move too the next step.
  388. insertLeaf(*Active.Node, EndIdx, FirstChar);
  389. // The active node is an internal node, and we visited it, so it must
  390. // need a link if it doesn't have one.
  391. if (NeedsLink) {
  392. NeedsLink->Link = Active.Node;
  393. NeedsLink = nullptr;
  394. }
  395. } else {
  396. // There's a match with FirstChar, so look for the point in the tree to
  397. // insert a new node.
  398. SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
  399. size_t SubstringLen = NextNode->size();
  400. // Is the current suffix we're trying to insert longer than the size of
  401. // the child we want to move to?
  402. if (Active.Len >= SubstringLen) {
  403. // If yes, then consume the characters we've seen and move to the next
  404. // node.
  405. Active.Idx += SubstringLen;
  406. Active.Len -= SubstringLen;
  407. Active.Node = NextNode;
  408. continue;
  409. }
  410. // Otherwise, the suffix we're trying to insert must be contained in the
  411. // next node we want to move to.
  412. unsigned LastChar = Str[EndIdx];
  413. // Is the string we're trying to insert a substring of the next node?
  414. if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
  415. // If yes, then we're done for this step. Remember our insertion point
  416. // and move to the next end index. At this point, we have an implicit
  417. // suffix tree.
  418. if (NeedsLink && !Active.Node->isRoot()) {
  419. NeedsLink->Link = Active.Node;
  420. NeedsLink = nullptr;
  421. }
  422. Active.Len++;
  423. break;
  424. }
  425. // The string we're trying to insert isn't a substring of the next node,
  426. // but matches up to a point. Split the node.
  427. //
  428. // For example, say we ended our search at a node n and we're trying to
  429. // insert ABD. Then we'll create a new node s for AB, reduce n to just
  430. // representing C, and insert a new leaf node l to represent d. This
  431. // allows us to ensure that if n was a leaf, it remains a leaf.
  432. //
  433. // | ABC ---split---> | AB
  434. // n s
  435. // C / \ D
  436. // n l
  437. // The node s from the diagram
  438. SuffixTreeNode *SplitNode =
  439. insertInternalNode(Active.Node,
  440. NextNode->StartIdx,
  441. NextNode->StartIdx + Active.Len - 1,
  442. FirstChar);
  443. // Insert the new node representing the new substring into the tree as
  444. // a child of the split node. This is the node l from the diagram.
  445. insertLeaf(*SplitNode, EndIdx, LastChar);
  446. // Make the old node a child of the split node and update its start
  447. // index. This is the node n from the diagram.
  448. NextNode->StartIdx += Active.Len;
  449. NextNode->Parent = SplitNode;
  450. SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
  451. // SplitNode is an internal node, update the suffix link.
  452. if (NeedsLink)
  453. NeedsLink->Link = SplitNode;
  454. NeedsLink = SplitNode;
  455. }
  456. // We've added something new to the tree, so there's one less suffix to
  457. // add.
  458. SuffixesToAdd--;
  459. if (Active.Node->isRoot()) {
  460. if (Active.Len > 0) {
  461. Active.Len--;
  462. Active.Idx = EndIdx - SuffixesToAdd + 1;
  463. }
  464. } else {
  465. // Start the next phase at the next smallest suffix.
  466. Active.Node = Active.Node->Link;
  467. }
  468. }
  469. return SuffixesToAdd;
  470. }
  471. public:
  472. /// Find all repeated substrings that satisfy \p BenefitFn.
  473. ///
  474. /// If a substring appears at least twice, then it must be represented by
  475. /// an internal node which appears in at least two suffixes. Each suffix is
  476. /// represented by a leaf node. To do this, we visit each internal node in
  477. /// the tree, using the leaf children of each internal node. If an internal
  478. /// node represents a beneficial substring, then we use each of its leaf
  479. /// children to find the locations of its substring.
  480. ///
  481. /// \param[out] CandidateList Filled with candidates representing each
  482. /// beneficial substring.
  483. /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
  484. /// type of candidate.
  485. /// \param BenefitFn The function to satisfy.
  486. ///
  487. /// \returns The length of the longest candidate found.
  488. size_t findCandidates(std::vector<Candidate> &CandidateList,
  489. std::vector<OutlinedFunction> &FunctionList,
  490. const std::function<unsigned(SuffixTreeNode &, size_t, unsigned)>
  491. &BenefitFn) {
  492. CandidateList.clear();
  493. FunctionList.clear();
  494. size_t FnIdx = 0;
  495. size_t MaxLen = 0;
  496. for (SuffixTreeNode* Leaf : LeafVector) {
  497. assert(Leaf && "Leaves in LeafVector cannot be null!");
  498. if (!Leaf->IsInTree)
  499. continue;
  500. assert(Leaf->Parent && "All leaves must have parents!");
  501. SuffixTreeNode &Parent = *(Leaf->Parent);
  502. // If it doesn't appear enough, or we already outlined from it, skip it.
  503. if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
  504. continue;
  505. size_t StringLen = Leaf->ConcatLen - Leaf->size();
  506. // How many instructions would outlining this string save?
  507. unsigned Benefit = BenefitFn(Parent,
  508. StringLen, Str[Leaf->SuffixIdx + StringLen - 1]);
  509. // If it's not beneficial, skip it.
  510. if (Benefit < 1)
  511. continue;
  512. if (StringLen > MaxLen)
  513. MaxLen = StringLen;
  514. unsigned OccurrenceCount = 0;
  515. for (auto &ChildPair : Parent.Children) {
  516. SuffixTreeNode *M = ChildPair.second;
  517. // Is it a leaf? If so, we have an occurrence of this candidate.
  518. if (M && M->IsInTree && M->isLeaf()) {
  519. OccurrenceCount++;
  520. CandidateList.emplace_back(M->SuffixIdx, StringLen, FnIdx);
  521. CandidateList.back().Benefit = Benefit;
  522. M->IsInTree = false;
  523. }
  524. }
  525. // Save the function for the new candidate sequence.
  526. std::vector<unsigned> CandidateSequence;
  527. for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
  528. CandidateSequence.push_back(Str[i]);
  529. FunctionList.emplace_back(FnIdx, OccurrenceCount, CandidateSequence,
  530. Benefit, false);
  531. // Move to the next function.
  532. FnIdx++;
  533. Parent.IsInTree = false;
  534. }
  535. return MaxLen;
  536. }
  537. /// Construct a suffix tree from a sequence of unsigned integers.
  538. ///
  539. /// \param Str The string to construct the suffix tree for.
  540. SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
  541. Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
  542. Root->IsInTree = true;
  543. Active.Node = Root;
  544. LeafVector = std::vector<SuffixTreeNode*>(Str.size());
  545. // Keep track of the number of suffixes we have to add of the current
  546. // prefix.
  547. size_t SuffixesToAdd = 0;
  548. Active.Node = Root;
  549. // Construct the suffix tree iteratively on each prefix of the string.
  550. // PfxEndIdx is the end index of the current prefix.
  551. // End is one past the last element in the string.
  552. for (size_t PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; PfxEndIdx++) {
  553. SuffixesToAdd++;
  554. LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
  555. SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
  556. }
  557. // Set the suffix indices of each leaf.
  558. assert(Root && "Root node can't be nullptr!");
  559. setSuffixIndices(*Root, 0);
  560. }
  561. };
  562. /// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
  563. struct InstructionMapper {
  564. /// \brief The next available integer to assign to a \p MachineInstr that
  565. /// cannot be outlined.
  566. ///
  567. /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
  568. unsigned IllegalInstrNumber = -3;
  569. /// \brief The next available integer to assign to a \p MachineInstr that can
  570. /// be outlined.
  571. unsigned LegalInstrNumber = 0;
  572. /// Correspondence from \p MachineInstrs to unsigned integers.
  573. DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
  574. InstructionIntegerMap;
  575. /// Corresponcence from unsigned integers to \p MachineInstrs.
  576. /// Inverse of \p InstructionIntegerMap.
  577. DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
  578. /// The vector of unsigned integers that the module is mapped to.
  579. std::vector<unsigned> UnsignedVec;
  580. /// \brief Stores the location of the instruction associated with the integer
  581. /// at index i in \p UnsignedVec for each index i.
  582. std::vector<MachineBasicBlock::iterator> InstrList;
  583. /// \brief Maps \p *It to a legal integer.
  584. ///
  585. /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
  586. /// \p IntegerInstructionMap, and \p LegalInstrNumber.
  587. ///
  588. /// \returns The integer that \p *It was mapped to.
  589. unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
  590. // Get the integer for this instruction or give it the current
  591. // LegalInstrNumber.
  592. InstrList.push_back(It);
  593. MachineInstr &MI = *It;
  594. bool WasInserted;
  595. DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
  596. ResultIt;
  597. std::tie(ResultIt, WasInserted) =
  598. InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
  599. unsigned MINumber = ResultIt->second;
  600. // There was an insertion.
  601. if (WasInserted) {
  602. LegalInstrNumber++;
  603. IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
  604. }
  605. UnsignedVec.push_back(MINumber);
  606. // Make sure we don't overflow or use any integers reserved by the DenseMap.
  607. if (LegalInstrNumber >= IllegalInstrNumber)
  608. report_fatal_error("Instruction mapping overflow!");
  609. assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey()
  610. && "Tried to assign DenseMap tombstone or empty key to instruction.");
  611. assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey()
  612. && "Tried to assign DenseMap tombstone or empty key to instruction.");
  613. return MINumber;
  614. }
  615. /// Maps \p *It to an illegal integer.
  616. ///
  617. /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
  618. ///
  619. /// \returns The integer that \p *It was mapped to.
  620. unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
  621. unsigned MINumber = IllegalInstrNumber;
  622. InstrList.push_back(It);
  623. UnsignedVec.push_back(IllegalInstrNumber);
  624. IllegalInstrNumber--;
  625. assert(LegalInstrNumber < IllegalInstrNumber &&
  626. "Instruction mapping overflow!");
  627. assert(IllegalInstrNumber !=
  628. DenseMapInfo<unsigned>::getEmptyKey() &&
  629. "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
  630. assert(IllegalInstrNumber !=
  631. DenseMapInfo<unsigned>::getTombstoneKey() &&
  632. "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
  633. return MINumber;
  634. }
  635. /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
  636. /// and appends it to \p UnsignedVec and \p InstrList.
  637. ///
  638. /// Two instructions are assigned the same integer if they are identical.
  639. /// If an instruction is deemed unsafe to outline, then it will be assigned an
  640. /// unique integer. The resulting mapping is placed into a suffix tree and
  641. /// queried for candidates.
  642. ///
  643. /// \param MBB The \p MachineBasicBlock to be translated into integers.
  644. /// \param TRI \p TargetRegisterInfo for the module.
  645. /// \param TII \p TargetInstrInfo for the module.
  646. void convertToUnsignedVec(MachineBasicBlock &MBB,
  647. const TargetRegisterInfo &TRI,
  648. const TargetInstrInfo &TII) {
  649. for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
  650. It++) {
  651. // Keep track of where this instruction is in the module.
  652. switch(TII.getOutliningType(*It)) {
  653. case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
  654. mapToIllegalUnsigned(It);
  655. break;
  656. case TargetInstrInfo::MachineOutlinerInstrType::Legal:
  657. mapToLegalUnsigned(It);
  658. break;
  659. case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
  660. break;
  661. }
  662. }
  663. // After we're done every insertion, uniquely terminate this part of the
  664. // "string". This makes sure we won't match across basic block or function
  665. // boundaries since the "end" is encoded uniquely and thus appears in no
  666. // repeated substring.
  667. InstrList.push_back(MBB.end());
  668. UnsignedVec.push_back(IllegalInstrNumber);
  669. IllegalInstrNumber--;
  670. }
  671. InstructionMapper() {
  672. // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
  673. // changed.
  674. assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
  675. "DenseMapInfo<unsigned>'s empty key isn't -1!");
  676. assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
  677. "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
  678. }
  679. };
  680. /// \brief An interprocedural pass which finds repeated sequences of
  681. /// instructions and replaces them with calls to functions.
  682. ///
  683. /// Each instruction is mapped to an unsigned integer and placed in a string.
  684. /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
  685. /// is then repeatedly queried for repeated sequences of instructions. Each
  686. /// non-overlapping repeated sequence is then placed in its own
  687. /// \p MachineFunction and each instance is then replaced with a call to that
  688. /// function.
  689. struct MachineOutliner : public ModulePass {
  690. static char ID;
  691. StringRef getPassName() const override { return "Machine Outliner"; }
  692. void getAnalysisUsage(AnalysisUsage &AU) const override {
  693. AU.addRequired<MachineModuleInfo>();
  694. AU.addPreserved<MachineModuleInfo>();
  695. AU.setPreservesAll();
  696. ModulePass::getAnalysisUsage(AU);
  697. }
  698. MachineOutliner() : ModulePass(ID) {
  699. initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
  700. }
  701. /// \brief Replace the sequences of instructions represented by the
  702. /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
  703. /// described in \p FunctionList.
  704. ///
  705. /// \param M The module we are outlining from.
  706. /// \param CandidateList A list of candidates to be outlined.
  707. /// \param FunctionList A list of functions to be inserted into the module.
  708. /// \param Mapper Contains the instruction mappings for the module.
  709. bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
  710. std::vector<OutlinedFunction> &FunctionList,
  711. InstructionMapper &Mapper);
  712. /// Creates a function for \p OF and inserts it into the module.
  713. MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
  714. InstructionMapper &Mapper);
  715. /// Find potential outlining candidates and store them in \p CandidateList.
  716. ///
  717. /// For each type of potential candidate, also build an \p OutlinedFunction
  718. /// struct containing the information to build the function for that
  719. /// candidate.
  720. ///
  721. /// \param[out] CandidateList Filled with outlining candidates for the module.
  722. /// \param[out] FunctionList Filled with functions corresponding to each type
  723. /// of \p Candidate.
  724. /// \param ST The suffix tree for the module.
  725. /// \param TII TargetInstrInfo for the module.
  726. ///
  727. /// \returns The length of the longest candidate found. 0 if there are none.
  728. unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
  729. std::vector<OutlinedFunction> &FunctionList,
  730. SuffixTree &ST,
  731. InstructionMapper &Mapper,
  732. const TargetInstrInfo &TII);
  733. /// \brief Remove any overlapping candidates that weren't handled by the
  734. /// suffix tree's pruning method.
  735. ///
  736. /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
  737. /// If a short candidate is chosen for outlining, then a longer candidate
  738. /// which has that short candidate as a suffix is chosen, the tree's pruning
  739. /// method will not find it. Thus, we need to prune before outlining as well.
  740. ///
  741. /// \param[in,out] CandidateList A list of outlining candidates.
  742. /// \param[in,out] FunctionList A list of functions to be outlined.
  743. /// \param MaxCandidateLen The length of the longest candidate.
  744. /// \param TII TargetInstrInfo for the module.
  745. void pruneOverlaps(std::vector<Candidate> &CandidateList,
  746. std::vector<OutlinedFunction> &FunctionList,
  747. unsigned MaxCandidateLen,
  748. const TargetInstrInfo &TII);
  749. /// Construct a suffix tree on the instructions in \p M and outline repeated
  750. /// strings from that tree.
  751. bool runOnModule(Module &M) override;
  752. };
  753. } // Anonymous namespace.
  754. char MachineOutliner::ID = 0;
  755. namespace llvm {
  756. ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); }
  757. }
  758. INITIALIZE_PASS(MachineOutliner, "machine-outliner",
  759. "Machine Function Outliner", false, false)
  760. void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
  761. std::vector<OutlinedFunction> &FunctionList,
  762. unsigned MaxCandidateLen,
  763. const TargetInstrInfo &TII) {
  764. // TODO: Experiment with interval trees or other interval-checking structures
  765. // to lower the time complexity of this function.
  766. // TODO: Can we do better than the simple greedy choice?
  767. // Check for overlaps in the range.
  768. // This is O(MaxCandidateLen * CandidateList.size()).
  769. for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
  770. It++) {
  771. Candidate &C1 = *It;
  772. OutlinedFunction &F1 = FunctionList[C1.FunctionIdx];
  773. // If we removed this candidate, skip it.
  774. if (!C1.InCandidateList)
  775. continue;
  776. // Is it still worth it to outline C1?
  777. if (F1.Benefit < 1 || F1.OccurrenceCount < 2) {
  778. assert(F1.OccurrenceCount > 0 &&
  779. "Can't remove OutlinedFunction with no occurrences!");
  780. F1.OccurrenceCount--;
  781. C1.InCandidateList = false;
  782. continue;
  783. }
  784. // The minimum start index of any candidate that could overlap with this
  785. // one.
  786. unsigned FarthestPossibleIdx = 0;
  787. // Either the index is 0, or it's at most MaxCandidateLen indices away.
  788. if (C1.StartIdx > MaxCandidateLen)
  789. FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen;
  790. // Compare against the candidates in the list that start at at most
  791. // FarthestPossibleIdx indices away from C1. There are at most
  792. // MaxCandidateLen of these.
  793. for (auto Sit = It + 1; Sit != Et; Sit++) {
  794. Candidate &C2 = *Sit;
  795. OutlinedFunction &F2 = FunctionList[C2.FunctionIdx];
  796. // Is this candidate too far away to overlap?
  797. if (C2.StartIdx < FarthestPossibleIdx)
  798. break;
  799. // Did we already remove this candidate in a previous step?
  800. if (!C2.InCandidateList)
  801. continue;
  802. // Is the function beneficial to outline?
  803. if (F2.OccurrenceCount < 2 || F2.Benefit < 1) {
  804. // If not, remove this candidate and move to the next one.
  805. assert(F2.OccurrenceCount > 0 &&
  806. "Can't remove OutlinedFunction with no occurrences!");
  807. F2.OccurrenceCount--;
  808. C2.InCandidateList = false;
  809. continue;
  810. }
  811. size_t C2End = C2.StartIdx + C2.Len - 1;
  812. // Do C1 and C2 overlap?
  813. //
  814. // Not overlapping:
  815. // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
  816. //
  817. // We sorted our candidate list so C2Start <= C1Start. We know that
  818. // C2End > C2Start since each candidate has length >= 2. Therefore, all we
  819. // have to check is C2End < C2Start to see if we overlap.
  820. if (C2End < C1.StartIdx)
  821. continue;
  822. // C1 and C2 overlap.
  823. // We need to choose the better of the two.
  824. //
  825. // Approximate this by picking the one which would have saved us the
  826. // most instructions before any pruning.
  827. if (C1.Benefit >= C2.Benefit) {
  828. // C1 is better, so remove C2 and update C2's OutlinedFunction to
  829. // reflect the removal.
  830. assert(F2.OccurrenceCount > 0 &&
  831. "Can't remove OutlinedFunction with no occurrences!");
  832. F2.OccurrenceCount--;
  833. F2.Benefit = TII.getOutliningBenefit(F2.Sequence.size(),
  834. F2.OccurrenceCount,
  835. F2.IsTailCall
  836. );
  837. C2.InCandidateList = false;
  838. DEBUG (
  839. dbgs() << "- Removed C2. \n";
  840. dbgs() << "--- Num fns left for C2: " << F2.OccurrenceCount << "\n";
  841. dbgs() << "--- C2's benefit: " << F2.Benefit << "\n";
  842. );
  843. } else {
  844. // C2 is better, so remove C1 and update C1's OutlinedFunction to
  845. // reflect the removal.
  846. assert(F1.OccurrenceCount > 0 &&
  847. "Can't remove OutlinedFunction with no occurrences!");
  848. F1.OccurrenceCount--;
  849. F1.Benefit = TII.getOutliningBenefit(F1.Sequence.size(),
  850. F1.OccurrenceCount,
  851. F1.IsTailCall
  852. );
  853. C1.InCandidateList = false;
  854. DEBUG (
  855. dbgs() << "- Removed C1. \n";
  856. dbgs() << "--- Num fns left for C1: " << F1.OccurrenceCount << "\n";
  857. dbgs() << "--- C1's benefit: " << F1.Benefit << "\n";
  858. );
  859. // C1 is out, so we don't have to compare it against anyone else.
  860. break;
  861. }
  862. }
  863. }
  864. }
  865. unsigned
  866. MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
  867. std::vector<OutlinedFunction> &FunctionList,
  868. SuffixTree &ST,
  869. InstructionMapper &Mapper,
  870. const TargetInstrInfo &TII) {
  871. std::vector<unsigned> CandidateSequence; // Current outlining candidate.
  872. size_t MaxCandidateLen = 0; // Length of the longest candidate.
  873. // Function for maximizing query in the suffix tree.
  874. // This allows us to define more fine-grained types of things to outline in
  875. // the target without putting target-specific info in the suffix tree.
  876. auto BenefitFn = [&TII, &Mapper](const SuffixTreeNode &Curr,
  877. size_t StringLen, unsigned EndVal) {
  878. // The root represents the empty string.
  879. if (Curr.isRoot())
  880. return 0u;
  881. // Is this long enough to outline?
  882. // TODO: Let the target decide how "long" a string is in terms of the sizes
  883. // of the instructions in the string. For example, if a call instruction
  884. // is smaller than a one instruction string, we should outline that string.
  885. if (StringLen < 2)
  886. return 0u;
  887. size_t Occurrences = Curr.OccurrenceCount;
  888. // Anything we want to outline has to appear at least twice.
  889. if (Occurrences < 2)
  890. return 0u;
  891. // Check if the last instruction in the sequence is a return.
  892. MachineInstr *LastInstr =
  893. Mapper.IntegerInstructionMap[EndVal];
  894. assert(LastInstr && "Last instruction in sequence was unmapped!");
  895. // The only way a terminator could be mapped as legal is if it was safe to
  896. // tail call.
  897. bool IsTailCall = LastInstr->isTerminator();
  898. return TII.getOutliningBenefit(StringLen, Occurrences, IsTailCall);
  899. };
  900. MaxCandidateLen = ST.findCandidates(CandidateList, FunctionList, BenefitFn);
  901. for (auto &OF : FunctionList)
  902. OF.IsTailCall = Mapper.
  903. IntegerInstructionMap[OF.Sequence.back()]->isTerminator();
  904. // Sort the candidates in decending order. This will simplify the outlining
  905. // process when we have to remove the candidates from the mapping by
  906. // allowing us to cut them out without keeping track of an offset.
  907. std::stable_sort(CandidateList.begin(), CandidateList.end());
  908. return MaxCandidateLen;
  909. }
  910. MachineFunction *
  911. MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
  912. InstructionMapper &Mapper) {
  913. // Create the function name. This should be unique. For now, just hash the
  914. // module name and include it in the function name plus the number of this
  915. // function.
  916. std::ostringstream NameStream;
  917. NameStream << "OUTLINED_FUNCTION" << "_" << OF.Name;
  918. // Create the function using an IR-level function.
  919. LLVMContext &C = M.getContext();
  920. Function *F = dyn_cast<Function>(
  921. M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
  922. assert(F && "Function was null!");
  923. // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
  924. // which gives us better results when we outline from linkonceodr functions.
  925. F->setLinkage(GlobalValue::PrivateLinkage);
  926. F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
  927. BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
  928. IRBuilder<> Builder(EntryBB);
  929. Builder.CreateRetVoid();
  930. MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
  931. MachineFunction &MF = MMI.getMachineFunction(*F);
  932. MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
  933. const TargetSubtargetInfo &STI = MF.getSubtarget();
  934. const TargetInstrInfo &TII = *STI.getInstrInfo();
  935. // Insert the new function into the module.
  936. MF.insert(MF.begin(), &MBB);
  937. TII.insertOutlinerPrologue(MBB, MF, OF.IsTailCall);
  938. // Copy over the instructions for the function using the integer mappings in
  939. // its sequence.
  940. for (unsigned Str : OF.Sequence) {
  941. MachineInstr *NewMI =
  942. MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
  943. NewMI->dropMemRefs();
  944. // Don't keep debug information for outlined instructions.
  945. // FIXME: This means outlined functions are currently undebuggable.
  946. NewMI->setDebugLoc(DebugLoc());
  947. MBB.insert(MBB.end(), NewMI);
  948. }
  949. TII.insertOutlinerEpilogue(MBB, MF, OF.IsTailCall);
  950. return &MF;
  951. }
  952. bool MachineOutliner::outline(Module &M,
  953. const ArrayRef<Candidate> &CandidateList,
  954. std::vector<OutlinedFunction> &FunctionList,
  955. InstructionMapper &Mapper) {
  956. bool OutlinedSomething = false;
  957. // Replace the candidates with calls to their respective outlined functions.
  958. for (const Candidate &C : CandidateList) {
  959. // Was the candidate removed during pruneOverlaps?
  960. if (!C.InCandidateList)
  961. continue;
  962. // If not, then look at its OutlinedFunction.
  963. OutlinedFunction &OF = FunctionList[C.FunctionIdx];
  964. // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
  965. if (OF.OccurrenceCount < 2 || OF.Benefit < 1)
  966. continue;
  967. // If not, then outline it.
  968. assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
  969. MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent();
  970. MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx];
  971. unsigned EndIdx = C.StartIdx + C.Len - 1;
  972. assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
  973. MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
  974. assert(EndIt != MBB->end() && "EndIt out of bounds!");
  975. EndIt++; // Erase needs one past the end index.
  976. // Does this candidate have a function yet?
  977. if (!OF.MF) {
  978. OF.MF = createOutlinedFunction(M, OF, Mapper);
  979. FunctionsCreated++;
  980. }
  981. MachineFunction *MF = OF.MF;
  982. const TargetSubtargetInfo &STI = MF->getSubtarget();
  983. const TargetInstrInfo &TII = *STI.getInstrInfo();
  984. // Insert a call to the new function and erase the old sequence.
  985. TII.insertOutlinedCall(M, *MBB, StartIt, *MF, OF.IsTailCall);
  986. StartIt = Mapper.InstrList[C.StartIdx];
  987. MBB->erase(StartIt, EndIt);
  988. OutlinedSomething = true;
  989. // Statistics.
  990. NumOutlined++;
  991. }
  992. DEBUG (
  993. dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";
  994. );
  995. return OutlinedSomething;
  996. }
  997. bool MachineOutliner::runOnModule(Module &M) {
  998. // Is there anything in the module at all?
  999. if (M.empty())
  1000. return false;
  1001. MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
  1002. const TargetSubtargetInfo &STI = MMI.getMachineFunction(*M.begin())
  1003. .getSubtarget();
  1004. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  1005. const TargetInstrInfo *TII = STI.getInstrInfo();
  1006. InstructionMapper Mapper;
  1007. // Build instruction mappings for each function in the module.
  1008. for (Function &F : M) {
  1009. MachineFunction &MF = MMI.getMachineFunction(F);
  1010. // Is the function empty? Safe to outline from?
  1011. if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF))
  1012. continue;
  1013. // If it is, look at each MachineBasicBlock in the function.
  1014. for (MachineBasicBlock &MBB : MF) {
  1015. // Is there anything in MBB?
  1016. if (MBB.empty())
  1017. continue;
  1018. // If yes, map it.
  1019. Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
  1020. }
  1021. }
  1022. // Construct a suffix tree, use it to find candidates, and then outline them.
  1023. SuffixTree ST(Mapper.UnsignedVec);
  1024. std::vector<Candidate> CandidateList;
  1025. std::vector<OutlinedFunction> FunctionList;
  1026. // Find all of the outlining candidates.
  1027. unsigned MaxCandidateLen =
  1028. buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
  1029. // Remove candidates that overlap with other candidates.
  1030. pruneOverlaps(CandidateList, FunctionList, MaxCandidateLen, *TII);
  1031. // Outline each of the candidates and return true if something was outlined.
  1032. return outline(M, CandidateList, FunctionList, Mapper);
  1033. }