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"
59*fc6fda90SJin 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 
100596f483aSJessica Paquette namespace {
101596f483aSJessica Paquette 
102596f483aSJessica Paquette /// Represents an undefined index in the suffix tree.
1034cf187b5SJessica Paquette const unsigned EmptyIdx = -1;
104596f483aSJessica Paquette 
105596f483aSJessica Paquette /// A node in a suffix tree which represents a substring or suffix.
106596f483aSJessica Paquette ///
107596f483aSJessica Paquette /// Each node has either no children or at least two children, with the root
108596f483aSJessica Paquette /// being a exception in the empty tree.
109596f483aSJessica Paquette ///
110596f483aSJessica Paquette /// Children are represented as a map between unsigned integers and nodes. If
111596f483aSJessica Paquette /// a node N has a child M on unsigned integer k, then the mapping represented
112596f483aSJessica Paquette /// by N is a proper prefix of the mapping represented by M. Note that this,
113596f483aSJessica Paquette /// although similar to a trie is somewhat different: each node stores a full
114596f483aSJessica Paquette /// substring of the full mapping rather than a single character state.
115596f483aSJessica Paquette ///
116596f483aSJessica Paquette /// Each internal node contains a pointer to the internal node representing
117596f483aSJessica Paquette /// the same string, but with the first character chopped off. This is stored
118596f483aSJessica Paquette /// in \p Link. Each leaf node stores the start index of its respective
119596f483aSJessica Paquette /// suffix in \p SuffixIdx.
120596f483aSJessica Paquette struct SuffixTreeNode {
121596f483aSJessica Paquette 
122596f483aSJessica Paquette   /// The children of this node.
123596f483aSJessica Paquette   ///
124596f483aSJessica Paquette   /// A child existing on an unsigned integer implies that from the mapping
125596f483aSJessica Paquette   /// represented by the current node, there is a way to reach another
126596f483aSJessica Paquette   /// mapping by tacking that character on the end of the current string.
127596f483aSJessica Paquette   DenseMap<unsigned, SuffixTreeNode *> Children;
128596f483aSJessica Paquette 
129596f483aSJessica Paquette   /// The start index of this node's substring in the main string.
1304cf187b5SJessica Paquette   unsigned StartIdx = EmptyIdx;
131596f483aSJessica Paquette 
132596f483aSJessica Paquette   /// The end index of this node's substring in the main string.
133596f483aSJessica Paquette   ///
134596f483aSJessica Paquette   /// Every leaf node must have its \p EndIdx incremented at the end of every
135596f483aSJessica Paquette   /// step in the construction algorithm. To avoid having to update O(N)
136596f483aSJessica Paquette   /// nodes individually at the end of every step, the end index is stored
137596f483aSJessica Paquette   /// as a pointer.
1384cf187b5SJessica Paquette   unsigned *EndIdx = nullptr;
139596f483aSJessica Paquette 
140596f483aSJessica Paquette   /// For leaves, the start index of the suffix represented by this node.
141596f483aSJessica Paquette   ///
142596f483aSJessica Paquette   /// For all other nodes, this is ignored.
1434cf187b5SJessica Paquette   unsigned SuffixIdx = EmptyIdx;
144596f483aSJessica Paquette 
1455f8f34e4SAdrian Prantl   /// For internal nodes, a pointer to the internal node representing
146596f483aSJessica Paquette   /// the same sequence with the first character chopped off.
147596f483aSJessica Paquette   ///
1484602c343SJessica Paquette   /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
149596f483aSJessica Paquette   /// Ukkonen's algorithm does to achieve linear-time construction is
150596f483aSJessica Paquette   /// keep track of which node the next insert should be at. This makes each
151596f483aSJessica Paquette   /// insert O(1), and there are a total of O(N) inserts. The suffix link
152596f483aSJessica Paquette   /// helps with inserting children of internal nodes.
153596f483aSJessica Paquette   ///
154596f483aSJessica Paquette   /// Say we add a child to an internal node with associated mapping S. The
155596f483aSJessica Paquette   /// next insertion must be at the node representing S - its first character.
156596f483aSJessica Paquette   /// This is given by the way that we iteratively build the tree in Ukkonen's
157596f483aSJessica Paquette   /// algorithm. The main idea is to look at the suffixes of each prefix in the
158596f483aSJessica Paquette   /// string, starting with the longest suffix of the prefix, and ending with
159596f483aSJessica Paquette   /// the shortest. Therefore, if we keep pointers between such nodes, we can
160596f483aSJessica Paquette   /// move to the next insertion point in O(1) time. If we don't, then we'd
161596f483aSJessica Paquette   /// have to query from the root, which takes O(N) time. This would make the
162596f483aSJessica Paquette   /// construction algorithm O(N^2) rather than O(N).
163596f483aSJessica Paquette   SuffixTreeNode *Link = nullptr;
164596f483aSJessica Paquette 
165acffa28cSJessica Paquette   /// The length of the string formed by concatenating the edge labels from the
166acffa28cSJessica Paquette   /// root to this node.
1674cf187b5SJessica Paquette   unsigned ConcatLen = 0;
168acffa28cSJessica Paquette 
169596f483aSJessica Paquette   /// Returns true if this node is a leaf.
170596f483aSJessica Paquette   bool isLeaf() const { return SuffixIdx != EmptyIdx; }
171596f483aSJessica Paquette 
172596f483aSJessica Paquette   /// Returns true if this node is the root of its owning \p SuffixTree.
173596f483aSJessica Paquette   bool isRoot() const { return StartIdx == EmptyIdx; }
174596f483aSJessica Paquette 
175596f483aSJessica Paquette   /// Return the number of elements in the substring associated with this node.
176596f483aSJessica Paquette   size_t size() const {
177596f483aSJessica Paquette 
178596f483aSJessica Paquette     // Is it the root? If so, it's the empty string so return 0.
179596f483aSJessica Paquette     if (isRoot())
180596f483aSJessica Paquette       return 0;
181596f483aSJessica Paquette 
182596f483aSJessica Paquette     assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
183596f483aSJessica Paquette 
184596f483aSJessica Paquette     // Size = the number of elements in the string.
185596f483aSJessica Paquette     // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
186596f483aSJessica Paquette     return *EndIdx - StartIdx + 1;
187596f483aSJessica Paquette   }
188596f483aSJessica Paquette 
189df5b09b8SJessica Paquette   SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
190df5b09b8SJessica Paquette       : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
191596f483aSJessica Paquette 
192596f483aSJessica Paquette   SuffixTreeNode() {}
193596f483aSJessica Paquette };
194596f483aSJessica Paquette 
195596f483aSJessica Paquette /// A data structure for fast substring queries.
196596f483aSJessica Paquette ///
197596f483aSJessica Paquette /// Suffix trees represent the suffixes of their input strings in their leaves.
198596f483aSJessica Paquette /// A suffix tree is a type of compressed trie structure where each node
199596f483aSJessica Paquette /// represents an entire substring rather than a single character. Each leaf
200596f483aSJessica Paquette /// of the tree is a suffix.
201596f483aSJessica Paquette ///
202596f483aSJessica Paquette /// A suffix tree can be seen as a type of state machine where each state is a
203596f483aSJessica Paquette /// substring of the full string. The tree is structured so that, for a string
204596f483aSJessica Paquette /// of length N, there are exactly N leaves in the tree. This structure allows
205596f483aSJessica Paquette /// us to quickly find repeated substrings of the input string.
206596f483aSJessica Paquette ///
207596f483aSJessica Paquette /// In this implementation, a "string" is a vector of unsigned integers.
208596f483aSJessica Paquette /// These integers may result from hashing some data type. A suffix tree can
209596f483aSJessica Paquette /// contain 1 or many strings, which can then be queried as one large string.
210596f483aSJessica Paquette ///
211596f483aSJessica Paquette /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
212596f483aSJessica Paquette /// suffix tree construction. Ukkonen's algorithm is explained in more detail
213596f483aSJessica Paquette /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
214596f483aSJessica Paquette /// paper is available at
215596f483aSJessica Paquette ///
216596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
217596f483aSJessica Paquette class SuffixTree {
21878681be2SJessica Paquette public:
219596f483aSJessica Paquette   /// Each element is an integer representing an instruction in the module.
220596f483aSJessica Paquette   ArrayRef<unsigned> Str;
221596f483aSJessica Paquette 
2224e54ef88SJessica Paquette   /// A repeated substring in the tree.
2234e54ef88SJessica Paquette   struct RepeatedSubstring {
2244e54ef88SJessica Paquette     /// The length of the string.
2254e54ef88SJessica Paquette     unsigned Length;
2264e54ef88SJessica Paquette 
2274e54ef88SJessica Paquette     /// The start indices of each occurrence.
2284e54ef88SJessica Paquette     std::vector<unsigned> StartIndices;
2294e54ef88SJessica Paquette   };
2304e54ef88SJessica Paquette 
23178681be2SJessica Paquette private:
232596f483aSJessica Paquette   /// Maintains each node in the tree.
233d4cb9c6dSJessica Paquette   SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
234596f483aSJessica Paquette 
235596f483aSJessica Paquette   /// The root of the suffix tree.
236596f483aSJessica Paquette   ///
237596f483aSJessica Paquette   /// The root represents the empty string. It is maintained by the
238596f483aSJessica Paquette   /// \p NodeAllocator like every other node in the tree.
239596f483aSJessica Paquette   SuffixTreeNode *Root = nullptr;
240596f483aSJessica Paquette 
241596f483aSJessica Paquette   /// Maintains the end indices of the internal nodes in the tree.
242596f483aSJessica Paquette   ///
243596f483aSJessica Paquette   /// Each internal node is guaranteed to never have its end index change
244596f483aSJessica Paquette   /// during the construction algorithm; however, leaves must be updated at
245596f483aSJessica Paquette   /// every step. Therefore, we need to store leaf end indices by reference
246596f483aSJessica Paquette   /// to avoid updating O(N) leaves at every step of construction. Thus,
247596f483aSJessica Paquette   /// every internal node must be allocated its own end index.
248596f483aSJessica Paquette   BumpPtrAllocator InternalEndIdxAllocator;
249596f483aSJessica Paquette 
250596f483aSJessica Paquette   /// The end index of each leaf in the tree.
2514cf187b5SJessica Paquette   unsigned LeafEndIdx = -1;
252596f483aSJessica Paquette 
2535f8f34e4SAdrian Prantl   /// Helper struct which keeps track of the next insertion point in
254596f483aSJessica Paquette   /// Ukkonen's algorithm.
255596f483aSJessica Paquette   struct ActiveState {
256596f483aSJessica Paquette     /// The next node to insert at.
257c7f127d9SSimon Pilgrim     SuffixTreeNode *Node = nullptr;
258596f483aSJessica Paquette 
259596f483aSJessica Paquette     /// The index of the first character in the substring currently being added.
2604cf187b5SJessica Paquette     unsigned Idx = EmptyIdx;
261596f483aSJessica Paquette 
262596f483aSJessica Paquette     /// The length of the substring we have to add at the current step.
2634cf187b5SJessica Paquette     unsigned Len = 0;
264596f483aSJessica Paquette   };
265596f483aSJessica Paquette 
2665f8f34e4SAdrian Prantl   /// The point the next insertion will take place at in the
267596f483aSJessica Paquette   /// construction algorithm.
268596f483aSJessica Paquette   ActiveState Active;
269596f483aSJessica Paquette 
270596f483aSJessica Paquette   /// Allocate a leaf node and add it to the tree.
271596f483aSJessica Paquette   ///
272596f483aSJessica Paquette   /// \param Parent The parent of this node.
273596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
274596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
275596f483aSJessica Paquette   ///
276596f483aSJessica Paquette   /// \returns A pointer to the allocated leaf node.
2774cf187b5SJessica Paquette   SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
278596f483aSJessica Paquette                              unsigned Edge) {
279596f483aSJessica Paquette 
280596f483aSJessica Paquette     assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
281596f483aSJessica Paquette 
28278681be2SJessica Paquette     SuffixTreeNode *N = new (NodeAllocator.Allocate())
283df5b09b8SJessica Paquette         SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
284596f483aSJessica Paquette     Parent.Children[Edge] = N;
285596f483aSJessica Paquette 
286596f483aSJessica Paquette     return N;
287596f483aSJessica Paquette   }
288596f483aSJessica Paquette 
289596f483aSJessica Paquette   /// Allocate an internal node and add it to the tree.
290596f483aSJessica Paquette   ///
291596f483aSJessica Paquette   /// \param Parent The parent of this node. Only null when allocating the root.
292596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
293596f483aSJessica Paquette   /// \param EndIdx The end index of this node's associated string.
294596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
295596f483aSJessica Paquette   ///
296596f483aSJessica Paquette   /// \returns A pointer to the allocated internal node.
2974cf187b5SJessica Paquette   SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
2984cf187b5SJessica Paquette                                      unsigned EndIdx, unsigned Edge) {
299596f483aSJessica Paquette 
300596f483aSJessica Paquette     assert(StartIdx <= EndIdx && "String can't start after it ends!");
301596f483aSJessica Paquette     assert(!(!Parent && StartIdx != EmptyIdx) &&
302596f483aSJessica Paquette            "Non-root internal nodes must have parents!");
303596f483aSJessica Paquette 
3044cf187b5SJessica Paquette     unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
3056b7615aeSPuyan Lotfi     SuffixTreeNode *N =
3066b7615aeSPuyan Lotfi         new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root);
307596f483aSJessica Paquette     if (Parent)
308596f483aSJessica Paquette       Parent->Children[Edge] = N;
309596f483aSJessica Paquette 
310596f483aSJessica Paquette     return N;
311596f483aSJessica Paquette   }
312596f483aSJessica Paquette 
3135f8f34e4SAdrian Prantl   /// Set the suffix indices of the leaves to the start indices of their
3144e54ef88SJessica Paquette   /// respective suffixes.
315d5750770SJessica Paquette   void setSuffixIndices() {
316d5750770SJessica Paquette     // List of nodes we need to visit along with the current length of the
317d5750770SJessica Paquette     // string.
318d5750770SJessica Paquette     std::vector<std::pair<SuffixTreeNode *, unsigned>> ToVisit;
319596f483aSJessica Paquette 
320d5750770SJessica Paquette     // Current node being visited.
321d5750770SJessica Paquette     SuffixTreeNode *CurrNode = Root;
322596f483aSJessica Paquette 
323d5750770SJessica Paquette     // Sum of the lengths of the nodes down the path to the current one.
324d5750770SJessica Paquette     unsigned CurrNodeLen = 0;
325d5750770SJessica Paquette     ToVisit.push_back({CurrNode, CurrNodeLen});
326d5750770SJessica Paquette     while (!ToVisit.empty()) {
327d5750770SJessica Paquette       std::tie(CurrNode, CurrNodeLen) = ToVisit.back();
328d5750770SJessica Paquette       ToVisit.pop_back();
329d5750770SJessica Paquette       CurrNode->ConcatLen = CurrNodeLen;
330d5750770SJessica Paquette       for (auto &ChildPair : CurrNode->Children) {
331596f483aSJessica Paquette         assert(ChildPair.second && "Node had a null child!");
332d5750770SJessica Paquette         ToVisit.push_back(
333d5750770SJessica Paquette             {ChildPair.second, CurrNodeLen + ChildPair.second->size()});
334596f483aSJessica Paquette       }
335596f483aSJessica Paquette 
336d5750770SJessica Paquette       // No children, so we are at the end of the string.
337d5750770SJessica Paquette       if (CurrNode->Children.size() == 0 && !CurrNode->isRoot())
338d5750770SJessica Paquette         CurrNode->SuffixIdx = Str.size() - CurrNodeLen;
339d5750770SJessica Paquette     }
340596f483aSJessica Paquette   }
341596f483aSJessica Paquette 
3425f8f34e4SAdrian Prantl   /// Construct the suffix tree for the prefix of the input ending at
343596f483aSJessica Paquette   /// \p EndIdx.
344596f483aSJessica Paquette   ///
345596f483aSJessica Paquette   /// Used to construct the full suffix tree iteratively. At the end of each
346596f483aSJessica Paquette   /// step, the constructed suffix tree is either a valid suffix tree, or a
347596f483aSJessica Paquette   /// suffix tree with implicit suffixes. At the end of the final step, the
348596f483aSJessica Paquette   /// suffix tree is a valid tree.
349596f483aSJessica Paquette   ///
350596f483aSJessica Paquette   /// \param EndIdx The end index of the current prefix in the main string.
351596f483aSJessica Paquette   /// \param SuffixesToAdd The number of suffixes that must be added
352596f483aSJessica Paquette   /// to complete the suffix tree at the current phase.
353596f483aSJessica Paquette   ///
354596f483aSJessica Paquette   /// \returns The number of suffixes that have not been added at the end of
355596f483aSJessica Paquette   /// this step.
3564cf187b5SJessica Paquette   unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
357596f483aSJessica Paquette     SuffixTreeNode *NeedsLink = nullptr;
358596f483aSJessica Paquette 
359596f483aSJessica Paquette     while (SuffixesToAdd > 0) {
360596f483aSJessica Paquette 
361596f483aSJessica Paquette       // Are we waiting to add anything other than just the last character?
362596f483aSJessica Paquette       if (Active.Len == 0) {
363596f483aSJessica Paquette         // If not, then say the active index is the end index.
364596f483aSJessica Paquette         Active.Idx = EndIdx;
365596f483aSJessica Paquette       }
366596f483aSJessica Paquette 
367596f483aSJessica Paquette       assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
368596f483aSJessica Paquette 
369596f483aSJessica Paquette       // The first character in the current substring we're looking at.
370596f483aSJessica Paquette       unsigned FirstChar = Str[Active.Idx];
371596f483aSJessica Paquette 
372596f483aSJessica Paquette       // Have we inserted anything starting with FirstChar at the current node?
373596f483aSJessica Paquette       if (Active.Node->Children.count(FirstChar) == 0) {
374596f483aSJessica Paquette         // If not, then we can just insert a leaf and move too the next step.
375596f483aSJessica Paquette         insertLeaf(*Active.Node, EndIdx, FirstChar);
376596f483aSJessica Paquette 
377596f483aSJessica Paquette         // The active node is an internal node, and we visited it, so it must
378596f483aSJessica Paquette         // need a link if it doesn't have one.
379596f483aSJessica Paquette         if (NeedsLink) {
380596f483aSJessica Paquette           NeedsLink->Link = Active.Node;
381596f483aSJessica Paquette           NeedsLink = nullptr;
382596f483aSJessica Paquette         }
383596f483aSJessica Paquette       } else {
384596f483aSJessica Paquette         // There's a match with FirstChar, so look for the point in the tree to
385596f483aSJessica Paquette         // insert a new node.
386596f483aSJessica Paquette         SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
387596f483aSJessica Paquette 
3884cf187b5SJessica Paquette         unsigned SubstringLen = NextNode->size();
389596f483aSJessica Paquette 
390596f483aSJessica Paquette         // Is the current suffix we're trying to insert longer than the size of
391596f483aSJessica Paquette         // the child we want to move to?
392596f483aSJessica Paquette         if (Active.Len >= SubstringLen) {
393596f483aSJessica Paquette           // If yes, then consume the characters we've seen and move to the next
394596f483aSJessica Paquette           // node.
395596f483aSJessica Paquette           Active.Idx += SubstringLen;
396596f483aSJessica Paquette           Active.Len -= SubstringLen;
397596f483aSJessica Paquette           Active.Node = NextNode;
398596f483aSJessica Paquette           continue;
399596f483aSJessica Paquette         }
400596f483aSJessica Paquette 
401596f483aSJessica Paquette         // Otherwise, the suffix we're trying to insert must be contained in the
402596f483aSJessica Paquette         // next node we want to move to.
403596f483aSJessica Paquette         unsigned LastChar = Str[EndIdx];
404596f483aSJessica Paquette 
405596f483aSJessica Paquette         // Is the string we're trying to insert a substring of the next node?
406596f483aSJessica Paquette         if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
407596f483aSJessica Paquette           // If yes, then we're done for this step. Remember our insertion point
408596f483aSJessica Paquette           // and move to the next end index. At this point, we have an implicit
409596f483aSJessica Paquette           // suffix tree.
410596f483aSJessica Paquette           if (NeedsLink && !Active.Node->isRoot()) {
411596f483aSJessica Paquette             NeedsLink->Link = Active.Node;
412596f483aSJessica Paquette             NeedsLink = nullptr;
413596f483aSJessica Paquette           }
414596f483aSJessica Paquette 
415596f483aSJessica Paquette           Active.Len++;
416596f483aSJessica Paquette           break;
417596f483aSJessica Paquette         }
418596f483aSJessica Paquette 
419596f483aSJessica Paquette         // The string we're trying to insert isn't a substring of the next node,
420596f483aSJessica Paquette         // but matches up to a point. Split the node.
421596f483aSJessica Paquette         //
422596f483aSJessica Paquette         // For example, say we ended our search at a node n and we're trying to
423596f483aSJessica Paquette         // insert ABD. Then we'll create a new node s for AB, reduce n to just
424596f483aSJessica Paquette         // representing C, and insert a new leaf node l to represent d. This
425596f483aSJessica Paquette         // allows us to ensure that if n was a leaf, it remains a leaf.
426596f483aSJessica Paquette         //
427596f483aSJessica Paquette         //   | ABC  ---split--->  | AB
428596f483aSJessica Paquette         //   n                    s
429596f483aSJessica Paquette         //                     C / \ D
430596f483aSJessica Paquette         //                      n   l
431596f483aSJessica Paquette 
432596f483aSJessica Paquette         // The node s from the diagram
433596f483aSJessica Paquette         SuffixTreeNode *SplitNode =
43478681be2SJessica Paquette             insertInternalNode(Active.Node, NextNode->StartIdx,
43578681be2SJessica Paquette                                NextNode->StartIdx + Active.Len - 1, FirstChar);
436596f483aSJessica Paquette 
437596f483aSJessica Paquette         // Insert the new node representing the new substring into the tree as
438596f483aSJessica Paquette         // a child of the split node. This is the node l from the diagram.
439596f483aSJessica Paquette         insertLeaf(*SplitNode, EndIdx, LastChar);
440596f483aSJessica Paquette 
441596f483aSJessica Paquette         // Make the old node a child of the split node and update its start
442596f483aSJessica Paquette         // index. This is the node n from the diagram.
443596f483aSJessica Paquette         NextNode->StartIdx += Active.Len;
444596f483aSJessica Paquette         SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
445596f483aSJessica Paquette 
446596f483aSJessica Paquette         // SplitNode is an internal node, update the suffix link.
447596f483aSJessica Paquette         if (NeedsLink)
448596f483aSJessica Paquette           NeedsLink->Link = SplitNode;
449596f483aSJessica Paquette 
450596f483aSJessica Paquette         NeedsLink = SplitNode;
451596f483aSJessica Paquette       }
452596f483aSJessica Paquette 
453596f483aSJessica Paquette       // We've added something new to the tree, so there's one less suffix to
454596f483aSJessica Paquette       // add.
455596f483aSJessica Paquette       SuffixesToAdd--;
456596f483aSJessica Paquette 
457596f483aSJessica Paquette       if (Active.Node->isRoot()) {
458596f483aSJessica Paquette         if (Active.Len > 0) {
459596f483aSJessica Paquette           Active.Len--;
460596f483aSJessica Paquette           Active.Idx = EndIdx - SuffixesToAdd + 1;
461596f483aSJessica Paquette         }
462596f483aSJessica Paquette       } else {
463596f483aSJessica Paquette         // Start the next phase at the next smallest suffix.
464596f483aSJessica Paquette         Active.Node = Active.Node->Link;
465596f483aSJessica Paquette       }
466596f483aSJessica Paquette     }
467596f483aSJessica Paquette 
468596f483aSJessica Paquette     return SuffixesToAdd;
469596f483aSJessica Paquette   }
470596f483aSJessica Paquette 
471596f483aSJessica Paquette public:
472596f483aSJessica Paquette   /// Construct a suffix tree from a sequence of unsigned integers.
473596f483aSJessica Paquette   ///
474596f483aSJessica Paquette   /// \param Str The string to construct the suffix tree for.
475596f483aSJessica Paquette   SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
476596f483aSJessica Paquette     Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
477596f483aSJessica Paquette     Active.Node = Root;
478596f483aSJessica Paquette 
479596f483aSJessica Paquette     // Keep track of the number of suffixes we have to add of the current
480596f483aSJessica Paquette     // prefix.
4814cf187b5SJessica Paquette     unsigned SuffixesToAdd = 0;
482596f483aSJessica Paquette 
483596f483aSJessica Paquette     // Construct the suffix tree iteratively on each prefix of the string.
484596f483aSJessica Paquette     // PfxEndIdx is the end index of the current prefix.
485596f483aSJessica Paquette     // End is one past the last element in the string.
4864cf187b5SJessica Paquette     for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
4874cf187b5SJessica Paquette          PfxEndIdx++) {
488596f483aSJessica Paquette       SuffixesToAdd++;
489596f483aSJessica Paquette       LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
490596f483aSJessica Paquette       SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
491596f483aSJessica Paquette     }
492596f483aSJessica Paquette 
493596f483aSJessica Paquette     // Set the suffix indices of each leaf.
494596f483aSJessica Paquette     assert(Root && "Root node can't be nullptr!");
495d5750770SJessica Paquette     setSuffixIndices();
496596f483aSJessica Paquette   }
4974e54ef88SJessica Paquette 
498a409cc95SJessica Paquette   /// Iterator for finding all repeated substrings in the suffix tree.
499a409cc95SJessica Paquette   struct RepeatedSubstringIterator {
500a409cc95SJessica Paquette   private:
501a409cc95SJessica Paquette     /// The current node we're visiting.
502a409cc95SJessica Paquette     SuffixTreeNode *N = nullptr;
503a409cc95SJessica Paquette 
504a409cc95SJessica Paquette     /// The repeated substring associated with this node.
505a409cc95SJessica Paquette     RepeatedSubstring RS;
506a409cc95SJessica Paquette 
507a409cc95SJessica Paquette     /// The nodes left to visit.
508a409cc95SJessica Paquette     std::vector<SuffixTreeNode *> ToVisit;
509a409cc95SJessica Paquette 
510a409cc95SJessica Paquette     /// The minimum length of a repeated substring to find.
511a409cc95SJessica Paquette     /// Since we're outlining, we want at least two instructions in the range.
512a409cc95SJessica Paquette     /// FIXME: This may not be true for targets like X86 which support many
513a409cc95SJessica Paquette     /// instruction lengths.
514a409cc95SJessica Paquette     const unsigned MinLength = 2;
515a409cc95SJessica Paquette 
516a409cc95SJessica Paquette     /// Move the iterator to the next repeated substring.
517a409cc95SJessica Paquette     void advance() {
518a409cc95SJessica Paquette       // Clear the current state. If we're at the end of the range, then this
519a409cc95SJessica Paquette       // is the state we want to be in.
520a409cc95SJessica Paquette       RS = RepeatedSubstring();
521a409cc95SJessica Paquette       N = nullptr;
522a409cc95SJessica Paquette 
5233cd70b38SJessica Paquette       // Each leaf node represents a repeat of a string.
5243cd70b38SJessica Paquette       std::vector<SuffixTreeNode *> LeafChildren;
5253cd70b38SJessica Paquette 
526a409cc95SJessica Paquette       // Continue visiting nodes until we find one which repeats more than once.
527a409cc95SJessica Paquette       while (!ToVisit.empty()) {
528a409cc95SJessica Paquette         SuffixTreeNode *Curr = ToVisit.back();
529a409cc95SJessica Paquette         ToVisit.pop_back();
5303cd70b38SJessica Paquette         LeafChildren.clear();
531a409cc95SJessica Paquette 
532a409cc95SJessica Paquette         // Keep track of the length of the string associated with the node. If
533a409cc95SJessica Paquette         // it's too short, we'll quit.
534a409cc95SJessica Paquette         unsigned Length = Curr->ConcatLen;
535a409cc95SJessica Paquette 
536a409cc95SJessica Paquette         // Iterate over each child, saving internal nodes for visiting, and
537a409cc95SJessica Paquette         // leaf nodes in LeafChildren. Internal nodes represent individual
538a409cc95SJessica Paquette         // strings, which may repeat.
539a409cc95SJessica Paquette         for (auto &ChildPair : Curr->Children) {
540a409cc95SJessica Paquette           // Save all of this node's children for processing.
541a409cc95SJessica Paquette           if (!ChildPair.second->isLeaf())
542a409cc95SJessica Paquette             ToVisit.push_back(ChildPair.second);
543a409cc95SJessica Paquette 
544a409cc95SJessica Paquette           // It's not an internal node, so it must be a leaf. If we have a
545a409cc95SJessica Paquette           // long enough string, then save the leaf children.
546a409cc95SJessica Paquette           else if (Length >= MinLength)
547a409cc95SJessica Paquette             LeafChildren.push_back(ChildPair.second);
5484e54ef88SJessica Paquette         }
549a409cc95SJessica Paquette 
550a409cc95SJessica Paquette         // The root never represents a repeated substring. If we're looking at
551a409cc95SJessica Paquette         // that, then skip it.
552a409cc95SJessica Paquette         if (Curr->isRoot())
553a409cc95SJessica Paquette           continue;
554a409cc95SJessica Paquette 
555a409cc95SJessica Paquette         // Do we have any repeated substrings?
556a409cc95SJessica Paquette         if (LeafChildren.size() >= 2) {
557a409cc95SJessica Paquette           // Yes. Update the state to reflect this, and then bail out.
558a409cc95SJessica Paquette           N = Curr;
559a409cc95SJessica Paquette           RS.Length = Length;
560a409cc95SJessica Paquette           for (SuffixTreeNode *Leaf : LeafChildren)
561a409cc95SJessica Paquette             RS.StartIndices.push_back(Leaf->SuffixIdx);
562a409cc95SJessica Paquette           break;
563a409cc95SJessica Paquette         }
564a409cc95SJessica Paquette       }
565a409cc95SJessica Paquette 
566a409cc95SJessica Paquette       // At this point, either NewRS is an empty RepeatedSubstring, or it was
567a409cc95SJessica Paquette       // set in the above loop. Similarly, N is either nullptr, or the node
568a409cc95SJessica Paquette       // associated with NewRS.
569a409cc95SJessica Paquette     }
570a409cc95SJessica Paquette 
571a409cc95SJessica Paquette   public:
572a409cc95SJessica Paquette     /// Return the current repeated substring.
573a409cc95SJessica Paquette     RepeatedSubstring &operator*() { return RS; }
574a409cc95SJessica Paquette 
575a409cc95SJessica Paquette     RepeatedSubstringIterator &operator++() {
576a409cc95SJessica Paquette       advance();
577a409cc95SJessica Paquette       return *this;
578a409cc95SJessica Paquette     }
579a409cc95SJessica Paquette 
580a409cc95SJessica Paquette     RepeatedSubstringIterator operator++(int I) {
581a409cc95SJessica Paquette       RepeatedSubstringIterator It(*this);
582a409cc95SJessica Paquette       advance();
583a409cc95SJessica Paquette       return It;
584a409cc95SJessica Paquette     }
585a409cc95SJessica Paquette 
586a409cc95SJessica Paquette     bool operator==(const RepeatedSubstringIterator &Other) {
587a409cc95SJessica Paquette       return N == Other.N;
588a409cc95SJessica Paquette     }
589a409cc95SJessica Paquette     bool operator!=(const RepeatedSubstringIterator &Other) {
590a409cc95SJessica Paquette       return !(*this == Other);
591a409cc95SJessica Paquette     }
592a409cc95SJessica Paquette 
593a409cc95SJessica Paquette     RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
594a409cc95SJessica Paquette       // Do we have a non-null node?
595a409cc95SJessica Paquette       if (N) {
596a409cc95SJessica Paquette         // Yes. At the first step, we need to visit all of N's children.
597a409cc95SJessica Paquette         // Note: This means that we visit N last.
598a409cc95SJessica Paquette         ToVisit.push_back(N);
599a409cc95SJessica Paquette         advance();
600a409cc95SJessica Paquette       }
601a409cc95SJessica Paquette     }
602a409cc95SJessica Paquette   };
603a409cc95SJessica Paquette 
604a409cc95SJessica Paquette   typedef RepeatedSubstringIterator iterator;
605a409cc95SJessica Paquette   iterator begin() { return iterator(Root); }
606a409cc95SJessica Paquette   iterator end() { return iterator(nullptr); }
607596f483aSJessica Paquette };
608596f483aSJessica Paquette 
6095f8f34e4SAdrian Prantl /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
610596f483aSJessica Paquette struct InstructionMapper {
611596f483aSJessica Paquette 
6125f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that
613596f483aSJessica Paquette   /// cannot be outlined.
614596f483aSJessica Paquette   ///
615596f483aSJessica Paquette   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
616596f483aSJessica Paquette   unsigned IllegalInstrNumber = -3;
617596f483aSJessica Paquette 
6185f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that can
619596f483aSJessica Paquette   /// be outlined.
620596f483aSJessica Paquette   unsigned LegalInstrNumber = 0;
621596f483aSJessica Paquette 
622596f483aSJessica Paquette   /// Correspondence from \p MachineInstrs to unsigned integers.
623596f483aSJessica Paquette   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
624596f483aSJessica Paquette       InstructionIntegerMap;
625596f483aSJessica Paquette 
626cad864d4SJessica Paquette   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
627cad864d4SJessica Paquette   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
628cad864d4SJessica Paquette 
629596f483aSJessica Paquette   /// The vector of unsigned integers that the module is mapped to.
630596f483aSJessica Paquette   std::vector<unsigned> UnsignedVec;
631596f483aSJessica Paquette 
6325f8f34e4SAdrian Prantl   /// Stores the location of the instruction associated with the integer
633596f483aSJessica Paquette   /// at index i in \p UnsignedVec for each index i.
634596f483aSJessica Paquette   std::vector<MachineBasicBlock::iterator> InstrList;
635596f483aSJessica Paquette 
636c991cf36SJessica Paquette   // Set if we added an illegal number in the previous step.
637c991cf36SJessica Paquette   // Since each illegal number is unique, we only need one of them between
638c991cf36SJessica Paquette   // each range of legal numbers. This lets us make sure we don't add more
639c991cf36SJessica Paquette   // than one illegal number per range.
640c991cf36SJessica Paquette   bool AddedIllegalLastTime = false;
641c991cf36SJessica Paquette 
6425f8f34e4SAdrian Prantl   /// Maps \p *It to a legal integer.
643596f483aSJessica Paquette   ///
644c4cf775aSJessica Paquette   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
645ca3ed964SJessica Paquette   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
646596f483aSJessica Paquette   ///
647596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
648267d266cSJessica Paquette   unsigned mapToLegalUnsigned(
649c4cf775aSJessica Paquette       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
650c4cf775aSJessica Paquette       bool &HaveLegalRange, unsigned &NumLegalInBlock,
651267d266cSJessica Paquette       std::vector<unsigned> &UnsignedVecForMBB,
652267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
653c991cf36SJessica Paquette     // We added something legal, so we should unset the AddedLegalLastTime
654c991cf36SJessica Paquette     // flag.
655c991cf36SJessica Paquette     AddedIllegalLastTime = false;
656596f483aSJessica Paquette 
657c4cf775aSJessica Paquette     // If we have at least two adjacent legal instructions (which may have
658c4cf775aSJessica Paquette     // invisible instructions in between), remember that.
659c4cf775aSJessica Paquette     if (CanOutlineWithPrevInstr)
660c4cf775aSJessica Paquette       HaveLegalRange = true;
661c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = true;
662c4cf775aSJessica Paquette 
663267d266cSJessica Paquette     // Keep track of the number of legal instructions we insert.
664267d266cSJessica Paquette     NumLegalInBlock++;
665267d266cSJessica Paquette 
666596f483aSJessica Paquette     // Get the integer for this instruction or give it the current
667596f483aSJessica Paquette     // LegalInstrNumber.
668267d266cSJessica Paquette     InstrListForMBB.push_back(It);
669596f483aSJessica Paquette     MachineInstr &MI = *It;
670596f483aSJessica Paquette     bool WasInserted;
671596f483aSJessica Paquette     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
672596f483aSJessica Paquette         ResultIt;
673596f483aSJessica Paquette     std::tie(ResultIt, WasInserted) =
674596f483aSJessica Paquette         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
675596f483aSJessica Paquette     unsigned MINumber = ResultIt->second;
676596f483aSJessica Paquette 
677596f483aSJessica Paquette     // There was an insertion.
678ca3ed964SJessica Paquette     if (WasInserted)
679596f483aSJessica Paquette       LegalInstrNumber++;
680596f483aSJessica Paquette 
681267d266cSJessica Paquette     UnsignedVecForMBB.push_back(MINumber);
682596f483aSJessica Paquette 
683596f483aSJessica Paquette     // Make sure we don't overflow or use any integers reserved by the DenseMap.
684596f483aSJessica Paquette     if (LegalInstrNumber >= IllegalInstrNumber)
685596f483aSJessica Paquette       report_fatal_error("Instruction mapping overflow!");
686596f483aSJessica Paquette 
68778681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
68878681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
68978681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
69078681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
691596f483aSJessica Paquette 
692596f483aSJessica Paquette     return MINumber;
693596f483aSJessica Paquette   }
694596f483aSJessica Paquette 
695596f483aSJessica Paquette   /// Maps \p *It to an illegal integer.
696596f483aSJessica Paquette   ///
697267d266cSJessica Paquette   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
698267d266cSJessica Paquette   /// IllegalInstrNumber.
699596f483aSJessica Paquette   ///
700596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
7016b7615aeSPuyan Lotfi   unsigned mapToIllegalUnsigned(
7026b7615aeSPuyan Lotfi       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
7036b7615aeSPuyan Lotfi       std::vector<unsigned> &UnsignedVecForMBB,
704267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
705c4cf775aSJessica Paquette     // Can't outline an illegal instruction. Set the flag.
706c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = false;
707c4cf775aSJessica Paquette 
708c991cf36SJessica Paquette     // Only add one illegal number per range of legal numbers.
709c991cf36SJessica Paquette     if (AddedIllegalLastTime)
710c991cf36SJessica Paquette       return IllegalInstrNumber;
711c991cf36SJessica Paquette 
712c991cf36SJessica Paquette     // Remember that we added an illegal number last time.
713c991cf36SJessica Paquette     AddedIllegalLastTime = true;
714596f483aSJessica Paquette     unsigned MINumber = IllegalInstrNumber;
715596f483aSJessica Paquette 
716267d266cSJessica Paquette     InstrListForMBB.push_back(It);
717267d266cSJessica Paquette     UnsignedVecForMBB.push_back(IllegalInstrNumber);
718596f483aSJessica Paquette     IllegalInstrNumber--;
719596f483aSJessica Paquette 
720596f483aSJessica Paquette     assert(LegalInstrNumber < IllegalInstrNumber &&
721596f483aSJessica Paquette            "Instruction mapping overflow!");
722596f483aSJessica Paquette 
72378681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
724596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
725596f483aSJessica Paquette 
72678681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
727596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
728596f483aSJessica Paquette 
729596f483aSJessica Paquette     return MINumber;
730596f483aSJessica Paquette   }
731596f483aSJessica Paquette 
7325f8f34e4SAdrian Prantl   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
733596f483aSJessica Paquette   /// and appends it to \p UnsignedVec and \p InstrList.
734596f483aSJessica Paquette   ///
735596f483aSJessica Paquette   /// Two instructions are assigned the same integer if they are identical.
736596f483aSJessica Paquette   /// If an instruction is deemed unsafe to outline, then it will be assigned an
737596f483aSJessica Paquette   /// unique integer. The resulting mapping is placed into a suffix tree and
738596f483aSJessica Paquette   /// queried for candidates.
739596f483aSJessica Paquette   ///
740596f483aSJessica Paquette   /// \param MBB The \p MachineBasicBlock to be translated into integers.
741da08078fSEli Friedman   /// \param TII \p TargetInstrInfo for the function.
742596f483aSJessica Paquette   void convertToUnsignedVec(MachineBasicBlock &MBB,
743596f483aSJessica Paquette                             const TargetInstrInfo &TII) {
7443635c890SAlexander Kornienko     unsigned Flags = 0;
74582d9c0a3SJessica Paquette 
74682d9c0a3SJessica Paquette     // Don't even map in this case.
74782d9c0a3SJessica Paquette     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
74882d9c0a3SJessica Paquette       return;
74982d9c0a3SJessica Paquette 
750cad864d4SJessica Paquette     // Store info for the MBB for later outlining.
751cad864d4SJessica Paquette     MBBFlagsMap[&MBB] = Flags;
752cad864d4SJessica Paquette 
753c991cf36SJessica Paquette     MachineBasicBlock::iterator It = MBB.begin();
754267d266cSJessica Paquette 
755267d266cSJessica Paquette     // The number of instructions in this block that will be considered for
756267d266cSJessica Paquette     // outlining.
757267d266cSJessica Paquette     unsigned NumLegalInBlock = 0;
758267d266cSJessica Paquette 
759c4cf775aSJessica Paquette     // True if we have at least two legal instructions which aren't separated
760c4cf775aSJessica Paquette     // by an illegal instruction.
761c4cf775aSJessica Paquette     bool HaveLegalRange = false;
762c4cf775aSJessica Paquette 
763c4cf775aSJessica Paquette     // True if we can perform outlining given the last mapped (non-invisible)
764c4cf775aSJessica Paquette     // instruction. This lets us know if we have a legal range.
765c4cf775aSJessica Paquette     bool CanOutlineWithPrevInstr = false;
766c4cf775aSJessica Paquette 
767267d266cSJessica Paquette     // FIXME: Should this all just be handled in the target, rather than using
768267d266cSJessica Paquette     // repeated calls to getOutliningType?
769267d266cSJessica Paquette     std::vector<unsigned> UnsignedVecForMBB;
770267d266cSJessica Paquette     std::vector<MachineBasicBlock::iterator> InstrListForMBB;
771267d266cSJessica Paquette 
77276166a1aSSimon Pilgrim     for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
773596f483aSJessica Paquette       // Keep track of where this instruction is in the module.
7743291e735SJessica Paquette       switch (TII.getOutliningType(It, Flags)) {
775aa087327SJessica Paquette       case InstrType::Illegal:
7766b7615aeSPuyan Lotfi         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
7776b7615aeSPuyan Lotfi                              InstrListForMBB);
778596f483aSJessica Paquette         break;
779596f483aSJessica Paquette 
780aa087327SJessica Paquette       case InstrType::Legal:
781c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
782c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
783596f483aSJessica Paquette         break;
784596f483aSJessica Paquette 
785aa087327SJessica Paquette       case InstrType::LegalTerminator:
786c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
787c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
788c991cf36SJessica Paquette         // The instruction also acts as a terminator, so we have to record that
789c991cf36SJessica Paquette         // in the string.
790c4cf775aSJessica Paquette         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
791c4cf775aSJessica Paquette                              InstrListForMBB);
792042dc9e0SEli Friedman         break;
793042dc9e0SEli Friedman 
794aa087327SJessica Paquette       case InstrType::Invisible:
795c991cf36SJessica Paquette         // Normally this is set by mapTo(Blah)Unsigned, but we just want to
796c991cf36SJessica Paquette         // skip this instruction. So, unset the flag here.
797bd72988cSJessica Paquette         AddedIllegalLastTime = false;
798596f483aSJessica Paquette         break;
799596f483aSJessica Paquette       }
800596f483aSJessica Paquette     }
801596f483aSJessica Paquette 
802267d266cSJessica Paquette     // Are there enough legal instructions in the block for outlining to be
803267d266cSJessica Paquette     // possible?
804c4cf775aSJessica Paquette     if (HaveLegalRange) {
805596f483aSJessica Paquette       // After we're done every insertion, uniquely terminate this part of the
806596f483aSJessica Paquette       // "string". This makes sure we won't match across basic block or function
807596f483aSJessica Paquette       // boundaries since the "end" is encoded uniquely and thus appears in no
808596f483aSJessica Paquette       // repeated substring.
809c4cf775aSJessica Paquette       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
810c4cf775aSJessica Paquette                            InstrListForMBB);
811267d266cSJessica Paquette       InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
812267d266cSJessica Paquette                        InstrListForMBB.end());
813267d266cSJessica Paquette       UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
814267d266cSJessica Paquette                          UnsignedVecForMBB.end());
815267d266cSJessica Paquette     }
816596f483aSJessica Paquette   }
817596f483aSJessica Paquette 
818596f483aSJessica Paquette   InstructionMapper() {
819596f483aSJessica Paquette     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
820596f483aSJessica Paquette     // changed.
821596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
822596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s empty key isn't -1!");
823596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
824596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
825596f483aSJessica Paquette   }
826596f483aSJessica Paquette };
827596f483aSJessica Paquette 
8285f8f34e4SAdrian Prantl /// An interprocedural pass which finds repeated sequences of
829596f483aSJessica Paquette /// instructions and replaces them with calls to functions.
830596f483aSJessica Paquette ///
831596f483aSJessica Paquette /// Each instruction is mapped to an unsigned integer and placed in a string.
832596f483aSJessica Paquette /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
833596f483aSJessica Paquette /// is then repeatedly queried for repeated sequences of instructions. Each
834596f483aSJessica Paquette /// non-overlapping repeated sequence is then placed in its own
835596f483aSJessica Paquette /// \p MachineFunction and each instance is then replaced with a call to that
836596f483aSJessica Paquette /// function.
837596f483aSJessica Paquette struct MachineOutliner : public ModulePass {
838596f483aSJessica Paquette 
839596f483aSJessica Paquette   static char ID;
840596f483aSJessica Paquette 
8415f8f34e4SAdrian Prantl   /// Set to true if the outliner should consider functions with
84213593843SJessica Paquette   /// linkonceodr linkage.
84313593843SJessica Paquette   bool OutlineFromLinkOnceODRs = false;
84413593843SJessica Paquette 
8458bda1881SJessica Paquette   /// Set to true if the outliner should run on all functions in the module
8468bda1881SJessica Paquette   /// considered safe for outlining.
8478bda1881SJessica Paquette   /// Set to true by default for compatibility with llc's -run-pass option.
8488bda1881SJessica Paquette   /// Set when the pass is constructed in TargetPassConfig.
8498bda1881SJessica Paquette   bool RunOnAllFunctions = true;
8508bda1881SJessica Paquette 
851596f483aSJessica Paquette   StringRef getPassName() const override { return "Machine Outliner"; }
852596f483aSJessica Paquette 
853596f483aSJessica Paquette   void getAnalysisUsage(AnalysisUsage &AU) const override {
854cc382cf7SYuanfang Chen     AU.addRequired<MachineModuleInfoWrapperPass>();
855cc382cf7SYuanfang Chen     AU.addPreserved<MachineModuleInfoWrapperPass>();
856596f483aSJessica Paquette     AU.setPreservesAll();
857596f483aSJessica Paquette     ModulePass::getAnalysisUsage(AU);
858596f483aSJessica Paquette   }
859596f483aSJessica Paquette 
8601eca23bdSJessica Paquette   MachineOutliner() : ModulePass(ID) {
861596f483aSJessica Paquette     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
862596f483aSJessica Paquette   }
863596f483aSJessica Paquette 
8641cc52a00SJessica Paquette   /// Remark output explaining that not outlining a set of candidates would be
8651cc52a00SJessica Paquette   /// better than outlining that set.
8661cc52a00SJessica Paquette   void emitNotOutliningCheaperRemark(
8671cc52a00SJessica Paquette       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
8681cc52a00SJessica Paquette       OutlinedFunction &OF);
8691cc52a00SJessica Paquette 
87058e706a6SJessica Paquette   /// Remark output explaining that a function was outlined.
87158e706a6SJessica Paquette   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
87258e706a6SJessica Paquette 
873ce3a2dcfSJessica Paquette   /// Find all repeated substrings that satisfy the outlining cost model by
874ce3a2dcfSJessica Paquette   /// constructing a suffix tree.
87578681be2SJessica Paquette   ///
87678681be2SJessica Paquette   /// If a substring appears at least twice, then it must be represented by
8771cc52a00SJessica Paquette   /// an internal node which appears in at least two suffixes. Each suffix
8781cc52a00SJessica Paquette   /// is represented by a leaf node. To do this, we visit each internal node
8791cc52a00SJessica Paquette   /// in the tree, using the leaf children of each internal node. If an
8801cc52a00SJessica Paquette   /// internal node represents a beneficial substring, then we use each of
8811cc52a00SJessica Paquette   /// its leaf children to find the locations of its substring.
88278681be2SJessica Paquette   ///
88378681be2SJessica Paquette   /// \param Mapper Contains outlining mapping information.
8841cc52a00SJessica Paquette   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
8851cc52a00SJessica Paquette   /// each type of candidate.
886ce3a2dcfSJessica Paquette   void findCandidates(InstructionMapper &Mapper,
88778681be2SJessica Paquette                       std::vector<OutlinedFunction> &FunctionList);
88878681be2SJessica Paquette 
8894ae3b71dSJessica Paquette   /// Replace the sequences of instructions represented by \p OutlinedFunctions
8904ae3b71dSJessica Paquette   /// with calls to functions.
891596f483aSJessica Paquette   ///
892596f483aSJessica Paquette   /// \param M The module we are outlining from.
893596f483aSJessica Paquette   /// \param FunctionList A list of functions to be inserted into the module.
894596f483aSJessica Paquette   /// \param Mapper Contains the instruction mappings for the module.
8954ae3b71dSJessica Paquette   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
8966b7615aeSPuyan Lotfi                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
897596f483aSJessica Paquette 
898596f483aSJessica Paquette   /// Creates a function for \p OF and inserts it into the module.
899e18d6ff0SJessica Paquette   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
900a3eb0facSJessica Paquette                                           InstructionMapper &Mapper,
901a3eb0facSJessica Paquette                                           unsigned Name);
902596f483aSJessica Paquette 
903a51fc8ddSPuyan Lotfi   /// Calls 'doOutline()'.
904a51fc8ddSPuyan Lotfi   bool runOnModule(Module &M) override;
905a51fc8ddSPuyan Lotfi 
906596f483aSJessica Paquette   /// Construct a suffix tree on the instructions in \p M and outline repeated
907596f483aSJessica Paquette   /// strings from that tree.
908a51fc8ddSPuyan Lotfi   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
909aa087327SJessica Paquette 
910aa087327SJessica Paquette   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
911aa087327SJessica Paquette   /// function for remark emission.
912aa087327SJessica Paquette   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
913e18d6ff0SJessica Paquette     for (const Candidate &C : OF.Candidates)
9147ad25836SSimon Pilgrim       if (MachineFunction *MF = C.getMF())
9157ad25836SSimon Pilgrim         if (DISubprogram *SP = MF->getFunction().getSubprogram())
916aa087327SJessica Paquette           return SP;
917aa087327SJessica Paquette     return nullptr;
918aa087327SJessica Paquette   }
919050d1ac4SJessica Paquette 
920050d1ac4SJessica Paquette   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
921050d1ac4SJessica Paquette   /// These are used to construct a suffix tree.
922050d1ac4SJessica Paquette   void populateMapper(InstructionMapper &Mapper, Module &M,
923050d1ac4SJessica Paquette                       MachineModuleInfo &MMI);
924596f483aSJessica Paquette 
9252386eab3SJessica Paquette   /// Initialize information necessary to output a size remark.
9262386eab3SJessica Paquette   /// FIXME: This should be handled by the pass manager, not the outliner.
9272386eab3SJessica Paquette   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
9282386eab3SJessica Paquette   /// pass manager.
9296b7615aeSPuyan Lotfi   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
9302386eab3SJessica Paquette                           StringMap<unsigned> &FunctionToInstrCount);
9312386eab3SJessica Paquette 
9322386eab3SJessica Paquette   /// Emit the remark.
9332386eab3SJessica Paquette   // FIXME: This should be handled by the pass manager, not the outliner.
9346b7615aeSPuyan Lotfi   void
9356b7615aeSPuyan Lotfi   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
9362386eab3SJessica Paquette                               const StringMap<unsigned> &FunctionToInstrCount);
9372386eab3SJessica Paquette };
938596f483aSJessica Paquette } // Anonymous namespace.
939596f483aSJessica Paquette 
940596f483aSJessica Paquette char MachineOutliner::ID = 0;
941596f483aSJessica Paquette 
942596f483aSJessica Paquette namespace llvm {
9438bda1881SJessica Paquette ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
9448bda1881SJessica Paquette   MachineOutliner *OL = new MachineOutliner();
9458bda1881SJessica Paquette   OL->RunOnAllFunctions = RunOnAllFunctions;
9468bda1881SJessica Paquette   return OL;
94713593843SJessica Paquette }
94813593843SJessica Paquette 
94978681be2SJessica Paquette } // namespace llvm
95078681be2SJessica Paquette 
95178681be2SJessica Paquette INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
95278681be2SJessica Paquette                 false)
95378681be2SJessica Paquette 
9541cc52a00SJessica Paquette void MachineOutliner::emitNotOutliningCheaperRemark(
9551cc52a00SJessica Paquette     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
9561cc52a00SJessica Paquette     OutlinedFunction &OF) {
957c991cf36SJessica Paquette   // FIXME: Right now, we arbitrarily choose some Candidate from the
958c991cf36SJessica Paquette   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
959c991cf36SJessica Paquette   // We should probably sort these by function name or something to make sure
960c991cf36SJessica Paquette   // the remarks are stable.
9611cc52a00SJessica Paquette   Candidate &C = CandidatesForRepeatedSeq.front();
9621cc52a00SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
9631cc52a00SJessica Paquette   MORE.emit([&]() {
9641cc52a00SJessica Paquette     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
9651cc52a00SJessica Paquette                                       C.front()->getDebugLoc(), C.getMBB());
9661cc52a00SJessica Paquette     R << "Did not outline " << NV("Length", StringLen) << " instructions"
9671cc52a00SJessica Paquette       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
9681cc52a00SJessica Paquette       << " locations."
9691cc52a00SJessica Paquette       << " Bytes from outlining all occurrences ("
9701cc52a00SJessica Paquette       << NV("OutliningCost", OF.getOutliningCost()) << ")"
9711cc52a00SJessica Paquette       << " >= Unoutlined instruction bytes ("
9721cc52a00SJessica Paquette       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
9731cc52a00SJessica Paquette       << " (Also found at: ";
9741cc52a00SJessica Paquette 
9751cc52a00SJessica Paquette     // Tell the user the other places the candidate was found.
9761cc52a00SJessica Paquette     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
9771cc52a00SJessica Paquette       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
9781cc52a00SJessica Paquette               CandidatesForRepeatedSeq[i].front()->getDebugLoc());
9791cc52a00SJessica Paquette       if (i != e - 1)
9801cc52a00SJessica Paquette         R << ", ";
9811cc52a00SJessica Paquette     }
9821cc52a00SJessica Paquette 
9831cc52a00SJessica Paquette     R << ")";
9841cc52a00SJessica Paquette     return R;
9851cc52a00SJessica Paquette   });
9861cc52a00SJessica Paquette }
9871cc52a00SJessica Paquette 
98858e706a6SJessica Paquette void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
98958e706a6SJessica Paquette   MachineBasicBlock *MBB = &*OF.MF->begin();
99058e706a6SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
99158e706a6SJessica Paquette   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
99258e706a6SJessica Paquette                               MBB->findDebugLoc(MBB->begin()), MBB);
99358e706a6SJessica Paquette   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
99434b618bfSJessica Paquette     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
99558e706a6SJessica Paquette     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
99658e706a6SJessica Paquette     << " locations. "
99758e706a6SJessica Paquette     << "(Found at: ";
99858e706a6SJessica Paquette 
99958e706a6SJessica Paquette   // Tell the user the other places the candidate was found.
100058e706a6SJessica Paquette   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
100158e706a6SJessica Paquette 
100258e706a6SJessica Paquette     R << NV((Twine("StartLoc") + Twine(i)).str(),
1003e18d6ff0SJessica Paquette             OF.Candidates[i].front()->getDebugLoc());
100458e706a6SJessica Paquette     if (i != e - 1)
100558e706a6SJessica Paquette       R << ", ";
100658e706a6SJessica Paquette   }
100758e706a6SJessica Paquette 
100858e706a6SJessica Paquette   R << ")";
100958e706a6SJessica Paquette 
101058e706a6SJessica Paquette   MORE.emit(R);
101158e706a6SJessica Paquette }
101258e706a6SJessica Paquette 
10136b7615aeSPuyan Lotfi void MachineOutliner::findCandidates(
10146b7615aeSPuyan Lotfi     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
101578681be2SJessica Paquette   FunctionList.clear();
1016ce3a2dcfSJessica Paquette   SuffixTree ST(Mapper.UnsignedVec);
101778681be2SJessica Paquette 
1018fbe7f5e9SDavid Tellenbach   // First, find all of the repeated substrings in the tree of minimum length
10194e54ef88SJessica Paquette   // 2.
1020d87f5449SJessica Paquette   std::vector<Candidate> CandidatesForRepeatedSeq;
1021d4e7d074SJessica Paquette   for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
1022d4e7d074SJessica Paquette     CandidatesForRepeatedSeq.clear();
1023d4e7d074SJessica Paquette     SuffixTree::RepeatedSubstring RS = *It;
10244e54ef88SJessica Paquette     unsigned StringLen = RS.Length;
10254e54ef88SJessica Paquette     for (const unsigned &StartIdx : RS.StartIndices) {
102652df8015SJessica Paquette       unsigned EndIdx = StartIdx + StringLen - 1;
102752df8015SJessica Paquette       // Trick: Discard some candidates that would be incompatible with the
102852df8015SJessica Paquette       // ones we've already found for this sequence. This will save us some
102952df8015SJessica Paquette       // work in candidate selection.
103052df8015SJessica Paquette       //
103152df8015SJessica Paquette       // If two candidates overlap, then we can't outline them both. This
103252df8015SJessica Paquette       // happens when we have candidates that look like, say
103352df8015SJessica Paquette       //
103452df8015SJessica Paquette       // AA (where each "A" is an instruction).
103552df8015SJessica Paquette       //
103652df8015SJessica Paquette       // We might have some portion of the module that looks like this:
103752df8015SJessica Paquette       // AAAAAA (6 A's)
103852df8015SJessica Paquette       //
103952df8015SJessica Paquette       // In this case, there are 5 different copies of "AA" in this range, but
104052df8015SJessica Paquette       // at most 3 can be outlined. If only outlining 3 of these is going to
104152df8015SJessica Paquette       // be unbeneficial, then we ought to not bother.
104252df8015SJessica Paquette       //
104352df8015SJessica Paquette       // Note that two things DON'T overlap when they look like this:
104452df8015SJessica Paquette       // start1...end1 .... start2...end2
104552df8015SJessica Paquette       // That is, one must either
104652df8015SJessica Paquette       // * End before the other starts
104752df8015SJessica Paquette       // * Start after the other ends
10484e54ef88SJessica Paquette       if (std::all_of(
10494e54ef88SJessica Paquette               CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
105052df8015SJessica Paquette               [&StartIdx, &EndIdx](const Candidate &C) {
10514e54ef88SJessica Paquette                 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
105252df8015SJessica Paquette               })) {
105352df8015SJessica Paquette         // It doesn't overlap with anything, so we can outline it.
105452df8015SJessica Paquette         // Each sequence is over [StartIt, EndIt].
1055aa087327SJessica Paquette         // Save the candidate and its location.
1056aa087327SJessica Paquette 
105752df8015SJessica Paquette         MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
105852df8015SJessica Paquette         MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1059cad864d4SJessica Paquette         MachineBasicBlock *MBB = StartIt->getParent();
106052df8015SJessica Paquette 
1061aa087327SJessica Paquette         CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
1062cad864d4SJessica Paquette                                               EndIt, MBB, FunctionList.size(),
1063cad864d4SJessica Paquette                                               Mapper.MBBFlagsMap[MBB]);
106452df8015SJessica Paquette       }
1065809d708bSJessica Paquette     }
1066809d708bSJessica Paquette 
1067acc15e12SJessica Paquette     // We've found something we might want to outline.
1068acc15e12SJessica Paquette     // Create an OutlinedFunction to store it and check if it'd be beneficial
1069acc15e12SJessica Paquette     // to outline.
1070ddb039a1SJessica Paquette     if (CandidatesForRepeatedSeq.size() < 2)
1071da08078fSEli Friedman       continue;
1072da08078fSEli Friedman 
1073da08078fSEli Friedman     // Arbitrarily choose a TII from the first candidate.
1074da08078fSEli Friedman     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1075da08078fSEli Friedman     const TargetInstrInfo *TII =
1076da08078fSEli Friedman         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1077da08078fSEli Friedman 
10789d93c602SJessica Paquette     OutlinedFunction OF =
1079da08078fSEli Friedman         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
10809d93c602SJessica Paquette 
1081b2d53c5dSJessica Paquette     // If we deleted too many candidates, then there's nothing worth outlining.
1082b2d53c5dSJessica Paquette     // FIXME: This should take target-specified instruction sizes into account.
1083b2d53c5dSJessica Paquette     if (OF.Candidates.size() < 2)
10849d93c602SJessica Paquette       continue;
10859d93c602SJessica Paquette 
1086ffe4abc5SJessica Paquette     // Is it better to outline this candidate than not?
1087f94d1d29SJessica Paquette     if (OF.getBenefit() < 1) {
10881cc52a00SJessica Paquette       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
108978681be2SJessica Paquette       continue;
1090ffe4abc5SJessica Paquette     }
109178681be2SJessica Paquette 
1092acc15e12SJessica Paquette     FunctionList.push_back(OF);
109378681be2SJessica Paquette   }
1094596f483aSJessica Paquette }
1095596f483aSJessica Paquette 
10966b7615aeSPuyan Lotfi MachineFunction *MachineOutliner::createOutlinedFunction(
10976b7615aeSPuyan Lotfi     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
1098596f483aSJessica Paquette 
1099ae6c9403SFangrui Song   // Create the function name. This should be unique.
1100a3eb0facSJessica Paquette   // FIXME: We should have a better naming scheme. This should be stable,
1101a3eb0facSJessica Paquette   // regardless of changes to the outliner's cost model/traversal order.
1102ae6c9403SFangrui Song   std::string FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str();
1103596f483aSJessica Paquette 
1104596f483aSJessica Paquette   // Create the function using an IR-level function.
1105596f483aSJessica Paquette   LLVMContext &C = M.getContext();
1106ae6c9403SFangrui Song   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1107ae6c9403SFangrui Song                                  Function::ExternalLinkage, FunctionName, M);
1108596f483aSJessica Paquette 
1109596f483aSJessica Paquette   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1110596f483aSJessica Paquette   // which gives us better results when we outline from linkonceodr functions.
1111d506bf8eSJessica Paquette   F->setLinkage(GlobalValue::InternalLinkage);
1112596f483aSJessica Paquette   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1113596f483aSJessica Paquette 
111425bef201SEli Friedman   // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
111525bef201SEli Friedman   // necessary.
111625bef201SEli Friedman 
111725bef201SEli Friedman   // Set optsize/minsize, so we don't insert padding between outlined
111825bef201SEli Friedman   // functions.
111925bef201SEli Friedman   F->addFnAttr(Attribute::OptimizeForSize);
112025bef201SEli Friedman   F->addFnAttr(Attribute::MinSize);
112125bef201SEli Friedman 
1122e3932eeeSJessica Paquette   // Include target features from an arbitrary candidate for the outlined
1123e3932eeeSJessica Paquette   // function. This makes sure the outlined function knows what kinds of
1124e3932eeeSJessica Paquette   // instructions are going into it. This is fine, since all parent functions
1125e3932eeeSJessica Paquette   // must necessarily support the instructions that are in the outlined region.
1126e18d6ff0SJessica Paquette   Candidate &FirstCand = OF.Candidates.front();
112734b618bfSJessica Paquette   const Function &ParentFn = FirstCand.getMF()->getFunction();
1128e3932eeeSJessica Paquette   if (ParentFn.hasFnAttribute("target-features"))
1129e3932eeeSJessica Paquette     F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1130e3932eeeSJessica Paquette 
1131596f483aSJessica Paquette   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1132596f483aSJessica Paquette   IRBuilder<> Builder(EntryBB);
1133596f483aSJessica Paquette   Builder.CreateRetVoid();
1134596f483aSJessica Paquette 
1135cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
11367bda1958SMatthias Braun   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
1137596f483aSJessica Paquette   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1138596f483aSJessica Paquette   const TargetSubtargetInfo &STI = MF.getSubtarget();
1139596f483aSJessica Paquette   const TargetInstrInfo &TII = *STI.getInstrInfo();
1140596f483aSJessica Paquette 
1141596f483aSJessica Paquette   // Insert the new function into the module.
1142596f483aSJessica Paquette   MF.insert(MF.begin(), &MBB);
1143596f483aSJessica Paquette 
114434b618bfSJessica Paquette   for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
114534b618bfSJessica Paquette        ++I) {
114634b618bfSJessica Paquette     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
1147c73c0307SChandler Carruth     NewMI->dropMemRefs(MF);
1148596f483aSJessica Paquette 
1149596f483aSJessica Paquette     // Don't keep debug information for outlined instructions.
1150596f483aSJessica Paquette     NewMI->setDebugLoc(DebugLoc());
1151596f483aSJessica Paquette     MBB.insert(MBB.end(), NewMI);
1152596f483aSJessica Paquette   }
1153596f483aSJessica Paquette 
115469f517dfSJessica Paquette   TII.buildOutlinedFrame(MBB, MF, OF);
1155729e6869SJessica Paquette 
1156cc06a782SJessica Paquette   // Outlined functions shouldn't preserve liveness.
1157cc06a782SJessica Paquette   MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1158cc06a782SJessica Paquette   MF.getRegInfo().freezeReservedRegs(MF);
1159cc06a782SJessica Paquette 
1160a499c3c2SJessica Paquette   // If there's a DISubprogram associated with this outlined function, then
1161a499c3c2SJessica Paquette   // emit debug info for the outlined function.
1162aa087327SJessica Paquette   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1163a499c3c2SJessica Paquette     // We have a DISubprogram. Get its DICompileUnit.
1164a499c3c2SJessica Paquette     DICompileUnit *CU = SP->getUnit();
1165a499c3c2SJessica Paquette     DIBuilder DB(M, true, CU);
1166a499c3c2SJessica Paquette     DIFile *Unit = SP->getFile();
1167a499c3c2SJessica Paquette     Mangler Mg;
1168a499c3c2SJessica Paquette     // Get the mangled name of the function for the linkage name.
1169a499c3c2SJessica Paquette     std::string Dummy;
1170a499c3c2SJessica Paquette     llvm::raw_string_ostream MangledNameStream(Dummy);
1171a499c3c2SJessica Paquette     Mg.getNameWithPrefix(MangledNameStream, F, false);
1172a499c3c2SJessica Paquette 
1173cc06a782SJessica Paquette     DISubprogram *OutlinedSP = DB.createFunction(
1174a499c3c2SJessica Paquette         Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1175a499c3c2SJessica Paquette         Unit /* File */,
1176a499c3c2SJessica Paquette         0 /* Line 0 is reserved for compiler-generated code. */,
1177cc06a782SJessica Paquette         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
1178cda54210SPaul Robinson         0, /* Line 0 is reserved for compiler-generated code. */
1179a499c3c2SJessica Paquette         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1180cda54210SPaul Robinson         /* Outlined code is optimized code by definition. */
1181cda54210SPaul Robinson         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1182a499c3c2SJessica Paquette 
1183a499c3c2SJessica Paquette     // Don't add any new variables to the subprogram.
1184cc06a782SJessica Paquette     DB.finalizeSubprogram(OutlinedSP);
1185a499c3c2SJessica Paquette 
1186a499c3c2SJessica Paquette     // Attach subprogram to the function.
1187cc06a782SJessica Paquette     F->setSubprogram(OutlinedSP);
1188a499c3c2SJessica Paquette     // We're done with the DIBuilder.
1189a499c3c2SJessica Paquette     DB.finalize();
1190a499c3c2SJessica Paquette   }
1191a499c3c2SJessica Paquette 
1192596f483aSJessica Paquette   return &MF;
1193596f483aSJessica Paquette }
1194596f483aSJessica Paquette 
11954ae3b71dSJessica Paquette bool MachineOutliner::outline(Module &M,
11964ae3b71dSJessica Paquette                               std::vector<OutlinedFunction> &FunctionList,
1197a51fc8ddSPuyan Lotfi                               InstructionMapper &Mapper,
1198a51fc8ddSPuyan Lotfi                               unsigned &OutlinedFunctionNum) {
1199596f483aSJessica Paquette 
1200596f483aSJessica Paquette   bool OutlinedSomething = false;
1201a3eb0facSJessica Paquette 
1202962b3ae6SJessica Paquette   // Sort by benefit. The most beneficial functions should be outlined first.
1203efd94c56SFangrui Song   llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
1204efd94c56SFangrui Song                                      const OutlinedFunction &RHS) {
1205962b3ae6SJessica Paquette     return LHS.getBenefit() > RHS.getBenefit();
1206962b3ae6SJessica Paquette   });
1207596f483aSJessica Paquette 
1208962b3ae6SJessica Paquette   // Walk over each function, outlining them as we go along. Functions are
1209962b3ae6SJessica Paquette   // outlined greedily, based off the sort above.
1210962b3ae6SJessica Paquette   for (OutlinedFunction &OF : FunctionList) {
1211962b3ae6SJessica Paquette     // If we outlined something that overlapped with a candidate in a previous
1212962b3ae6SJessica Paquette     // step, then we can't outline from it.
1213e18d6ff0SJessica Paquette     erase_if(OF.Candidates, [&Mapper](Candidate &C) {
1214d9d9309bSJessica Paquette       return std::any_of(
1215e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getStartIdx(),
1216e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1217d9d9309bSJessica Paquette           [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
1218235d877eSJessica Paquette     });
1219596f483aSJessica Paquette 
1220962b3ae6SJessica Paquette     // If we made it unbeneficial to outline this function, skip it.
122185af63d0SJessica Paquette     if (OF.getBenefit() < 1)
1222596f483aSJessica Paquette       continue;
1223596f483aSJessica Paquette 
1224962b3ae6SJessica Paquette     // It's beneficial. Create the function and outline its sequence's
1225962b3ae6SJessica Paquette     // occurrences.
1226a3eb0facSJessica Paquette     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
122758e706a6SJessica Paquette     emitOutlinedFunctionRemark(OF);
1228acffa28cSJessica Paquette     FunctionsCreated++;
1229a3eb0facSJessica Paquette     OutlinedFunctionNum++; // Created a function, move to the next name.
1230596f483aSJessica Paquette     MachineFunction *MF = OF.MF;
1231596f483aSJessica Paquette     const TargetSubtargetInfo &STI = MF->getSubtarget();
1232596f483aSJessica Paquette     const TargetInstrInfo &TII = *STI.getInstrInfo();
1233596f483aSJessica Paquette 
1234962b3ae6SJessica Paquette     // Replace occurrences of the sequence with calls to the new function.
1235e18d6ff0SJessica Paquette     for (Candidate &C : OF.Candidates) {
1236962b3ae6SJessica Paquette       MachineBasicBlock &MBB = *C.getMBB();
1237962b3ae6SJessica Paquette       MachineBasicBlock::iterator StartIt = C.front();
1238962b3ae6SJessica Paquette       MachineBasicBlock::iterator EndIt = C.back();
1239596f483aSJessica Paquette 
1240962b3ae6SJessica Paquette       // Insert the call.
1241962b3ae6SJessica Paquette       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
1242962b3ae6SJessica Paquette 
1243962b3ae6SJessica Paquette       // If the caller tracks liveness, then we need to make sure that
1244962b3ae6SJessica Paquette       // anything we outline doesn't break liveness assumptions. The outlined
1245962b3ae6SJessica Paquette       // functions themselves currently don't track liveness, but we should
1246962b3ae6SJessica Paquette       // make sure that the ranges we yank things out of aren't wrong.
1247aa087327SJessica Paquette       if (MBB.getParent()->getProperties().hasProperty(
12480b672491SJessica Paquette               MachineFunctionProperties::Property::TracksLiveness)) {
1249*fc6fda90SJin Lin         // The following code is to add implicit def operands to the call
125071d3869fSDjordje Todorovic         // instruction. It also updates call site information for moved
125171d3869fSDjordje Todorovic         // code.
1252*fc6fda90SJin Lin         SmallSet<Register, 2> UseRegs, DefRegs;
12530b672491SJessica Paquette         // Copy over the defs in the outlined range.
12540b672491SJessica Paquette         // First inst in outlined range <-- Anything that's defined in this
1255962b3ae6SJessica Paquette         // ...                           .. range has to be added as an
1256962b3ae6SJessica Paquette         // implicit Last inst in outlined range  <-- def to the call
125771d3869fSDjordje Todorovic         // instruction. Also remove call site information for outlined block
1258*fc6fda90SJin Lin         // of code. The exposed uses need to be copied in the outlined range.
1259*fc6fda90SJin Lin         for (MachineBasicBlock::reverse_iterator Iter = EndIt.getReverse(),
1260*fc6fda90SJin Lin              Last = std::next(CallInst.getReverse());
1261*fc6fda90SJin Lin              Iter != Last; Iter++) {
1262*fc6fda90SJin Lin           MachineInstr *MI = &*Iter;
1263*fc6fda90SJin Lin           for (MachineOperand &MOP : MI->operands()) {
1264*fc6fda90SJin Lin             // Skip over anything that isn't a register.
1265*fc6fda90SJin Lin             if (!MOP.isReg())
1266*fc6fda90SJin Lin               continue;
1267*fc6fda90SJin Lin 
1268*fc6fda90SJin Lin             if (MOP.isDef()) {
1269*fc6fda90SJin Lin               // Introduce DefRegs set to skip the redundant register.
1270*fc6fda90SJin Lin               DefRegs.insert(MOP.getReg());
1271*fc6fda90SJin Lin               if (UseRegs.count(MOP.getReg()))
1272*fc6fda90SJin Lin                 // Since the regiester is modeled as defined,
1273*fc6fda90SJin Lin                 // it is not necessary to be put in use register set.
1274*fc6fda90SJin Lin                 UseRegs.erase(MOP.getReg());
1275*fc6fda90SJin Lin             } else if (!MOP.isUndef()) {
1276*fc6fda90SJin Lin               // Any register which is not undefined should
1277*fc6fda90SJin Lin               // be put in the use register set.
1278*fc6fda90SJin Lin               UseRegs.insert(MOP.getReg());
1279*fc6fda90SJin Lin             }
1280*fc6fda90SJin Lin           }
1281*fc6fda90SJin Lin           if (MI->isCandidateForCallSiteEntry())
1282*fc6fda90SJin Lin             MI->getMF()->eraseCallSiteInfo(MI);
1283*fc6fda90SJin Lin         }
1284*fc6fda90SJin Lin 
1285*fc6fda90SJin Lin         for (const Register &I : DefRegs)
1286*fc6fda90SJin Lin            // If it's a def, add it to the call instruction.
1287*fc6fda90SJin Lin           CallInst->addOperand(MachineOperand::CreateReg(
1288*fc6fda90SJin Lin                   I, true, /* isDef = true */
1289*fc6fda90SJin Lin                   true /* isImp = true */));
1290*fc6fda90SJin Lin 
1291*fc6fda90SJin Lin         for (const Register &I : UseRegs)
1292*fc6fda90SJin Lin           // If it's a exposed use, add it to the call instruction.
1293*fc6fda90SJin Lin           CallInst->addOperand(
1294*fc6fda90SJin Lin               MachineOperand::CreateReg(I, false, /* isDef = false */
1295*fc6fda90SJin Lin                                         true /* isImp = true */));
12960b672491SJessica Paquette       }
12970b672491SJessica Paquette 
1298aa087327SJessica Paquette       // Erase from the point after where the call was inserted up to, and
1299aa087327SJessica Paquette       // including, the final instruction in the sequence.
1300aa087327SJessica Paquette       // Erase needs one past the end, so we need std::next there too.
1301aa087327SJessica Paquette       MBB.erase(std::next(StartIt), std::next(EndIt));
1302235d877eSJessica Paquette 
1303d9d9309bSJessica Paquette       // Keep track of what we removed by marking them all as -1.
1304235d877eSJessica Paquette       std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1305235d877eSJessica Paquette                     Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1306d9d9309bSJessica Paquette                     [](unsigned &I) { I = static_cast<unsigned>(-1); });
1307596f483aSJessica Paquette       OutlinedSomething = true;
1308596f483aSJessica Paquette 
1309596f483aSJessica Paquette       // Statistics.
1310596f483aSJessica Paquette       NumOutlined++;
1311596f483aSJessica Paquette     }
1312962b3ae6SJessica Paquette   }
1313596f483aSJessica Paquette 
1314d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
1315596f483aSJessica Paquette 
1316596f483aSJessica Paquette   return OutlinedSomething;
1317596f483aSJessica Paquette }
1318596f483aSJessica Paquette 
1319050d1ac4SJessica Paquette void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1320050d1ac4SJessica Paquette                                      MachineModuleInfo &MMI) {
1321df82274fSJessica Paquette   // Build instruction mappings for each function in the module. Start by
1322df82274fSJessica Paquette   // iterating over each Function in M.
1323596f483aSJessica Paquette   for (Function &F : M) {
1324596f483aSJessica Paquette 
1325df82274fSJessica Paquette     // If there's nothing in F, then there's no reason to try and outline from
1326df82274fSJessica Paquette     // it.
1327df82274fSJessica Paquette     if (F.empty())
1328596f483aSJessica Paquette       continue;
1329596f483aSJessica Paquette 
1330df82274fSJessica Paquette     // There's something in F. Check if it has a MachineFunction associated with
1331df82274fSJessica Paquette     // it.
1332df82274fSJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
1333596f483aSJessica Paquette 
1334df82274fSJessica Paquette     // If it doesn't, then there's nothing to outline from. Move to the next
1335df82274fSJessica Paquette     // Function.
1336df82274fSJessica Paquette     if (!MF)
1337596f483aSJessica Paquette       continue;
1338596f483aSJessica Paquette 
1339da08078fSEli Friedman     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1340da08078fSEli Friedman 
13418bda1881SJessica Paquette     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
13428bda1881SJessica Paquette       continue;
13438bda1881SJessica Paquette 
1344df82274fSJessica Paquette     // We have a MachineFunction. Ask the target if it's suitable for outlining.
1345df82274fSJessica Paquette     // If it isn't, then move on to the next Function in the module.
1346df82274fSJessica Paquette     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1347df82274fSJessica Paquette       continue;
1348df82274fSJessica Paquette 
1349df82274fSJessica Paquette     // We have a function suitable for outlining. Iterate over every
1350df82274fSJessica Paquette     // MachineBasicBlock in MF and try to map its instructions to a list of
1351df82274fSJessica Paquette     // unsigned integers.
1352df82274fSJessica Paquette     for (MachineBasicBlock &MBB : *MF) {
1353df82274fSJessica Paquette       // If there isn't anything in MBB, then there's no point in outlining from
1354df82274fSJessica Paquette       // it.
1355b320ca26SJessica Paquette       // If there are fewer than 2 instructions in the MBB, then it can't ever
1356b320ca26SJessica Paquette       // contain something worth outlining.
1357b320ca26SJessica Paquette       // FIXME: This should be based off of the maximum size in B of an outlined
1358b320ca26SJessica Paquette       // call versus the size in B of the MBB.
1359b320ca26SJessica Paquette       if (MBB.empty() || MBB.size() < 2)
1360df82274fSJessica Paquette         continue;
1361df82274fSJessica Paquette 
1362df82274fSJessica Paquette       // Check if MBB could be the target of an indirect branch. If it is, then
1363df82274fSJessica Paquette       // we don't want to outline from it.
1364df82274fSJessica Paquette       if (MBB.hasAddressTaken())
1365df82274fSJessica Paquette         continue;
1366df82274fSJessica Paquette 
1367df82274fSJessica Paquette       // MBB is suitable for outlining. Map it to a list of unsigneds.
1368da08078fSEli Friedman       Mapper.convertToUnsignedVec(MBB, *TII);
1369596f483aSJessica Paquette     }
1370596f483aSJessica Paquette   }
1371050d1ac4SJessica Paquette }
1372050d1ac4SJessica Paquette 
13732386eab3SJessica Paquette void MachineOutliner::initSizeRemarkInfo(
13742386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
13752386eab3SJessica Paquette     StringMap<unsigned> &FunctionToInstrCount) {
13762386eab3SJessica Paquette   // Collect instruction counts for every function. We'll use this to emit
13772386eab3SJessica Paquette   // per-function size remarks later.
13782386eab3SJessica Paquette   for (const Function &F : M) {
13792386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
13802386eab3SJessica Paquette 
13812386eab3SJessica Paquette     // We only care about MI counts here. If there's no MachineFunction at this
13822386eab3SJessica Paquette     // point, then there won't be after the outliner runs, so let's move on.
13832386eab3SJessica Paquette     if (!MF)
13842386eab3SJessica Paquette       continue;
13852386eab3SJessica Paquette     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
13862386eab3SJessica Paquette   }
13872386eab3SJessica Paquette }
13882386eab3SJessica Paquette 
13892386eab3SJessica Paquette void MachineOutliner::emitInstrCountChangedRemark(
13902386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
13912386eab3SJessica Paquette     const StringMap<unsigned> &FunctionToInstrCount) {
13922386eab3SJessica Paquette   // Iterate over each function in the module and emit remarks.
13932386eab3SJessica Paquette   // Note that we won't miss anything by doing this, because the outliner never
13942386eab3SJessica Paquette   // deletes functions.
13952386eab3SJessica Paquette   for (const Function &F : M) {
13962386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
13972386eab3SJessica Paquette 
13982386eab3SJessica Paquette     // The outliner never deletes functions. If we don't have a MF here, then we
13992386eab3SJessica Paquette     // didn't have one prior to outlining either.
14002386eab3SJessica Paquette     if (!MF)
14012386eab3SJessica Paquette       continue;
14022386eab3SJessica Paquette 
1403adcd0268SBenjamin Kramer     std::string Fname = std::string(F.getName());
14042386eab3SJessica Paquette     unsigned FnCountAfter = MF->getInstructionCount();
14052386eab3SJessica Paquette     unsigned FnCountBefore = 0;
14062386eab3SJessica Paquette 
14072386eab3SJessica Paquette     // Check if the function was recorded before.
14082386eab3SJessica Paquette     auto It = FunctionToInstrCount.find(Fname);
14092386eab3SJessica Paquette 
14102386eab3SJessica Paquette     // Did we have a previously-recorded size? If yes, then set FnCountBefore
14112386eab3SJessica Paquette     // to that.
14122386eab3SJessica Paquette     if (It != FunctionToInstrCount.end())
14132386eab3SJessica Paquette       FnCountBefore = It->second;
14142386eab3SJessica Paquette 
14152386eab3SJessica Paquette     // Compute the delta and emit a remark if there was a change.
14162386eab3SJessica Paquette     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
14172386eab3SJessica Paquette                       static_cast<int64_t>(FnCountBefore);
14182386eab3SJessica Paquette     if (FnDelta == 0)
14192386eab3SJessica Paquette       continue;
14202386eab3SJessica Paquette 
14212386eab3SJessica Paquette     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
14222386eab3SJessica Paquette     MORE.emit([&]() {
14232386eab3SJessica Paquette       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
14246b7615aeSPuyan Lotfi                                           DiagnosticLocation(), &MF->front());
14252386eab3SJessica Paquette       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
14262386eab3SJessica Paquette         << ": Function: "
14272386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
14282386eab3SJessica Paquette         << ": MI instruction count changed from "
14292386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
14302386eab3SJessica Paquette                                                     FnCountBefore)
14312386eab3SJessica Paquette         << " to "
14322386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
14332386eab3SJessica Paquette                                                     FnCountAfter)
14342386eab3SJessica Paquette         << "; Delta: "
14352386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
14362386eab3SJessica Paquette       return R;
14372386eab3SJessica Paquette     });
14382386eab3SJessica Paquette   }
14392386eab3SJessica Paquette }
14402386eab3SJessica Paquette 
1441050d1ac4SJessica Paquette bool MachineOutliner::runOnModule(Module &M) {
1442050d1ac4SJessica Paquette   // Check if there's anything in the module. If it's empty, then there's
1443050d1ac4SJessica Paquette   // nothing to outline.
1444050d1ac4SJessica Paquette   if (M.empty())
1445050d1ac4SJessica Paquette     return false;
1446050d1ac4SJessica Paquette 
1447a51fc8ddSPuyan Lotfi   // Number to append to the current outlined function.
1448a51fc8ddSPuyan Lotfi   unsigned OutlinedFunctionNum = 0;
1449a51fc8ddSPuyan Lotfi 
1450a51fc8ddSPuyan Lotfi   if (!doOutline(M, OutlinedFunctionNum))
1451a51fc8ddSPuyan Lotfi     return false;
1452a51fc8ddSPuyan Lotfi   return true;
1453a51fc8ddSPuyan Lotfi }
1454a51fc8ddSPuyan Lotfi 
1455a51fc8ddSPuyan Lotfi bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1456cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1457050d1ac4SJessica Paquette 
1458050d1ac4SJessica Paquette   // If the user passed -enable-machine-outliner=always or
1459050d1ac4SJessica Paquette   // -enable-machine-outliner, the pass will run on all functions in the module.
1460050d1ac4SJessica Paquette   // Otherwise, if the target supports default outlining, it will run on all
1461050d1ac4SJessica Paquette   // functions deemed by the target to be worth outlining from by default. Tell
1462050d1ac4SJessica Paquette   // the user how the outliner is running.
14636b7615aeSPuyan Lotfi   LLVM_DEBUG({
1464050d1ac4SJessica Paquette     dbgs() << "Machine Outliner: Running on ";
1465050d1ac4SJessica Paquette     if (RunOnAllFunctions)
1466050d1ac4SJessica Paquette       dbgs() << "all functions";
1467050d1ac4SJessica Paquette     else
1468050d1ac4SJessica Paquette       dbgs() << "target-default functions";
14696b7615aeSPuyan Lotfi     dbgs() << "\n";
14706b7615aeSPuyan Lotfi   });
1471050d1ac4SJessica Paquette 
1472050d1ac4SJessica Paquette   // If the user specifies that they want to outline from linkonceodrs, set
1473050d1ac4SJessica Paquette   // it here.
1474050d1ac4SJessica Paquette   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1475050d1ac4SJessica Paquette   InstructionMapper Mapper;
1476050d1ac4SJessica Paquette 
1477050d1ac4SJessica Paquette   // Prepare instruction mappings for the suffix tree.
1478050d1ac4SJessica Paquette   populateMapper(Mapper, M, MMI);
1479596f483aSJessica Paquette   std::vector<OutlinedFunction> FunctionList;
1480596f483aSJessica Paquette 
1481acffa28cSJessica Paquette   // Find all of the outlining candidates.
1482ce3a2dcfSJessica Paquette   findCandidates(Mapper, FunctionList);
1483596f483aSJessica Paquette 
14842386eab3SJessica Paquette   // If we've requested size remarks, then collect the MI counts of every
14852386eab3SJessica Paquette   // function before outlining, and the MI counts after outlining.
14862386eab3SJessica Paquette   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
14872386eab3SJessica Paquette   // the pass manager's responsibility.
14882386eab3SJessica Paquette   // This could pretty easily be placed in outline instead, but because we
14892386eab3SJessica Paquette   // really ultimately *don't* want this here, it's done like this for now
14902386eab3SJessica Paquette   // instead.
14912386eab3SJessica Paquette 
14922386eab3SJessica Paquette   // Check if we want size remarks.
14932386eab3SJessica Paquette   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
14942386eab3SJessica Paquette   StringMap<unsigned> FunctionToInstrCount;
14952386eab3SJessica Paquette   if (ShouldEmitSizeRemarks)
14962386eab3SJessica Paquette     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
14972386eab3SJessica Paquette 
1498acffa28cSJessica Paquette   // Outline each of the candidates and return true if something was outlined.
1499a51fc8ddSPuyan Lotfi   bool OutlinedSomething =
1500a51fc8ddSPuyan Lotfi       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1501729e6869SJessica Paquette 
15022386eab3SJessica Paquette   // If we outlined something, we definitely changed the MI count of the
15032386eab3SJessica Paquette   // module. If we've asked for size remarks, then output them.
15042386eab3SJessica Paquette   // FIXME: This should be in the pass manager.
15052386eab3SJessica Paquette   if (ShouldEmitSizeRemarks && OutlinedSomething)
15062386eab3SJessica Paquette     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
15072386eab3SJessica Paquette 
1508729e6869SJessica Paquette   return OutlinedSomething;
1509596f483aSJessica Paquette }
1510