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"
59fc6fda90SJin Lin #include "llvm/ADT/SmallSet.h"
60596f483aSJessica Paquette #include "llvm/ADT/Statistic.h"
61596f483aSJessica Paquette #include "llvm/ADT/Twine.h"
62596f483aSJessica Paquette #include "llvm/CodeGen/MachineFunction.h"
63596f483aSJessica Paquette #include "llvm/CodeGen/MachineModuleInfo.h"
64ffe4abc5SJessica Paquette #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
6582203c41SGeoff Berry #include "llvm/CodeGen/MachineRegisterInfo.h"
66596f483aSJessica Paquette #include "llvm/CodeGen/Passes.h"
673f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
68b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
69729e6869SJessica Paquette #include "llvm/IR/DIBuilder.h"
70596f483aSJessica Paquette #include "llvm/IR/IRBuilder.h"
71a499c3c2SJessica Paquette #include "llvm/IR/Mangler.h"
7205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
73596f483aSJessica Paquette #include "llvm/Support/Allocator.h"
741eca23bdSJessica Paquette #include "llvm/Support/CommandLine.h"
75596f483aSJessica Paquette #include "llvm/Support/Debug.h"
76596f483aSJessica Paquette #include "llvm/Support/raw_ostream.h"
77596f483aSJessica Paquette #include <functional>
78596f483aSJessica Paquette #include <tuple>
79596f483aSJessica Paquette #include <vector>
80596f483aSJessica Paquette 
81596f483aSJessica Paquette #define DEBUG_TYPE "machine-outliner"
82596f483aSJessica Paquette 
83596f483aSJessica Paquette using namespace llvm;
84ffe4abc5SJessica Paquette using namespace ore;
85aa087327SJessica Paquette using namespace outliner;
86596f483aSJessica Paquette 
87596f483aSJessica Paquette STATISTIC(NumOutlined, "Number of candidates outlined");
88596f483aSJessica Paquette STATISTIC(FunctionsCreated, "Number of functions created");
89596f483aSJessica Paquette 
901eca23bdSJessica Paquette // Set to true if the user wants the outliner to run on linkonceodr linkage
911eca23bdSJessica Paquette // functions. This is false by default because the linker can dedupe linkonceodr
921eca23bdSJessica Paquette // functions. Since the outliner is confined to a single module (modulo LTO),
931eca23bdSJessica Paquette // this is off by default. It should, however, be the default behaviour in
941eca23bdSJessica Paquette // LTO.
951eca23bdSJessica Paquette static cl::opt<bool> EnableLinkOnceODROutlining(
966b7615aeSPuyan Lotfi     "enable-linkonceodr-outlining", cl::Hidden,
971eca23bdSJessica Paquette     cl::desc("Enable the machine outliner on linkonceodr functions"),
981eca23bdSJessica Paquette     cl::init(false));
991eca23bdSJessica Paquette 
100*ab2dcff3SJin Lin // Set the number of times to repeatedly apply outlining.
101*ab2dcff3SJin Lin // Defaults to 1, but more repetitions can save additional size.
102*ab2dcff3SJin Lin static cl::opt<unsigned>
103*ab2dcff3SJin Lin     NumRepeat("machine-outline-runs", cl::Hidden,
104*ab2dcff3SJin Lin               cl::desc("The number of times to apply machine outlining"),
105*ab2dcff3SJin Lin               cl::init(1));
106*ab2dcff3SJin Lin 
107596f483aSJessica Paquette namespace {
108596f483aSJessica Paquette 
109596f483aSJessica Paquette /// Represents an undefined index in the suffix tree.
1104cf187b5SJessica Paquette const unsigned EmptyIdx = -1;
111596f483aSJessica Paquette 
112596f483aSJessica Paquette /// A node in a suffix tree which represents a substring or suffix.
113596f483aSJessica Paquette ///
114596f483aSJessica Paquette /// Each node has either no children or at least two children, with the root
115596f483aSJessica Paquette /// being a exception in the empty tree.
116596f483aSJessica Paquette ///
117596f483aSJessica Paquette /// Children are represented as a map between unsigned integers and nodes. If
118596f483aSJessica Paquette /// a node N has a child M on unsigned integer k, then the mapping represented
119596f483aSJessica Paquette /// by N is a proper prefix of the mapping represented by M. Note that this,
120596f483aSJessica Paquette /// although similar to a trie is somewhat different: each node stores a full
121596f483aSJessica Paquette /// substring of the full mapping rather than a single character state.
122596f483aSJessica Paquette ///
123596f483aSJessica Paquette /// Each internal node contains a pointer to the internal node representing
124596f483aSJessica Paquette /// the same string, but with the first character chopped off. This is stored
125596f483aSJessica Paquette /// in \p Link. Each leaf node stores the start index of its respective
126596f483aSJessica Paquette /// suffix in \p SuffixIdx.
127596f483aSJessica Paquette struct SuffixTreeNode {
128596f483aSJessica Paquette 
129596f483aSJessica Paquette   /// The children of this node.
130596f483aSJessica Paquette   ///
131596f483aSJessica Paquette   /// A child existing on an unsigned integer implies that from the mapping
132596f483aSJessica Paquette   /// represented by the current node, there is a way to reach another
133596f483aSJessica Paquette   /// mapping by tacking that character on the end of the current string.
134596f483aSJessica Paquette   DenseMap<unsigned, SuffixTreeNode *> Children;
135596f483aSJessica Paquette 
136596f483aSJessica Paquette   /// The start index of this node's substring in the main string.
1374cf187b5SJessica Paquette   unsigned StartIdx = EmptyIdx;
138596f483aSJessica Paquette 
139596f483aSJessica Paquette   /// The end index of this node's substring in the main string.
140596f483aSJessica Paquette   ///
141596f483aSJessica Paquette   /// Every leaf node must have its \p EndIdx incremented at the end of every
142596f483aSJessica Paquette   /// step in the construction algorithm. To avoid having to update O(N)
143596f483aSJessica Paquette   /// nodes individually at the end of every step, the end index is stored
144596f483aSJessica Paquette   /// as a pointer.
1454cf187b5SJessica Paquette   unsigned *EndIdx = nullptr;
146596f483aSJessica Paquette 
147596f483aSJessica Paquette   /// For leaves, the start index of the suffix represented by this node.
148596f483aSJessica Paquette   ///
149596f483aSJessica Paquette   /// For all other nodes, this is ignored.
1504cf187b5SJessica Paquette   unsigned SuffixIdx = EmptyIdx;
151596f483aSJessica Paquette 
1525f8f34e4SAdrian Prantl   /// For internal nodes, a pointer to the internal node representing
153596f483aSJessica Paquette   /// the same sequence with the first character chopped off.
154596f483aSJessica Paquette   ///
1554602c343SJessica Paquette   /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
156596f483aSJessica Paquette   /// Ukkonen's algorithm does to achieve linear-time construction is
157596f483aSJessica Paquette   /// keep track of which node the next insert should be at. This makes each
158596f483aSJessica Paquette   /// insert O(1), and there are a total of O(N) inserts. The suffix link
159596f483aSJessica Paquette   /// helps with inserting children of internal nodes.
160596f483aSJessica Paquette   ///
161596f483aSJessica Paquette   /// Say we add a child to an internal node with associated mapping S. The
162596f483aSJessica Paquette   /// next insertion must be at the node representing S - its first character.
163596f483aSJessica Paquette   /// This is given by the way that we iteratively build the tree in Ukkonen's
164596f483aSJessica Paquette   /// algorithm. The main idea is to look at the suffixes of each prefix in the
165596f483aSJessica Paquette   /// string, starting with the longest suffix of the prefix, and ending with
166596f483aSJessica Paquette   /// the shortest. Therefore, if we keep pointers between such nodes, we can
167596f483aSJessica Paquette   /// move to the next insertion point in O(1) time. If we don't, then we'd
168596f483aSJessica Paquette   /// have to query from the root, which takes O(N) time. This would make the
169596f483aSJessica Paquette   /// construction algorithm O(N^2) rather than O(N).
170596f483aSJessica Paquette   SuffixTreeNode *Link = nullptr;
171596f483aSJessica Paquette 
172acffa28cSJessica Paquette   /// The length of the string formed by concatenating the edge labels from the
173acffa28cSJessica Paquette   /// root to this node.
1744cf187b5SJessica Paquette   unsigned ConcatLen = 0;
175acffa28cSJessica Paquette 
176596f483aSJessica Paquette   /// Returns true if this node is a leaf.
177596f483aSJessica Paquette   bool isLeaf() const { return SuffixIdx != EmptyIdx; }
178596f483aSJessica Paquette 
179596f483aSJessica Paquette   /// Returns true if this node is the root of its owning \p SuffixTree.
180596f483aSJessica Paquette   bool isRoot() const { return StartIdx == EmptyIdx; }
181596f483aSJessica Paquette 
182596f483aSJessica Paquette   /// Return the number of elements in the substring associated with this node.
183596f483aSJessica Paquette   size_t size() const {
184596f483aSJessica Paquette 
185596f483aSJessica Paquette     // Is it the root? If so, it's the empty string so return 0.
186596f483aSJessica Paquette     if (isRoot())
187596f483aSJessica Paquette       return 0;
188596f483aSJessica Paquette 
189596f483aSJessica Paquette     assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
190596f483aSJessica Paquette 
191596f483aSJessica Paquette     // Size = the number of elements in the string.
192596f483aSJessica Paquette     // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
193596f483aSJessica Paquette     return *EndIdx - StartIdx + 1;
194596f483aSJessica Paquette   }
195596f483aSJessica Paquette 
196df5b09b8SJessica Paquette   SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
197df5b09b8SJessica Paquette       : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
198596f483aSJessica Paquette 
199596f483aSJessica Paquette   SuffixTreeNode() {}
200596f483aSJessica Paquette };
201596f483aSJessica Paquette 
202596f483aSJessica Paquette /// A data structure for fast substring queries.
203596f483aSJessica Paquette ///
204596f483aSJessica Paquette /// Suffix trees represent the suffixes of their input strings in their leaves.
205596f483aSJessica Paquette /// A suffix tree is a type of compressed trie structure where each node
206596f483aSJessica Paquette /// represents an entire substring rather than a single character. Each leaf
207596f483aSJessica Paquette /// of the tree is a suffix.
208596f483aSJessica Paquette ///
209596f483aSJessica Paquette /// A suffix tree can be seen as a type of state machine where each state is a
210596f483aSJessica Paquette /// substring of the full string. The tree is structured so that, for a string
211596f483aSJessica Paquette /// of length N, there are exactly N leaves in the tree. This structure allows
212596f483aSJessica Paquette /// us to quickly find repeated substrings of the input string.
213596f483aSJessica Paquette ///
214596f483aSJessica Paquette /// In this implementation, a "string" is a vector of unsigned integers.
215596f483aSJessica Paquette /// These integers may result from hashing some data type. A suffix tree can
216596f483aSJessica Paquette /// contain 1 or many strings, which can then be queried as one large string.
217596f483aSJessica Paquette ///
218596f483aSJessica Paquette /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
219596f483aSJessica Paquette /// suffix tree construction. Ukkonen's algorithm is explained in more detail
220596f483aSJessica Paquette /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
221596f483aSJessica Paquette /// paper is available at
222596f483aSJessica Paquette ///
223596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
224596f483aSJessica Paquette class SuffixTree {
22578681be2SJessica Paquette public:
226596f483aSJessica Paquette   /// Each element is an integer representing an instruction in the module.
227596f483aSJessica Paquette   ArrayRef<unsigned> Str;
228596f483aSJessica Paquette 
2294e54ef88SJessica Paquette   /// A repeated substring in the tree.
2304e54ef88SJessica Paquette   struct RepeatedSubstring {
2314e54ef88SJessica Paquette     /// The length of the string.
2324e54ef88SJessica Paquette     unsigned Length;
2334e54ef88SJessica Paquette 
2344e54ef88SJessica Paquette     /// The start indices of each occurrence.
2354e54ef88SJessica Paquette     std::vector<unsigned> StartIndices;
2364e54ef88SJessica Paquette   };
2374e54ef88SJessica Paquette 
23878681be2SJessica Paquette private:
239596f483aSJessica Paquette   /// Maintains each node in the tree.
240d4cb9c6dSJessica Paquette   SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
241596f483aSJessica Paquette 
242596f483aSJessica Paquette   /// The root of the suffix tree.
243596f483aSJessica Paquette   ///
244596f483aSJessica Paquette   /// The root represents the empty string. It is maintained by the
245596f483aSJessica Paquette   /// \p NodeAllocator like every other node in the tree.
246596f483aSJessica Paquette   SuffixTreeNode *Root = nullptr;
247596f483aSJessica Paquette 
248596f483aSJessica Paquette   /// Maintains the end indices of the internal nodes in the tree.
249596f483aSJessica Paquette   ///
250596f483aSJessica Paquette   /// Each internal node is guaranteed to never have its end index change
251596f483aSJessica Paquette   /// during the construction algorithm; however, leaves must be updated at
252596f483aSJessica Paquette   /// every step. Therefore, we need to store leaf end indices by reference
253596f483aSJessica Paquette   /// to avoid updating O(N) leaves at every step of construction. Thus,
254596f483aSJessica Paquette   /// every internal node must be allocated its own end index.
255596f483aSJessica Paquette   BumpPtrAllocator InternalEndIdxAllocator;
256596f483aSJessica Paquette 
257596f483aSJessica Paquette   /// The end index of each leaf in the tree.
2584cf187b5SJessica Paquette   unsigned LeafEndIdx = -1;
259596f483aSJessica Paquette 
2605f8f34e4SAdrian Prantl   /// Helper struct which keeps track of the next insertion point in
261596f483aSJessica Paquette   /// Ukkonen's algorithm.
262596f483aSJessica Paquette   struct ActiveState {
263596f483aSJessica Paquette     /// The next node to insert at.
264c7f127d9SSimon Pilgrim     SuffixTreeNode *Node = nullptr;
265596f483aSJessica Paquette 
266596f483aSJessica Paquette     /// The index of the first character in the substring currently being added.
2674cf187b5SJessica Paquette     unsigned Idx = EmptyIdx;
268596f483aSJessica Paquette 
269596f483aSJessica Paquette     /// The length of the substring we have to add at the current step.
2704cf187b5SJessica Paquette     unsigned Len = 0;
271596f483aSJessica Paquette   };
272596f483aSJessica Paquette 
2735f8f34e4SAdrian Prantl   /// The point the next insertion will take place at in the
274596f483aSJessica Paquette   /// construction algorithm.
275596f483aSJessica Paquette   ActiveState Active;
276596f483aSJessica Paquette 
277596f483aSJessica Paquette   /// Allocate a leaf node and add it to the tree.
278596f483aSJessica Paquette   ///
279596f483aSJessica Paquette   /// \param Parent The parent of this node.
280596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
281596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
282596f483aSJessica Paquette   ///
283596f483aSJessica Paquette   /// \returns A pointer to the allocated leaf node.
2844cf187b5SJessica Paquette   SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
285596f483aSJessica Paquette                              unsigned Edge) {
286596f483aSJessica Paquette 
287596f483aSJessica Paquette     assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
288596f483aSJessica Paquette 
28978681be2SJessica Paquette     SuffixTreeNode *N = new (NodeAllocator.Allocate())
290df5b09b8SJessica Paquette         SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
291596f483aSJessica Paquette     Parent.Children[Edge] = N;
292596f483aSJessica Paquette 
293596f483aSJessica Paquette     return N;
294596f483aSJessica Paquette   }
295596f483aSJessica Paquette 
296596f483aSJessica Paquette   /// Allocate an internal node and add it to the tree.
297596f483aSJessica Paquette   ///
298596f483aSJessica Paquette   /// \param Parent The parent of this node. Only null when allocating the root.
299596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
300596f483aSJessica Paquette   /// \param EndIdx The end index of this node's associated string.
301596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
302596f483aSJessica Paquette   ///
303596f483aSJessica Paquette   /// \returns A pointer to the allocated internal node.
3044cf187b5SJessica Paquette   SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
3054cf187b5SJessica Paquette                                      unsigned EndIdx, unsigned Edge) {
306596f483aSJessica Paquette 
307596f483aSJessica Paquette     assert(StartIdx <= EndIdx && "String can't start after it ends!");
308596f483aSJessica Paquette     assert(!(!Parent && StartIdx != EmptyIdx) &&
309596f483aSJessica Paquette            "Non-root internal nodes must have parents!");
310596f483aSJessica Paquette 
3114cf187b5SJessica Paquette     unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
3126b7615aeSPuyan Lotfi     SuffixTreeNode *N =
3136b7615aeSPuyan Lotfi         new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root);
314596f483aSJessica Paquette     if (Parent)
315596f483aSJessica Paquette       Parent->Children[Edge] = N;
316596f483aSJessica Paquette 
317596f483aSJessica Paquette     return N;
318596f483aSJessica Paquette   }
319596f483aSJessica Paquette 
3205f8f34e4SAdrian Prantl   /// Set the suffix indices of the leaves to the start indices of their
3214e54ef88SJessica Paquette   /// respective suffixes.
322d5750770SJessica Paquette   void setSuffixIndices() {
323d5750770SJessica Paquette     // List of nodes we need to visit along with the current length of the
324d5750770SJessica Paquette     // string.
325d5750770SJessica Paquette     std::vector<std::pair<SuffixTreeNode *, unsigned>> ToVisit;
326596f483aSJessica Paquette 
327d5750770SJessica Paquette     // Current node being visited.
328d5750770SJessica Paquette     SuffixTreeNode *CurrNode = Root;
329596f483aSJessica Paquette 
330d5750770SJessica Paquette     // Sum of the lengths of the nodes down the path to the current one.
331d5750770SJessica Paquette     unsigned CurrNodeLen = 0;
332d5750770SJessica Paquette     ToVisit.push_back({CurrNode, CurrNodeLen});
333d5750770SJessica Paquette     while (!ToVisit.empty()) {
334d5750770SJessica Paquette       std::tie(CurrNode, CurrNodeLen) = ToVisit.back();
335d5750770SJessica Paquette       ToVisit.pop_back();
336d5750770SJessica Paquette       CurrNode->ConcatLen = CurrNodeLen;
337d5750770SJessica Paquette       for (auto &ChildPair : CurrNode->Children) {
338596f483aSJessica Paquette         assert(ChildPair.second && "Node had a null child!");
339d5750770SJessica Paquette         ToVisit.push_back(
340d5750770SJessica Paquette             {ChildPair.second, CurrNodeLen + ChildPair.second->size()});
341596f483aSJessica Paquette       }
342596f483aSJessica Paquette 
343d5750770SJessica Paquette       // No children, so we are at the end of the string.
344d5750770SJessica Paquette       if (CurrNode->Children.size() == 0 && !CurrNode->isRoot())
345d5750770SJessica Paquette         CurrNode->SuffixIdx = Str.size() - CurrNodeLen;
346d5750770SJessica Paquette     }
347596f483aSJessica Paquette   }
348596f483aSJessica Paquette 
3495f8f34e4SAdrian Prantl   /// Construct the suffix tree for the prefix of the input ending at
350596f483aSJessica Paquette   /// \p EndIdx.
351596f483aSJessica Paquette   ///
352596f483aSJessica Paquette   /// Used to construct the full suffix tree iteratively. At the end of each
353596f483aSJessica Paquette   /// step, the constructed suffix tree is either a valid suffix tree, or a
354596f483aSJessica Paquette   /// suffix tree with implicit suffixes. At the end of the final step, the
355596f483aSJessica Paquette   /// suffix tree is a valid tree.
356596f483aSJessica Paquette   ///
357596f483aSJessica Paquette   /// \param EndIdx The end index of the current prefix in the main string.
358596f483aSJessica Paquette   /// \param SuffixesToAdd The number of suffixes that must be added
359596f483aSJessica Paquette   /// to complete the suffix tree at the current phase.
360596f483aSJessica Paquette   ///
361596f483aSJessica Paquette   /// \returns The number of suffixes that have not been added at the end of
362596f483aSJessica Paquette   /// this step.
3634cf187b5SJessica Paquette   unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
364596f483aSJessica Paquette     SuffixTreeNode *NeedsLink = nullptr;
365596f483aSJessica Paquette 
366596f483aSJessica Paquette     while (SuffixesToAdd > 0) {
367596f483aSJessica Paquette 
368596f483aSJessica Paquette       // Are we waiting to add anything other than just the last character?
369596f483aSJessica Paquette       if (Active.Len == 0) {
370596f483aSJessica Paquette         // If not, then say the active index is the end index.
371596f483aSJessica Paquette         Active.Idx = EndIdx;
372596f483aSJessica Paquette       }
373596f483aSJessica Paquette 
374596f483aSJessica Paquette       assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
375596f483aSJessica Paquette 
376596f483aSJessica Paquette       // The first character in the current substring we're looking at.
377596f483aSJessica Paquette       unsigned FirstChar = Str[Active.Idx];
378596f483aSJessica Paquette 
379596f483aSJessica Paquette       // Have we inserted anything starting with FirstChar at the current node?
380596f483aSJessica Paquette       if (Active.Node->Children.count(FirstChar) == 0) {
381596f483aSJessica Paquette         // If not, then we can just insert a leaf and move too the next step.
382596f483aSJessica Paquette         insertLeaf(*Active.Node, EndIdx, FirstChar);
383596f483aSJessica Paquette 
384596f483aSJessica Paquette         // The active node is an internal node, and we visited it, so it must
385596f483aSJessica Paquette         // need a link if it doesn't have one.
386596f483aSJessica Paquette         if (NeedsLink) {
387596f483aSJessica Paquette           NeedsLink->Link = Active.Node;
388596f483aSJessica Paquette           NeedsLink = nullptr;
389596f483aSJessica Paquette         }
390596f483aSJessica Paquette       } else {
391596f483aSJessica Paquette         // There's a match with FirstChar, so look for the point in the tree to
392596f483aSJessica Paquette         // insert a new node.
393596f483aSJessica Paquette         SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
394596f483aSJessica Paquette 
3954cf187b5SJessica Paquette         unsigned SubstringLen = NextNode->size();
396596f483aSJessica Paquette 
397596f483aSJessica Paquette         // Is the current suffix we're trying to insert longer than the size of
398596f483aSJessica Paquette         // the child we want to move to?
399596f483aSJessica Paquette         if (Active.Len >= SubstringLen) {
400596f483aSJessica Paquette           // If yes, then consume the characters we've seen and move to the next
401596f483aSJessica Paquette           // node.
402596f483aSJessica Paquette           Active.Idx += SubstringLen;
403596f483aSJessica Paquette           Active.Len -= SubstringLen;
404596f483aSJessica Paquette           Active.Node = NextNode;
405596f483aSJessica Paquette           continue;
406596f483aSJessica Paquette         }
407596f483aSJessica Paquette 
408596f483aSJessica Paquette         // Otherwise, the suffix we're trying to insert must be contained in the
409596f483aSJessica Paquette         // next node we want to move to.
410596f483aSJessica Paquette         unsigned LastChar = Str[EndIdx];
411596f483aSJessica Paquette 
412596f483aSJessica Paquette         // Is the string we're trying to insert a substring of the next node?
413596f483aSJessica Paquette         if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
414596f483aSJessica Paquette           // If yes, then we're done for this step. Remember our insertion point
415596f483aSJessica Paquette           // and move to the next end index. At this point, we have an implicit
416596f483aSJessica Paquette           // suffix tree.
417596f483aSJessica Paquette           if (NeedsLink && !Active.Node->isRoot()) {
418596f483aSJessica Paquette             NeedsLink->Link = Active.Node;
419596f483aSJessica Paquette             NeedsLink = nullptr;
420596f483aSJessica Paquette           }
421596f483aSJessica Paquette 
422596f483aSJessica Paquette           Active.Len++;
423596f483aSJessica Paquette           break;
424596f483aSJessica Paquette         }
425596f483aSJessica Paquette 
426596f483aSJessica Paquette         // The string we're trying to insert isn't a substring of the next node,
427596f483aSJessica Paquette         // but matches up to a point. Split the node.
428596f483aSJessica Paquette         //
429596f483aSJessica Paquette         // For example, say we ended our search at a node n and we're trying to
430596f483aSJessica Paquette         // insert ABD. Then we'll create a new node s for AB, reduce n to just
431596f483aSJessica Paquette         // representing C, and insert a new leaf node l to represent d. This
432596f483aSJessica Paquette         // allows us to ensure that if n was a leaf, it remains a leaf.
433596f483aSJessica Paquette         //
434596f483aSJessica Paquette         //   | ABC  ---split--->  | AB
435596f483aSJessica Paquette         //   n                    s
436596f483aSJessica Paquette         //                     C / \ D
437596f483aSJessica Paquette         //                      n   l
438596f483aSJessica Paquette 
439596f483aSJessica Paquette         // The node s from the diagram
440596f483aSJessica Paquette         SuffixTreeNode *SplitNode =
44178681be2SJessica Paquette             insertInternalNode(Active.Node, NextNode->StartIdx,
44278681be2SJessica Paquette                                NextNode->StartIdx + Active.Len - 1, FirstChar);
443596f483aSJessica Paquette 
444596f483aSJessica Paquette         // Insert the new node representing the new substring into the tree as
445596f483aSJessica Paquette         // a child of the split node. This is the node l from the diagram.
446596f483aSJessica Paquette         insertLeaf(*SplitNode, EndIdx, LastChar);
447596f483aSJessica Paquette 
448596f483aSJessica Paquette         // Make the old node a child of the split node and update its start
449596f483aSJessica Paquette         // index. This is the node n from the diagram.
450596f483aSJessica Paquette         NextNode->StartIdx += Active.Len;
451596f483aSJessica Paquette         SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
452596f483aSJessica Paquette 
453596f483aSJessica Paquette         // SplitNode is an internal node, update the suffix link.
454596f483aSJessica Paquette         if (NeedsLink)
455596f483aSJessica Paquette           NeedsLink->Link = SplitNode;
456596f483aSJessica Paquette 
457596f483aSJessica Paquette         NeedsLink = SplitNode;
458596f483aSJessica Paquette       }
459596f483aSJessica Paquette 
460596f483aSJessica Paquette       // We've added something new to the tree, so there's one less suffix to
461596f483aSJessica Paquette       // add.
462596f483aSJessica Paquette       SuffixesToAdd--;
463596f483aSJessica Paquette 
464596f483aSJessica Paquette       if (Active.Node->isRoot()) {
465596f483aSJessica Paquette         if (Active.Len > 0) {
466596f483aSJessica Paquette           Active.Len--;
467596f483aSJessica Paquette           Active.Idx = EndIdx - SuffixesToAdd + 1;
468596f483aSJessica Paquette         }
469596f483aSJessica Paquette       } else {
470596f483aSJessica Paquette         // Start the next phase at the next smallest suffix.
471596f483aSJessica Paquette         Active.Node = Active.Node->Link;
472596f483aSJessica Paquette       }
473596f483aSJessica Paquette     }
474596f483aSJessica Paquette 
475596f483aSJessica Paquette     return SuffixesToAdd;
476596f483aSJessica Paquette   }
477596f483aSJessica Paquette 
478596f483aSJessica Paquette public:
479596f483aSJessica Paquette   /// Construct a suffix tree from a sequence of unsigned integers.
480596f483aSJessica Paquette   ///
481596f483aSJessica Paquette   /// \param Str The string to construct the suffix tree for.
482596f483aSJessica Paquette   SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
483596f483aSJessica Paquette     Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
484596f483aSJessica Paquette     Active.Node = Root;
485596f483aSJessica Paquette 
486596f483aSJessica Paquette     // Keep track of the number of suffixes we have to add of the current
487596f483aSJessica Paquette     // prefix.
4884cf187b5SJessica Paquette     unsigned SuffixesToAdd = 0;
489596f483aSJessica Paquette 
490596f483aSJessica Paquette     // Construct the suffix tree iteratively on each prefix of the string.
491596f483aSJessica Paquette     // PfxEndIdx is the end index of the current prefix.
492596f483aSJessica Paquette     // End is one past the last element in the string.
4934cf187b5SJessica Paquette     for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
4944cf187b5SJessica Paquette          PfxEndIdx++) {
495596f483aSJessica Paquette       SuffixesToAdd++;
496596f483aSJessica Paquette       LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
497596f483aSJessica Paquette       SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
498596f483aSJessica Paquette     }
499596f483aSJessica Paquette 
500596f483aSJessica Paquette     // Set the suffix indices of each leaf.
501596f483aSJessica Paquette     assert(Root && "Root node can't be nullptr!");
502d5750770SJessica Paquette     setSuffixIndices();
503596f483aSJessica Paquette   }
5044e54ef88SJessica Paquette 
505a409cc95SJessica Paquette   /// Iterator for finding all repeated substrings in the suffix tree.
506a409cc95SJessica Paquette   struct RepeatedSubstringIterator {
507a409cc95SJessica Paquette   private:
508a409cc95SJessica Paquette     /// The current node we're visiting.
509a409cc95SJessica Paquette     SuffixTreeNode *N = nullptr;
510a409cc95SJessica Paquette 
511a409cc95SJessica Paquette     /// The repeated substring associated with this node.
512a409cc95SJessica Paquette     RepeatedSubstring RS;
513a409cc95SJessica Paquette 
514a409cc95SJessica Paquette     /// The nodes left to visit.
515a409cc95SJessica Paquette     std::vector<SuffixTreeNode *> ToVisit;
516a409cc95SJessica Paquette 
517a409cc95SJessica Paquette     /// The minimum length of a repeated substring to find.
518a409cc95SJessica Paquette     /// Since we're outlining, we want at least two instructions in the range.
519a409cc95SJessica Paquette     /// FIXME: This may not be true for targets like X86 which support many
520a409cc95SJessica Paquette     /// instruction lengths.
521a409cc95SJessica Paquette     const unsigned MinLength = 2;
522a409cc95SJessica Paquette 
523a409cc95SJessica Paquette     /// Move the iterator to the next repeated substring.
524a409cc95SJessica Paquette     void advance() {
525a409cc95SJessica Paquette       // Clear the current state. If we're at the end of the range, then this
526a409cc95SJessica Paquette       // is the state we want to be in.
527a409cc95SJessica Paquette       RS = RepeatedSubstring();
528a409cc95SJessica Paquette       N = nullptr;
529a409cc95SJessica Paquette 
5303cd70b38SJessica Paquette       // Each leaf node represents a repeat of a string.
5313cd70b38SJessica Paquette       std::vector<SuffixTreeNode *> LeafChildren;
5323cd70b38SJessica Paquette 
533a409cc95SJessica Paquette       // Continue visiting nodes until we find one which repeats more than once.
534a409cc95SJessica Paquette       while (!ToVisit.empty()) {
535a409cc95SJessica Paquette         SuffixTreeNode *Curr = ToVisit.back();
536a409cc95SJessica Paquette         ToVisit.pop_back();
5373cd70b38SJessica Paquette         LeafChildren.clear();
538a409cc95SJessica Paquette 
539a409cc95SJessica Paquette         // Keep track of the length of the string associated with the node. If
540a409cc95SJessica Paquette         // it's too short, we'll quit.
541a409cc95SJessica Paquette         unsigned Length = Curr->ConcatLen;
542a409cc95SJessica Paquette 
543a409cc95SJessica Paquette         // Iterate over each child, saving internal nodes for visiting, and
544a409cc95SJessica Paquette         // leaf nodes in LeafChildren. Internal nodes represent individual
545a409cc95SJessica Paquette         // strings, which may repeat.
546a409cc95SJessica Paquette         for (auto &ChildPair : Curr->Children) {
547a409cc95SJessica Paquette           // Save all of this node's children for processing.
548a409cc95SJessica Paquette           if (!ChildPair.second->isLeaf())
549a409cc95SJessica Paquette             ToVisit.push_back(ChildPair.second);
550a409cc95SJessica Paquette 
551a409cc95SJessica Paquette           // It's not an internal node, so it must be a leaf. If we have a
552a409cc95SJessica Paquette           // long enough string, then save the leaf children.
553a409cc95SJessica Paquette           else if (Length >= MinLength)
554a409cc95SJessica Paquette             LeafChildren.push_back(ChildPair.second);
5554e54ef88SJessica Paquette         }
556a409cc95SJessica Paquette 
557a409cc95SJessica Paquette         // The root never represents a repeated substring. If we're looking at
558a409cc95SJessica Paquette         // that, then skip it.
559a409cc95SJessica Paquette         if (Curr->isRoot())
560a409cc95SJessica Paquette           continue;
561a409cc95SJessica Paquette 
562a409cc95SJessica Paquette         // Do we have any repeated substrings?
563a409cc95SJessica Paquette         if (LeafChildren.size() >= 2) {
564a409cc95SJessica Paquette           // Yes. Update the state to reflect this, and then bail out.
565a409cc95SJessica Paquette           N = Curr;
566a409cc95SJessica Paquette           RS.Length = Length;
567a409cc95SJessica Paquette           for (SuffixTreeNode *Leaf : LeafChildren)
568a409cc95SJessica Paquette             RS.StartIndices.push_back(Leaf->SuffixIdx);
569a409cc95SJessica Paquette           break;
570a409cc95SJessica Paquette         }
571a409cc95SJessica Paquette       }
572a409cc95SJessica Paquette 
573a409cc95SJessica Paquette       // At this point, either NewRS is an empty RepeatedSubstring, or it was
574a409cc95SJessica Paquette       // set in the above loop. Similarly, N is either nullptr, or the node
575a409cc95SJessica Paquette       // associated with NewRS.
576a409cc95SJessica Paquette     }
577a409cc95SJessica Paquette 
578a409cc95SJessica Paquette   public:
579a409cc95SJessica Paquette     /// Return the current repeated substring.
580a409cc95SJessica Paquette     RepeatedSubstring &operator*() { return RS; }
581a409cc95SJessica Paquette 
582a409cc95SJessica Paquette     RepeatedSubstringIterator &operator++() {
583a409cc95SJessica Paquette       advance();
584a409cc95SJessica Paquette       return *this;
585a409cc95SJessica Paquette     }
586a409cc95SJessica Paquette 
587a409cc95SJessica Paquette     RepeatedSubstringIterator operator++(int I) {
588a409cc95SJessica Paquette       RepeatedSubstringIterator It(*this);
589a409cc95SJessica Paquette       advance();
590a409cc95SJessica Paquette       return It;
591a409cc95SJessica Paquette     }
592a409cc95SJessica Paquette 
593a409cc95SJessica Paquette     bool operator==(const RepeatedSubstringIterator &Other) {
594a409cc95SJessica Paquette       return N == Other.N;
595a409cc95SJessica Paquette     }
596a409cc95SJessica Paquette     bool operator!=(const RepeatedSubstringIterator &Other) {
597a409cc95SJessica Paquette       return !(*this == Other);
598a409cc95SJessica Paquette     }
599a409cc95SJessica Paquette 
600a409cc95SJessica Paquette     RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
601a409cc95SJessica Paquette       // Do we have a non-null node?
602a409cc95SJessica Paquette       if (N) {
603a409cc95SJessica Paquette         // Yes. At the first step, we need to visit all of N's children.
604a409cc95SJessica Paquette         // Note: This means that we visit N last.
605a409cc95SJessica Paquette         ToVisit.push_back(N);
606a409cc95SJessica Paquette         advance();
607a409cc95SJessica Paquette       }
608a409cc95SJessica Paquette     }
609a409cc95SJessica Paquette   };
610a409cc95SJessica Paquette 
611a409cc95SJessica Paquette   typedef RepeatedSubstringIterator iterator;
612a409cc95SJessica Paquette   iterator begin() { return iterator(Root); }
613a409cc95SJessica Paquette   iterator end() { return iterator(nullptr); }
614596f483aSJessica Paquette };
615596f483aSJessica Paquette 
6165f8f34e4SAdrian Prantl /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
617596f483aSJessica Paquette struct InstructionMapper {
618596f483aSJessica Paquette 
6195f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that
620596f483aSJessica Paquette   /// cannot be outlined.
621596f483aSJessica Paquette   ///
622596f483aSJessica Paquette   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
623596f483aSJessica Paquette   unsigned IllegalInstrNumber = -3;
624596f483aSJessica Paquette 
6255f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that can
626596f483aSJessica Paquette   /// be outlined.
627596f483aSJessica Paquette   unsigned LegalInstrNumber = 0;
628596f483aSJessica Paquette 
629596f483aSJessica Paquette   /// Correspondence from \p MachineInstrs to unsigned integers.
630596f483aSJessica Paquette   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
631596f483aSJessica Paquette       InstructionIntegerMap;
632596f483aSJessica Paquette 
633cad864d4SJessica Paquette   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
634cad864d4SJessica Paquette   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
635cad864d4SJessica Paquette 
636596f483aSJessica Paquette   /// The vector of unsigned integers that the module is mapped to.
637596f483aSJessica Paquette   std::vector<unsigned> UnsignedVec;
638596f483aSJessica Paquette 
6395f8f34e4SAdrian Prantl   /// Stores the location of the instruction associated with the integer
640596f483aSJessica Paquette   /// at index i in \p UnsignedVec for each index i.
641596f483aSJessica Paquette   std::vector<MachineBasicBlock::iterator> InstrList;
642596f483aSJessica Paquette 
643c991cf36SJessica Paquette   // Set if we added an illegal number in the previous step.
644c991cf36SJessica Paquette   // Since each illegal number is unique, we only need one of them between
645c991cf36SJessica Paquette   // each range of legal numbers. This lets us make sure we don't add more
646c991cf36SJessica Paquette   // than one illegal number per range.
647c991cf36SJessica Paquette   bool AddedIllegalLastTime = false;
648c991cf36SJessica Paquette 
6495f8f34e4SAdrian Prantl   /// Maps \p *It to a legal integer.
650596f483aSJessica Paquette   ///
651c4cf775aSJessica Paquette   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
652ca3ed964SJessica Paquette   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
653596f483aSJessica Paquette   ///
654596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
655267d266cSJessica Paquette   unsigned mapToLegalUnsigned(
656c4cf775aSJessica Paquette       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
657c4cf775aSJessica Paquette       bool &HaveLegalRange, unsigned &NumLegalInBlock,
658267d266cSJessica Paquette       std::vector<unsigned> &UnsignedVecForMBB,
659267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
660c991cf36SJessica Paquette     // We added something legal, so we should unset the AddedLegalLastTime
661c991cf36SJessica Paquette     // flag.
662c991cf36SJessica Paquette     AddedIllegalLastTime = false;
663596f483aSJessica Paquette 
664c4cf775aSJessica Paquette     // If we have at least two adjacent legal instructions (which may have
665c4cf775aSJessica Paquette     // invisible instructions in between), remember that.
666c4cf775aSJessica Paquette     if (CanOutlineWithPrevInstr)
667c4cf775aSJessica Paquette       HaveLegalRange = true;
668c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = true;
669c4cf775aSJessica Paquette 
670267d266cSJessica Paquette     // Keep track of the number of legal instructions we insert.
671267d266cSJessica Paquette     NumLegalInBlock++;
672267d266cSJessica Paquette 
673596f483aSJessica Paquette     // Get the integer for this instruction or give it the current
674596f483aSJessica Paquette     // LegalInstrNumber.
675267d266cSJessica Paquette     InstrListForMBB.push_back(It);
676596f483aSJessica Paquette     MachineInstr &MI = *It;
677596f483aSJessica Paquette     bool WasInserted;
678596f483aSJessica Paquette     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
679596f483aSJessica Paquette         ResultIt;
680596f483aSJessica Paquette     std::tie(ResultIt, WasInserted) =
681596f483aSJessica Paquette         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
682596f483aSJessica Paquette     unsigned MINumber = ResultIt->second;
683596f483aSJessica Paquette 
684596f483aSJessica Paquette     // There was an insertion.
685ca3ed964SJessica Paquette     if (WasInserted)
686596f483aSJessica Paquette       LegalInstrNumber++;
687596f483aSJessica Paquette 
688267d266cSJessica Paquette     UnsignedVecForMBB.push_back(MINumber);
689596f483aSJessica Paquette 
690596f483aSJessica Paquette     // Make sure we don't overflow or use any integers reserved by the DenseMap.
691596f483aSJessica Paquette     if (LegalInstrNumber >= IllegalInstrNumber)
692596f483aSJessica Paquette       report_fatal_error("Instruction mapping overflow!");
693596f483aSJessica Paquette 
69478681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
69578681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
69678681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
69778681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
698596f483aSJessica Paquette 
699596f483aSJessica Paquette     return MINumber;
700596f483aSJessica Paquette   }
701596f483aSJessica Paquette 
702596f483aSJessica Paquette   /// Maps \p *It to an illegal integer.
703596f483aSJessica Paquette   ///
704267d266cSJessica Paquette   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
705267d266cSJessica Paquette   /// IllegalInstrNumber.
706596f483aSJessica Paquette   ///
707596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
7086b7615aeSPuyan Lotfi   unsigned mapToIllegalUnsigned(
7096b7615aeSPuyan Lotfi       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
7106b7615aeSPuyan Lotfi       std::vector<unsigned> &UnsignedVecForMBB,
711267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
712c4cf775aSJessica Paquette     // Can't outline an illegal instruction. Set the flag.
713c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = false;
714c4cf775aSJessica Paquette 
715c991cf36SJessica Paquette     // Only add one illegal number per range of legal numbers.
716c991cf36SJessica Paquette     if (AddedIllegalLastTime)
717c991cf36SJessica Paquette       return IllegalInstrNumber;
718c991cf36SJessica Paquette 
719c991cf36SJessica Paquette     // Remember that we added an illegal number last time.
720c991cf36SJessica Paquette     AddedIllegalLastTime = true;
721596f483aSJessica Paquette     unsigned MINumber = IllegalInstrNumber;
722596f483aSJessica Paquette 
723267d266cSJessica Paquette     InstrListForMBB.push_back(It);
724267d266cSJessica Paquette     UnsignedVecForMBB.push_back(IllegalInstrNumber);
725596f483aSJessica Paquette     IllegalInstrNumber--;
726596f483aSJessica Paquette 
727596f483aSJessica Paquette     assert(LegalInstrNumber < IllegalInstrNumber &&
728596f483aSJessica Paquette            "Instruction mapping overflow!");
729596f483aSJessica Paquette 
73078681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
731596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
732596f483aSJessica Paquette 
73378681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
734596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
735596f483aSJessica Paquette 
736596f483aSJessica Paquette     return MINumber;
737596f483aSJessica Paquette   }
738596f483aSJessica Paquette 
7395f8f34e4SAdrian Prantl   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
740596f483aSJessica Paquette   /// and appends it to \p UnsignedVec and \p InstrList.
741596f483aSJessica Paquette   ///
742596f483aSJessica Paquette   /// Two instructions are assigned the same integer if they are identical.
743596f483aSJessica Paquette   /// If an instruction is deemed unsafe to outline, then it will be assigned an
744596f483aSJessica Paquette   /// unique integer. The resulting mapping is placed into a suffix tree and
745596f483aSJessica Paquette   /// queried for candidates.
746596f483aSJessica Paquette   ///
747596f483aSJessica Paquette   /// \param MBB The \p MachineBasicBlock to be translated into integers.
748da08078fSEli Friedman   /// \param TII \p TargetInstrInfo for the function.
749596f483aSJessica Paquette   void convertToUnsignedVec(MachineBasicBlock &MBB,
750596f483aSJessica Paquette                             const TargetInstrInfo &TII) {
7513635c890SAlexander Kornienko     unsigned Flags = 0;
75282d9c0a3SJessica Paquette 
75382d9c0a3SJessica Paquette     // Don't even map in this case.
75482d9c0a3SJessica Paquette     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
75582d9c0a3SJessica Paquette       return;
75682d9c0a3SJessica Paquette 
757cad864d4SJessica Paquette     // Store info for the MBB for later outlining.
758cad864d4SJessica Paquette     MBBFlagsMap[&MBB] = Flags;
759cad864d4SJessica Paquette 
760c991cf36SJessica Paquette     MachineBasicBlock::iterator It = MBB.begin();
761267d266cSJessica Paquette 
762267d266cSJessica Paquette     // The number of instructions in this block that will be considered for
763267d266cSJessica Paquette     // outlining.
764267d266cSJessica Paquette     unsigned NumLegalInBlock = 0;
765267d266cSJessica Paquette 
766c4cf775aSJessica Paquette     // True if we have at least two legal instructions which aren't separated
767c4cf775aSJessica Paquette     // by an illegal instruction.
768c4cf775aSJessica Paquette     bool HaveLegalRange = false;
769c4cf775aSJessica Paquette 
770c4cf775aSJessica Paquette     // True if we can perform outlining given the last mapped (non-invisible)
771c4cf775aSJessica Paquette     // instruction. This lets us know if we have a legal range.
772c4cf775aSJessica Paquette     bool CanOutlineWithPrevInstr = false;
773c4cf775aSJessica Paquette 
774267d266cSJessica Paquette     // FIXME: Should this all just be handled in the target, rather than using
775267d266cSJessica Paquette     // repeated calls to getOutliningType?
776267d266cSJessica Paquette     std::vector<unsigned> UnsignedVecForMBB;
777267d266cSJessica Paquette     std::vector<MachineBasicBlock::iterator> InstrListForMBB;
778267d266cSJessica Paquette 
77976166a1aSSimon Pilgrim     for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
780596f483aSJessica Paquette       // Keep track of where this instruction is in the module.
7813291e735SJessica Paquette       switch (TII.getOutliningType(It, Flags)) {
782aa087327SJessica Paquette       case InstrType::Illegal:
7836b7615aeSPuyan Lotfi         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
7846b7615aeSPuyan Lotfi                              InstrListForMBB);
785596f483aSJessica Paquette         break;
786596f483aSJessica Paquette 
787aa087327SJessica Paquette       case InstrType::Legal:
788c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
789c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
790596f483aSJessica Paquette         break;
791596f483aSJessica Paquette 
792aa087327SJessica Paquette       case InstrType::LegalTerminator:
793c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
794c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
795c991cf36SJessica Paquette         // The instruction also acts as a terminator, so we have to record that
796c991cf36SJessica Paquette         // in the string.
797c4cf775aSJessica Paquette         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
798c4cf775aSJessica Paquette                              InstrListForMBB);
799042dc9e0SEli Friedman         break;
800042dc9e0SEli Friedman 
801aa087327SJessica Paquette       case InstrType::Invisible:
802c991cf36SJessica Paquette         // Normally this is set by mapTo(Blah)Unsigned, but we just want to
803c991cf36SJessica Paquette         // skip this instruction. So, unset the flag here.
804bd72988cSJessica Paquette         AddedIllegalLastTime = false;
805596f483aSJessica Paquette         break;
806596f483aSJessica Paquette       }
807596f483aSJessica Paquette     }
808596f483aSJessica Paquette 
809267d266cSJessica Paquette     // Are there enough legal instructions in the block for outlining to be
810267d266cSJessica Paquette     // possible?
811c4cf775aSJessica Paquette     if (HaveLegalRange) {
812596f483aSJessica Paquette       // After we're done every insertion, uniquely terminate this part of the
813596f483aSJessica Paquette       // "string". This makes sure we won't match across basic block or function
814596f483aSJessica Paquette       // boundaries since the "end" is encoded uniquely and thus appears in no
815596f483aSJessica Paquette       // repeated substring.
816c4cf775aSJessica Paquette       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
817c4cf775aSJessica Paquette                            InstrListForMBB);
818267d266cSJessica Paquette       InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
819267d266cSJessica Paquette                        InstrListForMBB.end());
820267d266cSJessica Paquette       UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
821267d266cSJessica Paquette                          UnsignedVecForMBB.end());
822267d266cSJessica Paquette     }
823596f483aSJessica Paquette   }
824596f483aSJessica Paquette 
825596f483aSJessica Paquette   InstructionMapper() {
826596f483aSJessica Paquette     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
827596f483aSJessica Paquette     // changed.
828596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
829596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s empty key isn't -1!");
830596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
831596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
832596f483aSJessica Paquette   }
833596f483aSJessica Paquette };
834596f483aSJessica Paquette 
8355f8f34e4SAdrian Prantl /// An interprocedural pass which finds repeated sequences of
836596f483aSJessica Paquette /// instructions and replaces them with calls to functions.
837596f483aSJessica Paquette ///
838596f483aSJessica Paquette /// Each instruction is mapped to an unsigned integer and placed in a string.
839596f483aSJessica Paquette /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
840596f483aSJessica Paquette /// is then repeatedly queried for repeated sequences of instructions. Each
841596f483aSJessica Paquette /// non-overlapping repeated sequence is then placed in its own
842596f483aSJessica Paquette /// \p MachineFunction and each instance is then replaced with a call to that
843596f483aSJessica Paquette /// function.
844596f483aSJessica Paquette struct MachineOutliner : public ModulePass {
845596f483aSJessica Paquette 
846596f483aSJessica Paquette   static char ID;
847596f483aSJessica Paquette 
8485f8f34e4SAdrian Prantl   /// Set to true if the outliner should consider functions with
84913593843SJessica Paquette   /// linkonceodr linkage.
85013593843SJessica Paquette   bool OutlineFromLinkOnceODRs = false;
85113593843SJessica Paquette 
852*ab2dcff3SJin Lin   /// The current repeat number of machine outlining.
853*ab2dcff3SJin Lin   unsigned OutlineRepeatedNum = 0;
854*ab2dcff3SJin Lin 
8558bda1881SJessica Paquette   /// Set to true if the outliner should run on all functions in the module
8568bda1881SJessica Paquette   /// considered safe for outlining.
8578bda1881SJessica Paquette   /// Set to true by default for compatibility with llc's -run-pass option.
8588bda1881SJessica Paquette   /// Set when the pass is constructed in TargetPassConfig.
8598bda1881SJessica Paquette   bool RunOnAllFunctions = true;
8608bda1881SJessica Paquette 
861596f483aSJessica Paquette   StringRef getPassName() const override { return "Machine Outliner"; }
862596f483aSJessica Paquette 
863596f483aSJessica Paquette   void getAnalysisUsage(AnalysisUsage &AU) const override {
864cc382cf7SYuanfang Chen     AU.addRequired<MachineModuleInfoWrapperPass>();
865cc382cf7SYuanfang Chen     AU.addPreserved<MachineModuleInfoWrapperPass>();
866596f483aSJessica Paquette     AU.setPreservesAll();
867596f483aSJessica Paquette     ModulePass::getAnalysisUsage(AU);
868596f483aSJessica Paquette   }
869596f483aSJessica Paquette 
8701eca23bdSJessica Paquette   MachineOutliner() : ModulePass(ID) {
871596f483aSJessica Paquette     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
872596f483aSJessica Paquette   }
873596f483aSJessica Paquette 
8741cc52a00SJessica Paquette   /// Remark output explaining that not outlining a set of candidates would be
8751cc52a00SJessica Paquette   /// better than outlining that set.
8761cc52a00SJessica Paquette   void emitNotOutliningCheaperRemark(
8771cc52a00SJessica Paquette       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
8781cc52a00SJessica Paquette       OutlinedFunction &OF);
8791cc52a00SJessica Paquette 
88058e706a6SJessica Paquette   /// Remark output explaining that a function was outlined.
88158e706a6SJessica Paquette   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
88258e706a6SJessica Paquette 
883ce3a2dcfSJessica Paquette   /// Find all repeated substrings that satisfy the outlining cost model by
884ce3a2dcfSJessica Paquette   /// constructing a suffix tree.
88578681be2SJessica Paquette   ///
88678681be2SJessica Paquette   /// If a substring appears at least twice, then it must be represented by
8871cc52a00SJessica Paquette   /// an internal node which appears in at least two suffixes. Each suffix
8881cc52a00SJessica Paquette   /// is represented by a leaf node. To do this, we visit each internal node
8891cc52a00SJessica Paquette   /// in the tree, using the leaf children of each internal node. If an
8901cc52a00SJessica Paquette   /// internal node represents a beneficial substring, then we use each of
8911cc52a00SJessica Paquette   /// its leaf children to find the locations of its substring.
89278681be2SJessica Paquette   ///
89378681be2SJessica Paquette   /// \param Mapper Contains outlining mapping information.
8941cc52a00SJessica Paquette   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
8951cc52a00SJessica Paquette   /// each type of candidate.
896ce3a2dcfSJessica Paquette   void findCandidates(InstructionMapper &Mapper,
89778681be2SJessica Paquette                       std::vector<OutlinedFunction> &FunctionList);
89878681be2SJessica Paquette 
8994ae3b71dSJessica Paquette   /// Replace the sequences of instructions represented by \p OutlinedFunctions
9004ae3b71dSJessica Paquette   /// with calls to functions.
901596f483aSJessica Paquette   ///
902596f483aSJessica Paquette   /// \param M The module we are outlining from.
903596f483aSJessica Paquette   /// \param FunctionList A list of functions to be inserted into the module.
904596f483aSJessica Paquette   /// \param Mapper Contains the instruction mappings for the module.
9054ae3b71dSJessica Paquette   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
9066b7615aeSPuyan Lotfi                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
907596f483aSJessica Paquette 
908596f483aSJessica Paquette   /// Creates a function for \p OF and inserts it into the module.
909e18d6ff0SJessica Paquette   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
910a3eb0facSJessica Paquette                                           InstructionMapper &Mapper,
911a3eb0facSJessica Paquette                                           unsigned Name);
912596f483aSJessica Paquette 
913*ab2dcff3SJin Lin   /// Calls runOnceOnModule NumRepeat times
914b9f1b8beSJin Lin   bool runOnModule(Module &M) override;
9151f93b162SJin Lin 
916*ab2dcff3SJin Lin   /// Calls 'doOutline()'.
917*ab2dcff3SJin Lin   bool runOnceOnModule(Module &M, unsigned Iter);
918*ab2dcff3SJin Lin 
919596f483aSJessica Paquette   /// Construct a suffix tree on the instructions in \p M and outline repeated
920596f483aSJessica Paquette   /// strings from that tree.
921a51fc8ddSPuyan Lotfi   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
922aa087327SJessica Paquette 
923aa087327SJessica Paquette   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
924aa087327SJessica Paquette   /// function for remark emission.
925aa087327SJessica Paquette   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
926e18d6ff0SJessica Paquette     for (const Candidate &C : OF.Candidates)
9277ad25836SSimon Pilgrim       if (MachineFunction *MF = C.getMF())
9287ad25836SSimon Pilgrim         if (DISubprogram *SP = MF->getFunction().getSubprogram())
929aa087327SJessica Paquette           return SP;
930aa087327SJessica Paquette     return nullptr;
931aa087327SJessica Paquette   }
932050d1ac4SJessica Paquette 
933050d1ac4SJessica Paquette   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
934050d1ac4SJessica Paquette   /// These are used to construct a suffix tree.
935050d1ac4SJessica Paquette   void populateMapper(InstructionMapper &Mapper, Module &M,
936050d1ac4SJessica Paquette                       MachineModuleInfo &MMI);
937596f483aSJessica Paquette 
9382386eab3SJessica Paquette   /// Initialize information necessary to output a size remark.
9392386eab3SJessica Paquette   /// FIXME: This should be handled by the pass manager, not the outliner.
9402386eab3SJessica Paquette   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
9412386eab3SJessica Paquette   /// pass manager.
9426b7615aeSPuyan Lotfi   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
9432386eab3SJessica Paquette                           StringMap<unsigned> &FunctionToInstrCount);
9442386eab3SJessica Paquette 
9452386eab3SJessica Paquette   /// Emit the remark.
9462386eab3SJessica Paquette   // FIXME: This should be handled by the pass manager, not the outliner.
9476b7615aeSPuyan Lotfi   void
9486b7615aeSPuyan Lotfi   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
9492386eab3SJessica Paquette                               const StringMap<unsigned> &FunctionToInstrCount);
9502386eab3SJessica Paquette };
951596f483aSJessica Paquette } // Anonymous namespace.
952596f483aSJessica Paquette 
953596f483aSJessica Paquette char MachineOutliner::ID = 0;
954596f483aSJessica Paquette 
955596f483aSJessica Paquette namespace llvm {
9568bda1881SJessica Paquette ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
9578bda1881SJessica Paquette   MachineOutliner *OL = new MachineOutliner();
9588bda1881SJessica Paquette   OL->RunOnAllFunctions = RunOnAllFunctions;
9598bda1881SJessica Paquette   return OL;
96013593843SJessica Paquette }
96113593843SJessica Paquette 
96278681be2SJessica Paquette } // namespace llvm
96378681be2SJessica Paquette 
96478681be2SJessica Paquette INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
96578681be2SJessica Paquette                 false)
96678681be2SJessica Paquette 
9671cc52a00SJessica Paquette void MachineOutliner::emitNotOutliningCheaperRemark(
9681cc52a00SJessica Paquette     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
9691cc52a00SJessica Paquette     OutlinedFunction &OF) {
970c991cf36SJessica Paquette   // FIXME: Right now, we arbitrarily choose some Candidate from the
971c991cf36SJessica Paquette   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
972c991cf36SJessica Paquette   // We should probably sort these by function name or something to make sure
973c991cf36SJessica Paquette   // the remarks are stable.
9741cc52a00SJessica Paquette   Candidate &C = CandidatesForRepeatedSeq.front();
9751cc52a00SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
9761cc52a00SJessica Paquette   MORE.emit([&]() {
9771cc52a00SJessica Paquette     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
9781cc52a00SJessica Paquette                                       C.front()->getDebugLoc(), C.getMBB());
9791cc52a00SJessica Paquette     R << "Did not outline " << NV("Length", StringLen) << " instructions"
9801cc52a00SJessica Paquette       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
9811cc52a00SJessica Paquette       << " locations."
9821cc52a00SJessica Paquette       << " Bytes from outlining all occurrences ("
9831cc52a00SJessica Paquette       << NV("OutliningCost", OF.getOutliningCost()) << ")"
9841cc52a00SJessica Paquette       << " >= Unoutlined instruction bytes ("
9851cc52a00SJessica Paquette       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
9861cc52a00SJessica Paquette       << " (Also found at: ";
9871cc52a00SJessica Paquette 
9881cc52a00SJessica Paquette     // Tell the user the other places the candidate was found.
9891cc52a00SJessica Paquette     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
9901cc52a00SJessica Paquette       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
9911cc52a00SJessica Paquette               CandidatesForRepeatedSeq[i].front()->getDebugLoc());
9921cc52a00SJessica Paquette       if (i != e - 1)
9931cc52a00SJessica Paquette         R << ", ";
9941cc52a00SJessica Paquette     }
9951cc52a00SJessica Paquette 
9961cc52a00SJessica Paquette     R << ")";
9971cc52a00SJessica Paquette     return R;
9981cc52a00SJessica Paquette   });
9991cc52a00SJessica Paquette }
10001cc52a00SJessica Paquette 
100158e706a6SJessica Paquette void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
100258e706a6SJessica Paquette   MachineBasicBlock *MBB = &*OF.MF->begin();
100358e706a6SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
100458e706a6SJessica Paquette   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
100558e706a6SJessica Paquette                               MBB->findDebugLoc(MBB->begin()), MBB);
100658e706a6SJessica Paquette   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
100734b618bfSJessica Paquette     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
100858e706a6SJessica Paquette     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
100958e706a6SJessica Paquette     << " locations. "
101058e706a6SJessica Paquette     << "(Found at: ";
101158e706a6SJessica Paquette 
101258e706a6SJessica Paquette   // Tell the user the other places the candidate was found.
101358e706a6SJessica Paquette   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
101458e706a6SJessica Paquette 
101558e706a6SJessica Paquette     R << NV((Twine("StartLoc") + Twine(i)).str(),
1016e18d6ff0SJessica Paquette             OF.Candidates[i].front()->getDebugLoc());
101758e706a6SJessica Paquette     if (i != e - 1)
101858e706a6SJessica Paquette       R << ", ";
101958e706a6SJessica Paquette   }
102058e706a6SJessica Paquette 
102158e706a6SJessica Paquette   R << ")";
102258e706a6SJessica Paquette 
102358e706a6SJessica Paquette   MORE.emit(R);
102458e706a6SJessica Paquette }
102558e706a6SJessica Paquette 
10266b7615aeSPuyan Lotfi void MachineOutliner::findCandidates(
10276b7615aeSPuyan Lotfi     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
102878681be2SJessica Paquette   FunctionList.clear();
1029ce3a2dcfSJessica Paquette   SuffixTree ST(Mapper.UnsignedVec);
103078681be2SJessica Paquette 
1031fbe7f5e9SDavid Tellenbach   // First, find all of the repeated substrings in the tree of minimum length
10324e54ef88SJessica Paquette   // 2.
1033d87f5449SJessica Paquette   std::vector<Candidate> CandidatesForRepeatedSeq;
1034d4e7d074SJessica Paquette   for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
1035d4e7d074SJessica Paquette     CandidatesForRepeatedSeq.clear();
1036d4e7d074SJessica Paquette     SuffixTree::RepeatedSubstring RS = *It;
10374e54ef88SJessica Paquette     unsigned StringLen = RS.Length;
10384e54ef88SJessica Paquette     for (const unsigned &StartIdx : RS.StartIndices) {
103952df8015SJessica Paquette       unsigned EndIdx = StartIdx + StringLen - 1;
104052df8015SJessica Paquette       // Trick: Discard some candidates that would be incompatible with the
104152df8015SJessica Paquette       // ones we've already found for this sequence. This will save us some
104252df8015SJessica Paquette       // work in candidate selection.
104352df8015SJessica Paquette       //
104452df8015SJessica Paquette       // If two candidates overlap, then we can't outline them both. This
104552df8015SJessica Paquette       // happens when we have candidates that look like, say
104652df8015SJessica Paquette       //
104752df8015SJessica Paquette       // AA (where each "A" is an instruction).
104852df8015SJessica Paquette       //
104952df8015SJessica Paquette       // We might have some portion of the module that looks like this:
105052df8015SJessica Paquette       // AAAAAA (6 A's)
105152df8015SJessica Paquette       //
105252df8015SJessica Paquette       // In this case, there are 5 different copies of "AA" in this range, but
105352df8015SJessica Paquette       // at most 3 can be outlined. If only outlining 3 of these is going to
105452df8015SJessica Paquette       // be unbeneficial, then we ought to not bother.
105552df8015SJessica Paquette       //
105652df8015SJessica Paquette       // Note that two things DON'T overlap when they look like this:
105752df8015SJessica Paquette       // start1...end1 .... start2...end2
105852df8015SJessica Paquette       // That is, one must either
105952df8015SJessica Paquette       // * End before the other starts
106052df8015SJessica Paquette       // * Start after the other ends
10614e54ef88SJessica Paquette       if (std::all_of(
10624e54ef88SJessica Paquette               CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
106352df8015SJessica Paquette               [&StartIdx, &EndIdx](const Candidate &C) {
10644e54ef88SJessica Paquette                 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
106552df8015SJessica Paquette               })) {
106652df8015SJessica Paquette         // It doesn't overlap with anything, so we can outline it.
106752df8015SJessica Paquette         // Each sequence is over [StartIt, EndIt].
1068aa087327SJessica Paquette         // Save the candidate and its location.
1069aa087327SJessica Paquette 
107052df8015SJessica Paquette         MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
107152df8015SJessica Paquette         MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1072cad864d4SJessica Paquette         MachineBasicBlock *MBB = StartIt->getParent();
107352df8015SJessica Paquette 
1074aa087327SJessica Paquette         CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
1075cad864d4SJessica Paquette                                               EndIt, MBB, FunctionList.size(),
1076cad864d4SJessica Paquette                                               Mapper.MBBFlagsMap[MBB]);
107752df8015SJessica Paquette       }
1078809d708bSJessica Paquette     }
1079809d708bSJessica Paquette 
1080acc15e12SJessica Paquette     // We've found something we might want to outline.
1081acc15e12SJessica Paquette     // Create an OutlinedFunction to store it and check if it'd be beneficial
1082acc15e12SJessica Paquette     // to outline.
1083ddb039a1SJessica Paquette     if (CandidatesForRepeatedSeq.size() < 2)
1084da08078fSEli Friedman       continue;
1085da08078fSEli Friedman 
1086da08078fSEli Friedman     // Arbitrarily choose a TII from the first candidate.
1087da08078fSEli Friedman     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1088da08078fSEli Friedman     const TargetInstrInfo *TII =
1089da08078fSEli Friedman         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1090da08078fSEli Friedman 
10919d93c602SJessica Paquette     OutlinedFunction OF =
1092da08078fSEli Friedman         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
10939d93c602SJessica Paquette 
1094b2d53c5dSJessica Paquette     // If we deleted too many candidates, then there's nothing worth outlining.
1095b2d53c5dSJessica Paquette     // FIXME: This should take target-specified instruction sizes into account.
1096b2d53c5dSJessica Paquette     if (OF.Candidates.size() < 2)
10979d93c602SJessica Paquette       continue;
10989d93c602SJessica Paquette 
1099ffe4abc5SJessica Paquette     // Is it better to outline this candidate than not?
1100f94d1d29SJessica Paquette     if (OF.getBenefit() < 1) {
11011cc52a00SJessica Paquette       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
110278681be2SJessica Paquette       continue;
1103ffe4abc5SJessica Paquette     }
110478681be2SJessica Paquette 
1105acc15e12SJessica Paquette     FunctionList.push_back(OF);
110678681be2SJessica Paquette   }
1107596f483aSJessica Paquette }
1108596f483aSJessica Paquette 
11096b7615aeSPuyan Lotfi MachineFunction *MachineOutliner::createOutlinedFunction(
11106b7615aeSPuyan Lotfi     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
1111596f483aSJessica Paquette 
1112ae6c9403SFangrui Song   // Create the function name. This should be unique.
1113a3eb0facSJessica Paquette   // FIXME: We should have a better naming scheme. This should be stable,
1114a3eb0facSJessica Paquette   // regardless of changes to the outliner's cost model/traversal order.
1115*ab2dcff3SJin Lin   std::string FunctionName;
1116*ab2dcff3SJin Lin   if (OutlineRepeatedNum > 0)
1117*ab2dcff3SJin Lin     FunctionName = ("OUTLINED_FUNCTION_" + Twine(OutlineRepeatedNum + 1) + "_" +
1118*ab2dcff3SJin Lin                     Twine(Name))
1119*ab2dcff3SJin Lin                        .str();
1120*ab2dcff3SJin Lin   else
1121*ab2dcff3SJin Lin     FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str();
1122596f483aSJessica Paquette 
1123596f483aSJessica Paquette   // Create the function using an IR-level function.
1124596f483aSJessica Paquette   LLVMContext &C = M.getContext();
1125ae6c9403SFangrui Song   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1126ae6c9403SFangrui Song                                  Function::ExternalLinkage, FunctionName, M);
1127596f483aSJessica Paquette 
1128596f483aSJessica Paquette   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1129596f483aSJessica Paquette   // which gives us better results when we outline from linkonceodr functions.
1130d506bf8eSJessica Paquette   F->setLinkage(GlobalValue::InternalLinkage);
1131596f483aSJessica Paquette   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1132596f483aSJessica Paquette 
113325bef201SEli Friedman   // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
113425bef201SEli Friedman   // necessary.
113525bef201SEli Friedman 
113625bef201SEli Friedman   // Set optsize/minsize, so we don't insert padding between outlined
113725bef201SEli Friedman   // functions.
113825bef201SEli Friedman   F->addFnAttr(Attribute::OptimizeForSize);
113925bef201SEli Friedman   F->addFnAttr(Attribute::MinSize);
114025bef201SEli Friedman 
1141e3932eeeSJessica Paquette   // Include target features from an arbitrary candidate for the outlined
1142e3932eeeSJessica Paquette   // function. This makes sure the outlined function knows what kinds of
1143e3932eeeSJessica Paquette   // instructions are going into it. This is fine, since all parent functions
1144e3932eeeSJessica Paquette   // must necessarily support the instructions that are in the outlined region.
1145e18d6ff0SJessica Paquette   Candidate &FirstCand = OF.Candidates.front();
114634b618bfSJessica Paquette   const Function &ParentFn = FirstCand.getMF()->getFunction();
1147e3932eeeSJessica Paquette   if (ParentFn.hasFnAttribute("target-features"))
1148e3932eeeSJessica Paquette     F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1149e3932eeeSJessica Paquette 
1150596f483aSJessica Paquette   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1151596f483aSJessica Paquette   IRBuilder<> Builder(EntryBB);
1152596f483aSJessica Paquette   Builder.CreateRetVoid();
1153596f483aSJessica Paquette 
1154cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
11557bda1958SMatthias Braun   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
1156596f483aSJessica Paquette   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1157596f483aSJessica Paquette   const TargetSubtargetInfo &STI = MF.getSubtarget();
1158596f483aSJessica Paquette   const TargetInstrInfo &TII = *STI.getInstrInfo();
1159596f483aSJessica Paquette 
1160596f483aSJessica Paquette   // Insert the new function into the module.
1161596f483aSJessica Paquette   MF.insert(MF.begin(), &MBB);
1162596f483aSJessica Paquette 
116334b618bfSJessica Paquette   for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
116434b618bfSJessica Paquette        ++I) {
116534b618bfSJessica Paquette     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
1166c73c0307SChandler Carruth     NewMI->dropMemRefs(MF);
1167596f483aSJessica Paquette 
1168596f483aSJessica Paquette     // Don't keep debug information for outlined instructions.
1169596f483aSJessica Paquette     NewMI->setDebugLoc(DebugLoc());
1170596f483aSJessica Paquette     MBB.insert(MBB.end(), NewMI);
1171596f483aSJessica Paquette   }
1172596f483aSJessica Paquette 
117369f517dfSJessica Paquette   TII.buildOutlinedFrame(MBB, MF, OF);
1174729e6869SJessica Paquette 
1175cc06a782SJessica Paquette   // Outlined functions shouldn't preserve liveness.
1176cc06a782SJessica Paquette   MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1177cc06a782SJessica Paquette   MF.getRegInfo().freezeReservedRegs(MF);
1178cc06a782SJessica Paquette 
1179a499c3c2SJessica Paquette   // If there's a DISubprogram associated with this outlined function, then
1180a499c3c2SJessica Paquette   // emit debug info for the outlined function.
1181aa087327SJessica Paquette   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1182a499c3c2SJessica Paquette     // We have a DISubprogram. Get its DICompileUnit.
1183a499c3c2SJessica Paquette     DICompileUnit *CU = SP->getUnit();
1184a499c3c2SJessica Paquette     DIBuilder DB(M, true, CU);
1185a499c3c2SJessica Paquette     DIFile *Unit = SP->getFile();
1186a499c3c2SJessica Paquette     Mangler Mg;
1187a499c3c2SJessica Paquette     // Get the mangled name of the function for the linkage name.
1188a499c3c2SJessica Paquette     std::string Dummy;
1189a499c3c2SJessica Paquette     llvm::raw_string_ostream MangledNameStream(Dummy);
1190a499c3c2SJessica Paquette     Mg.getNameWithPrefix(MangledNameStream, F, false);
1191a499c3c2SJessica Paquette 
1192cc06a782SJessica Paquette     DISubprogram *OutlinedSP = DB.createFunction(
1193a499c3c2SJessica Paquette         Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1194a499c3c2SJessica Paquette         Unit /* File */,
1195a499c3c2SJessica Paquette         0 /* Line 0 is reserved for compiler-generated code. */,
1196cc06a782SJessica Paquette         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
1197cda54210SPaul Robinson         0, /* Line 0 is reserved for compiler-generated code. */
1198a499c3c2SJessica Paquette         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1199cda54210SPaul Robinson         /* Outlined code is optimized code by definition. */
1200cda54210SPaul Robinson         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1201a499c3c2SJessica Paquette 
1202a499c3c2SJessica Paquette     // Don't add any new variables to the subprogram.
1203cc06a782SJessica Paquette     DB.finalizeSubprogram(OutlinedSP);
1204a499c3c2SJessica Paquette 
1205a499c3c2SJessica Paquette     // Attach subprogram to the function.
1206cc06a782SJessica Paquette     F->setSubprogram(OutlinedSP);
1207a499c3c2SJessica Paquette     // We're done with the DIBuilder.
1208a499c3c2SJessica Paquette     DB.finalize();
1209a499c3c2SJessica Paquette   }
1210a499c3c2SJessica Paquette 
1211596f483aSJessica Paquette   return &MF;
1212596f483aSJessica Paquette }
1213596f483aSJessica Paquette 
12144ae3b71dSJessica Paquette bool MachineOutliner::outline(Module &M,
12154ae3b71dSJessica Paquette                               std::vector<OutlinedFunction> &FunctionList,
1216a51fc8ddSPuyan Lotfi                               InstructionMapper &Mapper,
1217a51fc8ddSPuyan Lotfi                               unsigned &OutlinedFunctionNum) {
1218596f483aSJessica Paquette 
1219596f483aSJessica Paquette   bool OutlinedSomething = false;
1220a3eb0facSJessica Paquette 
1221962b3ae6SJessica Paquette   // Sort by benefit. The most beneficial functions should be outlined first.
1222efd94c56SFangrui Song   llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
1223efd94c56SFangrui Song                                      const OutlinedFunction &RHS) {
1224962b3ae6SJessica Paquette     return LHS.getBenefit() > RHS.getBenefit();
1225962b3ae6SJessica Paquette   });
1226596f483aSJessica Paquette 
1227962b3ae6SJessica Paquette   // Walk over each function, outlining them as we go along. Functions are
1228962b3ae6SJessica Paquette   // outlined greedily, based off the sort above.
1229962b3ae6SJessica Paquette   for (OutlinedFunction &OF : FunctionList) {
1230962b3ae6SJessica Paquette     // If we outlined something that overlapped with a candidate in a previous
1231962b3ae6SJessica Paquette     // step, then we can't outline from it.
1232e18d6ff0SJessica Paquette     erase_if(OF.Candidates, [&Mapper](Candidate &C) {
1233d9d9309bSJessica Paquette       return std::any_of(
1234e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getStartIdx(),
1235e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1236d9d9309bSJessica Paquette           [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
1237235d877eSJessica Paquette     });
1238596f483aSJessica Paquette 
1239962b3ae6SJessica Paquette     // If we made it unbeneficial to outline this function, skip it.
124085af63d0SJessica Paquette     if (OF.getBenefit() < 1)
1241596f483aSJessica Paquette       continue;
1242596f483aSJessica Paquette 
1243962b3ae6SJessica Paquette     // It's beneficial. Create the function and outline its sequence's
1244962b3ae6SJessica Paquette     // occurrences.
1245a3eb0facSJessica Paquette     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
124658e706a6SJessica Paquette     emitOutlinedFunctionRemark(OF);
1247acffa28cSJessica Paquette     FunctionsCreated++;
1248a3eb0facSJessica Paquette     OutlinedFunctionNum++; // Created a function, move to the next name.
1249596f483aSJessica Paquette     MachineFunction *MF = OF.MF;
1250596f483aSJessica Paquette     const TargetSubtargetInfo &STI = MF->getSubtarget();
1251596f483aSJessica Paquette     const TargetInstrInfo &TII = *STI.getInstrInfo();
1252596f483aSJessica Paquette 
1253962b3ae6SJessica Paquette     // Replace occurrences of the sequence with calls to the new function.
1254e18d6ff0SJessica Paquette     for (Candidate &C : OF.Candidates) {
1255962b3ae6SJessica Paquette       MachineBasicBlock &MBB = *C.getMBB();
1256962b3ae6SJessica Paquette       MachineBasicBlock::iterator StartIt = C.front();
1257962b3ae6SJessica Paquette       MachineBasicBlock::iterator EndIt = C.back();
1258596f483aSJessica Paquette 
1259962b3ae6SJessica Paquette       // Insert the call.
1260962b3ae6SJessica Paquette       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
1261962b3ae6SJessica Paquette 
1262962b3ae6SJessica Paquette       // If the caller tracks liveness, then we need to make sure that
1263962b3ae6SJessica Paquette       // anything we outline doesn't break liveness assumptions. The outlined
1264962b3ae6SJessica Paquette       // functions themselves currently don't track liveness, but we should
1265962b3ae6SJessica Paquette       // make sure that the ranges we yank things out of aren't wrong.
1266aa087327SJessica Paquette       if (MBB.getParent()->getProperties().hasProperty(
12670b672491SJessica Paquette               MachineFunctionProperties::Property::TracksLiveness)) {
1268fc6fda90SJin Lin         // The following code is to add implicit def operands to the call
126971d3869fSDjordje Todorovic         // instruction. It also updates call site information for moved
127071d3869fSDjordje Todorovic         // code.
1271fc6fda90SJin Lin         SmallSet<Register, 2> UseRegs, DefRegs;
12720b672491SJessica Paquette         // Copy over the defs in the outlined range.
12730b672491SJessica Paquette         // First inst in outlined range <-- Anything that's defined in this
1274962b3ae6SJessica Paquette         // ...                           .. range has to be added as an
1275962b3ae6SJessica Paquette         // implicit Last inst in outlined range  <-- def to the call
127671d3869fSDjordje Todorovic         // instruction. Also remove call site information for outlined block
1277fc6fda90SJin Lin         // of code. The exposed uses need to be copied in the outlined range.
1278fc6fda90SJin Lin         for (MachineBasicBlock::reverse_iterator Iter = EndIt.getReverse(),
1279fc6fda90SJin Lin              Last = std::next(CallInst.getReverse());
1280fc6fda90SJin Lin              Iter != Last; Iter++) {
1281fc6fda90SJin Lin           MachineInstr *MI = &*Iter;
1282fc6fda90SJin Lin           for (MachineOperand &MOP : MI->operands()) {
1283fc6fda90SJin Lin             // Skip over anything that isn't a register.
1284fc6fda90SJin Lin             if (!MOP.isReg())
1285fc6fda90SJin Lin               continue;
1286fc6fda90SJin Lin 
1287fc6fda90SJin Lin             if (MOP.isDef()) {
1288fc6fda90SJin Lin               // Introduce DefRegs set to skip the redundant register.
1289fc6fda90SJin Lin               DefRegs.insert(MOP.getReg());
1290fc6fda90SJin Lin               if (UseRegs.count(MOP.getReg()))
1291fc6fda90SJin Lin                 // Since the regiester is modeled as defined,
1292fc6fda90SJin Lin                 // it is not necessary to be put in use register set.
1293fc6fda90SJin Lin                 UseRegs.erase(MOP.getReg());
1294fc6fda90SJin Lin             } else if (!MOP.isUndef()) {
1295fc6fda90SJin Lin               // Any register which is not undefined should
1296fc6fda90SJin Lin               // be put in the use register set.
1297fc6fda90SJin Lin               UseRegs.insert(MOP.getReg());
1298fc6fda90SJin Lin             }
1299fc6fda90SJin Lin           }
1300fc6fda90SJin Lin           if (MI->isCandidateForCallSiteEntry())
1301fc6fda90SJin Lin             MI->getMF()->eraseCallSiteInfo(MI);
1302fc6fda90SJin Lin         }
1303fc6fda90SJin Lin 
1304fc6fda90SJin Lin         for (const Register &I : DefRegs)
1305fc6fda90SJin Lin            // If it's a def, add it to the call instruction.
1306fc6fda90SJin Lin           CallInst->addOperand(MachineOperand::CreateReg(
1307fc6fda90SJin Lin                   I, true, /* isDef = true */
1308fc6fda90SJin Lin                   true /* isImp = true */));
1309fc6fda90SJin Lin 
1310fc6fda90SJin Lin         for (const Register &I : UseRegs)
1311fc6fda90SJin Lin           // If it's a exposed use, add it to the call instruction.
1312fc6fda90SJin Lin           CallInst->addOperand(
1313fc6fda90SJin Lin               MachineOperand::CreateReg(I, false, /* isDef = false */
1314fc6fda90SJin Lin                                         true /* isImp = true */));
13150b672491SJessica Paquette       }
13160b672491SJessica Paquette 
1317aa087327SJessica Paquette       // Erase from the point after where the call was inserted up to, and
1318aa087327SJessica Paquette       // including, the final instruction in the sequence.
1319aa087327SJessica Paquette       // Erase needs one past the end, so we need std::next there too.
1320aa087327SJessica Paquette       MBB.erase(std::next(StartIt), std::next(EndIt));
1321235d877eSJessica Paquette 
1322d9d9309bSJessica Paquette       // Keep track of what we removed by marking them all as -1.
1323235d877eSJessica Paquette       std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1324235d877eSJessica Paquette                     Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1325d9d9309bSJessica Paquette                     [](unsigned &I) { I = static_cast<unsigned>(-1); });
1326596f483aSJessica Paquette       OutlinedSomething = true;
1327596f483aSJessica Paquette 
1328596f483aSJessica Paquette       // Statistics.
1329596f483aSJessica Paquette       NumOutlined++;
1330596f483aSJessica Paquette     }
1331962b3ae6SJessica Paquette   }
1332596f483aSJessica Paquette 
1333d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
1334596f483aSJessica Paquette 
1335596f483aSJessica Paquette   return OutlinedSomething;
1336596f483aSJessica Paquette }
1337596f483aSJessica Paquette 
1338050d1ac4SJessica Paquette void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1339050d1ac4SJessica Paquette                                      MachineModuleInfo &MMI) {
1340df82274fSJessica Paquette   // Build instruction mappings for each function in the module. Start by
1341df82274fSJessica Paquette   // iterating over each Function in M.
1342596f483aSJessica Paquette   for (Function &F : M) {
1343596f483aSJessica Paquette 
1344df82274fSJessica Paquette     // If there's nothing in F, then there's no reason to try and outline from
1345df82274fSJessica Paquette     // it.
1346df82274fSJessica Paquette     if (F.empty())
1347596f483aSJessica Paquette       continue;
1348596f483aSJessica Paquette 
1349df82274fSJessica Paquette     // There's something in F. Check if it has a MachineFunction associated with
1350df82274fSJessica Paquette     // it.
1351df82274fSJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
1352596f483aSJessica Paquette 
1353df82274fSJessica Paquette     // If it doesn't, then there's nothing to outline from. Move to the next
1354df82274fSJessica Paquette     // Function.
1355df82274fSJessica Paquette     if (!MF)
1356596f483aSJessica Paquette       continue;
1357596f483aSJessica Paquette 
1358da08078fSEli Friedman     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1359da08078fSEli Friedman 
13608bda1881SJessica Paquette     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
13618bda1881SJessica Paquette       continue;
13628bda1881SJessica Paquette 
1363df82274fSJessica Paquette     // We have a MachineFunction. Ask the target if it's suitable for outlining.
1364df82274fSJessica Paquette     // If it isn't, then move on to the next Function in the module.
1365df82274fSJessica Paquette     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1366df82274fSJessica Paquette       continue;
1367df82274fSJessica Paquette 
1368df82274fSJessica Paquette     // We have a function suitable for outlining. Iterate over every
1369df82274fSJessica Paquette     // MachineBasicBlock in MF and try to map its instructions to a list of
1370df82274fSJessica Paquette     // unsigned integers.
1371df82274fSJessica Paquette     for (MachineBasicBlock &MBB : *MF) {
1372df82274fSJessica Paquette       // If there isn't anything in MBB, then there's no point in outlining from
1373df82274fSJessica Paquette       // it.
1374b320ca26SJessica Paquette       // If there are fewer than 2 instructions in the MBB, then it can't ever
1375b320ca26SJessica Paquette       // contain something worth outlining.
1376b320ca26SJessica Paquette       // FIXME: This should be based off of the maximum size in B of an outlined
1377b320ca26SJessica Paquette       // call versus the size in B of the MBB.
1378b320ca26SJessica Paquette       if (MBB.empty() || MBB.size() < 2)
1379df82274fSJessica Paquette         continue;
1380df82274fSJessica Paquette 
1381df82274fSJessica Paquette       // Check if MBB could be the target of an indirect branch. If it is, then
1382df82274fSJessica Paquette       // we don't want to outline from it.
1383df82274fSJessica Paquette       if (MBB.hasAddressTaken())
1384df82274fSJessica Paquette         continue;
1385df82274fSJessica Paquette 
1386df82274fSJessica Paquette       // MBB is suitable for outlining. Map it to a list of unsigneds.
1387da08078fSEli Friedman       Mapper.convertToUnsignedVec(MBB, *TII);
1388596f483aSJessica Paquette     }
1389596f483aSJessica Paquette   }
1390050d1ac4SJessica Paquette }
1391050d1ac4SJessica Paquette 
13922386eab3SJessica Paquette void MachineOutliner::initSizeRemarkInfo(
13932386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
13942386eab3SJessica Paquette     StringMap<unsigned> &FunctionToInstrCount) {
13952386eab3SJessica Paquette   // Collect instruction counts for every function. We'll use this to emit
13962386eab3SJessica Paquette   // per-function size remarks later.
13972386eab3SJessica Paquette   for (const Function &F : M) {
13982386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
13992386eab3SJessica Paquette 
14002386eab3SJessica Paquette     // We only care about MI counts here. If there's no MachineFunction at this
14012386eab3SJessica Paquette     // point, then there won't be after the outliner runs, so let's move on.
14022386eab3SJessica Paquette     if (!MF)
14032386eab3SJessica Paquette       continue;
14042386eab3SJessica Paquette     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
14052386eab3SJessica Paquette   }
14062386eab3SJessica Paquette }
14072386eab3SJessica Paquette 
14082386eab3SJessica Paquette void MachineOutliner::emitInstrCountChangedRemark(
14092386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
14102386eab3SJessica Paquette     const StringMap<unsigned> &FunctionToInstrCount) {
14112386eab3SJessica Paquette   // Iterate over each function in the module and emit remarks.
14122386eab3SJessica Paquette   // Note that we won't miss anything by doing this, because the outliner never
14132386eab3SJessica Paquette   // deletes functions.
14142386eab3SJessica Paquette   for (const Function &F : M) {
14152386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
14162386eab3SJessica Paquette 
14172386eab3SJessica Paquette     // The outliner never deletes functions. If we don't have a MF here, then we
14182386eab3SJessica Paquette     // didn't have one prior to outlining either.
14192386eab3SJessica Paquette     if (!MF)
14202386eab3SJessica Paquette       continue;
14212386eab3SJessica Paquette 
1422adcd0268SBenjamin Kramer     std::string Fname = std::string(F.getName());
14232386eab3SJessica Paquette     unsigned FnCountAfter = MF->getInstructionCount();
14242386eab3SJessica Paquette     unsigned FnCountBefore = 0;
14252386eab3SJessica Paquette 
14262386eab3SJessica Paquette     // Check if the function was recorded before.
14272386eab3SJessica Paquette     auto It = FunctionToInstrCount.find(Fname);
14282386eab3SJessica Paquette 
14292386eab3SJessica Paquette     // Did we have a previously-recorded size? If yes, then set FnCountBefore
14302386eab3SJessica Paquette     // to that.
14312386eab3SJessica Paquette     if (It != FunctionToInstrCount.end())
14322386eab3SJessica Paquette       FnCountBefore = It->second;
14332386eab3SJessica Paquette 
14342386eab3SJessica Paquette     // Compute the delta and emit a remark if there was a change.
14352386eab3SJessica Paquette     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
14362386eab3SJessica Paquette                       static_cast<int64_t>(FnCountBefore);
14372386eab3SJessica Paquette     if (FnDelta == 0)
14382386eab3SJessica Paquette       continue;
14392386eab3SJessica Paquette 
14402386eab3SJessica Paquette     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
14412386eab3SJessica Paquette     MORE.emit([&]() {
14422386eab3SJessica Paquette       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
14436b7615aeSPuyan Lotfi                                           DiagnosticLocation(), &MF->front());
14442386eab3SJessica Paquette       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
14452386eab3SJessica Paquette         << ": Function: "
14462386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
14472386eab3SJessica Paquette         << ": MI instruction count changed from "
14482386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
14492386eab3SJessica Paquette                                                     FnCountBefore)
14502386eab3SJessica Paquette         << " to "
14512386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
14522386eab3SJessica Paquette                                                     FnCountAfter)
14532386eab3SJessica Paquette         << "; Delta: "
14542386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
14552386eab3SJessica Paquette       return R;
14562386eab3SJessica Paquette     });
14572386eab3SJessica Paquette   }
14582386eab3SJessica Paquette }
14592386eab3SJessica Paquette 
1460*ab2dcff3SJin Lin bool MachineOutliner::runOnceOnModule(Module &M, unsigned Iter) {
1461050d1ac4SJessica Paquette   // Check if there's anything in the module. If it's empty, then there's
1462050d1ac4SJessica Paquette   // nothing to outline.
1463050d1ac4SJessica Paquette   if (M.empty())
1464050d1ac4SJessica Paquette     return false;
1465050d1ac4SJessica Paquette 
1466*ab2dcff3SJin Lin   OutlineRepeatedNum = Iter;
1467*ab2dcff3SJin Lin 
1468a51fc8ddSPuyan Lotfi   // Number to append to the current outlined function.
1469a51fc8ddSPuyan Lotfi   unsigned OutlinedFunctionNum = 0;
1470a51fc8ddSPuyan Lotfi 
1471a51fc8ddSPuyan Lotfi   if (!doOutline(M, OutlinedFunctionNum))
1472a51fc8ddSPuyan Lotfi     return false;
1473a51fc8ddSPuyan Lotfi   return true;
1474a51fc8ddSPuyan Lotfi }
1475a51fc8ddSPuyan Lotfi 
1476a51fc8ddSPuyan Lotfi bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1477cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1478050d1ac4SJessica Paquette 
1479050d1ac4SJessica Paquette   // If the user passed -enable-machine-outliner=always or
1480050d1ac4SJessica Paquette   // -enable-machine-outliner, the pass will run on all functions in the module.
1481050d1ac4SJessica Paquette   // Otherwise, if the target supports default outlining, it will run on all
1482050d1ac4SJessica Paquette   // functions deemed by the target to be worth outlining from by default. Tell
1483050d1ac4SJessica Paquette   // the user how the outliner is running.
14846b7615aeSPuyan Lotfi   LLVM_DEBUG({
1485050d1ac4SJessica Paquette     dbgs() << "Machine Outliner: Running on ";
1486050d1ac4SJessica Paquette     if (RunOnAllFunctions)
1487050d1ac4SJessica Paquette       dbgs() << "all functions";
1488050d1ac4SJessica Paquette     else
1489050d1ac4SJessica Paquette       dbgs() << "target-default functions";
14906b7615aeSPuyan Lotfi     dbgs() << "\n";
14916b7615aeSPuyan Lotfi   });
1492050d1ac4SJessica Paquette 
1493050d1ac4SJessica Paquette   // If the user specifies that they want to outline from linkonceodrs, set
1494050d1ac4SJessica Paquette   // it here.
1495050d1ac4SJessica Paquette   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1496050d1ac4SJessica Paquette   InstructionMapper Mapper;
1497050d1ac4SJessica Paquette 
1498050d1ac4SJessica Paquette   // Prepare instruction mappings for the suffix tree.
1499050d1ac4SJessica Paquette   populateMapper(Mapper, M, MMI);
1500596f483aSJessica Paquette   std::vector<OutlinedFunction> FunctionList;
1501596f483aSJessica Paquette 
1502acffa28cSJessica Paquette   // Find all of the outlining candidates.
1503ce3a2dcfSJessica Paquette   findCandidates(Mapper, FunctionList);
1504596f483aSJessica Paquette 
15052386eab3SJessica Paquette   // If we've requested size remarks, then collect the MI counts of every
15062386eab3SJessica Paquette   // function before outlining, and the MI counts after outlining.
15072386eab3SJessica Paquette   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
15082386eab3SJessica Paquette   // the pass manager's responsibility.
15092386eab3SJessica Paquette   // This could pretty easily be placed in outline instead, but because we
15102386eab3SJessica Paquette   // really ultimately *don't* want this here, it's done like this for now
15112386eab3SJessica Paquette   // instead.
15122386eab3SJessica Paquette 
15132386eab3SJessica Paquette   // Check if we want size remarks.
15142386eab3SJessica Paquette   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
15152386eab3SJessica Paquette   StringMap<unsigned> FunctionToInstrCount;
15162386eab3SJessica Paquette   if (ShouldEmitSizeRemarks)
15172386eab3SJessica Paquette     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
15182386eab3SJessica Paquette 
1519acffa28cSJessica Paquette   // Outline each of the candidates and return true if something was outlined.
1520a51fc8ddSPuyan Lotfi   bool OutlinedSomething =
1521a51fc8ddSPuyan Lotfi       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1522729e6869SJessica Paquette 
15232386eab3SJessica Paquette   // If we outlined something, we definitely changed the MI count of the
15242386eab3SJessica Paquette   // module. If we've asked for size remarks, then output them.
15252386eab3SJessica Paquette   // FIXME: This should be in the pass manager.
15262386eab3SJessica Paquette   if (ShouldEmitSizeRemarks && OutlinedSomething)
15272386eab3SJessica Paquette     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
15282386eab3SJessica Paquette 
1529729e6869SJessica Paquette   return OutlinedSomething;
1530596f483aSJessica Paquette }
1531*ab2dcff3SJin Lin 
1532*ab2dcff3SJin Lin // Apply machine outlining for NumRepeat times.
1533*ab2dcff3SJin Lin bool MachineOutliner::runOnModule(Module &M) {
1534*ab2dcff3SJin Lin   if (NumRepeat < 1)
1535*ab2dcff3SJin Lin     report_fatal_error("Expect NumRepeat for machine outlining "
1536*ab2dcff3SJin Lin                        "to be greater than or equal to 1!\n");
1537*ab2dcff3SJin Lin 
1538*ab2dcff3SJin Lin   bool Changed = false;
1539*ab2dcff3SJin Lin   for (unsigned I = 0; I < NumRepeat; I++) {
1540*ab2dcff3SJin Lin     if (!runOnceOnModule(M, I)) {
1541*ab2dcff3SJin Lin       LLVM_DEBUG(dbgs() << "Stopped outlining at iteration " << I
1542*ab2dcff3SJin Lin                         << " because no changes were found.\n";);
1543*ab2dcff3SJin Lin       return Changed;
1544*ab2dcff3SJin Lin     }
1545*ab2dcff3SJin Lin     Changed = true;
1546*ab2dcff3SJin Lin   }
1547*ab2dcff3SJin Lin   LLVM_DEBUG(dbgs() << "Stopped outlining because iteration is "
1548*ab2dcff3SJin Lin                        "equal to " << NumRepeat << "\n";);
1549*ab2dcff3SJin Lin   return Changed;
1550*ab2dcff3SJin Lin }
1551