1 //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// Replaces repeated sequences of instructions with function calls.
12 ///
13 /// This works by placing every instruction from every basic block in a
14 /// suffix tree, and repeatedly querying that tree for repeated sequences of
15 /// instructions. If a sequence of instructions appears often, then it ought
16 /// to be beneficial to pull out into a function.
17 ///
18 /// The MachineOutliner communicates with a given target using hooks defined in
19 /// TargetInstrInfo.h. The target supplies the outliner with information on how
20 /// a specific sequence of instructions should be outlined. This information
21 /// is used to deduce the number of instructions necessary to
22 ///
23 /// * Create an outlined function
24 /// * Call that outlined function
25 ///
26 /// Targets must implement
27 ///   * getOutliningCandidateInfo
28 ///   * insertOutlinerEpilogue
29 ///   * insertOutlinedCall
30 ///   * insertOutlinerPrologue
31 ///   * isFunctionSafeToOutlineFrom
32 ///
33 /// in order to make use of the MachineOutliner.
34 ///
35 /// This was originally presented at the 2016 LLVM Developers' Meeting in the
36 /// talk "Reducing Code Size Using Outlining". For a high-level overview of
37 /// how this pass works, the talk is available on YouTube at
38 ///
39 /// https://www.youtube.com/watch?v=yorld-WSOeU
40 ///
41 /// The slides for the talk are available at
42 ///
43 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
44 ///
45 /// The talk provides an overview of how the outliner finds candidates and
46 /// ultimately outlines them. It describes how the main data structure for this
47 /// pass, the suffix tree, is queried and purged for candidates. It also gives
48 /// a simplified suffix tree construction algorithm for suffix trees based off
49 /// of the algorithm actually used here, Ukkonen's algorithm.
50 ///
51 /// For the original RFC for this pass, please see
52 ///
53 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
54 ///
55 /// For more information on the suffix tree data structure, please see
56 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
57 ///
58 //===----------------------------------------------------------------------===//
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/Twine.h"
62 #include "llvm/CodeGen/MachineFrameInfo.h"
63 #include "llvm/CodeGen/MachineFunction.h"
64 #include "llvm/CodeGen/MachineInstrBuilder.h"
65 #include "llvm/CodeGen/MachineModuleInfo.h"
66 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
67 #include "llvm/CodeGen/Passes.h"
68 #include "llvm/IR/IRBuilder.h"
69 #include "llvm/Support/Allocator.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Target/TargetInstrInfo.h"
73 #include "llvm/Target/TargetMachine.h"
74 #include "llvm/Target/TargetRegisterInfo.h"
75 #include "llvm/Target/TargetSubtargetInfo.h"
76 #include <functional>
77 #include <map>
78 #include <sstream>
79 #include <tuple>
80 #include <vector>
81 
82 #define DEBUG_TYPE "machine-outliner"
83 
84 using namespace llvm;
85 using namespace ore;
86 
87 STATISTIC(NumOutlined, "Number of candidates outlined");
88 STATISTIC(FunctionsCreated, "Number of functions created");
89 
90 namespace {
91 
92 /// \brief An individual sequence of instructions to be replaced with a call to
93 /// an outlined function.
94 struct Candidate {
95 private:
96   /// The start index of this \p Candidate in the instruction list.
97   unsigned StartIdx;
98 
99   /// The number of instructions in this \p Candidate.
100   unsigned Len;
101 
102 public:
103   /// Set to false if the candidate overlapped with another candidate.
104   bool InCandidateList = true;
105 
106   /// \brief The index of this \p Candidate's \p OutlinedFunction in the list of
107   /// \p OutlinedFunctions.
108   unsigned FunctionIdx;
109 
110   /// Contains all target-specific information for this \p Candidate.
111   TargetInstrInfo::MachineOutlinerInfo MInfo;
112 
113   /// Return the number of instructions in this Candidate.
114   unsigned length() const { return Len; }
115 
116   /// Return the start index of this candidate.
117   unsigned startIdx() const { return StartIdx; }
118 
119   // Return the end index of this candidate.
120   unsigned endIdx() const { return StartIdx + Len - 1; }
121 
122   /// \brief The number of instructions that would be saved by outlining every
123   /// candidate of this type.
124   ///
125   /// This is a fixed value which is not updated during the candidate pruning
126   /// process. It is only used for deciding which candidate to keep if two
127   /// candidates overlap. The true benefit is stored in the OutlinedFunction
128   /// for some given candidate.
129   unsigned Benefit = 0;
130 
131   Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx)
132       : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
133 
134   Candidate() {}
135 
136   /// \brief Used to ensure that \p Candidates are outlined in an order that
137   /// preserves the start and end indices of other \p Candidates.
138   bool operator<(const Candidate &RHS) const {
139     return startIdx() > RHS.startIdx();
140   }
141 };
142 
143 /// \brief The information necessary to create an outlined function for some
144 /// class of candidate.
145 struct OutlinedFunction {
146 
147 private:
148   /// The number of candidates for this \p OutlinedFunction.
149   unsigned OccurrenceCount = 0;
150 
151 public:
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     for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
725          It++) {
726 
727       // Keep track of where this instruction is in the module.
728       switch (TII.getOutliningType(*It)) {
729       case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
730         mapToIllegalUnsigned(It);
731         break;
732 
733       case TargetInstrInfo::MachineOutlinerInstrType::Legal:
734         mapToLegalUnsigned(It);
735         break;
736 
737       case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
738         break;
739       }
740     }
741 
742     // After we're done every insertion, uniquely terminate this part of the
743     // "string". This makes sure we won't match across basic block or function
744     // boundaries since the "end" is encoded uniquely and thus appears in no
745     // repeated substring.
746     InstrList.push_back(MBB.end());
747     UnsignedVec.push_back(IllegalInstrNumber);
748     IllegalInstrNumber--;
749   }
750 
751   InstructionMapper() {
752     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
753     // changed.
754     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
755            "DenseMapInfo<unsigned>'s empty key isn't -1!");
756     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
757            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
758   }
759 };
760 
761 /// \brief An interprocedural pass which finds repeated sequences of
762 /// instructions and replaces them with calls to functions.
763 ///
764 /// Each instruction is mapped to an unsigned integer and placed in a string.
765 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
766 /// is then repeatedly queried for repeated sequences of instructions. Each
767 /// non-overlapping repeated sequence is then placed in its own
768 /// \p MachineFunction and each instance is then replaced with a call to that
769 /// function.
770 struct MachineOutliner : public ModulePass {
771 
772   static char ID;
773 
774   /// \brief Set to true if the outliner should consider functions with
775   /// linkonceodr linkage.
776   bool OutlineFromLinkOnceODRs = false;
777 
778   StringRef getPassName() const override { return "Machine Outliner"; }
779 
780   void getAnalysisUsage(AnalysisUsage &AU) const override {
781     AU.addRequired<MachineModuleInfo>();
782     AU.addPreserved<MachineModuleInfo>();
783     AU.setPreservesAll();
784     ModulePass::getAnalysisUsage(AU);
785   }
786 
787   MachineOutliner(bool OutlineFromLinkOnceODRs = false)
788       : ModulePass(ID), OutlineFromLinkOnceODRs(OutlineFromLinkOnceODRs) {
789     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
790   }
791 
792   /// Find all repeated substrings that satisfy the outlining cost model.
793   ///
794   /// If a substring appears at least twice, then it must be represented by
795   /// an internal node which appears in at least two suffixes. Each suffix is
796   /// represented by a leaf node. To do this, we visit each internal node in
797   /// the tree, using the leaf children of each internal node. If an internal
798   /// node represents a beneficial substring, then we use each of its leaf
799   /// children to find the locations of its substring.
800   ///
801   /// \param ST A suffix tree to query.
802   /// \param TII TargetInstrInfo for the target.
803   /// \param Mapper Contains outlining mapping information.
804   /// \param[out] CandidateList Filled with candidates representing each
805   /// beneficial substring.
806   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
807   /// type of candidate.
808   ///
809   /// \returns The length of the longest candidate found.
810   unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
811                           InstructionMapper &Mapper,
812                           std::vector<Candidate> &CandidateList,
813                           std::vector<OutlinedFunction> &FunctionList);
814 
815   /// \brief Replace the sequences of instructions represented by the
816   /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
817   /// described in \p FunctionList.
818   ///
819   /// \param M The module we are outlining from.
820   /// \param CandidateList A list of candidates to be outlined.
821   /// \param FunctionList A list of functions to be inserted into the module.
822   /// \param Mapper Contains the instruction mappings for the module.
823   bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
824                std::vector<OutlinedFunction> &FunctionList,
825                InstructionMapper &Mapper);
826 
827   /// Creates a function for \p OF and inserts it into the module.
828   MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
829                                           InstructionMapper &Mapper);
830 
831   /// Find potential outlining candidates and store them in \p CandidateList.
832   ///
833   /// For each type of potential candidate, also build an \p OutlinedFunction
834   /// struct containing the information to build the function for that
835   /// candidate.
836   ///
837   /// \param[out] CandidateList Filled with outlining candidates for the module.
838   /// \param[out] FunctionList Filled with functions corresponding to each type
839   /// of \p Candidate.
840   /// \param ST The suffix tree for the module.
841   /// \param TII TargetInstrInfo for the module.
842   ///
843   /// \returns The length of the longest candidate found. 0 if there are none.
844   unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
845                               std::vector<OutlinedFunction> &FunctionList,
846                               SuffixTree &ST, InstructionMapper &Mapper,
847                               const TargetInstrInfo &TII);
848 
849   /// Helper function for pruneOverlaps.
850   /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
851   void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
852 
853   /// \brief Remove any overlapping candidates that weren't handled by the
854   /// suffix tree's pruning method.
855   ///
856   /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
857   /// If a short candidate is chosen for outlining, then a longer candidate
858   /// which has that short candidate as a suffix is chosen, the tree's pruning
859   /// method will not find it. Thus, we need to prune before outlining as well.
860   ///
861   /// \param[in,out] CandidateList A list of outlining candidates.
862   /// \param[in,out] FunctionList A list of functions to be outlined.
863   /// \param Mapper Contains instruction mapping info for outlining.
864   /// \param MaxCandidateLen The length of the longest candidate.
865   /// \param TII TargetInstrInfo for the module.
866   void pruneOverlaps(std::vector<Candidate> &CandidateList,
867                      std::vector<OutlinedFunction> &FunctionList,
868                      InstructionMapper &Mapper, unsigned MaxCandidateLen,
869                      const TargetInstrInfo &TII);
870 
871   /// Construct a suffix tree on the instructions in \p M and outline repeated
872   /// strings from that tree.
873   bool runOnModule(Module &M) override;
874 };
875 
876 } // Anonymous namespace.
877 
878 char MachineOutliner::ID = 0;
879 
880 namespace llvm {
881 ModulePass *createMachineOutlinerPass(bool OutlineFromLinkOnceODRs) {
882   return new MachineOutliner(OutlineFromLinkOnceODRs);
883 }
884 
885 } // namespace llvm
886 
887 INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
888                 false)
889 
890 unsigned
891 MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
892                                 InstructionMapper &Mapper,
893                                 std::vector<Candidate> &CandidateList,
894                                 std::vector<OutlinedFunction> &FunctionList) {
895   CandidateList.clear();
896   FunctionList.clear();
897   unsigned MaxLen = 0;
898 
899   // FIXME: Visit internal nodes instead of leaves.
900   for (SuffixTreeNode *Leaf : ST.LeafVector) {
901     assert(Leaf && "Leaves in LeafVector cannot be null!");
902     if (!Leaf->IsInTree)
903       continue;
904 
905     assert(Leaf->Parent && "All leaves must have parents!");
906     SuffixTreeNode &Parent = *(Leaf->Parent);
907 
908     // If it doesn't appear enough, or we already outlined from it, skip it.
909     if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
910       continue;
911 
912     // Figure out if this candidate is beneficial.
913     unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
914 
915     // Too short to be beneficial; skip it.
916     // FIXME: This isn't necessarily true for, say, X86. If we factor in
917     // instruction lengths we need more information than this.
918     if (StringLen < 2)
919       continue;
920 
921     // If this is a beneficial class of candidate, then every one is stored in
922     // this vector.
923     std::vector<Candidate> CandidatesForRepeatedSeq;
924 
925     // Describes the start and end point of each candidate. This allows the
926     // target to infer some information about each occurrence of each repeated
927     // sequence.
928     // FIXME: CandidatesForRepeatedSeq and this should be combined.
929     std::vector<
930         std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
931         RepeatedSequenceLocs;
932 
933     // Figure out the call overhead for each instance of the sequence.
934     for (auto &ChildPair : Parent.Children) {
935       SuffixTreeNode *M = ChildPair.second;
936 
937       if (M && M->IsInTree && M->isLeaf()) {
938         // Each sequence is over [StartIt, EndIt].
939         MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx];
940         MachineBasicBlock::iterator EndIt =
941             Mapper.InstrList[M->SuffixIdx + StringLen - 1];
942 
943         CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen,
944                                               FunctionList.size());
945         RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
946 
947         // Never visit this leaf again.
948         M->IsInTree = false;
949       }
950     }
951 
952     // We've found something we might want to outline.
953     // Create an OutlinedFunction to store it and check if it'd be beneficial
954     // to outline.
955     TargetInstrInfo::MachineOutlinerInfo MInfo =
956         TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
957     std::vector<unsigned> Seq;
958     for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
959       Seq.push_back(ST.Str[i]);
960     OutlinedFunction OF(FunctionList.size(), Parent.OccurrenceCount, Seq,
961                         MInfo);
962     unsigned Benefit = OF.getBenefit();
963 
964     // Is it better to outline this candidate than not?
965     if (Benefit < 1) {
966       // Outlining this candidate would take more instructions than not
967       // outlining.
968       // Emit a remark explaining why we didn't outline this candidate.
969       std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
970           RepeatedSequenceLocs[0];
971       MachineOptimizationRemarkEmitter MORE(
972           *(C.first->getParent()->getParent()), nullptr);
973       MORE.emit([&]() {
974         MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
975                                           C.first->getDebugLoc(),
976                                           C.first->getParent());
977         R << "Did not outline " << NV("Length", StringLen) << " instructions"
978           << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
979           << " locations."
980           << " Instructions from outlining all occurrences ("
981           << NV("OutliningCost", OF.getOutliningCost()) << ")"
982           << " >= Unoutlined instruction count ("
983           << NV("NotOutliningCost", StringLen * OF.getOccurrenceCount()) << ")"
984           << " (Also found at: ";
985 
986         // Tell the user the other places the candidate was found.
987         for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
988           R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
989                   RepeatedSequenceLocs[i].first->getDebugLoc());
990           if (i != e - 1)
991             R << ", ";
992         }
993 
994         R << ")";
995         return R;
996       });
997 
998       // Move to the next candidate.
999       continue;
1000     }
1001 
1002     if (StringLen > MaxLen)
1003       MaxLen = StringLen;
1004 
1005     // At this point, the candidate class is seen as beneficial. Set their
1006     // benefit values and save them in the candidate list.
1007     for (Candidate &C : CandidatesForRepeatedSeq) {
1008       C.Benefit = Benefit;
1009       C.MInfo = MInfo;
1010       CandidateList.push_back(C);
1011     }
1012 
1013     FunctionList.push_back(OF);
1014 
1015     // Move to the next function.
1016     Parent.IsInTree = false;
1017   }
1018 
1019   return MaxLen;
1020 }
1021 
1022 // Remove C from the candidate space, and update its OutlinedFunction.
1023 void MachineOutliner::prune(Candidate &C,
1024                             std::vector<OutlinedFunction> &FunctionList) {
1025   // Get the OutlinedFunction associated with this Candidate.
1026   OutlinedFunction &F = FunctionList[C.FunctionIdx];
1027 
1028   // Update C's associated function's occurrence count.
1029   F.decrement();
1030 
1031   // Remove C from the CandidateList.
1032   C.InCandidateList = false;
1033 
1034   DEBUG(dbgs() << "- Removed a Candidate \n";
1035         dbgs() << "--- Num fns left for candidate: " << F.getOccurrenceCount()
1036                << "\n";
1037         dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1038                << "\n";);
1039 }
1040 
1041 void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
1042                                     std::vector<OutlinedFunction> &FunctionList,
1043                                     InstructionMapper &Mapper,
1044                                     unsigned MaxCandidateLen,
1045                                     const TargetInstrInfo &TII) {
1046 
1047   // Return true if this candidate became unbeneficial for outlining in a
1048   // previous step.
1049   auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
1050 
1051     // Check if the candidate was removed in a previous step.
1052     if (!C.InCandidateList)
1053       return true;
1054 
1055     // C must be alive. Check if we should remove it.
1056     if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1057       prune(C, FunctionList);
1058       return true;
1059     }
1060 
1061     // C is in the list, and F is still beneficial.
1062     return false;
1063   };
1064 
1065   // TODO: Experiment with interval trees or other interval-checking structures
1066   // to lower the time complexity of this function.
1067   // TODO: Can we do better than the simple greedy choice?
1068   // Check for overlaps in the range.
1069   // This is O(MaxCandidateLen * CandidateList.size()).
1070   for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1071        It++) {
1072     Candidate &C1 = *It;
1073 
1074     // If C1 was already pruned, or its function is no longer beneficial for
1075     // outlining, move to the next candidate.
1076     if (ShouldSkipCandidate(C1))
1077       continue;
1078 
1079     // The minimum start index of any candidate that could overlap with this
1080     // one.
1081     unsigned FarthestPossibleIdx = 0;
1082 
1083     // Either the index is 0, or it's at most MaxCandidateLen indices away.
1084     if (C1.startIdx() > MaxCandidateLen)
1085       FarthestPossibleIdx = C1.startIdx() - MaxCandidateLen;
1086 
1087     // Compare against the candidates in the list that start at at most
1088     // FarthestPossibleIdx indices away from C1. There are at most
1089     // MaxCandidateLen of these.
1090     for (auto Sit = It + 1; Sit != Et; Sit++) {
1091       Candidate &C2 = *Sit;
1092 
1093       // Is this candidate too far away to overlap?
1094       if (C2.startIdx() < FarthestPossibleIdx)
1095         break;
1096 
1097       // If C2 was already pruned, or its function is no longer beneficial for
1098       // outlining, move to the next candidate.
1099       if (ShouldSkipCandidate(C2))
1100         continue;
1101 
1102       // Do C1 and C2 overlap?
1103       //
1104       // Not overlapping:
1105       // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1106       //
1107       // We sorted our candidate list so C2Start <= C1Start. We know that
1108       // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1109       // have to check is C2End < C2Start to see if we overlap.
1110       if (C2.endIdx() < C1.startIdx())
1111         continue;
1112 
1113       // C1 and C2 overlap.
1114       // We need to choose the better of the two.
1115       //
1116       // Approximate this by picking the one which would have saved us the
1117       // most instructions before any pruning.
1118 
1119       // Is C2 a better candidate?
1120       if (C2.Benefit > C1.Benefit) {
1121         // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1122         // against anything anymore, so break.
1123         prune(C1, FunctionList);
1124         break;
1125       }
1126 
1127       // Prune C2 and move on to the next candidate.
1128       prune(C2, FunctionList);
1129     }
1130   }
1131 }
1132 
1133 unsigned
1134 MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1135                                     std::vector<OutlinedFunction> &FunctionList,
1136                                     SuffixTree &ST, InstructionMapper &Mapper,
1137                                     const TargetInstrInfo &TII) {
1138 
1139   std::vector<unsigned> CandidateSequence; // Current outlining candidate.
1140   unsigned MaxCandidateLen = 0;            // Length of the longest candidate.
1141 
1142   MaxCandidateLen =
1143       findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
1144 
1145   // Sort the candidates in decending order. This will simplify the outlining
1146   // process when we have to remove the candidates from the mapping by
1147   // allowing us to cut them out without keeping track of an offset.
1148   std::stable_sort(CandidateList.begin(), CandidateList.end());
1149 
1150   return MaxCandidateLen;
1151 }
1152 
1153 MachineFunction *
1154 MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
1155                                         InstructionMapper &Mapper) {
1156 
1157   // Create the function name. This should be unique. For now, just hash the
1158   // module name and include it in the function name plus the number of this
1159   // function.
1160   std::ostringstream NameStream;
1161   NameStream << "OUTLINED_FUNCTION_" << OF.Name;
1162 
1163   // Create the function using an IR-level function.
1164   LLVMContext &C = M.getContext();
1165   Function *F = dyn_cast<Function>(
1166       M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
1167   assert(F && "Function was null!");
1168 
1169   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1170   // which gives us better results when we outline from linkonceodr functions.
1171   F->setLinkage(GlobalValue::PrivateLinkage);
1172   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1173 
1174   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1175   IRBuilder<> Builder(EntryBB);
1176   Builder.CreateRetVoid();
1177 
1178   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1179   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
1180   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1181   const TargetSubtargetInfo &STI = MF.getSubtarget();
1182   const TargetInstrInfo &TII = *STI.getInstrInfo();
1183 
1184   // Insert the new function into the module.
1185   MF.insert(MF.begin(), &MBB);
1186 
1187   TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
1188 
1189   // Copy over the instructions for the function using the integer mappings in
1190   // its sequence.
1191   for (unsigned Str : OF.Sequence) {
1192     MachineInstr *NewMI =
1193         MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1194     NewMI->dropMemRefs();
1195 
1196     // Don't keep debug information for outlined instructions.
1197     // FIXME: This means outlined functions are currently undebuggable.
1198     NewMI->setDebugLoc(DebugLoc());
1199     MBB.insert(MBB.end(), NewMI);
1200   }
1201 
1202   TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
1203 
1204   return &MF;
1205 }
1206 
1207 bool MachineOutliner::outline(Module &M,
1208                               const ArrayRef<Candidate> &CandidateList,
1209                               std::vector<OutlinedFunction> &FunctionList,
1210                               InstructionMapper &Mapper) {
1211 
1212   bool OutlinedSomething = false;
1213   // Replace the candidates with calls to their respective outlined functions.
1214   for (const Candidate &C : CandidateList) {
1215 
1216     // Was the candidate removed during pruneOverlaps?
1217     if (!C.InCandidateList)
1218       continue;
1219 
1220     // If not, then look at its OutlinedFunction.
1221     OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1222 
1223     // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
1224     if (OF.getBenefit() < 1)
1225       continue;
1226 
1227     // If not, then outline it.
1228     assert(C.startIdx() < Mapper.InstrList.size() &&
1229            "Candidate out of bounds!");
1230     MachineBasicBlock *MBB = (*Mapper.InstrList[C.startIdx()]).getParent();
1231     MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.startIdx()];
1232     unsigned EndIdx = C.endIdx();
1233 
1234     assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1235     MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1236     assert(EndIt != MBB->end() && "EndIt out of bounds!");
1237 
1238     EndIt++; // Erase needs one past the end index.
1239 
1240     // Does this candidate have a function yet?
1241     if (!OF.MF) {
1242       OF.MF = createOutlinedFunction(M, OF, Mapper);
1243       FunctionsCreated++;
1244     }
1245 
1246     MachineFunction *MF = OF.MF;
1247     const TargetSubtargetInfo &STI = MF->getSubtarget();
1248     const TargetInstrInfo &TII = *STI.getInstrInfo();
1249 
1250     // Insert a call to the new function and erase the old sequence.
1251     TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
1252     StartIt = Mapper.InstrList[C.startIdx()];
1253     MBB->erase(StartIt, EndIt);
1254 
1255     OutlinedSomething = true;
1256 
1257     // Statistics.
1258     NumOutlined++;
1259   }
1260 
1261   DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
1262 
1263   return OutlinedSomething;
1264 }
1265 
1266 bool MachineOutliner::runOnModule(Module &M) {
1267 
1268   // Is there anything in the module at all?
1269   if (M.empty())
1270     return false;
1271 
1272   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1273   const TargetSubtargetInfo &STI =
1274       MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
1275   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1276   const TargetInstrInfo *TII = STI.getInstrInfo();
1277 
1278   InstructionMapper Mapper;
1279 
1280   // Build instruction mappings for each function in the module.
1281   for (Function &F : M) {
1282     MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
1283 
1284     // Is the function empty? Safe to outline from?
1285     if (F.empty() ||
1286         !TII->isFunctionSafeToOutlineFrom(MF, OutlineFromLinkOnceODRs))
1287       continue;
1288 
1289     // If it is, look at each MachineBasicBlock in the function.
1290     for (MachineBasicBlock &MBB : MF) {
1291 
1292       // Is there anything in MBB?
1293       if (MBB.empty())
1294         continue;
1295 
1296       // If yes, map it.
1297       Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1298     }
1299   }
1300 
1301   // Construct a suffix tree, use it to find candidates, and then outline them.
1302   SuffixTree ST(Mapper.UnsignedVec);
1303   std::vector<Candidate> CandidateList;
1304   std::vector<OutlinedFunction> FunctionList;
1305 
1306   // Find all of the outlining candidates.
1307   unsigned MaxCandidateLen =
1308       buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
1309 
1310   // Remove candidates that overlap with other candidates.
1311   pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
1312 
1313   // Outline each of the candidates and return true if something was outlined.
1314   return outline(M, CandidateList, FunctionList, Mapper);
1315 }
1316