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