MachineOutliner.cpp 64 KB

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