1596f483aSJessica Paquette //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2596f483aSJessica Paquette //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6596f483aSJessica Paquette //
7596f483aSJessica Paquette //===----------------------------------------------------------------------===//
8596f483aSJessica Paquette ///
9596f483aSJessica Paquette /// \file
10596f483aSJessica Paquette /// Replaces repeated sequences of instructions with function calls.
11596f483aSJessica Paquette ///
12596f483aSJessica Paquette /// This works by placing every instruction from every basic block in a
13596f483aSJessica Paquette /// suffix tree, and repeatedly querying that tree for repeated sequences of
14596f483aSJessica Paquette /// instructions. If a sequence of instructions appears often, then it ought
15596f483aSJessica Paquette /// to be beneficial to pull out into a function.
16596f483aSJessica Paquette ///
174cf187b5SJessica Paquette /// The MachineOutliner communicates with a given target using hooks defined in
184cf187b5SJessica Paquette /// TargetInstrInfo.h. The target supplies the outliner with information on how
194cf187b5SJessica Paquette /// a specific sequence of instructions should be outlined. This information
204cf187b5SJessica Paquette /// is used to deduce the number of instructions necessary to
214cf187b5SJessica Paquette ///
224cf187b5SJessica Paquette /// * Create an outlined function
234cf187b5SJessica Paquette /// * Call that outlined function
244cf187b5SJessica Paquette ///
254cf187b5SJessica Paquette /// Targets must implement
264cf187b5SJessica Paquette ///   * getOutliningCandidateInfo
2732de26d4SJessica Paquette ///   * buildOutlinedFrame
284cf187b5SJessica Paquette ///   * insertOutlinedCall
294cf187b5SJessica Paquette ///   * isFunctionSafeToOutlineFrom
304cf187b5SJessica Paquette ///
314cf187b5SJessica Paquette /// in order to make use of the MachineOutliner.
324cf187b5SJessica Paquette ///
33596f483aSJessica Paquette /// This was originally presented at the 2016 LLVM Developers' Meeting in the
34596f483aSJessica Paquette /// talk "Reducing Code Size Using Outlining". For a high-level overview of
35596f483aSJessica Paquette /// how this pass works, the talk is available on YouTube at
36596f483aSJessica Paquette ///
37596f483aSJessica Paquette /// https://www.youtube.com/watch?v=yorld-WSOeU
38596f483aSJessica Paquette ///
39596f483aSJessica Paquette /// The slides for the talk are available at
40596f483aSJessica Paquette ///
41596f483aSJessica Paquette /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
42596f483aSJessica Paquette ///
43596f483aSJessica Paquette /// The talk provides an overview of how the outliner finds candidates and
44596f483aSJessica Paquette /// ultimately outlines them. It describes how the main data structure for this
45596f483aSJessica Paquette /// pass, the suffix tree, is queried and purged for candidates. It also gives
46596f483aSJessica Paquette /// a simplified suffix tree construction algorithm for suffix trees based off
47596f483aSJessica Paquette /// of the algorithm actually used here, Ukkonen's algorithm.
48596f483aSJessica Paquette ///
49596f483aSJessica Paquette /// For the original RFC for this pass, please see
50596f483aSJessica Paquette ///
51596f483aSJessica Paquette /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
52596f483aSJessica Paquette ///
53596f483aSJessica Paquette /// For more information on the suffix tree data structure, please see
54596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
55596f483aSJessica Paquette ///
56596f483aSJessica Paquette //===----------------------------------------------------------------------===//
57aa087327SJessica Paquette #include "llvm/CodeGen/MachineOutliner.h"
58596f483aSJessica Paquette #include "llvm/ADT/DenseMap.h"
59596f483aSJessica Paquette #include "llvm/ADT/Statistic.h"
60596f483aSJessica Paquette #include "llvm/ADT/Twine.h"
61596f483aSJessica Paquette #include "llvm/CodeGen/MachineFunction.h"
62596f483aSJessica Paquette #include "llvm/CodeGen/MachineModuleInfo.h"
63ffe4abc5SJessica Paquette #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
6482203c41SGeoff Berry #include "llvm/CodeGen/MachineRegisterInfo.h"
65596f483aSJessica Paquette #include "llvm/CodeGen/Passes.h"
663f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
67b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
68729e6869SJessica Paquette #include "llvm/IR/DIBuilder.h"
69596f483aSJessica Paquette #include "llvm/IR/IRBuilder.h"
70a499c3c2SJessica Paquette #include "llvm/IR/Mangler.h"
71596f483aSJessica Paquette #include "llvm/Support/Allocator.h"
721eca23bdSJessica Paquette #include "llvm/Support/CommandLine.h"
73596f483aSJessica Paquette #include "llvm/Support/Debug.h"
74596f483aSJessica Paquette #include "llvm/Support/raw_ostream.h"
75596f483aSJessica Paquette #include <functional>
76596f483aSJessica Paquette #include <tuple>
77596f483aSJessica Paquette #include <vector>
78596f483aSJessica Paquette 
79596f483aSJessica Paquette #define DEBUG_TYPE "machine-outliner"
80596f483aSJessica Paquette 
81596f483aSJessica Paquette using namespace llvm;
82ffe4abc5SJessica Paquette using namespace ore;
83aa087327SJessica Paquette using namespace outliner;
84596f483aSJessica Paquette 
85596f483aSJessica Paquette STATISTIC(NumOutlined, "Number of candidates outlined");
86596f483aSJessica Paquette STATISTIC(FunctionsCreated, "Number of functions created");
87596f483aSJessica Paquette 
881eca23bdSJessica Paquette // Set to true if the user wants the outliner to run on linkonceodr linkage
891eca23bdSJessica Paquette // functions. This is false by default because the linker can dedupe linkonceodr
901eca23bdSJessica Paquette // functions. Since the outliner is confined to a single module (modulo LTO),
911eca23bdSJessica Paquette // this is off by default. It should, however, be the default behaviour in
921eca23bdSJessica Paquette // LTO.
931eca23bdSJessica Paquette static cl::opt<bool> EnableLinkOnceODROutlining(
946b7615aeSPuyan Lotfi     "enable-linkonceodr-outlining", cl::Hidden,
951eca23bdSJessica Paquette     cl::desc("Enable the machine outliner on linkonceodr functions"),
961eca23bdSJessica Paquette     cl::init(false));
971eca23bdSJessica Paquette 
98596f483aSJessica Paquette namespace {
99596f483aSJessica Paquette 
100596f483aSJessica Paquette /// Represents an undefined index in the suffix tree.
1014cf187b5SJessica Paquette const unsigned EmptyIdx = -1;
102596f483aSJessica Paquette 
103596f483aSJessica Paquette /// A node in a suffix tree which represents a substring or suffix.
104596f483aSJessica Paquette ///
105596f483aSJessica Paquette /// Each node has either no children or at least two children, with the root
106596f483aSJessica Paquette /// being a exception in the empty tree.
107596f483aSJessica Paquette ///
108596f483aSJessica Paquette /// Children are represented as a map between unsigned integers and nodes. If
109596f483aSJessica Paquette /// a node N has a child M on unsigned integer k, then the mapping represented
110596f483aSJessica Paquette /// by N is a proper prefix of the mapping represented by M. Note that this,
111596f483aSJessica Paquette /// although similar to a trie is somewhat different: each node stores a full
112596f483aSJessica Paquette /// substring of the full mapping rather than a single character state.
113596f483aSJessica Paquette ///
114596f483aSJessica Paquette /// Each internal node contains a pointer to the internal node representing
115596f483aSJessica Paquette /// the same string, but with the first character chopped off. This is stored
116596f483aSJessica Paquette /// in \p Link. Each leaf node stores the start index of its respective
117596f483aSJessica Paquette /// suffix in \p SuffixIdx.
118596f483aSJessica Paquette struct SuffixTreeNode {
119596f483aSJessica Paquette 
120596f483aSJessica Paquette   /// The children of this node.
121596f483aSJessica Paquette   ///
122596f483aSJessica Paquette   /// A child existing on an unsigned integer implies that from the mapping
123596f483aSJessica Paquette   /// represented by the current node, there is a way to reach another
124596f483aSJessica Paquette   /// mapping by tacking that character on the end of the current string.
125596f483aSJessica Paquette   DenseMap<unsigned, SuffixTreeNode *> Children;
126596f483aSJessica Paquette 
127596f483aSJessica Paquette   /// The start index of this node's substring in the main string.
1284cf187b5SJessica Paquette   unsigned StartIdx = EmptyIdx;
129596f483aSJessica Paquette 
130596f483aSJessica Paquette   /// The end index of this node's substring in the main string.
131596f483aSJessica Paquette   ///
132596f483aSJessica Paquette   /// Every leaf node must have its \p EndIdx incremented at the end of every
133596f483aSJessica Paquette   /// step in the construction algorithm. To avoid having to update O(N)
134596f483aSJessica Paquette   /// nodes individually at the end of every step, the end index is stored
135596f483aSJessica Paquette   /// as a pointer.
1364cf187b5SJessica Paquette   unsigned *EndIdx = nullptr;
137596f483aSJessica Paquette 
138596f483aSJessica Paquette   /// For leaves, the start index of the suffix represented by this node.
139596f483aSJessica Paquette   ///
140596f483aSJessica Paquette   /// For all other nodes, this is ignored.
1414cf187b5SJessica Paquette   unsigned SuffixIdx = EmptyIdx;
142596f483aSJessica Paquette 
1435f8f34e4SAdrian Prantl   /// For internal nodes, a pointer to the internal node representing
144596f483aSJessica Paquette   /// the same sequence with the first character chopped off.
145596f483aSJessica Paquette   ///
1464602c343SJessica Paquette   /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
147596f483aSJessica Paquette   /// Ukkonen's algorithm does to achieve linear-time construction is
148596f483aSJessica Paquette   /// keep track of which node the next insert should be at. This makes each
149596f483aSJessica Paquette   /// insert O(1), and there are a total of O(N) inserts. The suffix link
150596f483aSJessica Paquette   /// helps with inserting children of internal nodes.
151596f483aSJessica Paquette   ///
152596f483aSJessica Paquette   /// Say we add a child to an internal node with associated mapping S. The
153596f483aSJessica Paquette   /// next insertion must be at the node representing S - its first character.
154596f483aSJessica Paquette   /// This is given by the way that we iteratively build the tree in Ukkonen's
155596f483aSJessica Paquette   /// algorithm. The main idea is to look at the suffixes of each prefix in the
156596f483aSJessica Paquette   /// string, starting with the longest suffix of the prefix, and ending with
157596f483aSJessica Paquette   /// the shortest. Therefore, if we keep pointers between such nodes, we can
158596f483aSJessica Paquette   /// move to the next insertion point in O(1) time. If we don't, then we'd
159596f483aSJessica Paquette   /// have to query from the root, which takes O(N) time. This would make the
160596f483aSJessica Paquette   /// construction algorithm O(N^2) rather than O(N).
161596f483aSJessica Paquette   SuffixTreeNode *Link = nullptr;
162596f483aSJessica Paquette 
163acffa28cSJessica Paquette   /// The length of the string formed by concatenating the edge labels from the
164acffa28cSJessica Paquette   /// root to this node.
1654cf187b5SJessica Paquette   unsigned ConcatLen = 0;
166acffa28cSJessica Paquette 
167596f483aSJessica Paquette   /// Returns true if this node is a leaf.
168596f483aSJessica Paquette   bool isLeaf() const { return SuffixIdx != EmptyIdx; }
169596f483aSJessica Paquette 
170596f483aSJessica Paquette   /// Returns true if this node is the root of its owning \p SuffixTree.
171596f483aSJessica Paquette   bool isRoot() const { return StartIdx == EmptyIdx; }
172596f483aSJessica Paquette 
173596f483aSJessica Paquette   /// Return the number of elements in the substring associated with this node.
174596f483aSJessica Paquette   size_t size() const {
175596f483aSJessica Paquette 
176596f483aSJessica Paquette     // Is it the root? If so, it's the empty string so return 0.
177596f483aSJessica Paquette     if (isRoot())
178596f483aSJessica Paquette       return 0;
179596f483aSJessica Paquette 
180596f483aSJessica Paquette     assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
181596f483aSJessica Paquette 
182596f483aSJessica Paquette     // Size = the number of elements in the string.
183596f483aSJessica Paquette     // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
184596f483aSJessica Paquette     return *EndIdx - StartIdx + 1;
185596f483aSJessica Paquette   }
186596f483aSJessica Paquette 
187df5b09b8SJessica Paquette   SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
188df5b09b8SJessica Paquette       : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
189596f483aSJessica Paquette 
190596f483aSJessica Paquette   SuffixTreeNode() {}
191596f483aSJessica Paquette };
192596f483aSJessica Paquette 
193596f483aSJessica Paquette /// A data structure for fast substring queries.
194596f483aSJessica Paquette ///
195596f483aSJessica Paquette /// Suffix trees represent the suffixes of their input strings in their leaves.
196596f483aSJessica Paquette /// A suffix tree is a type of compressed trie structure where each node
197596f483aSJessica Paquette /// represents an entire substring rather than a single character. Each leaf
198596f483aSJessica Paquette /// of the tree is a suffix.
199596f483aSJessica Paquette ///
200596f483aSJessica Paquette /// A suffix tree can be seen as a type of state machine where each state is a
201596f483aSJessica Paquette /// substring of the full string. The tree is structured so that, for a string
202596f483aSJessica Paquette /// of length N, there are exactly N leaves in the tree. This structure allows
203596f483aSJessica Paquette /// us to quickly find repeated substrings of the input string.
204596f483aSJessica Paquette ///
205596f483aSJessica Paquette /// In this implementation, a "string" is a vector of unsigned integers.
206596f483aSJessica Paquette /// These integers may result from hashing some data type. A suffix tree can
207596f483aSJessica Paquette /// contain 1 or many strings, which can then be queried as one large string.
208596f483aSJessica Paquette ///
209596f483aSJessica Paquette /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
210596f483aSJessica Paquette /// suffix tree construction. Ukkonen's algorithm is explained in more detail
211596f483aSJessica Paquette /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
212596f483aSJessica Paquette /// paper is available at
213596f483aSJessica Paquette ///
214596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
215596f483aSJessica Paquette class SuffixTree {
21678681be2SJessica Paquette public:
217596f483aSJessica Paquette   /// Each element is an integer representing an instruction in the module.
218596f483aSJessica Paquette   ArrayRef<unsigned> Str;
219596f483aSJessica Paquette 
2204e54ef88SJessica Paquette   /// A repeated substring in the tree.
2214e54ef88SJessica Paquette   struct RepeatedSubstring {
2224e54ef88SJessica Paquette     /// The length of the string.
2234e54ef88SJessica Paquette     unsigned Length;
2244e54ef88SJessica Paquette 
2254e54ef88SJessica Paquette     /// The start indices of each occurrence.
2264e54ef88SJessica Paquette     std::vector<unsigned> StartIndices;
2274e54ef88SJessica Paquette   };
2284e54ef88SJessica Paquette 
22978681be2SJessica Paquette private:
230596f483aSJessica Paquette   /// Maintains each node in the tree.
231d4cb9c6dSJessica Paquette   SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
232596f483aSJessica Paquette 
233596f483aSJessica Paquette   /// The root of the suffix tree.
234596f483aSJessica Paquette   ///
235596f483aSJessica Paquette   /// The root represents the empty string. It is maintained by the
236596f483aSJessica Paquette   /// \p NodeAllocator like every other node in the tree.
237596f483aSJessica Paquette   SuffixTreeNode *Root = nullptr;
238596f483aSJessica Paquette 
239596f483aSJessica Paquette   /// Maintains the end indices of the internal nodes in the tree.
240596f483aSJessica Paquette   ///
241596f483aSJessica Paquette   /// Each internal node is guaranteed to never have its end index change
242596f483aSJessica Paquette   /// during the construction algorithm; however, leaves must be updated at
243596f483aSJessica Paquette   /// every step. Therefore, we need to store leaf end indices by reference
244596f483aSJessica Paquette   /// to avoid updating O(N) leaves at every step of construction. Thus,
245596f483aSJessica Paquette   /// every internal node must be allocated its own end index.
246596f483aSJessica Paquette   BumpPtrAllocator InternalEndIdxAllocator;
247596f483aSJessica Paquette 
248596f483aSJessica Paquette   /// The end index of each leaf in the tree.
2494cf187b5SJessica Paquette   unsigned LeafEndIdx = -1;
250596f483aSJessica Paquette 
2515f8f34e4SAdrian Prantl   /// Helper struct which keeps track of the next insertion point in
252596f483aSJessica Paquette   /// Ukkonen's algorithm.
253596f483aSJessica Paquette   struct ActiveState {
254596f483aSJessica Paquette     /// The next node to insert at.
255c7f127d9SSimon Pilgrim     SuffixTreeNode *Node = nullptr;
256596f483aSJessica Paquette 
257596f483aSJessica Paquette     /// The index of the first character in the substring currently being added.
2584cf187b5SJessica Paquette     unsigned Idx = EmptyIdx;
259596f483aSJessica Paquette 
260596f483aSJessica Paquette     /// The length of the substring we have to add at the current step.
2614cf187b5SJessica Paquette     unsigned Len = 0;
262596f483aSJessica Paquette   };
263596f483aSJessica Paquette 
2645f8f34e4SAdrian Prantl   /// The point the next insertion will take place at in the
265596f483aSJessica Paquette   /// construction algorithm.
266596f483aSJessica Paquette   ActiveState Active;
267596f483aSJessica Paquette 
268596f483aSJessica Paquette   /// Allocate a leaf node and add it to the tree.
269596f483aSJessica Paquette   ///
270596f483aSJessica Paquette   /// \param Parent The parent of this node.
271596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
272596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
273596f483aSJessica Paquette   ///
274596f483aSJessica Paquette   /// \returns A pointer to the allocated leaf node.
2754cf187b5SJessica Paquette   SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
276596f483aSJessica Paquette                              unsigned Edge) {
277596f483aSJessica Paquette 
278596f483aSJessica Paquette     assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
279596f483aSJessica Paquette 
28078681be2SJessica Paquette     SuffixTreeNode *N = new (NodeAllocator.Allocate())
281df5b09b8SJessica Paquette         SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
282596f483aSJessica Paquette     Parent.Children[Edge] = N;
283596f483aSJessica Paquette 
284596f483aSJessica Paquette     return N;
285596f483aSJessica Paquette   }
286596f483aSJessica Paquette 
287596f483aSJessica Paquette   /// Allocate an internal node and add it to the tree.
288596f483aSJessica Paquette   ///
289596f483aSJessica Paquette   /// \param Parent The parent of this node. Only null when allocating the root.
290596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
291596f483aSJessica Paquette   /// \param EndIdx The end index of this node's associated string.
292596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
293596f483aSJessica Paquette   ///
294596f483aSJessica Paquette   /// \returns A pointer to the allocated internal node.
2954cf187b5SJessica Paquette   SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
2964cf187b5SJessica Paquette                                      unsigned EndIdx, unsigned Edge) {
297596f483aSJessica Paquette 
298596f483aSJessica Paquette     assert(StartIdx <= EndIdx && "String can't start after it ends!");
299596f483aSJessica Paquette     assert(!(!Parent && StartIdx != EmptyIdx) &&
300596f483aSJessica Paquette            "Non-root internal nodes must have parents!");
301596f483aSJessica Paquette 
3024cf187b5SJessica Paquette     unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
3036b7615aeSPuyan Lotfi     SuffixTreeNode *N =
3046b7615aeSPuyan Lotfi         new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root);
305596f483aSJessica Paquette     if (Parent)
306596f483aSJessica Paquette       Parent->Children[Edge] = N;
307596f483aSJessica Paquette 
308596f483aSJessica Paquette     return N;
309596f483aSJessica Paquette   }
310596f483aSJessica Paquette 
3115f8f34e4SAdrian Prantl   /// Set the suffix indices of the leaves to the start indices of their
3124e54ef88SJessica Paquette   /// respective suffixes.
313596f483aSJessica Paquette   ///
314596f483aSJessica Paquette   /// \param[in] CurrNode The node currently being visited.
315df5b09b8SJessica Paquette   /// \param CurrNodeLen The concatenation of all node sizes from the root to
316df5b09b8SJessica Paquette   /// this node. Used to produce suffix indices.
317df5b09b8SJessica Paquette   void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrNodeLen) {
318596f483aSJessica Paquette 
319596f483aSJessica Paquette     bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
320596f483aSJessica Paquette 
321df5b09b8SJessica Paquette     // Store the concatenation of lengths down from the root.
322df5b09b8SJessica Paquette     CurrNode.ConcatLen = CurrNodeLen;
323596f483aSJessica Paquette     // Traverse the tree depth-first.
324596f483aSJessica Paquette     for (auto &ChildPair : CurrNode.Children) {
325596f483aSJessica Paquette       assert(ChildPair.second && "Node had a null child!");
326df5b09b8SJessica Paquette       setSuffixIndices(*ChildPair.second,
327df5b09b8SJessica Paquette                        CurrNodeLen + ChildPair.second->size());
328596f483aSJessica Paquette     }
329596f483aSJessica Paquette 
330df5b09b8SJessica Paquette     // Is this node a leaf? If it is, give it a suffix index.
331df5b09b8SJessica Paquette     if (IsLeaf)
332df5b09b8SJessica Paquette       CurrNode.SuffixIdx = Str.size() - CurrNodeLen;
333596f483aSJessica Paquette   }
334596f483aSJessica Paquette 
3355f8f34e4SAdrian Prantl   /// Construct the suffix tree for the prefix of the input ending at
336596f483aSJessica Paquette   /// \p EndIdx.
337596f483aSJessica Paquette   ///
338596f483aSJessica Paquette   /// Used to construct the full suffix tree iteratively. At the end of each
339596f483aSJessica Paquette   /// step, the constructed suffix tree is either a valid suffix tree, or a
340596f483aSJessica Paquette   /// suffix tree with implicit suffixes. At the end of the final step, the
341596f483aSJessica Paquette   /// suffix tree is a valid tree.
342596f483aSJessica Paquette   ///
343596f483aSJessica Paquette   /// \param EndIdx The end index of the current prefix in the main string.
344596f483aSJessica Paquette   /// \param SuffixesToAdd The number of suffixes that must be added
345596f483aSJessica Paquette   /// to complete the suffix tree at the current phase.
346596f483aSJessica Paquette   ///
347596f483aSJessica Paquette   /// \returns The number of suffixes that have not been added at the end of
348596f483aSJessica Paquette   /// this step.
3494cf187b5SJessica Paquette   unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
350596f483aSJessica Paquette     SuffixTreeNode *NeedsLink = nullptr;
351596f483aSJessica Paquette 
352596f483aSJessica Paquette     while (SuffixesToAdd > 0) {
353596f483aSJessica Paquette 
354596f483aSJessica Paquette       // Are we waiting to add anything other than just the last character?
355596f483aSJessica Paquette       if (Active.Len == 0) {
356596f483aSJessica Paquette         // If not, then say the active index is the end index.
357596f483aSJessica Paquette         Active.Idx = EndIdx;
358596f483aSJessica Paquette       }
359596f483aSJessica Paquette 
360596f483aSJessica Paquette       assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
361596f483aSJessica Paquette 
362596f483aSJessica Paquette       // The first character in the current substring we're looking at.
363596f483aSJessica Paquette       unsigned FirstChar = Str[Active.Idx];
364596f483aSJessica Paquette 
365596f483aSJessica Paquette       // Have we inserted anything starting with FirstChar at the current node?
366596f483aSJessica Paquette       if (Active.Node->Children.count(FirstChar) == 0) {
367596f483aSJessica Paquette         // If not, then we can just insert a leaf and move too the next step.
368596f483aSJessica Paquette         insertLeaf(*Active.Node, EndIdx, FirstChar);
369596f483aSJessica Paquette 
370596f483aSJessica Paquette         // The active node is an internal node, and we visited it, so it must
371596f483aSJessica Paquette         // need a link if it doesn't have one.
372596f483aSJessica Paquette         if (NeedsLink) {
373596f483aSJessica Paquette           NeedsLink->Link = Active.Node;
374596f483aSJessica Paquette           NeedsLink = nullptr;
375596f483aSJessica Paquette         }
376596f483aSJessica Paquette       } else {
377596f483aSJessica Paquette         // There's a match with FirstChar, so look for the point in the tree to
378596f483aSJessica Paquette         // insert a new node.
379596f483aSJessica Paquette         SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
380596f483aSJessica Paquette 
3814cf187b5SJessica Paquette         unsigned SubstringLen = NextNode->size();
382596f483aSJessica Paquette 
383596f483aSJessica Paquette         // Is the current suffix we're trying to insert longer than the size of
384596f483aSJessica Paquette         // the child we want to move to?
385596f483aSJessica Paquette         if (Active.Len >= SubstringLen) {
386596f483aSJessica Paquette           // If yes, then consume the characters we've seen and move to the next
387596f483aSJessica Paquette           // node.
388596f483aSJessica Paquette           Active.Idx += SubstringLen;
389596f483aSJessica Paquette           Active.Len -= SubstringLen;
390596f483aSJessica Paquette           Active.Node = NextNode;
391596f483aSJessica Paquette           continue;
392596f483aSJessica Paquette         }
393596f483aSJessica Paquette 
394596f483aSJessica Paquette         // Otherwise, the suffix we're trying to insert must be contained in the
395596f483aSJessica Paquette         // next node we want to move to.
396596f483aSJessica Paquette         unsigned LastChar = Str[EndIdx];
397596f483aSJessica Paquette 
398596f483aSJessica Paquette         // Is the string we're trying to insert a substring of the next node?
399596f483aSJessica Paquette         if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
400596f483aSJessica Paquette           // If yes, then we're done for this step. Remember our insertion point
401596f483aSJessica Paquette           // and move to the next end index. At this point, we have an implicit
402596f483aSJessica Paquette           // suffix tree.
403596f483aSJessica Paquette           if (NeedsLink && !Active.Node->isRoot()) {
404596f483aSJessica Paquette             NeedsLink->Link = Active.Node;
405596f483aSJessica Paquette             NeedsLink = nullptr;
406596f483aSJessica Paquette           }
407596f483aSJessica Paquette 
408596f483aSJessica Paquette           Active.Len++;
409596f483aSJessica Paquette           break;
410596f483aSJessica Paquette         }
411596f483aSJessica Paquette 
412596f483aSJessica Paquette         // The string we're trying to insert isn't a substring of the next node,
413596f483aSJessica Paquette         // but matches up to a point. Split the node.
414596f483aSJessica Paquette         //
415596f483aSJessica Paquette         // For example, say we ended our search at a node n and we're trying to
416596f483aSJessica Paquette         // insert ABD. Then we'll create a new node s for AB, reduce n to just
417596f483aSJessica Paquette         // representing C, and insert a new leaf node l to represent d. This
418596f483aSJessica Paquette         // allows us to ensure that if n was a leaf, it remains a leaf.
419596f483aSJessica Paquette         //
420596f483aSJessica Paquette         //   | ABC  ---split--->  | AB
421596f483aSJessica Paquette         //   n                    s
422596f483aSJessica Paquette         //                     C / \ D
423596f483aSJessica Paquette         //                      n   l
424596f483aSJessica Paquette 
425596f483aSJessica Paquette         // The node s from the diagram
426596f483aSJessica Paquette         SuffixTreeNode *SplitNode =
42778681be2SJessica Paquette             insertInternalNode(Active.Node, NextNode->StartIdx,
42878681be2SJessica Paquette                                NextNode->StartIdx + Active.Len - 1, FirstChar);
429596f483aSJessica Paquette 
430596f483aSJessica Paquette         // Insert the new node representing the new substring into the tree as
431596f483aSJessica Paquette         // a child of the split node. This is the node l from the diagram.
432596f483aSJessica Paquette         insertLeaf(*SplitNode, EndIdx, LastChar);
433596f483aSJessica Paquette 
434596f483aSJessica Paquette         // Make the old node a child of the split node and update its start
435596f483aSJessica Paquette         // index. This is the node n from the diagram.
436596f483aSJessica Paquette         NextNode->StartIdx += Active.Len;
437596f483aSJessica Paquette         SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
438596f483aSJessica Paquette 
439596f483aSJessica Paquette         // SplitNode is an internal node, update the suffix link.
440596f483aSJessica Paquette         if (NeedsLink)
441596f483aSJessica Paquette           NeedsLink->Link = SplitNode;
442596f483aSJessica Paquette 
443596f483aSJessica Paquette         NeedsLink = SplitNode;
444596f483aSJessica Paquette       }
445596f483aSJessica Paquette 
446596f483aSJessica Paquette       // We've added something new to the tree, so there's one less suffix to
447596f483aSJessica Paquette       // add.
448596f483aSJessica Paquette       SuffixesToAdd--;
449596f483aSJessica Paquette 
450596f483aSJessica Paquette       if (Active.Node->isRoot()) {
451596f483aSJessica Paquette         if (Active.Len > 0) {
452596f483aSJessica Paquette           Active.Len--;
453596f483aSJessica Paquette           Active.Idx = EndIdx - SuffixesToAdd + 1;
454596f483aSJessica Paquette         }
455596f483aSJessica Paquette       } else {
456596f483aSJessica Paquette         // Start the next phase at the next smallest suffix.
457596f483aSJessica Paquette         Active.Node = Active.Node->Link;
458596f483aSJessica Paquette       }
459596f483aSJessica Paquette     }
460596f483aSJessica Paquette 
461596f483aSJessica Paquette     return SuffixesToAdd;
462596f483aSJessica Paquette   }
463596f483aSJessica Paquette 
464596f483aSJessica Paquette public:
465596f483aSJessica Paquette   /// Construct a suffix tree from a sequence of unsigned integers.
466596f483aSJessica Paquette   ///
467596f483aSJessica Paquette   /// \param Str The string to construct the suffix tree for.
468596f483aSJessica Paquette   SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
469596f483aSJessica Paquette     Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
470596f483aSJessica Paquette     Active.Node = Root;
471596f483aSJessica Paquette 
472596f483aSJessica Paquette     // Keep track of the number of suffixes we have to add of the current
473596f483aSJessica Paquette     // prefix.
4744cf187b5SJessica Paquette     unsigned SuffixesToAdd = 0;
475596f483aSJessica Paquette     Active.Node = Root;
476596f483aSJessica Paquette 
477596f483aSJessica Paquette     // Construct the suffix tree iteratively on each prefix of the string.
478596f483aSJessica Paquette     // PfxEndIdx is the end index of the current prefix.
479596f483aSJessica Paquette     // End is one past the last element in the string.
4804cf187b5SJessica Paquette     for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
4814cf187b5SJessica Paquette          PfxEndIdx++) {
482596f483aSJessica Paquette       SuffixesToAdd++;
483596f483aSJessica Paquette       LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
484596f483aSJessica Paquette       SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
485596f483aSJessica Paquette     }
486596f483aSJessica Paquette 
487596f483aSJessica Paquette     // Set the suffix indices of each leaf.
488596f483aSJessica Paquette     assert(Root && "Root node can't be nullptr!");
489596f483aSJessica Paquette     setSuffixIndices(*Root, 0);
490596f483aSJessica Paquette   }
4914e54ef88SJessica Paquette 
492a409cc95SJessica Paquette   /// Iterator for finding all repeated substrings in the suffix tree.
493a409cc95SJessica Paquette   struct RepeatedSubstringIterator {
494a409cc95SJessica Paquette   private:
495a409cc95SJessica Paquette     /// The current node we're visiting.
496a409cc95SJessica Paquette     SuffixTreeNode *N = nullptr;
497a409cc95SJessica Paquette 
498a409cc95SJessica Paquette     /// The repeated substring associated with this node.
499a409cc95SJessica Paquette     RepeatedSubstring RS;
500a409cc95SJessica Paquette 
501a409cc95SJessica Paquette     /// The nodes left to visit.
502a409cc95SJessica Paquette     std::vector<SuffixTreeNode *> ToVisit;
503a409cc95SJessica Paquette 
504a409cc95SJessica Paquette     /// The minimum length of a repeated substring to find.
505a409cc95SJessica Paquette     /// Since we're outlining, we want at least two instructions in the range.
506a409cc95SJessica Paquette     /// FIXME: This may not be true for targets like X86 which support many
507a409cc95SJessica Paquette     /// instruction lengths.
508a409cc95SJessica Paquette     const unsigned MinLength = 2;
509a409cc95SJessica Paquette 
510a409cc95SJessica Paquette     /// Move the iterator to the next repeated substring.
511a409cc95SJessica Paquette     void advance() {
512a409cc95SJessica Paquette       // Clear the current state. If we're at the end of the range, then this
513a409cc95SJessica Paquette       // is the state we want to be in.
514a409cc95SJessica Paquette       RS = RepeatedSubstring();
515a409cc95SJessica Paquette       N = nullptr;
516a409cc95SJessica Paquette 
5173cd70b38SJessica Paquette       // Each leaf node represents a repeat of a string.
5183cd70b38SJessica Paquette       std::vector<SuffixTreeNode *> LeafChildren;
5193cd70b38SJessica Paquette 
520a409cc95SJessica Paquette       // Continue visiting nodes until we find one which repeats more than once.
521a409cc95SJessica Paquette       while (!ToVisit.empty()) {
522a409cc95SJessica Paquette         SuffixTreeNode *Curr = ToVisit.back();
523a409cc95SJessica Paquette         ToVisit.pop_back();
5243cd70b38SJessica Paquette         LeafChildren.clear();
525a409cc95SJessica Paquette 
526a409cc95SJessica Paquette         // Keep track of the length of the string associated with the node. If
527a409cc95SJessica Paquette         // it's too short, we'll quit.
528a409cc95SJessica Paquette         unsigned Length = Curr->ConcatLen;
529a409cc95SJessica Paquette 
530a409cc95SJessica Paquette         // Iterate over each child, saving internal nodes for visiting, and
531a409cc95SJessica Paquette         // leaf nodes in LeafChildren. Internal nodes represent individual
532a409cc95SJessica Paquette         // strings, which may repeat.
533a409cc95SJessica Paquette         for (auto &ChildPair : Curr->Children) {
534a409cc95SJessica Paquette           // Save all of this node's children for processing.
535a409cc95SJessica Paquette           if (!ChildPair.second->isLeaf())
536a409cc95SJessica Paquette             ToVisit.push_back(ChildPair.second);
537a409cc95SJessica Paquette 
538a409cc95SJessica Paquette           // It's not an internal node, so it must be a leaf. If we have a
539a409cc95SJessica Paquette           // long enough string, then save the leaf children.
540a409cc95SJessica Paquette           else if (Length >= MinLength)
541a409cc95SJessica Paquette             LeafChildren.push_back(ChildPair.second);
5424e54ef88SJessica Paquette         }
543a409cc95SJessica Paquette 
544a409cc95SJessica Paquette         // The root never represents a repeated substring. If we're looking at
545a409cc95SJessica Paquette         // that, then skip it.
546a409cc95SJessica Paquette         if (Curr->isRoot())
547a409cc95SJessica Paquette           continue;
548a409cc95SJessica Paquette 
549a409cc95SJessica Paquette         // Do we have any repeated substrings?
550a409cc95SJessica Paquette         if (LeafChildren.size() >= 2) {
551a409cc95SJessica Paquette           // Yes. Update the state to reflect this, and then bail out.
552a409cc95SJessica Paquette           N = Curr;
553a409cc95SJessica Paquette           RS.Length = Length;
554a409cc95SJessica Paquette           for (SuffixTreeNode *Leaf : LeafChildren)
555a409cc95SJessica Paquette             RS.StartIndices.push_back(Leaf->SuffixIdx);
556a409cc95SJessica Paquette           break;
557a409cc95SJessica Paquette         }
558a409cc95SJessica Paquette       }
559a409cc95SJessica Paquette 
560a409cc95SJessica Paquette       // At this point, either NewRS is an empty RepeatedSubstring, or it was
561a409cc95SJessica Paquette       // set in the above loop. Similarly, N is either nullptr, or the node
562a409cc95SJessica Paquette       // associated with NewRS.
563a409cc95SJessica Paquette     }
564a409cc95SJessica Paquette 
565a409cc95SJessica Paquette   public:
566a409cc95SJessica Paquette     /// Return the current repeated substring.
567a409cc95SJessica Paquette     RepeatedSubstring &operator*() { return RS; }
568a409cc95SJessica Paquette 
569a409cc95SJessica Paquette     RepeatedSubstringIterator &operator++() {
570a409cc95SJessica Paquette       advance();
571a409cc95SJessica Paquette       return *this;
572a409cc95SJessica Paquette     }
573a409cc95SJessica Paquette 
574a409cc95SJessica Paquette     RepeatedSubstringIterator operator++(int I) {
575a409cc95SJessica Paquette       RepeatedSubstringIterator It(*this);
576a409cc95SJessica Paquette       advance();
577a409cc95SJessica Paquette       return It;
578a409cc95SJessica Paquette     }
579a409cc95SJessica Paquette 
580a409cc95SJessica Paquette     bool operator==(const RepeatedSubstringIterator &Other) {
581a409cc95SJessica Paquette       return N == Other.N;
582a409cc95SJessica Paquette     }
583a409cc95SJessica Paquette     bool operator!=(const RepeatedSubstringIterator &Other) {
584a409cc95SJessica Paquette       return !(*this == Other);
585a409cc95SJessica Paquette     }
586a409cc95SJessica Paquette 
587a409cc95SJessica Paquette     RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
588a409cc95SJessica Paquette       // Do we have a non-null node?
589a409cc95SJessica Paquette       if (N) {
590a409cc95SJessica Paquette         // Yes. At the first step, we need to visit all of N's children.
591a409cc95SJessica Paquette         // Note: This means that we visit N last.
592a409cc95SJessica Paquette         ToVisit.push_back(N);
593a409cc95SJessica Paquette         advance();
594a409cc95SJessica Paquette       }
595a409cc95SJessica Paquette     }
596a409cc95SJessica Paquette   };
597a409cc95SJessica Paquette 
598a409cc95SJessica Paquette   typedef RepeatedSubstringIterator iterator;
599a409cc95SJessica Paquette   iterator begin() { return iterator(Root); }
600a409cc95SJessica Paquette   iterator end() { return iterator(nullptr); }
601596f483aSJessica Paquette };
602596f483aSJessica Paquette 
6035f8f34e4SAdrian Prantl /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
604596f483aSJessica Paquette struct InstructionMapper {
605596f483aSJessica Paquette 
6065f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that
607596f483aSJessica Paquette   /// cannot be outlined.
608596f483aSJessica Paquette   ///
609596f483aSJessica Paquette   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
610596f483aSJessica Paquette   unsigned IllegalInstrNumber = -3;
611596f483aSJessica Paquette 
6125f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that can
613596f483aSJessica Paquette   /// be outlined.
614596f483aSJessica Paquette   unsigned LegalInstrNumber = 0;
615596f483aSJessica Paquette 
616596f483aSJessica Paquette   /// Correspondence from \p MachineInstrs to unsigned integers.
617596f483aSJessica Paquette   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
618596f483aSJessica Paquette       InstructionIntegerMap;
619596f483aSJessica Paquette 
620cad864d4SJessica Paquette   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
621cad864d4SJessica Paquette   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
622cad864d4SJessica Paquette 
623596f483aSJessica Paquette   /// The vector of unsigned integers that the module is mapped to.
624596f483aSJessica Paquette   std::vector<unsigned> UnsignedVec;
625596f483aSJessica Paquette 
6265f8f34e4SAdrian Prantl   /// Stores the location of the instruction associated with the integer
627596f483aSJessica Paquette   /// at index i in \p UnsignedVec for each index i.
628596f483aSJessica Paquette   std::vector<MachineBasicBlock::iterator> InstrList;
629596f483aSJessica Paquette 
630c991cf36SJessica Paquette   // Set if we added an illegal number in the previous step.
631c991cf36SJessica Paquette   // Since each illegal number is unique, we only need one of them between
632c991cf36SJessica Paquette   // each range of legal numbers. This lets us make sure we don't add more
633c991cf36SJessica Paquette   // than one illegal number per range.
634c991cf36SJessica Paquette   bool AddedIllegalLastTime = false;
635c991cf36SJessica Paquette 
6365f8f34e4SAdrian Prantl   /// Maps \p *It to a legal integer.
637596f483aSJessica Paquette   ///
638c4cf775aSJessica Paquette   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
639ca3ed964SJessica Paquette   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
640596f483aSJessica Paquette   ///
641596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
642267d266cSJessica Paquette   unsigned mapToLegalUnsigned(
643c4cf775aSJessica Paquette       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
644c4cf775aSJessica Paquette       bool &HaveLegalRange, unsigned &NumLegalInBlock,
645267d266cSJessica Paquette       std::vector<unsigned> &UnsignedVecForMBB,
646267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
647c991cf36SJessica Paquette     // We added something legal, so we should unset the AddedLegalLastTime
648c991cf36SJessica Paquette     // flag.
649c991cf36SJessica Paquette     AddedIllegalLastTime = false;
650596f483aSJessica Paquette 
651c4cf775aSJessica Paquette     // If we have at least two adjacent legal instructions (which may have
652c4cf775aSJessica Paquette     // invisible instructions in between), remember that.
653c4cf775aSJessica Paquette     if (CanOutlineWithPrevInstr)
654c4cf775aSJessica Paquette       HaveLegalRange = true;
655c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = true;
656c4cf775aSJessica Paquette 
657267d266cSJessica Paquette     // Keep track of the number of legal instructions we insert.
658267d266cSJessica Paquette     NumLegalInBlock++;
659267d266cSJessica Paquette 
660596f483aSJessica Paquette     // Get the integer for this instruction or give it the current
661596f483aSJessica Paquette     // LegalInstrNumber.
662267d266cSJessica Paquette     InstrListForMBB.push_back(It);
663596f483aSJessica Paquette     MachineInstr &MI = *It;
664596f483aSJessica Paquette     bool WasInserted;
665596f483aSJessica Paquette     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
666596f483aSJessica Paquette         ResultIt;
667596f483aSJessica Paquette     std::tie(ResultIt, WasInserted) =
668596f483aSJessica Paquette         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
669596f483aSJessica Paquette     unsigned MINumber = ResultIt->second;
670596f483aSJessica Paquette 
671596f483aSJessica Paquette     // There was an insertion.
672ca3ed964SJessica Paquette     if (WasInserted)
673596f483aSJessica Paquette       LegalInstrNumber++;
674596f483aSJessica Paquette 
675267d266cSJessica Paquette     UnsignedVecForMBB.push_back(MINumber);
676596f483aSJessica Paquette 
677596f483aSJessica Paquette     // Make sure we don't overflow or use any integers reserved by the DenseMap.
678596f483aSJessica Paquette     if (LegalInstrNumber >= IllegalInstrNumber)
679596f483aSJessica Paquette       report_fatal_error("Instruction mapping overflow!");
680596f483aSJessica Paquette 
68178681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
68278681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
68378681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
68478681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
685596f483aSJessica Paquette 
686596f483aSJessica Paquette     return MINumber;
687596f483aSJessica Paquette   }
688596f483aSJessica Paquette 
689596f483aSJessica Paquette   /// Maps \p *It to an illegal integer.
690596f483aSJessica Paquette   ///
691267d266cSJessica Paquette   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
692267d266cSJessica Paquette   /// IllegalInstrNumber.
693596f483aSJessica Paquette   ///
694596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
6956b7615aeSPuyan Lotfi   unsigned mapToIllegalUnsigned(
6966b7615aeSPuyan Lotfi       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
6976b7615aeSPuyan Lotfi       std::vector<unsigned> &UnsignedVecForMBB,
698267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
699c4cf775aSJessica Paquette     // Can't outline an illegal instruction. Set the flag.
700c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = false;
701c4cf775aSJessica Paquette 
702c991cf36SJessica Paquette     // Only add one illegal number per range of legal numbers.
703c991cf36SJessica Paquette     if (AddedIllegalLastTime)
704c991cf36SJessica Paquette       return IllegalInstrNumber;
705c991cf36SJessica Paquette 
706c991cf36SJessica Paquette     // Remember that we added an illegal number last time.
707c991cf36SJessica Paquette     AddedIllegalLastTime = true;
708596f483aSJessica Paquette     unsigned MINumber = IllegalInstrNumber;
709596f483aSJessica Paquette 
710267d266cSJessica Paquette     InstrListForMBB.push_back(It);
711267d266cSJessica Paquette     UnsignedVecForMBB.push_back(IllegalInstrNumber);
712596f483aSJessica Paquette     IllegalInstrNumber--;
713596f483aSJessica Paquette 
714596f483aSJessica Paquette     assert(LegalInstrNumber < IllegalInstrNumber &&
715596f483aSJessica Paquette            "Instruction mapping overflow!");
716596f483aSJessica Paquette 
71778681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
718596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
719596f483aSJessica Paquette 
72078681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
721596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
722596f483aSJessica Paquette 
723596f483aSJessica Paquette     return MINumber;
724596f483aSJessica Paquette   }
725596f483aSJessica Paquette 
7265f8f34e4SAdrian Prantl   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
727596f483aSJessica Paquette   /// and appends it to \p UnsignedVec and \p InstrList.
728596f483aSJessica Paquette   ///
729596f483aSJessica Paquette   /// Two instructions are assigned the same integer if they are identical.
730596f483aSJessica Paquette   /// If an instruction is deemed unsafe to outline, then it will be assigned an
731596f483aSJessica Paquette   /// unique integer. The resulting mapping is placed into a suffix tree and
732596f483aSJessica Paquette   /// queried for candidates.
733596f483aSJessica Paquette   ///
734596f483aSJessica Paquette   /// \param MBB The \p MachineBasicBlock to be translated into integers.
735da08078fSEli Friedman   /// \param TII \p TargetInstrInfo for the function.
736596f483aSJessica Paquette   void convertToUnsignedVec(MachineBasicBlock &MBB,
737596f483aSJessica Paquette                             const TargetInstrInfo &TII) {
7383635c890SAlexander Kornienko     unsigned Flags = 0;
73982d9c0a3SJessica Paquette 
74082d9c0a3SJessica Paquette     // Don't even map in this case.
74182d9c0a3SJessica Paquette     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
74282d9c0a3SJessica Paquette       return;
74382d9c0a3SJessica Paquette 
744cad864d4SJessica Paquette     // Store info for the MBB for later outlining.
745cad864d4SJessica Paquette     MBBFlagsMap[&MBB] = Flags;
746cad864d4SJessica Paquette 
747c991cf36SJessica Paquette     MachineBasicBlock::iterator It = MBB.begin();
748267d266cSJessica Paquette 
749267d266cSJessica Paquette     // The number of instructions in this block that will be considered for
750267d266cSJessica Paquette     // outlining.
751267d266cSJessica Paquette     unsigned NumLegalInBlock = 0;
752267d266cSJessica Paquette 
753c4cf775aSJessica Paquette     // True if we have at least two legal instructions which aren't separated
754c4cf775aSJessica Paquette     // by an illegal instruction.
755c4cf775aSJessica Paquette     bool HaveLegalRange = false;
756c4cf775aSJessica Paquette 
757c4cf775aSJessica Paquette     // True if we can perform outlining given the last mapped (non-invisible)
758c4cf775aSJessica Paquette     // instruction. This lets us know if we have a legal range.
759c4cf775aSJessica Paquette     bool CanOutlineWithPrevInstr = false;
760c4cf775aSJessica Paquette 
761267d266cSJessica Paquette     // FIXME: Should this all just be handled in the target, rather than using
762267d266cSJessica Paquette     // repeated calls to getOutliningType?
763267d266cSJessica Paquette     std::vector<unsigned> UnsignedVecForMBB;
764267d266cSJessica Paquette     std::vector<MachineBasicBlock::iterator> InstrListForMBB;
765267d266cSJessica Paquette 
766*76166a1aSSimon Pilgrim     for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
767596f483aSJessica Paquette       // Keep track of where this instruction is in the module.
7683291e735SJessica Paquette       switch (TII.getOutliningType(It, Flags)) {
769aa087327SJessica Paquette       case InstrType::Illegal:
7706b7615aeSPuyan Lotfi         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
7716b7615aeSPuyan Lotfi                              InstrListForMBB);
772596f483aSJessica Paquette         break;
773596f483aSJessica Paquette 
774aa087327SJessica Paquette       case InstrType::Legal:
775c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
776c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
777596f483aSJessica Paquette         break;
778596f483aSJessica Paquette 
779aa087327SJessica Paquette       case InstrType::LegalTerminator:
780c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
781c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
782c991cf36SJessica Paquette         // The instruction also acts as a terminator, so we have to record that
783c991cf36SJessica Paquette         // in the string.
784c4cf775aSJessica Paquette         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
785c4cf775aSJessica Paquette                              InstrListForMBB);
786042dc9e0SEli Friedman         break;
787042dc9e0SEli Friedman 
788aa087327SJessica Paquette       case InstrType::Invisible:
789c991cf36SJessica Paquette         // Normally this is set by mapTo(Blah)Unsigned, but we just want to
790c991cf36SJessica Paquette         // skip this instruction. So, unset the flag here.
791bd72988cSJessica Paquette         AddedIllegalLastTime = false;
792596f483aSJessica Paquette         break;
793596f483aSJessica Paquette       }
794596f483aSJessica Paquette     }
795596f483aSJessica Paquette 
796267d266cSJessica Paquette     // Are there enough legal instructions in the block for outlining to be
797267d266cSJessica Paquette     // possible?
798c4cf775aSJessica Paquette     if (HaveLegalRange) {
799596f483aSJessica Paquette       // After we're done every insertion, uniquely terminate this part of the
800596f483aSJessica Paquette       // "string". This makes sure we won't match across basic block or function
801596f483aSJessica Paquette       // boundaries since the "end" is encoded uniquely and thus appears in no
802596f483aSJessica Paquette       // repeated substring.
803c4cf775aSJessica Paquette       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
804c4cf775aSJessica Paquette                            InstrListForMBB);
805267d266cSJessica Paquette       InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
806267d266cSJessica Paquette                        InstrListForMBB.end());
807267d266cSJessica Paquette       UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
808267d266cSJessica Paquette                          UnsignedVecForMBB.end());
809267d266cSJessica Paquette     }
810596f483aSJessica Paquette   }
811596f483aSJessica Paquette 
812596f483aSJessica Paquette   InstructionMapper() {
813596f483aSJessica Paquette     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
814596f483aSJessica Paquette     // changed.
815596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
816596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s empty key isn't -1!");
817596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
818596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
819596f483aSJessica Paquette   }
820596f483aSJessica Paquette };
821596f483aSJessica Paquette 
8225f8f34e4SAdrian Prantl /// An interprocedural pass which finds repeated sequences of
823596f483aSJessica Paquette /// instructions and replaces them with calls to functions.
824596f483aSJessica Paquette ///
825596f483aSJessica Paquette /// Each instruction is mapped to an unsigned integer and placed in a string.
826596f483aSJessica Paquette /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
827596f483aSJessica Paquette /// is then repeatedly queried for repeated sequences of instructions. Each
828596f483aSJessica Paquette /// non-overlapping repeated sequence is then placed in its own
829596f483aSJessica Paquette /// \p MachineFunction and each instance is then replaced with a call to that
830596f483aSJessica Paquette /// function.
831596f483aSJessica Paquette struct MachineOutliner : public ModulePass {
832596f483aSJessica Paquette 
833596f483aSJessica Paquette   static char ID;
834596f483aSJessica Paquette 
8355f8f34e4SAdrian Prantl   /// Set to true if the outliner should consider functions with
83613593843SJessica Paquette   /// linkonceodr linkage.
83713593843SJessica Paquette   bool OutlineFromLinkOnceODRs = false;
83813593843SJessica Paquette 
8398bda1881SJessica Paquette   /// Set to true if the outliner should run on all functions in the module
8408bda1881SJessica Paquette   /// considered safe for outlining.
8418bda1881SJessica Paquette   /// Set to true by default for compatibility with llc's -run-pass option.
8428bda1881SJessica Paquette   /// Set when the pass is constructed in TargetPassConfig.
8438bda1881SJessica Paquette   bool RunOnAllFunctions = true;
8448bda1881SJessica Paquette 
845596f483aSJessica Paquette   StringRef getPassName() const override { return "Machine Outliner"; }
846596f483aSJessica Paquette 
847596f483aSJessica Paquette   void getAnalysisUsage(AnalysisUsage &AU) const override {
848cc382cf7SYuanfang Chen     AU.addRequired<MachineModuleInfoWrapperPass>();
849cc382cf7SYuanfang Chen     AU.addPreserved<MachineModuleInfoWrapperPass>();
850596f483aSJessica Paquette     AU.setPreservesAll();
851596f483aSJessica Paquette     ModulePass::getAnalysisUsage(AU);
852596f483aSJessica Paquette   }
853596f483aSJessica Paquette 
8541eca23bdSJessica Paquette   MachineOutliner() : ModulePass(ID) {
855596f483aSJessica Paquette     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
856596f483aSJessica Paquette   }
857596f483aSJessica Paquette 
8581cc52a00SJessica Paquette   /// Remark output explaining that not outlining a set of candidates would be
8591cc52a00SJessica Paquette   /// better than outlining that set.
8601cc52a00SJessica Paquette   void emitNotOutliningCheaperRemark(
8611cc52a00SJessica Paquette       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
8621cc52a00SJessica Paquette       OutlinedFunction &OF);
8631cc52a00SJessica Paquette 
86458e706a6SJessica Paquette   /// Remark output explaining that a function was outlined.
86558e706a6SJessica Paquette   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
86658e706a6SJessica Paquette 
867ce3a2dcfSJessica Paquette   /// Find all repeated substrings that satisfy the outlining cost model by
868ce3a2dcfSJessica Paquette   /// constructing a suffix tree.
86978681be2SJessica Paquette   ///
87078681be2SJessica Paquette   /// If a substring appears at least twice, then it must be represented by
8711cc52a00SJessica Paquette   /// an internal node which appears in at least two suffixes. Each suffix
8721cc52a00SJessica Paquette   /// is represented by a leaf node. To do this, we visit each internal node
8731cc52a00SJessica Paquette   /// in the tree, using the leaf children of each internal node. If an
8741cc52a00SJessica Paquette   /// internal node represents a beneficial substring, then we use each of
8751cc52a00SJessica Paquette   /// its leaf children to find the locations of its substring.
87678681be2SJessica Paquette   ///
87778681be2SJessica Paquette   /// \param Mapper Contains outlining mapping information.
8781cc52a00SJessica Paquette   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
8791cc52a00SJessica Paquette   /// each type of candidate.
880ce3a2dcfSJessica Paquette   void findCandidates(InstructionMapper &Mapper,
88178681be2SJessica Paquette                       std::vector<OutlinedFunction> &FunctionList);
88278681be2SJessica Paquette 
8834ae3b71dSJessica Paquette   /// Replace the sequences of instructions represented by \p OutlinedFunctions
8844ae3b71dSJessica Paquette   /// with calls to functions.
885596f483aSJessica Paquette   ///
886596f483aSJessica Paquette   /// \param M The module we are outlining from.
887596f483aSJessica Paquette   /// \param FunctionList A list of functions to be inserted into the module.
888596f483aSJessica Paquette   /// \param Mapper Contains the instruction mappings for the module.
8894ae3b71dSJessica Paquette   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
8906b7615aeSPuyan Lotfi                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
891596f483aSJessica Paquette 
892596f483aSJessica Paquette   /// Creates a function for \p OF and inserts it into the module.
893e18d6ff0SJessica Paquette   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
894a3eb0facSJessica Paquette                                           InstructionMapper &Mapper,
895a3eb0facSJessica Paquette                                           unsigned Name);
896596f483aSJessica Paquette 
897a51fc8ddSPuyan Lotfi   /// Calls 'doOutline()'.
898a51fc8ddSPuyan Lotfi   bool runOnModule(Module &M) override;
899a51fc8ddSPuyan Lotfi 
900596f483aSJessica Paquette   /// Construct a suffix tree on the instructions in \p M and outline repeated
901596f483aSJessica Paquette   /// strings from that tree.
902a51fc8ddSPuyan Lotfi   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
903aa087327SJessica Paquette 
904aa087327SJessica Paquette   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
905aa087327SJessica Paquette   /// function for remark emission.
906aa087327SJessica Paquette   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
907e18d6ff0SJessica Paquette     for (const Candidate &C : OF.Candidates)
9087ad25836SSimon Pilgrim       if (MachineFunction *MF = C.getMF())
9097ad25836SSimon Pilgrim         if (DISubprogram *SP = MF->getFunction().getSubprogram())
910aa087327SJessica Paquette           return SP;
911aa087327SJessica Paquette     return nullptr;
912aa087327SJessica Paquette   }
913050d1ac4SJessica Paquette 
914050d1ac4SJessica Paquette   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
915050d1ac4SJessica Paquette   /// These are used to construct a suffix tree.
916050d1ac4SJessica Paquette   void populateMapper(InstructionMapper &Mapper, Module &M,
917050d1ac4SJessica Paquette                       MachineModuleInfo &MMI);
918596f483aSJessica Paquette 
9192386eab3SJessica Paquette   /// Initialize information necessary to output a size remark.
9202386eab3SJessica Paquette   /// FIXME: This should be handled by the pass manager, not the outliner.
9212386eab3SJessica Paquette   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
9222386eab3SJessica Paquette   /// pass manager.
9236b7615aeSPuyan Lotfi   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
9242386eab3SJessica Paquette                           StringMap<unsigned> &FunctionToInstrCount);
9252386eab3SJessica Paquette 
9262386eab3SJessica Paquette   /// Emit the remark.
9272386eab3SJessica Paquette   // FIXME: This should be handled by the pass manager, not the outliner.
9286b7615aeSPuyan Lotfi   void
9296b7615aeSPuyan Lotfi   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
9302386eab3SJessica Paquette                               const StringMap<unsigned> &FunctionToInstrCount);
9312386eab3SJessica Paquette };
932596f483aSJessica Paquette } // Anonymous namespace.
933596f483aSJessica Paquette 
934596f483aSJessica Paquette char MachineOutliner::ID = 0;
935596f483aSJessica Paquette 
936596f483aSJessica Paquette namespace llvm {
9378bda1881SJessica Paquette ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
9388bda1881SJessica Paquette   MachineOutliner *OL = new MachineOutliner();
9398bda1881SJessica Paquette   OL->RunOnAllFunctions = RunOnAllFunctions;
9408bda1881SJessica Paquette   return OL;
94113593843SJessica Paquette }
94213593843SJessica Paquette 
94378681be2SJessica Paquette } // namespace llvm
94478681be2SJessica Paquette 
94578681be2SJessica Paquette INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
94678681be2SJessica Paquette                 false)
94778681be2SJessica Paquette 
9481cc52a00SJessica Paquette void MachineOutliner::emitNotOutliningCheaperRemark(
9491cc52a00SJessica Paquette     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
9501cc52a00SJessica Paquette     OutlinedFunction &OF) {
951c991cf36SJessica Paquette   // FIXME: Right now, we arbitrarily choose some Candidate from the
952c991cf36SJessica Paquette   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
953c991cf36SJessica Paquette   // We should probably sort these by function name or something to make sure
954c991cf36SJessica Paquette   // the remarks are stable.
9551cc52a00SJessica Paquette   Candidate &C = CandidatesForRepeatedSeq.front();
9561cc52a00SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
9571cc52a00SJessica Paquette   MORE.emit([&]() {
9581cc52a00SJessica Paquette     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
9591cc52a00SJessica Paquette                                       C.front()->getDebugLoc(), C.getMBB());
9601cc52a00SJessica Paquette     R << "Did not outline " << NV("Length", StringLen) << " instructions"
9611cc52a00SJessica Paquette       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
9621cc52a00SJessica Paquette       << " locations."
9631cc52a00SJessica Paquette       << " Bytes from outlining all occurrences ("
9641cc52a00SJessica Paquette       << NV("OutliningCost", OF.getOutliningCost()) << ")"
9651cc52a00SJessica Paquette       << " >= Unoutlined instruction bytes ("
9661cc52a00SJessica Paquette       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
9671cc52a00SJessica Paquette       << " (Also found at: ";
9681cc52a00SJessica Paquette 
9691cc52a00SJessica Paquette     // Tell the user the other places the candidate was found.
9701cc52a00SJessica Paquette     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
9711cc52a00SJessica Paquette       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
9721cc52a00SJessica Paquette               CandidatesForRepeatedSeq[i].front()->getDebugLoc());
9731cc52a00SJessica Paquette       if (i != e - 1)
9741cc52a00SJessica Paquette         R << ", ";
9751cc52a00SJessica Paquette     }
9761cc52a00SJessica Paquette 
9771cc52a00SJessica Paquette     R << ")";
9781cc52a00SJessica Paquette     return R;
9791cc52a00SJessica Paquette   });
9801cc52a00SJessica Paquette }
9811cc52a00SJessica Paquette 
98258e706a6SJessica Paquette void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
98358e706a6SJessica Paquette   MachineBasicBlock *MBB = &*OF.MF->begin();
98458e706a6SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
98558e706a6SJessica Paquette   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
98658e706a6SJessica Paquette                               MBB->findDebugLoc(MBB->begin()), MBB);
98758e706a6SJessica Paquette   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
98834b618bfSJessica Paquette     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
98958e706a6SJessica Paquette     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
99058e706a6SJessica Paquette     << " locations. "
99158e706a6SJessica Paquette     << "(Found at: ";
99258e706a6SJessica Paquette 
99358e706a6SJessica Paquette   // Tell the user the other places the candidate was found.
99458e706a6SJessica Paquette   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
99558e706a6SJessica Paquette 
99658e706a6SJessica Paquette     R << NV((Twine("StartLoc") + Twine(i)).str(),
997e18d6ff0SJessica Paquette             OF.Candidates[i].front()->getDebugLoc());
99858e706a6SJessica Paquette     if (i != e - 1)
99958e706a6SJessica Paquette       R << ", ";
100058e706a6SJessica Paquette   }
100158e706a6SJessica Paquette 
100258e706a6SJessica Paquette   R << ")";
100358e706a6SJessica Paquette 
100458e706a6SJessica Paquette   MORE.emit(R);
100558e706a6SJessica Paquette }
100658e706a6SJessica Paquette 
10076b7615aeSPuyan Lotfi void MachineOutliner::findCandidates(
10086b7615aeSPuyan Lotfi     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
100978681be2SJessica Paquette   FunctionList.clear();
1010ce3a2dcfSJessica Paquette   SuffixTree ST(Mapper.UnsignedVec);
101178681be2SJessica Paquette 
1012fbe7f5e9SDavid Tellenbach   // First, find all of the repeated substrings in the tree of minimum length
10134e54ef88SJessica Paquette   // 2.
1014d87f5449SJessica Paquette   std::vector<Candidate> CandidatesForRepeatedSeq;
1015d4e7d074SJessica Paquette   for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
1016d4e7d074SJessica Paquette     CandidatesForRepeatedSeq.clear();
1017d4e7d074SJessica Paquette     SuffixTree::RepeatedSubstring RS = *It;
10184e54ef88SJessica Paquette     unsigned StringLen = RS.Length;
10194e54ef88SJessica Paquette     for (const unsigned &StartIdx : RS.StartIndices) {
102052df8015SJessica Paquette       unsigned EndIdx = StartIdx + StringLen - 1;
102152df8015SJessica Paquette       // Trick: Discard some candidates that would be incompatible with the
102252df8015SJessica Paquette       // ones we've already found for this sequence. This will save us some
102352df8015SJessica Paquette       // work in candidate selection.
102452df8015SJessica Paquette       //
102552df8015SJessica Paquette       // If two candidates overlap, then we can't outline them both. This
102652df8015SJessica Paquette       // happens when we have candidates that look like, say
102752df8015SJessica Paquette       //
102852df8015SJessica Paquette       // AA (where each "A" is an instruction).
102952df8015SJessica Paquette       //
103052df8015SJessica Paquette       // We might have some portion of the module that looks like this:
103152df8015SJessica Paquette       // AAAAAA (6 A's)
103252df8015SJessica Paquette       //
103352df8015SJessica Paquette       // In this case, there are 5 different copies of "AA" in this range, but
103452df8015SJessica Paquette       // at most 3 can be outlined. If only outlining 3 of these is going to
103552df8015SJessica Paquette       // be unbeneficial, then we ought to not bother.
103652df8015SJessica Paquette       //
103752df8015SJessica Paquette       // Note that two things DON'T overlap when they look like this:
103852df8015SJessica Paquette       // start1...end1 .... start2...end2
103952df8015SJessica Paquette       // That is, one must either
104052df8015SJessica Paquette       // * End before the other starts
104152df8015SJessica Paquette       // * Start after the other ends
10424e54ef88SJessica Paquette       if (std::all_of(
10434e54ef88SJessica Paquette               CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
104452df8015SJessica Paquette               [&StartIdx, &EndIdx](const Candidate &C) {
10454e54ef88SJessica Paquette                 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
104652df8015SJessica Paquette               })) {
104752df8015SJessica Paquette         // It doesn't overlap with anything, so we can outline it.
104852df8015SJessica Paquette         // Each sequence is over [StartIt, EndIt].
1049aa087327SJessica Paquette         // Save the candidate and its location.
1050aa087327SJessica Paquette 
105152df8015SJessica Paquette         MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
105252df8015SJessica Paquette         MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1053cad864d4SJessica Paquette         MachineBasicBlock *MBB = StartIt->getParent();
105452df8015SJessica Paquette 
1055aa087327SJessica Paquette         CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
1056cad864d4SJessica Paquette                                               EndIt, MBB, FunctionList.size(),
1057cad864d4SJessica Paquette                                               Mapper.MBBFlagsMap[MBB]);
105852df8015SJessica Paquette       }
1059809d708bSJessica Paquette     }
1060809d708bSJessica Paquette 
1061acc15e12SJessica Paquette     // We've found something we might want to outline.
1062acc15e12SJessica Paquette     // Create an OutlinedFunction to store it and check if it'd be beneficial
1063acc15e12SJessica Paquette     // to outline.
1064ddb039a1SJessica Paquette     if (CandidatesForRepeatedSeq.size() < 2)
1065da08078fSEli Friedman       continue;
1066da08078fSEli Friedman 
1067da08078fSEli Friedman     // Arbitrarily choose a TII from the first candidate.
1068da08078fSEli Friedman     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1069da08078fSEli Friedman     const TargetInstrInfo *TII =
1070da08078fSEli Friedman         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1071da08078fSEli Friedman 
10729d93c602SJessica Paquette     OutlinedFunction OF =
1073da08078fSEli Friedman         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
10749d93c602SJessica Paquette 
1075b2d53c5dSJessica Paquette     // If we deleted too many candidates, then there's nothing worth outlining.
1076b2d53c5dSJessica Paquette     // FIXME: This should take target-specified instruction sizes into account.
1077b2d53c5dSJessica Paquette     if (OF.Candidates.size() < 2)
10789d93c602SJessica Paquette       continue;
10799d93c602SJessica Paquette 
1080ffe4abc5SJessica Paquette     // Is it better to outline this candidate than not?
1081f94d1d29SJessica Paquette     if (OF.getBenefit() < 1) {
10821cc52a00SJessica Paquette       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
108378681be2SJessica Paquette       continue;
1084ffe4abc5SJessica Paquette     }
108578681be2SJessica Paquette 
1086acc15e12SJessica Paquette     FunctionList.push_back(OF);
108778681be2SJessica Paquette   }
1088596f483aSJessica Paquette }
1089596f483aSJessica Paquette 
10906b7615aeSPuyan Lotfi MachineFunction *MachineOutliner::createOutlinedFunction(
10916b7615aeSPuyan Lotfi     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
1092596f483aSJessica Paquette 
1093ae6c9403SFangrui Song   // Create the function name. This should be unique.
1094a3eb0facSJessica Paquette   // FIXME: We should have a better naming scheme. This should be stable,
1095a3eb0facSJessica Paquette   // regardless of changes to the outliner's cost model/traversal order.
1096ae6c9403SFangrui Song   std::string FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str();
1097596f483aSJessica Paquette 
1098596f483aSJessica Paquette   // Create the function using an IR-level function.
1099596f483aSJessica Paquette   LLVMContext &C = M.getContext();
1100ae6c9403SFangrui Song   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1101ae6c9403SFangrui Song                                  Function::ExternalLinkage, FunctionName, M);
1102596f483aSJessica Paquette 
1103596f483aSJessica Paquette   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1104596f483aSJessica Paquette   // which gives us better results when we outline from linkonceodr functions.
1105d506bf8eSJessica Paquette   F->setLinkage(GlobalValue::InternalLinkage);
1106596f483aSJessica Paquette   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1107596f483aSJessica Paquette 
110825bef201SEli Friedman   // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
110925bef201SEli Friedman   // necessary.
111025bef201SEli Friedman 
111125bef201SEli Friedman   // Set optsize/minsize, so we don't insert padding between outlined
111225bef201SEli Friedman   // functions.
111325bef201SEli Friedman   F->addFnAttr(Attribute::OptimizeForSize);
111425bef201SEli Friedman   F->addFnAttr(Attribute::MinSize);
111525bef201SEli Friedman 
1116e3932eeeSJessica Paquette   // Include target features from an arbitrary candidate for the outlined
1117e3932eeeSJessica Paquette   // function. This makes sure the outlined function knows what kinds of
1118e3932eeeSJessica Paquette   // instructions are going into it. This is fine, since all parent functions
1119e3932eeeSJessica Paquette   // must necessarily support the instructions that are in the outlined region.
1120e18d6ff0SJessica Paquette   Candidate &FirstCand = OF.Candidates.front();
112134b618bfSJessica Paquette   const Function &ParentFn = FirstCand.getMF()->getFunction();
1122e3932eeeSJessica Paquette   if (ParentFn.hasFnAttribute("target-features"))
1123e3932eeeSJessica Paquette     F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1124e3932eeeSJessica Paquette 
1125596f483aSJessica Paquette   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1126596f483aSJessica Paquette   IRBuilder<> Builder(EntryBB);
1127596f483aSJessica Paquette   Builder.CreateRetVoid();
1128596f483aSJessica Paquette 
1129cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
11307bda1958SMatthias Braun   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
1131596f483aSJessica Paquette   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1132596f483aSJessica Paquette   const TargetSubtargetInfo &STI = MF.getSubtarget();
1133596f483aSJessica Paquette   const TargetInstrInfo &TII = *STI.getInstrInfo();
1134596f483aSJessica Paquette 
1135596f483aSJessica Paquette   // Insert the new function into the module.
1136596f483aSJessica Paquette   MF.insert(MF.begin(), &MBB);
1137596f483aSJessica Paquette 
113834b618bfSJessica Paquette   for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
113934b618bfSJessica Paquette        ++I) {
114034b618bfSJessica Paquette     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
1141c73c0307SChandler Carruth     NewMI->dropMemRefs(MF);
1142596f483aSJessica Paquette 
1143596f483aSJessica Paquette     // Don't keep debug information for outlined instructions.
1144596f483aSJessica Paquette     NewMI->setDebugLoc(DebugLoc());
1145596f483aSJessica Paquette     MBB.insert(MBB.end(), NewMI);
1146596f483aSJessica Paquette   }
1147596f483aSJessica Paquette 
114869f517dfSJessica Paquette   TII.buildOutlinedFrame(MBB, MF, OF);
1149729e6869SJessica Paquette 
1150cc06a782SJessica Paquette   // Outlined functions shouldn't preserve liveness.
1151cc06a782SJessica Paquette   MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1152cc06a782SJessica Paquette   MF.getRegInfo().freezeReservedRegs(MF);
1153cc06a782SJessica Paquette 
1154a499c3c2SJessica Paquette   // If there's a DISubprogram associated with this outlined function, then
1155a499c3c2SJessica Paquette   // emit debug info for the outlined function.
1156aa087327SJessica Paquette   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1157a499c3c2SJessica Paquette     // We have a DISubprogram. Get its DICompileUnit.
1158a499c3c2SJessica Paquette     DICompileUnit *CU = SP->getUnit();
1159a499c3c2SJessica Paquette     DIBuilder DB(M, true, CU);
1160a499c3c2SJessica Paquette     DIFile *Unit = SP->getFile();
1161a499c3c2SJessica Paquette     Mangler Mg;
1162a499c3c2SJessica Paquette     // Get the mangled name of the function for the linkage name.
1163a499c3c2SJessica Paquette     std::string Dummy;
1164a499c3c2SJessica Paquette     llvm::raw_string_ostream MangledNameStream(Dummy);
1165a499c3c2SJessica Paquette     Mg.getNameWithPrefix(MangledNameStream, F, false);
1166a499c3c2SJessica Paquette 
1167cc06a782SJessica Paquette     DISubprogram *OutlinedSP = DB.createFunction(
1168a499c3c2SJessica Paquette         Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1169a499c3c2SJessica Paquette         Unit /* File */,
1170a499c3c2SJessica Paquette         0 /* Line 0 is reserved for compiler-generated code. */,
1171cc06a782SJessica Paquette         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
1172cda54210SPaul Robinson         0, /* Line 0 is reserved for compiler-generated code. */
1173a499c3c2SJessica Paquette         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1174cda54210SPaul Robinson         /* Outlined code is optimized code by definition. */
1175cda54210SPaul Robinson         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1176a499c3c2SJessica Paquette 
1177a499c3c2SJessica Paquette     // Don't add any new variables to the subprogram.
1178cc06a782SJessica Paquette     DB.finalizeSubprogram(OutlinedSP);
1179a499c3c2SJessica Paquette 
1180a499c3c2SJessica Paquette     // Attach subprogram to the function.
1181cc06a782SJessica Paquette     F->setSubprogram(OutlinedSP);
1182a499c3c2SJessica Paquette     // We're done with the DIBuilder.
1183a499c3c2SJessica Paquette     DB.finalize();
1184a499c3c2SJessica Paquette   }
1185a499c3c2SJessica Paquette 
1186596f483aSJessica Paquette   return &MF;
1187596f483aSJessica Paquette }
1188596f483aSJessica Paquette 
11894ae3b71dSJessica Paquette bool MachineOutliner::outline(Module &M,
11904ae3b71dSJessica Paquette                               std::vector<OutlinedFunction> &FunctionList,
1191a51fc8ddSPuyan Lotfi                               InstructionMapper &Mapper,
1192a51fc8ddSPuyan Lotfi                               unsigned &OutlinedFunctionNum) {
1193596f483aSJessica Paquette 
1194596f483aSJessica Paquette   bool OutlinedSomething = false;
1195a3eb0facSJessica Paquette 
1196962b3ae6SJessica Paquette   // Sort by benefit. The most beneficial functions should be outlined first.
1197efd94c56SFangrui Song   llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
1198efd94c56SFangrui Song                                      const OutlinedFunction &RHS) {
1199962b3ae6SJessica Paquette     return LHS.getBenefit() > RHS.getBenefit();
1200962b3ae6SJessica Paquette   });
1201596f483aSJessica Paquette 
1202962b3ae6SJessica Paquette   // Walk over each function, outlining them as we go along. Functions are
1203962b3ae6SJessica Paquette   // outlined greedily, based off the sort above.
1204962b3ae6SJessica Paquette   for (OutlinedFunction &OF : FunctionList) {
1205962b3ae6SJessica Paquette     // If we outlined something that overlapped with a candidate in a previous
1206962b3ae6SJessica Paquette     // step, then we can't outline from it.
1207e18d6ff0SJessica Paquette     erase_if(OF.Candidates, [&Mapper](Candidate &C) {
1208d9d9309bSJessica Paquette       return std::any_of(
1209e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getStartIdx(),
1210e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1211d9d9309bSJessica Paquette           [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
1212235d877eSJessica Paquette     });
1213596f483aSJessica Paquette 
1214962b3ae6SJessica Paquette     // If we made it unbeneficial to outline this function, skip it.
121585af63d0SJessica Paquette     if (OF.getBenefit() < 1)
1216596f483aSJessica Paquette       continue;
1217596f483aSJessica Paquette 
1218962b3ae6SJessica Paquette     // It's beneficial. Create the function and outline its sequence's
1219962b3ae6SJessica Paquette     // occurrences.
1220a3eb0facSJessica Paquette     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
122158e706a6SJessica Paquette     emitOutlinedFunctionRemark(OF);
1222acffa28cSJessica Paquette     FunctionsCreated++;
1223a3eb0facSJessica Paquette     OutlinedFunctionNum++; // Created a function, move to the next name.
1224596f483aSJessica Paquette     MachineFunction *MF = OF.MF;
1225596f483aSJessica Paquette     const TargetSubtargetInfo &STI = MF->getSubtarget();
1226596f483aSJessica Paquette     const TargetInstrInfo &TII = *STI.getInstrInfo();
1227596f483aSJessica Paquette 
1228962b3ae6SJessica Paquette     // Replace occurrences of the sequence with calls to the new function.
1229e18d6ff0SJessica Paquette     for (Candidate &C : OF.Candidates) {
1230962b3ae6SJessica Paquette       MachineBasicBlock &MBB = *C.getMBB();
1231962b3ae6SJessica Paquette       MachineBasicBlock::iterator StartIt = C.front();
1232962b3ae6SJessica Paquette       MachineBasicBlock::iterator EndIt = C.back();
1233596f483aSJessica Paquette 
1234962b3ae6SJessica Paquette       // Insert the call.
1235962b3ae6SJessica Paquette       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
1236962b3ae6SJessica Paquette 
1237962b3ae6SJessica Paquette       // If the caller tracks liveness, then we need to make sure that
1238962b3ae6SJessica Paquette       // anything we outline doesn't break liveness assumptions. The outlined
1239962b3ae6SJessica Paquette       // functions themselves currently don't track liveness, but we should
1240962b3ae6SJessica Paquette       // make sure that the ranges we yank things out of aren't wrong.
1241aa087327SJessica Paquette       if (MBB.getParent()->getProperties().hasProperty(
12420b672491SJessica Paquette               MachineFunctionProperties::Property::TracksLiveness)) {
1243962b3ae6SJessica Paquette         // Helper lambda for adding implicit def operands to the call
124471d3869fSDjordje Todorovic         // instruction. It also updates call site information for moved
124571d3869fSDjordje Todorovic         // code.
124671d3869fSDjordje Todorovic         auto CopyDefsAndUpdateCalls = [&CallInst](MachineInstr &MI) {
12470b672491SJessica Paquette           for (MachineOperand &MOP : MI.operands()) {
12480b672491SJessica Paquette             // Skip over anything that isn't a register.
12490b672491SJessica Paquette             if (!MOP.isReg())
12500b672491SJessica Paquette               continue;
12510b672491SJessica Paquette 
12520b672491SJessica Paquette             // If it's a def, add it to the call instruction.
12530b672491SJessica Paquette             if (MOP.isDef())
1254962b3ae6SJessica Paquette               CallInst->addOperand(MachineOperand::CreateReg(
1255962b3ae6SJessica Paquette                   MOP.getReg(), true, /* isDef = true */
12560b672491SJessica Paquette                   true /* isImp = true */));
12570b672491SJessica Paquette           }
125871d3869fSDjordje Todorovic           if (MI.isCall())
125998603a81SNikola Prica             MI.getMF()->eraseCallSiteInfo(&MI);
12600b672491SJessica Paquette         };
12610b672491SJessica Paquette         // Copy over the defs in the outlined range.
12620b672491SJessica Paquette         // First inst in outlined range <-- Anything that's defined in this
1263962b3ae6SJessica Paquette         // ...                           .. range has to be added as an
1264962b3ae6SJessica Paquette         // implicit Last inst in outlined range  <-- def to the call
126571d3869fSDjordje Todorovic         // instruction. Also remove call site information for outlined block
126671d3869fSDjordje Todorovic         // of code.
126771d3869fSDjordje Todorovic         std::for_each(CallInst, std::next(EndIt), CopyDefsAndUpdateCalls);
12680b672491SJessica Paquette       }
12690b672491SJessica Paquette 
1270aa087327SJessica Paquette       // Erase from the point after where the call was inserted up to, and
1271aa087327SJessica Paquette       // including, the final instruction in the sequence.
1272aa087327SJessica Paquette       // Erase needs one past the end, so we need std::next there too.
1273aa087327SJessica Paquette       MBB.erase(std::next(StartIt), std::next(EndIt));
1274235d877eSJessica Paquette 
1275d9d9309bSJessica Paquette       // Keep track of what we removed by marking them all as -1.
1276235d877eSJessica Paquette       std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1277235d877eSJessica Paquette                     Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1278d9d9309bSJessica Paquette                     [](unsigned &I) { I = static_cast<unsigned>(-1); });
1279596f483aSJessica Paquette       OutlinedSomething = true;
1280596f483aSJessica Paquette 
1281596f483aSJessica Paquette       // Statistics.
1282596f483aSJessica Paquette       NumOutlined++;
1283596f483aSJessica Paquette     }
1284962b3ae6SJessica Paquette   }
1285596f483aSJessica Paquette 
1286d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
1287596f483aSJessica Paquette 
1288596f483aSJessica Paquette   return OutlinedSomething;
1289596f483aSJessica Paquette }
1290596f483aSJessica Paquette 
1291050d1ac4SJessica Paquette void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1292050d1ac4SJessica Paquette                                      MachineModuleInfo &MMI) {
1293df82274fSJessica Paquette   // Build instruction mappings for each function in the module. Start by
1294df82274fSJessica Paquette   // iterating over each Function in M.
1295596f483aSJessica Paquette   for (Function &F : M) {
1296596f483aSJessica Paquette 
1297df82274fSJessica Paquette     // If there's nothing in F, then there's no reason to try and outline from
1298df82274fSJessica Paquette     // it.
1299df82274fSJessica Paquette     if (F.empty())
1300596f483aSJessica Paquette       continue;
1301596f483aSJessica Paquette 
1302784892c9SJessica Paquette     // Disable outlining from noreturn functions right now. Noreturn requires
1303784892c9SJessica Paquette     // special handling for the case where what we are outlining could be a
1304784892c9SJessica Paquette     // tail call.
1305784892c9SJessica Paquette     if (F.hasFnAttribute(Attribute::NoReturn))
1306784892c9SJessica Paquette       continue;
1307784892c9SJessica Paquette 
1308df82274fSJessica Paquette     // There's something in F. Check if it has a MachineFunction associated with
1309df82274fSJessica Paquette     // it.
1310df82274fSJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
1311596f483aSJessica Paquette 
1312df82274fSJessica Paquette     // If it doesn't, then there's nothing to outline from. Move to the next
1313df82274fSJessica Paquette     // Function.
1314df82274fSJessica Paquette     if (!MF)
1315596f483aSJessica Paquette       continue;
1316596f483aSJessica Paquette 
1317da08078fSEli Friedman     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1318da08078fSEli Friedman 
13198bda1881SJessica Paquette     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
13208bda1881SJessica Paquette       continue;
13218bda1881SJessica Paquette 
1322df82274fSJessica Paquette     // We have a MachineFunction. Ask the target if it's suitable for outlining.
1323df82274fSJessica Paquette     // If it isn't, then move on to the next Function in the module.
1324df82274fSJessica Paquette     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1325df82274fSJessica Paquette       continue;
1326df82274fSJessica Paquette 
1327df82274fSJessica Paquette     // We have a function suitable for outlining. Iterate over every
1328df82274fSJessica Paquette     // MachineBasicBlock in MF and try to map its instructions to a list of
1329df82274fSJessica Paquette     // unsigned integers.
1330df82274fSJessica Paquette     for (MachineBasicBlock &MBB : *MF) {
1331df82274fSJessica Paquette       // If there isn't anything in MBB, then there's no point in outlining from
1332df82274fSJessica Paquette       // it.
1333b320ca26SJessica Paquette       // If there are fewer than 2 instructions in the MBB, then it can't ever
1334b320ca26SJessica Paquette       // contain something worth outlining.
1335b320ca26SJessica Paquette       // FIXME: This should be based off of the maximum size in B of an outlined
1336b320ca26SJessica Paquette       // call versus the size in B of the MBB.
1337b320ca26SJessica Paquette       if (MBB.empty() || MBB.size() < 2)
1338df82274fSJessica Paquette         continue;
1339df82274fSJessica Paquette 
1340df82274fSJessica Paquette       // Check if MBB could be the target of an indirect branch. If it is, then
1341df82274fSJessica Paquette       // we don't want to outline from it.
1342df82274fSJessica Paquette       if (MBB.hasAddressTaken())
1343df82274fSJessica Paquette         continue;
1344df82274fSJessica Paquette 
1345df82274fSJessica Paquette       // MBB is suitable for outlining. Map it to a list of unsigneds.
1346da08078fSEli Friedman       Mapper.convertToUnsignedVec(MBB, *TII);
1347596f483aSJessica Paquette     }
1348596f483aSJessica Paquette   }
1349050d1ac4SJessica Paquette }
1350050d1ac4SJessica Paquette 
13512386eab3SJessica Paquette void MachineOutliner::initSizeRemarkInfo(
13522386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
13532386eab3SJessica Paquette     StringMap<unsigned> &FunctionToInstrCount) {
13542386eab3SJessica Paquette   // Collect instruction counts for every function. We'll use this to emit
13552386eab3SJessica Paquette   // per-function size remarks later.
13562386eab3SJessica Paquette   for (const Function &F : M) {
13572386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
13582386eab3SJessica Paquette 
13592386eab3SJessica Paquette     // We only care about MI counts here. If there's no MachineFunction at this
13602386eab3SJessica Paquette     // point, then there won't be after the outliner runs, so let's move on.
13612386eab3SJessica Paquette     if (!MF)
13622386eab3SJessica Paquette       continue;
13632386eab3SJessica Paquette     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
13642386eab3SJessica Paquette   }
13652386eab3SJessica Paquette }
13662386eab3SJessica Paquette 
13672386eab3SJessica Paquette void MachineOutliner::emitInstrCountChangedRemark(
13682386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
13692386eab3SJessica Paquette     const StringMap<unsigned> &FunctionToInstrCount) {
13702386eab3SJessica Paquette   // Iterate over each function in the module and emit remarks.
13712386eab3SJessica Paquette   // Note that we won't miss anything by doing this, because the outliner never
13722386eab3SJessica Paquette   // deletes functions.
13732386eab3SJessica Paquette   for (const Function &F : M) {
13742386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
13752386eab3SJessica Paquette 
13762386eab3SJessica Paquette     // The outliner never deletes functions. If we don't have a MF here, then we
13772386eab3SJessica Paquette     // didn't have one prior to outlining either.
13782386eab3SJessica Paquette     if (!MF)
13792386eab3SJessica Paquette       continue;
13802386eab3SJessica Paquette 
13812386eab3SJessica Paquette     std::string Fname = F.getName();
13822386eab3SJessica Paquette     unsigned FnCountAfter = MF->getInstructionCount();
13832386eab3SJessica Paquette     unsigned FnCountBefore = 0;
13842386eab3SJessica Paquette 
13852386eab3SJessica Paquette     // Check if the function was recorded before.
13862386eab3SJessica Paquette     auto It = FunctionToInstrCount.find(Fname);
13872386eab3SJessica Paquette 
13882386eab3SJessica Paquette     // Did we have a previously-recorded size? If yes, then set FnCountBefore
13892386eab3SJessica Paquette     // to that.
13902386eab3SJessica Paquette     if (It != FunctionToInstrCount.end())
13912386eab3SJessica Paquette       FnCountBefore = It->second;
13922386eab3SJessica Paquette 
13932386eab3SJessica Paquette     // Compute the delta and emit a remark if there was a change.
13942386eab3SJessica Paquette     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
13952386eab3SJessica Paquette                       static_cast<int64_t>(FnCountBefore);
13962386eab3SJessica Paquette     if (FnDelta == 0)
13972386eab3SJessica Paquette       continue;
13982386eab3SJessica Paquette 
13992386eab3SJessica Paquette     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
14002386eab3SJessica Paquette     MORE.emit([&]() {
14012386eab3SJessica Paquette       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
14026b7615aeSPuyan Lotfi                                           DiagnosticLocation(), &MF->front());
14032386eab3SJessica Paquette       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
14042386eab3SJessica Paquette         << ": Function: "
14052386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
14062386eab3SJessica Paquette         << ": MI instruction count changed from "
14072386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
14082386eab3SJessica Paquette                                                     FnCountBefore)
14092386eab3SJessica Paquette         << " to "
14102386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
14112386eab3SJessica Paquette                                                     FnCountAfter)
14122386eab3SJessica Paquette         << "; Delta: "
14132386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
14142386eab3SJessica Paquette       return R;
14152386eab3SJessica Paquette     });
14162386eab3SJessica Paquette   }
14172386eab3SJessica Paquette }
14182386eab3SJessica Paquette 
1419050d1ac4SJessica Paquette bool MachineOutliner::runOnModule(Module &M) {
1420050d1ac4SJessica Paquette   // Check if there's anything in the module. If it's empty, then there's
1421050d1ac4SJessica Paquette   // nothing to outline.
1422050d1ac4SJessica Paquette   if (M.empty())
1423050d1ac4SJessica Paquette     return false;
1424050d1ac4SJessica Paquette 
1425a51fc8ddSPuyan Lotfi   // Number to append to the current outlined function.
1426a51fc8ddSPuyan Lotfi   unsigned OutlinedFunctionNum = 0;
1427a51fc8ddSPuyan Lotfi 
1428a51fc8ddSPuyan Lotfi   if (!doOutline(M, OutlinedFunctionNum))
1429a51fc8ddSPuyan Lotfi     return false;
1430a51fc8ddSPuyan Lotfi   return true;
1431a51fc8ddSPuyan Lotfi }
1432a51fc8ddSPuyan Lotfi 
1433a51fc8ddSPuyan Lotfi bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1434cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1435050d1ac4SJessica Paquette 
1436050d1ac4SJessica Paquette   // If the user passed -enable-machine-outliner=always or
1437050d1ac4SJessica Paquette   // -enable-machine-outliner, the pass will run on all functions in the module.
1438050d1ac4SJessica Paquette   // Otherwise, if the target supports default outlining, it will run on all
1439050d1ac4SJessica Paquette   // functions deemed by the target to be worth outlining from by default. Tell
1440050d1ac4SJessica Paquette   // the user how the outliner is running.
14416b7615aeSPuyan Lotfi   LLVM_DEBUG({
1442050d1ac4SJessica Paquette     dbgs() << "Machine Outliner: Running on ";
1443050d1ac4SJessica Paquette     if (RunOnAllFunctions)
1444050d1ac4SJessica Paquette       dbgs() << "all functions";
1445050d1ac4SJessica Paquette     else
1446050d1ac4SJessica Paquette       dbgs() << "target-default functions";
14476b7615aeSPuyan Lotfi     dbgs() << "\n";
14486b7615aeSPuyan Lotfi   });
1449050d1ac4SJessica Paquette 
1450050d1ac4SJessica Paquette   // If the user specifies that they want to outline from linkonceodrs, set
1451050d1ac4SJessica Paquette   // it here.
1452050d1ac4SJessica Paquette   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1453050d1ac4SJessica Paquette   InstructionMapper Mapper;
1454050d1ac4SJessica Paquette 
1455050d1ac4SJessica Paquette   // Prepare instruction mappings for the suffix tree.
1456050d1ac4SJessica Paquette   populateMapper(Mapper, M, MMI);
1457596f483aSJessica Paquette   std::vector<OutlinedFunction> FunctionList;
1458596f483aSJessica Paquette 
1459acffa28cSJessica Paquette   // Find all of the outlining candidates.
1460ce3a2dcfSJessica Paquette   findCandidates(Mapper, FunctionList);
1461596f483aSJessica Paquette 
14622386eab3SJessica Paquette   // If we've requested size remarks, then collect the MI counts of every
14632386eab3SJessica Paquette   // function before outlining, and the MI counts after outlining.
14642386eab3SJessica Paquette   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
14652386eab3SJessica Paquette   // the pass manager's responsibility.
14662386eab3SJessica Paquette   // This could pretty easily be placed in outline instead, but because we
14672386eab3SJessica Paquette   // really ultimately *don't* want this here, it's done like this for now
14682386eab3SJessica Paquette   // instead.
14692386eab3SJessica Paquette 
14702386eab3SJessica Paquette   // Check if we want size remarks.
14712386eab3SJessica Paquette   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
14722386eab3SJessica Paquette   StringMap<unsigned> FunctionToInstrCount;
14732386eab3SJessica Paquette   if (ShouldEmitSizeRemarks)
14742386eab3SJessica Paquette     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
14752386eab3SJessica Paquette 
1476acffa28cSJessica Paquette   // Outline each of the candidates and return true if something was outlined.
1477a51fc8ddSPuyan Lotfi   bool OutlinedSomething =
1478a51fc8ddSPuyan Lotfi       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1479729e6869SJessica Paquette 
14802386eab3SJessica Paquette   // If we outlined something, we definitely changed the MI count of the
14812386eab3SJessica Paquette   // module. If we've asked for size remarks, then output them.
14822386eab3SJessica Paquette   // FIXME: This should be in the pass manager.
14832386eab3SJessica Paquette   if (ShouldEmitSizeRemarks && OutlinedSomething)
14842386eab3SJessica Paquette     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
14852386eab3SJessica Paquette 
1486729e6869SJessica Paquette   return OutlinedSomething;
1487596f483aSJessica Paquette }
1488