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