MachineOutliner.cpp 48 KB

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