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