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