1596f483aSJessica Paquette //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2596f483aSJessica Paquette //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6596f483aSJessica Paquette //
7596f483aSJessica Paquette //===----------------------------------------------------------------------===//
8596f483aSJessica Paquette ///
9596f483aSJessica Paquette /// \file
10596f483aSJessica Paquette /// Replaces repeated sequences of instructions with function calls.
11596f483aSJessica Paquette ///
12596f483aSJessica Paquette /// This works by placing every instruction from every basic block in a
13596f483aSJessica Paquette /// suffix tree, and repeatedly querying that tree for repeated sequences of
14596f483aSJessica Paquette /// instructions. If a sequence of instructions appears often, then it ought
15596f483aSJessica Paquette /// to be beneficial to pull out into a function.
16596f483aSJessica Paquette ///
174cf187b5SJessica Paquette /// The MachineOutliner communicates with a given target using hooks defined in
184cf187b5SJessica Paquette /// TargetInstrInfo.h. The target supplies the outliner with information on how
194cf187b5SJessica Paquette /// a specific sequence of instructions should be outlined. This information
204cf187b5SJessica Paquette /// is used to deduce the number of instructions necessary to
214cf187b5SJessica Paquette ///
224cf187b5SJessica Paquette /// * Create an outlined function
234cf187b5SJessica Paquette /// * Call that outlined function
244cf187b5SJessica Paquette ///
254cf187b5SJessica Paquette /// Targets must implement
264cf187b5SJessica Paquette ///   * getOutliningCandidateInfo
2732de26d4SJessica Paquette ///   * buildOutlinedFrame
284cf187b5SJessica Paquette ///   * insertOutlinedCall
294cf187b5SJessica Paquette ///   * isFunctionSafeToOutlineFrom
304cf187b5SJessica Paquette ///
314cf187b5SJessica Paquette /// in order to make use of the MachineOutliner.
324cf187b5SJessica Paquette ///
33596f483aSJessica Paquette /// This was originally presented at the 2016 LLVM Developers' Meeting in the
34596f483aSJessica Paquette /// talk "Reducing Code Size Using Outlining". For a high-level overview of
35596f483aSJessica Paquette /// how this pass works, the talk is available on YouTube at
36596f483aSJessica Paquette ///
37596f483aSJessica Paquette /// https://www.youtube.com/watch?v=yorld-WSOeU
38596f483aSJessica Paquette ///
39596f483aSJessica Paquette /// The slides for the talk are available at
40596f483aSJessica Paquette ///
41596f483aSJessica Paquette /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
42596f483aSJessica Paquette ///
43596f483aSJessica Paquette /// The talk provides an overview of how the outliner finds candidates and
44596f483aSJessica Paquette /// ultimately outlines them. It describes how the main data structure for this
45596f483aSJessica Paquette /// pass, the suffix tree, is queried and purged for candidates. It also gives
46596f483aSJessica Paquette /// a simplified suffix tree construction algorithm for suffix trees based off
47596f483aSJessica Paquette /// of the algorithm actually used here, Ukkonen's algorithm.
48596f483aSJessica Paquette ///
49596f483aSJessica Paquette /// For the original RFC for this pass, please see
50596f483aSJessica Paquette ///
51596f483aSJessica Paquette /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
52596f483aSJessica Paquette ///
53596f483aSJessica Paquette /// For more information on the suffix tree data structure, please see
54596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
55596f483aSJessica Paquette ///
56596f483aSJessica Paquette //===----------------------------------------------------------------------===//
57aa087327SJessica Paquette #include "llvm/CodeGen/MachineOutliner.h"
58596f483aSJessica Paquette #include "llvm/ADT/DenseMap.h"
59fc6fda90SJin Lin #include "llvm/ADT/SmallSet.h"
60596f483aSJessica Paquette #include "llvm/ADT/Statistic.h"
61596f483aSJessica Paquette #include "llvm/ADT/Twine.h"
62596f483aSJessica Paquette #include "llvm/CodeGen/MachineFunction.h"
63596f483aSJessica Paquette #include "llvm/CodeGen/MachineModuleInfo.h"
64ffe4abc5SJessica Paquette #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
6582203c41SGeoff Berry #include "llvm/CodeGen/MachineRegisterInfo.h"
66596f483aSJessica Paquette #include "llvm/CodeGen/Passes.h"
673f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
68b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
69729e6869SJessica Paquette #include "llvm/IR/DIBuilder.h"
70596f483aSJessica Paquette #include "llvm/IR/IRBuilder.h"
71a499c3c2SJessica Paquette #include "llvm/IR/Mangler.h"
7205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
73596f483aSJessica Paquette #include "llvm/Support/Allocator.h"
741eca23bdSJessica Paquette #include "llvm/Support/CommandLine.h"
75596f483aSJessica Paquette #include "llvm/Support/Debug.h"
76596f483aSJessica Paquette #include "llvm/Support/raw_ostream.h"
77596f483aSJessica Paquette #include <functional>
78596f483aSJessica Paquette #include <tuple>
79596f483aSJessica Paquette #include <vector>
80596f483aSJessica Paquette 
81596f483aSJessica Paquette #define DEBUG_TYPE "machine-outliner"
82596f483aSJessica Paquette 
83596f483aSJessica Paquette using namespace llvm;
84ffe4abc5SJessica Paquette using namespace ore;
85aa087327SJessica Paquette using namespace outliner;
86596f483aSJessica Paquette 
87596f483aSJessica Paquette STATISTIC(NumOutlined, "Number of candidates outlined");
88596f483aSJessica Paquette STATISTIC(FunctionsCreated, "Number of functions created");
89596f483aSJessica Paquette 
901eca23bdSJessica Paquette // Set to true if the user wants the outliner to run on linkonceodr linkage
911eca23bdSJessica Paquette // functions. This is false by default because the linker can dedupe linkonceodr
921eca23bdSJessica Paquette // functions. Since the outliner is confined to a single module (modulo LTO),
931eca23bdSJessica Paquette // this is off by default. It should, however, be the default behaviour in
941eca23bdSJessica Paquette // LTO.
951eca23bdSJessica Paquette static cl::opt<bool> EnableLinkOnceODROutlining(
966b7615aeSPuyan Lotfi     "enable-linkonceodr-outlining", cl::Hidden,
971eca23bdSJessica Paquette     cl::desc("Enable the machine outliner on linkonceodr functions"),
981eca23bdSJessica Paquette     cl::init(false));
991eca23bdSJessica Paquette 
100*ffd5e121SPuyan Lotfi /// Number of times to re-run the outliner. This is not the total number of runs
101*ffd5e121SPuyan Lotfi /// as the outliner will run at least one time. The default value is set to 0,
102*ffd5e121SPuyan Lotfi /// meaning the outliner will run one time and rerun zero times after that.
103*ffd5e121SPuyan Lotfi static cl::opt<unsigned> OutlinerReruns(
104*ffd5e121SPuyan Lotfi     "machine-outliner-reruns", cl::init(0), cl::Hidden,
105*ffd5e121SPuyan Lotfi     cl::desc(
106*ffd5e121SPuyan Lotfi         "Number of times to rerun the outliner after the initial outline"));
1070d896278SJin Lin 
108596f483aSJessica Paquette namespace {
109596f483aSJessica Paquette 
110596f483aSJessica Paquette /// Represents an undefined index in the suffix tree.
1114cf187b5SJessica Paquette const unsigned EmptyIdx = -1;
112596f483aSJessica Paquette 
113596f483aSJessica Paquette /// A node in a suffix tree which represents a substring or suffix.
114596f483aSJessica Paquette ///
115596f483aSJessica Paquette /// Each node has either no children or at least two children, with the root
116596f483aSJessica Paquette /// being a exception in the empty tree.
117596f483aSJessica Paquette ///
118596f483aSJessica Paquette /// Children are represented as a map between unsigned integers and nodes. If
119596f483aSJessica Paquette /// a node N has a child M on unsigned integer k, then the mapping represented
120596f483aSJessica Paquette /// by N is a proper prefix of the mapping represented by M. Note that this,
121596f483aSJessica Paquette /// although similar to a trie is somewhat different: each node stores a full
122596f483aSJessica Paquette /// substring of the full mapping rather than a single character state.
123596f483aSJessica Paquette ///
124596f483aSJessica Paquette /// Each internal node contains a pointer to the internal node representing
125596f483aSJessica Paquette /// the same string, but with the first character chopped off. This is stored
126596f483aSJessica Paquette /// in \p Link. Each leaf node stores the start index of its respective
127596f483aSJessica Paquette /// suffix in \p SuffixIdx.
128596f483aSJessica Paquette struct SuffixTreeNode {
129596f483aSJessica Paquette 
130596f483aSJessica Paquette   /// The children of this node.
131596f483aSJessica Paquette   ///
132596f483aSJessica Paquette   /// A child existing on an unsigned integer implies that from the mapping
133596f483aSJessica Paquette   /// represented by the current node, there is a way to reach another
134596f483aSJessica Paquette   /// mapping by tacking that character on the end of the current string.
135596f483aSJessica Paquette   DenseMap<unsigned, SuffixTreeNode *> Children;
136596f483aSJessica Paquette 
137596f483aSJessica Paquette   /// The start index of this node's substring in the main string.
1384cf187b5SJessica Paquette   unsigned StartIdx = EmptyIdx;
139596f483aSJessica Paquette 
140596f483aSJessica Paquette   /// The end index of this node's substring in the main string.
141596f483aSJessica Paquette   ///
142596f483aSJessica Paquette   /// Every leaf node must have its \p EndIdx incremented at the end of every
143596f483aSJessica Paquette   /// step in the construction algorithm. To avoid having to update O(N)
144596f483aSJessica Paquette   /// nodes individually at the end of every step, the end index is stored
145596f483aSJessica Paquette   /// as a pointer.
1464cf187b5SJessica Paquette   unsigned *EndIdx = nullptr;
147596f483aSJessica Paquette 
148596f483aSJessica Paquette   /// For leaves, the start index of the suffix represented by this node.
149596f483aSJessica Paquette   ///
150596f483aSJessica Paquette   /// For all other nodes, this is ignored.
1514cf187b5SJessica Paquette   unsigned SuffixIdx = EmptyIdx;
152596f483aSJessica Paquette 
1535f8f34e4SAdrian Prantl   /// For internal nodes, a pointer to the internal node representing
154596f483aSJessica Paquette   /// the same sequence with the first character chopped off.
155596f483aSJessica Paquette   ///
1564602c343SJessica Paquette   /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
157596f483aSJessica Paquette   /// Ukkonen's algorithm does to achieve linear-time construction is
158596f483aSJessica Paquette   /// keep track of which node the next insert should be at. This makes each
159596f483aSJessica Paquette   /// insert O(1), and there are a total of O(N) inserts. The suffix link
160596f483aSJessica Paquette   /// helps with inserting children of internal nodes.
161596f483aSJessica Paquette   ///
162596f483aSJessica Paquette   /// Say we add a child to an internal node with associated mapping S. The
163596f483aSJessica Paquette   /// next insertion must be at the node representing S - its first character.
164596f483aSJessica Paquette   /// This is given by the way that we iteratively build the tree in Ukkonen's
165596f483aSJessica Paquette   /// algorithm. The main idea is to look at the suffixes of each prefix in the
166596f483aSJessica Paquette   /// string, starting with the longest suffix of the prefix, and ending with
167596f483aSJessica Paquette   /// the shortest. Therefore, if we keep pointers between such nodes, we can
168596f483aSJessica Paquette   /// move to the next insertion point in O(1) time. If we don't, then we'd
169596f483aSJessica Paquette   /// have to query from the root, which takes O(N) time. This would make the
170596f483aSJessica Paquette   /// construction algorithm O(N^2) rather than O(N).
171596f483aSJessica Paquette   SuffixTreeNode *Link = nullptr;
172596f483aSJessica Paquette 
173acffa28cSJessica Paquette   /// The length of the string formed by concatenating the edge labels from the
174acffa28cSJessica Paquette   /// root to this node.
1754cf187b5SJessica Paquette   unsigned ConcatLen = 0;
176acffa28cSJessica Paquette 
177596f483aSJessica Paquette   /// Returns true if this node is a leaf.
178596f483aSJessica Paquette   bool isLeaf() const { return SuffixIdx != EmptyIdx; }
179596f483aSJessica Paquette 
180596f483aSJessica Paquette   /// Returns true if this node is the root of its owning \p SuffixTree.
181596f483aSJessica Paquette   bool isRoot() const { return StartIdx == EmptyIdx; }
182596f483aSJessica Paquette 
183596f483aSJessica Paquette   /// Return the number of elements in the substring associated with this node.
184596f483aSJessica Paquette   size_t size() const {
185596f483aSJessica Paquette 
186596f483aSJessica Paquette     // Is it the root? If so, it's the empty string so return 0.
187596f483aSJessica Paquette     if (isRoot())
188596f483aSJessica Paquette       return 0;
189596f483aSJessica Paquette 
190596f483aSJessica Paquette     assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
191596f483aSJessica Paquette 
192596f483aSJessica Paquette     // Size = the number of elements in the string.
193596f483aSJessica Paquette     // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
194596f483aSJessica Paquette     return *EndIdx - StartIdx + 1;
195596f483aSJessica Paquette   }
196596f483aSJessica Paquette 
197df5b09b8SJessica Paquette   SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
198df5b09b8SJessica Paquette       : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
199596f483aSJessica Paquette 
200596f483aSJessica Paquette   SuffixTreeNode() {}
201596f483aSJessica Paquette };
202596f483aSJessica Paquette 
203596f483aSJessica Paquette /// A data structure for fast substring queries.
204596f483aSJessica Paquette ///
205596f483aSJessica Paquette /// Suffix trees represent the suffixes of their input strings in their leaves.
206596f483aSJessica Paquette /// A suffix tree is a type of compressed trie structure where each node
207596f483aSJessica Paquette /// represents an entire substring rather than a single character. Each leaf
208596f483aSJessica Paquette /// of the tree is a suffix.
209596f483aSJessica Paquette ///
210596f483aSJessica Paquette /// A suffix tree can be seen as a type of state machine where each state is a
211596f483aSJessica Paquette /// substring of the full string. The tree is structured so that, for a string
212596f483aSJessica Paquette /// of length N, there are exactly N leaves in the tree. This structure allows
213596f483aSJessica Paquette /// us to quickly find repeated substrings of the input string.
214596f483aSJessica Paquette ///
215596f483aSJessica Paquette /// In this implementation, a "string" is a vector of unsigned integers.
216596f483aSJessica Paquette /// These integers may result from hashing some data type. A suffix tree can
217596f483aSJessica Paquette /// contain 1 or many strings, which can then be queried as one large string.
218596f483aSJessica Paquette ///
219596f483aSJessica Paquette /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
220596f483aSJessica Paquette /// suffix tree construction. Ukkonen's algorithm is explained in more detail
221596f483aSJessica Paquette /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
222596f483aSJessica Paquette /// paper is available at
223596f483aSJessica Paquette ///
224596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
225596f483aSJessica Paquette class SuffixTree {
22678681be2SJessica Paquette public:
227596f483aSJessica Paquette   /// Each element is an integer representing an instruction in the module.
228596f483aSJessica Paquette   ArrayRef<unsigned> Str;
229596f483aSJessica Paquette 
2304e54ef88SJessica Paquette   /// A repeated substring in the tree.
2314e54ef88SJessica Paquette   struct RepeatedSubstring {
2324e54ef88SJessica Paquette     /// The length of the string.
2334e54ef88SJessica Paquette     unsigned Length;
2344e54ef88SJessica Paquette 
2354e54ef88SJessica Paquette     /// The start indices of each occurrence.
2364e54ef88SJessica Paquette     std::vector<unsigned> StartIndices;
2374e54ef88SJessica Paquette   };
2384e54ef88SJessica Paquette 
23978681be2SJessica Paquette private:
240596f483aSJessica Paquette   /// Maintains each node in the tree.
241d4cb9c6dSJessica Paquette   SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
242596f483aSJessica Paquette 
243596f483aSJessica Paquette   /// The root of the suffix tree.
244596f483aSJessica Paquette   ///
245596f483aSJessica Paquette   /// The root represents the empty string. It is maintained by the
246596f483aSJessica Paquette   /// \p NodeAllocator like every other node in the tree.
247596f483aSJessica Paquette   SuffixTreeNode *Root = nullptr;
248596f483aSJessica Paquette 
249596f483aSJessica Paquette   /// Maintains the end indices of the internal nodes in the tree.
250596f483aSJessica Paquette   ///
251596f483aSJessica Paquette   /// Each internal node is guaranteed to never have its end index change
252596f483aSJessica Paquette   /// during the construction algorithm; however, leaves must be updated at
253596f483aSJessica Paquette   /// every step. Therefore, we need to store leaf end indices by reference
254596f483aSJessica Paquette   /// to avoid updating O(N) leaves at every step of construction. Thus,
255596f483aSJessica Paquette   /// every internal node must be allocated its own end index.
256596f483aSJessica Paquette   BumpPtrAllocator InternalEndIdxAllocator;
257596f483aSJessica Paquette 
258596f483aSJessica Paquette   /// The end index of each leaf in the tree.
2594cf187b5SJessica Paquette   unsigned LeafEndIdx = -1;
260596f483aSJessica Paquette 
2615f8f34e4SAdrian Prantl   /// Helper struct which keeps track of the next insertion point in
262596f483aSJessica Paquette   /// Ukkonen's algorithm.
263596f483aSJessica Paquette   struct ActiveState {
264596f483aSJessica Paquette     /// The next node to insert at.
265c7f127d9SSimon Pilgrim     SuffixTreeNode *Node = nullptr;
266596f483aSJessica Paquette 
267596f483aSJessica Paquette     /// The index of the first character in the substring currently being added.
2684cf187b5SJessica Paquette     unsigned Idx = EmptyIdx;
269596f483aSJessica Paquette 
270596f483aSJessica Paquette     /// The length of the substring we have to add at the current step.
2714cf187b5SJessica Paquette     unsigned Len = 0;
272596f483aSJessica Paquette   };
273596f483aSJessica Paquette 
2745f8f34e4SAdrian Prantl   /// The point the next insertion will take place at in the
275596f483aSJessica Paquette   /// construction algorithm.
276596f483aSJessica Paquette   ActiveState Active;
277596f483aSJessica Paquette 
278596f483aSJessica Paquette   /// Allocate a leaf node and add it to the tree.
279596f483aSJessica Paquette   ///
280596f483aSJessica Paquette   /// \param Parent The parent of this node.
281596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
282596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
283596f483aSJessica Paquette   ///
284596f483aSJessica Paquette   /// \returns A pointer to the allocated leaf node.
2854cf187b5SJessica Paquette   SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
286596f483aSJessica Paquette                              unsigned Edge) {
287596f483aSJessica Paquette 
288596f483aSJessica Paquette     assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
289596f483aSJessica Paquette 
29078681be2SJessica Paquette     SuffixTreeNode *N = new (NodeAllocator.Allocate())
291df5b09b8SJessica Paquette         SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
292596f483aSJessica Paquette     Parent.Children[Edge] = N;
293596f483aSJessica Paquette 
294596f483aSJessica Paquette     return N;
295596f483aSJessica Paquette   }
296596f483aSJessica Paquette 
297596f483aSJessica Paquette   /// Allocate an internal node and add it to the tree.
298596f483aSJessica Paquette   ///
299596f483aSJessica Paquette   /// \param Parent The parent of this node. Only null when allocating the root.
300596f483aSJessica Paquette   /// \param StartIdx The start index of this node's associated string.
301596f483aSJessica Paquette   /// \param EndIdx The end index of this node's associated string.
302596f483aSJessica Paquette   /// \param Edge The label on the edge leaving \p Parent to this node.
303596f483aSJessica Paquette   ///
304596f483aSJessica Paquette   /// \returns A pointer to the allocated internal node.
3054cf187b5SJessica Paquette   SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
3064cf187b5SJessica Paquette                                      unsigned EndIdx, unsigned Edge) {
307596f483aSJessica Paquette 
308596f483aSJessica Paquette     assert(StartIdx <= EndIdx && "String can't start after it ends!");
309596f483aSJessica Paquette     assert(!(!Parent && StartIdx != EmptyIdx) &&
310596f483aSJessica Paquette            "Non-root internal nodes must have parents!");
311596f483aSJessica Paquette 
3124cf187b5SJessica Paquette     unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
3136b7615aeSPuyan Lotfi     SuffixTreeNode *N =
3146b7615aeSPuyan Lotfi         new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root);
315596f483aSJessica Paquette     if (Parent)
316596f483aSJessica Paquette       Parent->Children[Edge] = N;
317596f483aSJessica Paquette 
318596f483aSJessica Paquette     return N;
319596f483aSJessica Paquette   }
320596f483aSJessica Paquette 
3215f8f34e4SAdrian Prantl   /// Set the suffix indices of the leaves to the start indices of their
3224e54ef88SJessica Paquette   /// respective suffixes.
323d5750770SJessica Paquette   void setSuffixIndices() {
324d5750770SJessica Paquette     // List of nodes we need to visit along with the current length of the
325d5750770SJessica Paquette     // string.
326d5750770SJessica Paquette     std::vector<std::pair<SuffixTreeNode *, unsigned>> ToVisit;
327596f483aSJessica Paquette 
328d5750770SJessica Paquette     // Current node being visited.
329d5750770SJessica Paquette     SuffixTreeNode *CurrNode = Root;
330596f483aSJessica Paquette 
331d5750770SJessica Paquette     // Sum of the lengths of the nodes down the path to the current one.
332d5750770SJessica Paquette     unsigned CurrNodeLen = 0;
333d5750770SJessica Paquette     ToVisit.push_back({CurrNode, CurrNodeLen});
334d5750770SJessica Paquette     while (!ToVisit.empty()) {
335d5750770SJessica Paquette       std::tie(CurrNode, CurrNodeLen) = ToVisit.back();
336d5750770SJessica Paquette       ToVisit.pop_back();
337d5750770SJessica Paquette       CurrNode->ConcatLen = CurrNodeLen;
338d5750770SJessica Paquette       for (auto &ChildPair : CurrNode->Children) {
339596f483aSJessica Paquette         assert(ChildPair.second && "Node had a null child!");
340d5750770SJessica Paquette         ToVisit.push_back(
341d5750770SJessica Paquette             {ChildPair.second, CurrNodeLen + ChildPair.second->size()});
342596f483aSJessica Paquette       }
343596f483aSJessica Paquette 
344d5750770SJessica Paquette       // No children, so we are at the end of the string.
345d5750770SJessica Paquette       if (CurrNode->Children.size() == 0 && !CurrNode->isRoot())
346d5750770SJessica Paquette         CurrNode->SuffixIdx = Str.size() - CurrNodeLen;
347d5750770SJessica Paquette     }
348596f483aSJessica Paquette   }
349596f483aSJessica Paquette 
3505f8f34e4SAdrian Prantl   /// Construct the suffix tree for the prefix of the input ending at
351596f483aSJessica Paquette   /// \p EndIdx.
352596f483aSJessica Paquette   ///
353596f483aSJessica Paquette   /// Used to construct the full suffix tree iteratively. At the end of each
354596f483aSJessica Paquette   /// step, the constructed suffix tree is either a valid suffix tree, or a
355596f483aSJessica Paquette   /// suffix tree with implicit suffixes. At the end of the final step, the
356596f483aSJessica Paquette   /// suffix tree is a valid tree.
357596f483aSJessica Paquette   ///
358596f483aSJessica Paquette   /// \param EndIdx The end index of the current prefix in the main string.
359596f483aSJessica Paquette   /// \param SuffixesToAdd The number of suffixes that must be added
360596f483aSJessica Paquette   /// to complete the suffix tree at the current phase.
361596f483aSJessica Paquette   ///
362596f483aSJessica Paquette   /// \returns The number of suffixes that have not been added at the end of
363596f483aSJessica Paquette   /// this step.
3644cf187b5SJessica Paquette   unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
365596f483aSJessica Paquette     SuffixTreeNode *NeedsLink = nullptr;
366596f483aSJessica Paquette 
367596f483aSJessica Paquette     while (SuffixesToAdd > 0) {
368596f483aSJessica Paquette 
369596f483aSJessica Paquette       // Are we waiting to add anything other than just the last character?
370596f483aSJessica Paquette       if (Active.Len == 0) {
371596f483aSJessica Paquette         // If not, then say the active index is the end index.
372596f483aSJessica Paquette         Active.Idx = EndIdx;
373596f483aSJessica Paquette       }
374596f483aSJessica Paquette 
375596f483aSJessica Paquette       assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
376596f483aSJessica Paquette 
377596f483aSJessica Paquette       // The first character in the current substring we're looking at.
378596f483aSJessica Paquette       unsigned FirstChar = Str[Active.Idx];
379596f483aSJessica Paquette 
380596f483aSJessica Paquette       // Have we inserted anything starting with FirstChar at the current node?
381596f483aSJessica Paquette       if (Active.Node->Children.count(FirstChar) == 0) {
382596f483aSJessica Paquette         // If not, then we can just insert a leaf and move too the next step.
383596f483aSJessica Paquette         insertLeaf(*Active.Node, EndIdx, FirstChar);
384596f483aSJessica Paquette 
385596f483aSJessica Paquette         // The active node is an internal node, and we visited it, so it must
386596f483aSJessica Paquette         // need a link if it doesn't have one.
387596f483aSJessica Paquette         if (NeedsLink) {
388596f483aSJessica Paquette           NeedsLink->Link = Active.Node;
389596f483aSJessica Paquette           NeedsLink = nullptr;
390596f483aSJessica Paquette         }
391596f483aSJessica Paquette       } else {
392596f483aSJessica Paquette         // There's a match with FirstChar, so look for the point in the tree to
393596f483aSJessica Paquette         // insert a new node.
394596f483aSJessica Paquette         SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
395596f483aSJessica Paquette 
3964cf187b5SJessica Paquette         unsigned SubstringLen = NextNode->size();
397596f483aSJessica Paquette 
398596f483aSJessica Paquette         // Is the current suffix we're trying to insert longer than the size of
399596f483aSJessica Paquette         // the child we want to move to?
400596f483aSJessica Paquette         if (Active.Len >= SubstringLen) {
401596f483aSJessica Paquette           // If yes, then consume the characters we've seen and move to the next
402596f483aSJessica Paquette           // node.
403596f483aSJessica Paquette           Active.Idx += SubstringLen;
404596f483aSJessica Paquette           Active.Len -= SubstringLen;
405596f483aSJessica Paquette           Active.Node = NextNode;
406596f483aSJessica Paquette           continue;
407596f483aSJessica Paquette         }
408596f483aSJessica Paquette 
409596f483aSJessica Paquette         // Otherwise, the suffix we're trying to insert must be contained in the
410596f483aSJessica Paquette         // next node we want to move to.
411596f483aSJessica Paquette         unsigned LastChar = Str[EndIdx];
412596f483aSJessica Paquette 
413596f483aSJessica Paquette         // Is the string we're trying to insert a substring of the next node?
414596f483aSJessica Paquette         if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
415596f483aSJessica Paquette           // If yes, then we're done for this step. Remember our insertion point
416596f483aSJessica Paquette           // and move to the next end index. At this point, we have an implicit
417596f483aSJessica Paquette           // suffix tree.
418596f483aSJessica Paquette           if (NeedsLink && !Active.Node->isRoot()) {
419596f483aSJessica Paquette             NeedsLink->Link = Active.Node;
420596f483aSJessica Paquette             NeedsLink = nullptr;
421596f483aSJessica Paquette           }
422596f483aSJessica Paquette 
423596f483aSJessica Paquette           Active.Len++;
424596f483aSJessica Paquette           break;
425596f483aSJessica Paquette         }
426596f483aSJessica Paquette 
427596f483aSJessica Paquette         // The string we're trying to insert isn't a substring of the next node,
428596f483aSJessica Paquette         // but matches up to a point. Split the node.
429596f483aSJessica Paquette         //
430596f483aSJessica Paquette         // For example, say we ended our search at a node n and we're trying to
431596f483aSJessica Paquette         // insert ABD. Then we'll create a new node s for AB, reduce n to just
432596f483aSJessica Paquette         // representing C, and insert a new leaf node l to represent d. This
433596f483aSJessica Paquette         // allows us to ensure that if n was a leaf, it remains a leaf.
434596f483aSJessica Paquette         //
435596f483aSJessica Paquette         //   | ABC  ---split--->  | AB
436596f483aSJessica Paquette         //   n                    s
437596f483aSJessica Paquette         //                     C / \ D
438596f483aSJessica Paquette         //                      n   l
439596f483aSJessica Paquette 
440596f483aSJessica Paquette         // The node s from the diagram
441596f483aSJessica Paquette         SuffixTreeNode *SplitNode =
44278681be2SJessica Paquette             insertInternalNode(Active.Node, NextNode->StartIdx,
44378681be2SJessica Paquette                                NextNode->StartIdx + Active.Len - 1, FirstChar);
444596f483aSJessica Paquette 
445596f483aSJessica Paquette         // Insert the new node representing the new substring into the tree as
446596f483aSJessica Paquette         // a child of the split node. This is the node l from the diagram.
447596f483aSJessica Paquette         insertLeaf(*SplitNode, EndIdx, LastChar);
448596f483aSJessica Paquette 
449596f483aSJessica Paquette         // Make the old node a child of the split node and update its start
450596f483aSJessica Paquette         // index. This is the node n from the diagram.
451596f483aSJessica Paquette         NextNode->StartIdx += Active.Len;
452596f483aSJessica Paquette         SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
453596f483aSJessica Paquette 
454596f483aSJessica Paquette         // SplitNode is an internal node, update the suffix link.
455596f483aSJessica Paquette         if (NeedsLink)
456596f483aSJessica Paquette           NeedsLink->Link = SplitNode;
457596f483aSJessica Paquette 
458596f483aSJessica Paquette         NeedsLink = SplitNode;
459596f483aSJessica Paquette       }
460596f483aSJessica Paquette 
461596f483aSJessica Paquette       // We've added something new to the tree, so there's one less suffix to
462596f483aSJessica Paquette       // add.
463596f483aSJessica Paquette       SuffixesToAdd--;
464596f483aSJessica Paquette 
465596f483aSJessica Paquette       if (Active.Node->isRoot()) {
466596f483aSJessica Paquette         if (Active.Len > 0) {
467596f483aSJessica Paquette           Active.Len--;
468596f483aSJessica Paquette           Active.Idx = EndIdx - SuffixesToAdd + 1;
469596f483aSJessica Paquette         }
470596f483aSJessica Paquette       } else {
471596f483aSJessica Paquette         // Start the next phase at the next smallest suffix.
472596f483aSJessica Paquette         Active.Node = Active.Node->Link;
473596f483aSJessica Paquette       }
474596f483aSJessica Paquette     }
475596f483aSJessica Paquette 
476596f483aSJessica Paquette     return SuffixesToAdd;
477596f483aSJessica Paquette   }
478596f483aSJessica Paquette 
479596f483aSJessica Paquette public:
480596f483aSJessica Paquette   /// Construct a suffix tree from a sequence of unsigned integers.
481596f483aSJessica Paquette   ///
482596f483aSJessica Paquette   /// \param Str The string to construct the suffix tree for.
483596f483aSJessica Paquette   SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
484596f483aSJessica Paquette     Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
485596f483aSJessica Paquette     Active.Node = Root;
486596f483aSJessica Paquette 
487596f483aSJessica Paquette     // Keep track of the number of suffixes we have to add of the current
488596f483aSJessica Paquette     // prefix.
4894cf187b5SJessica Paquette     unsigned SuffixesToAdd = 0;
490596f483aSJessica Paquette 
491596f483aSJessica Paquette     // Construct the suffix tree iteratively on each prefix of the string.
492596f483aSJessica Paquette     // PfxEndIdx is the end index of the current prefix.
493596f483aSJessica Paquette     // End is one past the last element in the string.
4944cf187b5SJessica Paquette     for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
4954cf187b5SJessica Paquette          PfxEndIdx++) {
496596f483aSJessica Paquette       SuffixesToAdd++;
497596f483aSJessica Paquette       LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
498596f483aSJessica Paquette       SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
499596f483aSJessica Paquette     }
500596f483aSJessica Paquette 
501596f483aSJessica Paquette     // Set the suffix indices of each leaf.
502596f483aSJessica Paquette     assert(Root && "Root node can't be nullptr!");
503d5750770SJessica Paquette     setSuffixIndices();
504596f483aSJessica Paquette   }
5054e54ef88SJessica Paquette 
506a409cc95SJessica Paquette   /// Iterator for finding all repeated substrings in the suffix tree.
507a409cc95SJessica Paquette   struct RepeatedSubstringIterator {
508a409cc95SJessica Paquette   private:
509a409cc95SJessica Paquette     /// The current node we're visiting.
510a409cc95SJessica Paquette     SuffixTreeNode *N = nullptr;
511a409cc95SJessica Paquette 
512a409cc95SJessica Paquette     /// The repeated substring associated with this node.
513a409cc95SJessica Paquette     RepeatedSubstring RS;
514a409cc95SJessica Paquette 
515a409cc95SJessica Paquette     /// The nodes left to visit.
516a409cc95SJessica Paquette     std::vector<SuffixTreeNode *> ToVisit;
517a409cc95SJessica Paquette 
518a409cc95SJessica Paquette     /// The minimum length of a repeated substring to find.
519a409cc95SJessica Paquette     /// Since we're outlining, we want at least two instructions in the range.
520a409cc95SJessica Paquette     /// FIXME: This may not be true for targets like X86 which support many
521a409cc95SJessica Paquette     /// instruction lengths.
522a409cc95SJessica Paquette     const unsigned MinLength = 2;
523a409cc95SJessica Paquette 
524a409cc95SJessica Paquette     /// Move the iterator to the next repeated substring.
525a409cc95SJessica Paquette     void advance() {
526a409cc95SJessica Paquette       // Clear the current state. If we're at the end of the range, then this
527a409cc95SJessica Paquette       // is the state we want to be in.
528a409cc95SJessica Paquette       RS = RepeatedSubstring();
529a409cc95SJessica Paquette       N = nullptr;
530a409cc95SJessica Paquette 
5313cd70b38SJessica Paquette       // Each leaf node represents a repeat of a string.
5323cd70b38SJessica Paquette       std::vector<SuffixTreeNode *> LeafChildren;
5333cd70b38SJessica Paquette 
534a409cc95SJessica Paquette       // Continue visiting nodes until we find one which repeats more than once.
535a409cc95SJessica Paquette       while (!ToVisit.empty()) {
536a409cc95SJessica Paquette         SuffixTreeNode *Curr = ToVisit.back();
537a409cc95SJessica Paquette         ToVisit.pop_back();
5383cd70b38SJessica Paquette         LeafChildren.clear();
539a409cc95SJessica Paquette 
540a409cc95SJessica Paquette         // Keep track of the length of the string associated with the node. If
541a409cc95SJessica Paquette         // it's too short, we'll quit.
542a409cc95SJessica Paquette         unsigned Length = Curr->ConcatLen;
543a409cc95SJessica Paquette 
544a409cc95SJessica Paquette         // Iterate over each child, saving internal nodes for visiting, and
545a409cc95SJessica Paquette         // leaf nodes in LeafChildren. Internal nodes represent individual
546a409cc95SJessica Paquette         // strings, which may repeat.
547a409cc95SJessica Paquette         for (auto &ChildPair : Curr->Children) {
548a409cc95SJessica Paquette           // Save all of this node's children for processing.
549a409cc95SJessica Paquette           if (!ChildPair.second->isLeaf())
550a409cc95SJessica Paquette             ToVisit.push_back(ChildPair.second);
551a409cc95SJessica Paquette 
552a409cc95SJessica Paquette           // It's not an internal node, so it must be a leaf. If we have a
553a409cc95SJessica Paquette           // long enough string, then save the leaf children.
554a409cc95SJessica Paquette           else if (Length >= MinLength)
555a409cc95SJessica Paquette             LeafChildren.push_back(ChildPair.second);
5564e54ef88SJessica Paquette         }
557a409cc95SJessica Paquette 
558a409cc95SJessica Paquette         // The root never represents a repeated substring. If we're looking at
559a409cc95SJessica Paquette         // that, then skip it.
560a409cc95SJessica Paquette         if (Curr->isRoot())
561a409cc95SJessica Paquette           continue;
562a409cc95SJessica Paquette 
563a409cc95SJessica Paquette         // Do we have any repeated substrings?
564a409cc95SJessica Paquette         if (LeafChildren.size() >= 2) {
565a409cc95SJessica Paquette           // Yes. Update the state to reflect this, and then bail out.
566a409cc95SJessica Paquette           N = Curr;
567a409cc95SJessica Paquette           RS.Length = Length;
568a409cc95SJessica Paquette           for (SuffixTreeNode *Leaf : LeafChildren)
569a409cc95SJessica Paquette             RS.StartIndices.push_back(Leaf->SuffixIdx);
570a409cc95SJessica Paquette           break;
571a409cc95SJessica Paquette         }
572a409cc95SJessica Paquette       }
573a409cc95SJessica Paquette 
574a409cc95SJessica Paquette       // At this point, either NewRS is an empty RepeatedSubstring, or it was
575a409cc95SJessica Paquette       // set in the above loop. Similarly, N is either nullptr, or the node
576a409cc95SJessica Paquette       // associated with NewRS.
577a409cc95SJessica Paquette     }
578a409cc95SJessica Paquette 
579a409cc95SJessica Paquette   public:
580a409cc95SJessica Paquette     /// Return the current repeated substring.
581a409cc95SJessica Paquette     RepeatedSubstring &operator*() { return RS; }
582a409cc95SJessica Paquette 
583a409cc95SJessica Paquette     RepeatedSubstringIterator &operator++() {
584a409cc95SJessica Paquette       advance();
585a409cc95SJessica Paquette       return *this;
586a409cc95SJessica Paquette     }
587a409cc95SJessica Paquette 
588a409cc95SJessica Paquette     RepeatedSubstringIterator operator++(int I) {
589a409cc95SJessica Paquette       RepeatedSubstringIterator It(*this);
590a409cc95SJessica Paquette       advance();
591a409cc95SJessica Paquette       return It;
592a409cc95SJessica Paquette     }
593a409cc95SJessica Paquette 
594a409cc95SJessica Paquette     bool operator==(const RepeatedSubstringIterator &Other) {
595a409cc95SJessica Paquette       return N == Other.N;
596a409cc95SJessica Paquette     }
597a409cc95SJessica Paquette     bool operator!=(const RepeatedSubstringIterator &Other) {
598a409cc95SJessica Paquette       return !(*this == Other);
599a409cc95SJessica Paquette     }
600a409cc95SJessica Paquette 
601a409cc95SJessica Paquette     RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
602a409cc95SJessica Paquette       // Do we have a non-null node?
603a409cc95SJessica Paquette       if (N) {
604a409cc95SJessica Paquette         // Yes. At the first step, we need to visit all of N's children.
605a409cc95SJessica Paquette         // Note: This means that we visit N last.
606a409cc95SJessica Paquette         ToVisit.push_back(N);
607a409cc95SJessica Paquette         advance();
608a409cc95SJessica Paquette       }
609a409cc95SJessica Paquette     }
610a409cc95SJessica Paquette   };
611a409cc95SJessica Paquette 
612a409cc95SJessica Paquette   typedef RepeatedSubstringIterator iterator;
613a409cc95SJessica Paquette   iterator begin() { return iterator(Root); }
614a409cc95SJessica Paquette   iterator end() { return iterator(nullptr); }
615596f483aSJessica Paquette };
616596f483aSJessica Paquette 
6175f8f34e4SAdrian Prantl /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
618596f483aSJessica Paquette struct InstructionMapper {
619596f483aSJessica Paquette 
6205f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that
621596f483aSJessica Paquette   /// cannot be outlined.
622596f483aSJessica Paquette   ///
623596f483aSJessica Paquette   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
624596f483aSJessica Paquette   unsigned IllegalInstrNumber = -3;
625596f483aSJessica Paquette 
6265f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that can
627596f483aSJessica Paquette   /// be outlined.
628596f483aSJessica Paquette   unsigned LegalInstrNumber = 0;
629596f483aSJessica Paquette 
630596f483aSJessica Paquette   /// Correspondence from \p MachineInstrs to unsigned integers.
631596f483aSJessica Paquette   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
632596f483aSJessica Paquette       InstructionIntegerMap;
633596f483aSJessica Paquette 
634cad864d4SJessica Paquette   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
635cad864d4SJessica Paquette   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
636cad864d4SJessica Paquette 
637596f483aSJessica Paquette   /// The vector of unsigned integers that the module is mapped to.
638596f483aSJessica Paquette   std::vector<unsigned> UnsignedVec;
639596f483aSJessica Paquette 
6405f8f34e4SAdrian Prantl   /// Stores the location of the instruction associated with the integer
641596f483aSJessica Paquette   /// at index i in \p UnsignedVec for each index i.
642596f483aSJessica Paquette   std::vector<MachineBasicBlock::iterator> InstrList;
643596f483aSJessica Paquette 
644c991cf36SJessica Paquette   // Set if we added an illegal number in the previous step.
645c991cf36SJessica Paquette   // Since each illegal number is unique, we only need one of them between
646c991cf36SJessica Paquette   // each range of legal numbers. This lets us make sure we don't add more
647c991cf36SJessica Paquette   // than one illegal number per range.
648c991cf36SJessica Paquette   bool AddedIllegalLastTime = false;
649c991cf36SJessica Paquette 
6505f8f34e4SAdrian Prantl   /// Maps \p *It to a legal integer.
651596f483aSJessica Paquette   ///
652c4cf775aSJessica Paquette   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
653ca3ed964SJessica Paquette   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
654596f483aSJessica Paquette   ///
655596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
656267d266cSJessica Paquette   unsigned mapToLegalUnsigned(
657c4cf775aSJessica Paquette       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
658c4cf775aSJessica Paquette       bool &HaveLegalRange, unsigned &NumLegalInBlock,
659267d266cSJessica Paquette       std::vector<unsigned> &UnsignedVecForMBB,
660267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
661c991cf36SJessica Paquette     // We added something legal, so we should unset the AddedLegalLastTime
662c991cf36SJessica Paquette     // flag.
663c991cf36SJessica Paquette     AddedIllegalLastTime = false;
664596f483aSJessica Paquette 
665c4cf775aSJessica Paquette     // If we have at least two adjacent legal instructions (which may have
666c4cf775aSJessica Paquette     // invisible instructions in between), remember that.
667c4cf775aSJessica Paquette     if (CanOutlineWithPrevInstr)
668c4cf775aSJessica Paquette       HaveLegalRange = true;
669c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = true;
670c4cf775aSJessica Paquette 
671267d266cSJessica Paquette     // Keep track of the number of legal instructions we insert.
672267d266cSJessica Paquette     NumLegalInBlock++;
673267d266cSJessica Paquette 
674596f483aSJessica Paquette     // Get the integer for this instruction or give it the current
675596f483aSJessica Paquette     // LegalInstrNumber.
676267d266cSJessica Paquette     InstrListForMBB.push_back(It);
677596f483aSJessica Paquette     MachineInstr &MI = *It;
678596f483aSJessica Paquette     bool WasInserted;
679596f483aSJessica Paquette     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
680596f483aSJessica Paquette         ResultIt;
681596f483aSJessica Paquette     std::tie(ResultIt, WasInserted) =
682596f483aSJessica Paquette         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
683596f483aSJessica Paquette     unsigned MINumber = ResultIt->second;
684596f483aSJessica Paquette 
685596f483aSJessica Paquette     // There was an insertion.
686ca3ed964SJessica Paquette     if (WasInserted)
687596f483aSJessica Paquette       LegalInstrNumber++;
688596f483aSJessica Paquette 
689267d266cSJessica Paquette     UnsignedVecForMBB.push_back(MINumber);
690596f483aSJessica Paquette 
691596f483aSJessica Paquette     // Make sure we don't overflow or use any integers reserved by the DenseMap.
692596f483aSJessica Paquette     if (LegalInstrNumber >= IllegalInstrNumber)
693596f483aSJessica Paquette       report_fatal_error("Instruction mapping overflow!");
694596f483aSJessica Paquette 
69578681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
69678681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
69778681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
69878681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
699596f483aSJessica Paquette 
700596f483aSJessica Paquette     return MINumber;
701596f483aSJessica Paquette   }
702596f483aSJessica Paquette 
703596f483aSJessica Paquette   /// Maps \p *It to an illegal integer.
704596f483aSJessica Paquette   ///
705267d266cSJessica Paquette   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
706267d266cSJessica Paquette   /// IllegalInstrNumber.
707596f483aSJessica Paquette   ///
708596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
7096b7615aeSPuyan Lotfi   unsigned mapToIllegalUnsigned(
7106b7615aeSPuyan Lotfi       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
7116b7615aeSPuyan Lotfi       std::vector<unsigned> &UnsignedVecForMBB,
712267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
713c4cf775aSJessica Paquette     // Can't outline an illegal instruction. Set the flag.
714c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = false;
715c4cf775aSJessica Paquette 
716c991cf36SJessica Paquette     // Only add one illegal number per range of legal numbers.
717c991cf36SJessica Paquette     if (AddedIllegalLastTime)
718c991cf36SJessica Paquette       return IllegalInstrNumber;
719c991cf36SJessica Paquette 
720c991cf36SJessica Paquette     // Remember that we added an illegal number last time.
721c991cf36SJessica Paquette     AddedIllegalLastTime = true;
722596f483aSJessica Paquette     unsigned MINumber = IllegalInstrNumber;
723596f483aSJessica Paquette 
724267d266cSJessica Paquette     InstrListForMBB.push_back(It);
725267d266cSJessica Paquette     UnsignedVecForMBB.push_back(IllegalInstrNumber);
726596f483aSJessica Paquette     IllegalInstrNumber--;
727596f483aSJessica Paquette 
728596f483aSJessica Paquette     assert(LegalInstrNumber < IllegalInstrNumber &&
729596f483aSJessica Paquette            "Instruction mapping overflow!");
730596f483aSJessica Paquette 
73178681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
732596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
733596f483aSJessica Paquette 
73478681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
735596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
736596f483aSJessica Paquette 
737596f483aSJessica Paquette     return MINumber;
738596f483aSJessica Paquette   }
739596f483aSJessica Paquette 
7405f8f34e4SAdrian Prantl   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
741596f483aSJessica Paquette   /// and appends it to \p UnsignedVec and \p InstrList.
742596f483aSJessica Paquette   ///
743596f483aSJessica Paquette   /// Two instructions are assigned the same integer if they are identical.
744596f483aSJessica Paquette   /// If an instruction is deemed unsafe to outline, then it will be assigned an
745596f483aSJessica Paquette   /// unique integer. The resulting mapping is placed into a suffix tree and
746596f483aSJessica Paquette   /// queried for candidates.
747596f483aSJessica Paquette   ///
748596f483aSJessica Paquette   /// \param MBB The \p MachineBasicBlock to be translated into integers.
749da08078fSEli Friedman   /// \param TII \p TargetInstrInfo for the function.
750596f483aSJessica Paquette   void convertToUnsignedVec(MachineBasicBlock &MBB,
751596f483aSJessica Paquette                             const TargetInstrInfo &TII) {
7523635c890SAlexander Kornienko     unsigned Flags = 0;
75382d9c0a3SJessica Paquette 
75482d9c0a3SJessica Paquette     // Don't even map in this case.
75582d9c0a3SJessica Paquette     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
75682d9c0a3SJessica Paquette       return;
75782d9c0a3SJessica Paquette 
758cad864d4SJessica Paquette     // Store info for the MBB for later outlining.
759cad864d4SJessica Paquette     MBBFlagsMap[&MBB] = Flags;
760cad864d4SJessica Paquette 
761c991cf36SJessica Paquette     MachineBasicBlock::iterator It = MBB.begin();
762267d266cSJessica Paquette 
763267d266cSJessica Paquette     // The number of instructions in this block that will be considered for
764267d266cSJessica Paquette     // outlining.
765267d266cSJessica Paquette     unsigned NumLegalInBlock = 0;
766267d266cSJessica Paquette 
767c4cf775aSJessica Paquette     // True if we have at least two legal instructions which aren't separated
768c4cf775aSJessica Paquette     // by an illegal instruction.
769c4cf775aSJessica Paquette     bool HaveLegalRange = false;
770c4cf775aSJessica Paquette 
771c4cf775aSJessica Paquette     // True if we can perform outlining given the last mapped (non-invisible)
772c4cf775aSJessica Paquette     // instruction. This lets us know if we have a legal range.
773c4cf775aSJessica Paquette     bool CanOutlineWithPrevInstr = false;
774c4cf775aSJessica Paquette 
775267d266cSJessica Paquette     // FIXME: Should this all just be handled in the target, rather than using
776267d266cSJessica Paquette     // repeated calls to getOutliningType?
777267d266cSJessica Paquette     std::vector<unsigned> UnsignedVecForMBB;
778267d266cSJessica Paquette     std::vector<MachineBasicBlock::iterator> InstrListForMBB;
779267d266cSJessica Paquette 
78076166a1aSSimon Pilgrim     for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
781596f483aSJessica Paquette       // Keep track of where this instruction is in the module.
7823291e735SJessica Paquette       switch (TII.getOutliningType(It, Flags)) {
783aa087327SJessica Paquette       case InstrType::Illegal:
7846b7615aeSPuyan Lotfi         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
7856b7615aeSPuyan Lotfi                              InstrListForMBB);
786596f483aSJessica Paquette         break;
787596f483aSJessica Paquette 
788aa087327SJessica Paquette       case InstrType::Legal:
789c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
790c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
791596f483aSJessica Paquette         break;
792596f483aSJessica Paquette 
793aa087327SJessica Paquette       case InstrType::LegalTerminator:
794c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
795c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
796c991cf36SJessica Paquette         // The instruction also acts as a terminator, so we have to record that
797c991cf36SJessica Paquette         // in the string.
798c4cf775aSJessica Paquette         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
799c4cf775aSJessica Paquette                              InstrListForMBB);
800042dc9e0SEli Friedman         break;
801042dc9e0SEli Friedman 
802aa087327SJessica Paquette       case InstrType::Invisible:
803c991cf36SJessica Paquette         // Normally this is set by mapTo(Blah)Unsigned, but we just want to
804c991cf36SJessica Paquette         // skip this instruction. So, unset the flag here.
805bd72988cSJessica Paquette         AddedIllegalLastTime = false;
806596f483aSJessica Paquette         break;
807596f483aSJessica Paquette       }
808596f483aSJessica Paquette     }
809596f483aSJessica Paquette 
810267d266cSJessica Paquette     // Are there enough legal instructions in the block for outlining to be
811267d266cSJessica Paquette     // possible?
812c4cf775aSJessica Paquette     if (HaveLegalRange) {
813596f483aSJessica Paquette       // After we're done every insertion, uniquely terminate this part of the
814596f483aSJessica Paquette       // "string". This makes sure we won't match across basic block or function
815596f483aSJessica Paquette       // boundaries since the "end" is encoded uniquely and thus appears in no
816596f483aSJessica Paquette       // repeated substring.
817c4cf775aSJessica Paquette       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
818c4cf775aSJessica Paquette                            InstrListForMBB);
819267d266cSJessica Paquette       InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
820267d266cSJessica Paquette                        InstrListForMBB.end());
821267d266cSJessica Paquette       UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
822267d266cSJessica Paquette                          UnsignedVecForMBB.end());
823267d266cSJessica Paquette     }
824596f483aSJessica Paquette   }
825596f483aSJessica Paquette 
826596f483aSJessica Paquette   InstructionMapper() {
827596f483aSJessica Paquette     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
828596f483aSJessica Paquette     // changed.
829596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
830596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s empty key isn't -1!");
831596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
832596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
833596f483aSJessica Paquette   }
834596f483aSJessica Paquette };
835596f483aSJessica Paquette 
8365f8f34e4SAdrian Prantl /// An interprocedural pass which finds repeated sequences of
837596f483aSJessica Paquette /// instructions and replaces them with calls to functions.
838596f483aSJessica Paquette ///
839596f483aSJessica Paquette /// Each instruction is mapped to an unsigned integer and placed in a string.
840596f483aSJessica Paquette /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
841596f483aSJessica Paquette /// is then repeatedly queried for repeated sequences of instructions. Each
842596f483aSJessica Paquette /// non-overlapping repeated sequence is then placed in its own
843596f483aSJessica Paquette /// \p MachineFunction and each instance is then replaced with a call to that
844596f483aSJessica Paquette /// function.
845596f483aSJessica Paquette struct MachineOutliner : public ModulePass {
846596f483aSJessica Paquette 
847596f483aSJessica Paquette   static char ID;
848596f483aSJessica Paquette 
8495f8f34e4SAdrian Prantl   /// Set to true if the outliner should consider functions with
85013593843SJessica Paquette   /// linkonceodr linkage.
85113593843SJessica Paquette   bool OutlineFromLinkOnceODRs = false;
85213593843SJessica Paquette 
8530d896278SJin Lin   /// The current repeat number of machine outlining.
8540d896278SJin Lin   unsigned OutlineRepeatedNum = 0;
8550d896278SJin Lin 
8568bda1881SJessica Paquette   /// Set to true if the outliner should run on all functions in the module
8578bda1881SJessica Paquette   /// considered safe for outlining.
8588bda1881SJessica Paquette   /// Set to true by default for compatibility with llc's -run-pass option.
8598bda1881SJessica Paquette   /// Set when the pass is constructed in TargetPassConfig.
8608bda1881SJessica Paquette   bool RunOnAllFunctions = true;
8618bda1881SJessica Paquette 
862596f483aSJessica Paquette   StringRef getPassName() const override { return "Machine Outliner"; }
863596f483aSJessica Paquette 
864596f483aSJessica Paquette   void getAnalysisUsage(AnalysisUsage &AU) const override {
865cc382cf7SYuanfang Chen     AU.addRequired<MachineModuleInfoWrapperPass>();
866cc382cf7SYuanfang Chen     AU.addPreserved<MachineModuleInfoWrapperPass>();
867596f483aSJessica Paquette     AU.setPreservesAll();
868596f483aSJessica Paquette     ModulePass::getAnalysisUsage(AU);
869596f483aSJessica Paquette   }
870596f483aSJessica Paquette 
8711eca23bdSJessica Paquette   MachineOutliner() : ModulePass(ID) {
872596f483aSJessica Paquette     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
873596f483aSJessica Paquette   }
874596f483aSJessica Paquette 
8751cc52a00SJessica Paquette   /// Remark output explaining that not outlining a set of candidates would be
8761cc52a00SJessica Paquette   /// better than outlining that set.
8771cc52a00SJessica Paquette   void emitNotOutliningCheaperRemark(
8781cc52a00SJessica Paquette       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
8791cc52a00SJessica Paquette       OutlinedFunction &OF);
8801cc52a00SJessica Paquette 
88158e706a6SJessica Paquette   /// Remark output explaining that a function was outlined.
88258e706a6SJessica Paquette   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
88358e706a6SJessica Paquette 
884ce3a2dcfSJessica Paquette   /// Find all repeated substrings that satisfy the outlining cost model by
885ce3a2dcfSJessica Paquette   /// constructing a suffix tree.
88678681be2SJessica Paquette   ///
88778681be2SJessica Paquette   /// If a substring appears at least twice, then it must be represented by
8881cc52a00SJessica Paquette   /// an internal node which appears in at least two suffixes. Each suffix
8891cc52a00SJessica Paquette   /// is represented by a leaf node. To do this, we visit each internal node
8901cc52a00SJessica Paquette   /// in the tree, using the leaf children of each internal node. If an
8911cc52a00SJessica Paquette   /// internal node represents a beneficial substring, then we use each of
8921cc52a00SJessica Paquette   /// its leaf children to find the locations of its substring.
89378681be2SJessica Paquette   ///
89478681be2SJessica Paquette   /// \param Mapper Contains outlining mapping information.
8951cc52a00SJessica Paquette   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
8961cc52a00SJessica Paquette   /// each type of candidate.
897ce3a2dcfSJessica Paquette   void findCandidates(InstructionMapper &Mapper,
89878681be2SJessica Paquette                       std::vector<OutlinedFunction> &FunctionList);
89978681be2SJessica Paquette 
9004ae3b71dSJessica Paquette   /// Replace the sequences of instructions represented by \p OutlinedFunctions
9014ae3b71dSJessica Paquette   /// with calls to functions.
902596f483aSJessica Paquette   ///
903596f483aSJessica Paquette   /// \param M The module we are outlining from.
904596f483aSJessica Paquette   /// \param FunctionList A list of functions to be inserted into the module.
905596f483aSJessica Paquette   /// \param Mapper Contains the instruction mappings for the module.
9064ae3b71dSJessica Paquette   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
9076b7615aeSPuyan Lotfi                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
908596f483aSJessica Paquette 
909596f483aSJessica Paquette   /// Creates a function for \p OF and inserts it into the module.
910e18d6ff0SJessica Paquette   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
911a3eb0facSJessica Paquette                                           InstructionMapper &Mapper,
912a3eb0facSJessica Paquette                                           unsigned Name);
913596f483aSJessica Paquette 
914*ffd5e121SPuyan Lotfi   /// Calls 'doOutline()' 1 + OutlinerReruns times.
9157b166d51SJin Lin   bool runOnModule(Module &M) override;
916ab2dcff3SJin Lin 
917596f483aSJessica Paquette   /// Construct a suffix tree on the instructions in \p M and outline repeated
918596f483aSJessica Paquette   /// strings from that tree.
919a51fc8ddSPuyan Lotfi   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
920aa087327SJessica Paquette 
921aa087327SJessica Paquette   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
922aa087327SJessica Paquette   /// function for remark emission.
923aa087327SJessica Paquette   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
924e18d6ff0SJessica Paquette     for (const Candidate &C : OF.Candidates)
9257ad25836SSimon Pilgrim       if (MachineFunction *MF = C.getMF())
9267ad25836SSimon Pilgrim         if (DISubprogram *SP = MF->getFunction().getSubprogram())
927aa087327SJessica Paquette           return SP;
928aa087327SJessica Paquette     return nullptr;
929aa087327SJessica Paquette   }
930050d1ac4SJessica Paquette 
931050d1ac4SJessica Paquette   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
932050d1ac4SJessica Paquette   /// These are used to construct a suffix tree.
933050d1ac4SJessica Paquette   void populateMapper(InstructionMapper &Mapper, Module &M,
934050d1ac4SJessica Paquette                       MachineModuleInfo &MMI);
935596f483aSJessica Paquette 
9362386eab3SJessica Paquette   /// Initialize information necessary to output a size remark.
9372386eab3SJessica Paquette   /// FIXME: This should be handled by the pass manager, not the outliner.
9382386eab3SJessica Paquette   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
9392386eab3SJessica Paquette   /// pass manager.
9406b7615aeSPuyan Lotfi   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
9412386eab3SJessica Paquette                           StringMap<unsigned> &FunctionToInstrCount);
9422386eab3SJessica Paquette 
9432386eab3SJessica Paquette   /// Emit the remark.
9442386eab3SJessica Paquette   // FIXME: This should be handled by the pass manager, not the outliner.
9456b7615aeSPuyan Lotfi   void
9466b7615aeSPuyan Lotfi   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
9472386eab3SJessica Paquette                               const StringMap<unsigned> &FunctionToInstrCount);
9482386eab3SJessica Paquette };
949596f483aSJessica Paquette } // Anonymous namespace.
950596f483aSJessica Paquette 
951596f483aSJessica Paquette char MachineOutliner::ID = 0;
952596f483aSJessica Paquette 
953596f483aSJessica Paquette namespace llvm {
9548bda1881SJessica Paquette ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
9558bda1881SJessica Paquette   MachineOutliner *OL = new MachineOutliner();
9568bda1881SJessica Paquette   OL->RunOnAllFunctions = RunOnAllFunctions;
9578bda1881SJessica Paquette   return OL;
95813593843SJessica Paquette }
95913593843SJessica Paquette 
96078681be2SJessica Paquette } // namespace llvm
96178681be2SJessica Paquette 
96278681be2SJessica Paquette INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
96378681be2SJessica Paquette                 false)
96478681be2SJessica Paquette 
9651cc52a00SJessica Paquette void MachineOutliner::emitNotOutliningCheaperRemark(
9661cc52a00SJessica Paquette     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
9671cc52a00SJessica Paquette     OutlinedFunction &OF) {
968c991cf36SJessica Paquette   // FIXME: Right now, we arbitrarily choose some Candidate from the
969c991cf36SJessica Paquette   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
970c991cf36SJessica Paquette   // We should probably sort these by function name or something to make sure
971c991cf36SJessica Paquette   // the remarks are stable.
9721cc52a00SJessica Paquette   Candidate &C = CandidatesForRepeatedSeq.front();
9731cc52a00SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
9741cc52a00SJessica Paquette   MORE.emit([&]() {
9751cc52a00SJessica Paquette     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
9761cc52a00SJessica Paquette                                       C.front()->getDebugLoc(), C.getMBB());
9771cc52a00SJessica Paquette     R << "Did not outline " << NV("Length", StringLen) << " instructions"
9781cc52a00SJessica Paquette       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
9791cc52a00SJessica Paquette       << " locations."
9801cc52a00SJessica Paquette       << " Bytes from outlining all occurrences ("
9811cc52a00SJessica Paquette       << NV("OutliningCost", OF.getOutliningCost()) << ")"
9821cc52a00SJessica Paquette       << " >= Unoutlined instruction bytes ("
9831cc52a00SJessica Paquette       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
9841cc52a00SJessica Paquette       << " (Also found at: ";
9851cc52a00SJessica Paquette 
9861cc52a00SJessica Paquette     // Tell the user the other places the candidate was found.
9871cc52a00SJessica Paquette     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
9881cc52a00SJessica Paquette       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
9891cc52a00SJessica Paquette               CandidatesForRepeatedSeq[i].front()->getDebugLoc());
9901cc52a00SJessica Paquette       if (i != e - 1)
9911cc52a00SJessica Paquette         R << ", ";
9921cc52a00SJessica Paquette     }
9931cc52a00SJessica Paquette 
9941cc52a00SJessica Paquette     R << ")";
9951cc52a00SJessica Paquette     return R;
9961cc52a00SJessica Paquette   });
9971cc52a00SJessica Paquette }
9981cc52a00SJessica Paquette 
99958e706a6SJessica Paquette void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
100058e706a6SJessica Paquette   MachineBasicBlock *MBB = &*OF.MF->begin();
100158e706a6SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
100258e706a6SJessica Paquette   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
100358e706a6SJessica Paquette                               MBB->findDebugLoc(MBB->begin()), MBB);
100458e706a6SJessica Paquette   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
100534b618bfSJessica Paquette     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
100658e706a6SJessica Paquette     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
100758e706a6SJessica Paquette     << " locations. "
100858e706a6SJessica Paquette     << "(Found at: ";
100958e706a6SJessica Paquette 
101058e706a6SJessica Paquette   // Tell the user the other places the candidate was found.
101158e706a6SJessica Paquette   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
101258e706a6SJessica Paquette 
101358e706a6SJessica Paquette     R << NV((Twine("StartLoc") + Twine(i)).str(),
1014e18d6ff0SJessica Paquette             OF.Candidates[i].front()->getDebugLoc());
101558e706a6SJessica Paquette     if (i != e - 1)
101658e706a6SJessica Paquette       R << ", ";
101758e706a6SJessica Paquette   }
101858e706a6SJessica Paquette 
101958e706a6SJessica Paquette   R << ")";
102058e706a6SJessica Paquette 
102158e706a6SJessica Paquette   MORE.emit(R);
102258e706a6SJessica Paquette }
102358e706a6SJessica Paquette 
10246b7615aeSPuyan Lotfi void MachineOutliner::findCandidates(
10256b7615aeSPuyan Lotfi     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
102678681be2SJessica Paquette   FunctionList.clear();
1027ce3a2dcfSJessica Paquette   SuffixTree ST(Mapper.UnsignedVec);
102878681be2SJessica Paquette 
1029fbe7f5e9SDavid Tellenbach   // First, find all of the repeated substrings in the tree of minimum length
10304e54ef88SJessica Paquette   // 2.
1031d87f5449SJessica Paquette   std::vector<Candidate> CandidatesForRepeatedSeq;
1032d4e7d074SJessica Paquette   for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
1033d4e7d074SJessica Paquette     CandidatesForRepeatedSeq.clear();
1034d4e7d074SJessica Paquette     SuffixTree::RepeatedSubstring RS = *It;
10354e54ef88SJessica Paquette     unsigned StringLen = RS.Length;
10364e54ef88SJessica Paquette     for (const unsigned &StartIdx : RS.StartIndices) {
103752df8015SJessica Paquette       unsigned EndIdx = StartIdx + StringLen - 1;
103852df8015SJessica Paquette       // Trick: Discard some candidates that would be incompatible with the
103952df8015SJessica Paquette       // ones we've already found for this sequence. This will save us some
104052df8015SJessica Paquette       // work in candidate selection.
104152df8015SJessica Paquette       //
104252df8015SJessica Paquette       // If two candidates overlap, then we can't outline them both. This
104352df8015SJessica Paquette       // happens when we have candidates that look like, say
104452df8015SJessica Paquette       //
104552df8015SJessica Paquette       // AA (where each "A" is an instruction).
104652df8015SJessica Paquette       //
104752df8015SJessica Paquette       // We might have some portion of the module that looks like this:
104852df8015SJessica Paquette       // AAAAAA (6 A's)
104952df8015SJessica Paquette       //
105052df8015SJessica Paquette       // In this case, there are 5 different copies of "AA" in this range, but
105152df8015SJessica Paquette       // at most 3 can be outlined. If only outlining 3 of these is going to
105252df8015SJessica Paquette       // be unbeneficial, then we ought to not bother.
105352df8015SJessica Paquette       //
105452df8015SJessica Paquette       // Note that two things DON'T overlap when they look like this:
105552df8015SJessica Paquette       // start1...end1 .... start2...end2
105652df8015SJessica Paquette       // That is, one must either
105752df8015SJessica Paquette       // * End before the other starts
105852df8015SJessica Paquette       // * Start after the other ends
10594e54ef88SJessica Paquette       if (std::all_of(
10604e54ef88SJessica Paquette               CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
106152df8015SJessica Paquette               [&StartIdx, &EndIdx](const Candidate &C) {
10624e54ef88SJessica Paquette                 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
106352df8015SJessica Paquette               })) {
106452df8015SJessica Paquette         // It doesn't overlap with anything, so we can outline it.
106552df8015SJessica Paquette         // Each sequence is over [StartIt, EndIt].
1066aa087327SJessica Paquette         // Save the candidate and its location.
1067aa087327SJessica Paquette 
106852df8015SJessica Paquette         MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
106952df8015SJessica Paquette         MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1070cad864d4SJessica Paquette         MachineBasicBlock *MBB = StartIt->getParent();
107152df8015SJessica Paquette 
1072aa087327SJessica Paquette         CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
1073cad864d4SJessica Paquette                                               EndIt, MBB, FunctionList.size(),
1074cad864d4SJessica Paquette                                               Mapper.MBBFlagsMap[MBB]);
107552df8015SJessica Paquette       }
1076809d708bSJessica Paquette     }
1077809d708bSJessica Paquette 
1078acc15e12SJessica Paquette     // We've found something we might want to outline.
1079acc15e12SJessica Paquette     // Create an OutlinedFunction to store it and check if it'd be beneficial
1080acc15e12SJessica Paquette     // to outline.
1081ddb039a1SJessica Paquette     if (CandidatesForRepeatedSeq.size() < 2)
1082da08078fSEli Friedman       continue;
1083da08078fSEli Friedman 
1084da08078fSEli Friedman     // Arbitrarily choose a TII from the first candidate.
1085da08078fSEli Friedman     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1086da08078fSEli Friedman     const TargetInstrInfo *TII =
1087da08078fSEli Friedman         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1088da08078fSEli Friedman 
10899d93c602SJessica Paquette     OutlinedFunction OF =
1090da08078fSEli Friedman         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
10919d93c602SJessica Paquette 
1092b2d53c5dSJessica Paquette     // If we deleted too many candidates, then there's nothing worth outlining.
1093b2d53c5dSJessica Paquette     // FIXME: This should take target-specified instruction sizes into account.
1094b2d53c5dSJessica Paquette     if (OF.Candidates.size() < 2)
10959d93c602SJessica Paquette       continue;
10969d93c602SJessica Paquette 
1097ffe4abc5SJessica Paquette     // Is it better to outline this candidate than not?
1098f94d1d29SJessica Paquette     if (OF.getBenefit() < 1) {
10991cc52a00SJessica Paquette       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
110078681be2SJessica Paquette       continue;
1101ffe4abc5SJessica Paquette     }
110278681be2SJessica Paquette 
1103acc15e12SJessica Paquette     FunctionList.push_back(OF);
110478681be2SJessica Paquette   }
1105596f483aSJessica Paquette }
1106596f483aSJessica Paquette 
11076b7615aeSPuyan Lotfi MachineFunction *MachineOutliner::createOutlinedFunction(
11086b7615aeSPuyan Lotfi     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
1109596f483aSJessica Paquette 
1110ae6c9403SFangrui Song   // Create the function name. This should be unique.
1111a3eb0facSJessica Paquette   // FIXME: We should have a better naming scheme. This should be stable,
1112a3eb0facSJessica Paquette   // regardless of changes to the outliner's cost model/traversal order.
11130d896278SJin Lin   std::string FunctionName;
11140d896278SJin Lin   if (OutlineRepeatedNum > 0)
11150d896278SJin Lin     FunctionName = ("OUTLINED_FUNCTION_" + Twine(OutlineRepeatedNum + 1) + "_" +
11160d896278SJin Lin                     Twine(Name))
11170d896278SJin Lin                        .str();
11180d896278SJin Lin   else
11190d896278SJin Lin     FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str();
1120596f483aSJessica Paquette 
1121596f483aSJessica Paquette   // Create the function using an IR-level function.
1122596f483aSJessica Paquette   LLVMContext &C = M.getContext();
1123ae6c9403SFangrui Song   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1124ae6c9403SFangrui Song                                  Function::ExternalLinkage, FunctionName, M);
1125596f483aSJessica Paquette 
1126596f483aSJessica Paquette   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1127596f483aSJessica Paquette   // which gives us better results when we outline from linkonceodr functions.
1128d506bf8eSJessica Paquette   F->setLinkage(GlobalValue::InternalLinkage);
1129596f483aSJessica Paquette   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1130596f483aSJessica Paquette 
113125bef201SEli Friedman   // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
113225bef201SEli Friedman   // necessary.
113325bef201SEli Friedman 
113425bef201SEli Friedman   // Set optsize/minsize, so we don't insert padding between outlined
113525bef201SEli Friedman   // functions.
113625bef201SEli Friedman   F->addFnAttr(Attribute::OptimizeForSize);
113725bef201SEli Friedman   F->addFnAttr(Attribute::MinSize);
113825bef201SEli Friedman 
1139e3932eeeSJessica Paquette   // Include target features from an arbitrary candidate for the outlined
1140e3932eeeSJessica Paquette   // function. This makes sure the outlined function knows what kinds of
1141e3932eeeSJessica Paquette   // instructions are going into it. This is fine, since all parent functions
1142e3932eeeSJessica Paquette   // must necessarily support the instructions that are in the outlined region.
1143e18d6ff0SJessica Paquette   Candidate &FirstCand = OF.Candidates.front();
114434b618bfSJessica Paquette   const Function &ParentFn = FirstCand.getMF()->getFunction();
1145e3932eeeSJessica Paquette   if (ParentFn.hasFnAttribute("target-features"))
1146e3932eeeSJessica Paquette     F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1147e3932eeeSJessica Paquette 
1148596f483aSJessica Paquette   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1149596f483aSJessica Paquette   IRBuilder<> Builder(EntryBB);
1150596f483aSJessica Paquette   Builder.CreateRetVoid();
1151596f483aSJessica Paquette 
1152cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
11537bda1958SMatthias Braun   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
1154596f483aSJessica Paquette   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1155596f483aSJessica Paquette   const TargetSubtargetInfo &STI = MF.getSubtarget();
1156596f483aSJessica Paquette   const TargetInstrInfo &TII = *STI.getInstrInfo();
1157596f483aSJessica Paquette 
1158596f483aSJessica Paquette   // Insert the new function into the module.
1159596f483aSJessica Paquette   MF.insert(MF.begin(), &MBB);
1160596f483aSJessica Paquette 
11618d5024f7SAndrew Litteken   MachineFunction *OriginalMF = FirstCand.front()->getMF();
11628d5024f7SAndrew Litteken   const std::vector<MCCFIInstruction> &Instrs =
11638d5024f7SAndrew Litteken       OriginalMF->getFrameInstructions();
116434b618bfSJessica Paquette   for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
116534b618bfSJessica Paquette        ++I) {
116634b618bfSJessica Paquette     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
11678d5024f7SAndrew Litteken     if (I->isCFIInstruction()) {
11688d5024f7SAndrew Litteken       unsigned CFIIndex = NewMI->getOperand(0).getCFIIndex();
11698d5024f7SAndrew Litteken       MCCFIInstruction CFI = Instrs[CFIIndex];
11708d5024f7SAndrew Litteken       (void)MF.addFrameInst(CFI);
11718d5024f7SAndrew Litteken     }
1172c73c0307SChandler Carruth     NewMI->dropMemRefs(MF);
1173596f483aSJessica Paquette 
1174596f483aSJessica Paquette     // Don't keep debug information for outlined instructions.
1175596f483aSJessica Paquette     NewMI->setDebugLoc(DebugLoc());
1176596f483aSJessica Paquette     MBB.insert(MBB.end(), NewMI);
1177596f483aSJessica Paquette   }
1178596f483aSJessica Paquette 
11791a78b0bdSEli Friedman   // Set normal properties for a late MachineFunction.
11801a78b0bdSEli Friedman   MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
11811a78b0bdSEli Friedman   MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
11821a78b0bdSEli Friedman   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
11831a78b0bdSEli Friedman   MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
1184cc06a782SJessica Paquette   MF.getRegInfo().freezeReservedRegs(MF);
1185cc06a782SJessica Paquette 
11861a78b0bdSEli Friedman   // Compute live-in set for outlined fn
11871a78b0bdSEli Friedman   const MachineRegisterInfo &MRI = MF.getRegInfo();
11881a78b0bdSEli Friedman   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
11891a78b0bdSEli Friedman   LivePhysRegs LiveIns(TRI);
11901a78b0bdSEli Friedman   for (auto &Cand : OF.Candidates) {
11911a78b0bdSEli Friedman     // Figure out live-ins at the first instruction.
11921a78b0bdSEli Friedman     MachineBasicBlock &OutlineBB = *Cand.front()->getParent();
11931a78b0bdSEli Friedman     LivePhysRegs CandLiveIns(TRI);
11941a78b0bdSEli Friedman     CandLiveIns.addLiveOuts(OutlineBB);
11951a78b0bdSEli Friedman     for (const MachineInstr &MI :
11961a78b0bdSEli Friedman          reverse(make_range(Cand.front(), OutlineBB.end())))
11971a78b0bdSEli Friedman       CandLiveIns.stepBackward(MI);
11981a78b0bdSEli Friedman 
11991a78b0bdSEli Friedman     // The live-in set for the outlined function is the union of the live-ins
12001a78b0bdSEli Friedman     // from all the outlining points.
12011a78b0bdSEli Friedman     for (MCPhysReg Reg : make_range(CandLiveIns.begin(), CandLiveIns.end()))
12021a78b0bdSEli Friedman       LiveIns.addReg(Reg);
12031a78b0bdSEli Friedman   }
12041a78b0bdSEli Friedman   addLiveIns(MBB, LiveIns);
12051a78b0bdSEli Friedman 
12061a78b0bdSEli Friedman   TII.buildOutlinedFrame(MBB, MF, OF);
12071a78b0bdSEli Friedman 
1208a499c3c2SJessica Paquette   // If there's a DISubprogram associated with this outlined function, then
1209a499c3c2SJessica Paquette   // emit debug info for the outlined function.
1210aa087327SJessica Paquette   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1211a499c3c2SJessica Paquette     // We have a DISubprogram. Get its DICompileUnit.
1212a499c3c2SJessica Paquette     DICompileUnit *CU = SP->getUnit();
1213a499c3c2SJessica Paquette     DIBuilder DB(M, true, CU);
1214a499c3c2SJessica Paquette     DIFile *Unit = SP->getFile();
1215a499c3c2SJessica Paquette     Mangler Mg;
1216a499c3c2SJessica Paquette     // Get the mangled name of the function for the linkage name.
1217a499c3c2SJessica Paquette     std::string Dummy;
1218a499c3c2SJessica Paquette     llvm::raw_string_ostream MangledNameStream(Dummy);
1219a499c3c2SJessica Paquette     Mg.getNameWithPrefix(MangledNameStream, F, false);
1220a499c3c2SJessica Paquette 
1221cc06a782SJessica Paquette     DISubprogram *OutlinedSP = DB.createFunction(
1222a499c3c2SJessica Paquette         Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1223a499c3c2SJessica Paquette         Unit /* File */,
1224a499c3c2SJessica Paquette         0 /* Line 0 is reserved for compiler-generated code. */,
1225cc06a782SJessica Paquette         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
1226cda54210SPaul Robinson         0, /* Line 0 is reserved for compiler-generated code. */
1227a499c3c2SJessica Paquette         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1228cda54210SPaul Robinson         /* Outlined code is optimized code by definition. */
1229cda54210SPaul Robinson         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1230a499c3c2SJessica Paquette 
1231a499c3c2SJessica Paquette     // Don't add any new variables to the subprogram.
1232cc06a782SJessica Paquette     DB.finalizeSubprogram(OutlinedSP);
1233a499c3c2SJessica Paquette 
1234a499c3c2SJessica Paquette     // Attach subprogram to the function.
1235cc06a782SJessica Paquette     F->setSubprogram(OutlinedSP);
1236a499c3c2SJessica Paquette     // We're done with the DIBuilder.
1237a499c3c2SJessica Paquette     DB.finalize();
1238a499c3c2SJessica Paquette   }
1239a499c3c2SJessica Paquette 
1240596f483aSJessica Paquette   return &MF;
1241596f483aSJessica Paquette }
1242596f483aSJessica Paquette 
12434ae3b71dSJessica Paquette bool MachineOutliner::outline(Module &M,
12444ae3b71dSJessica Paquette                               std::vector<OutlinedFunction> &FunctionList,
1245a51fc8ddSPuyan Lotfi                               InstructionMapper &Mapper,
1246a51fc8ddSPuyan Lotfi                               unsigned &OutlinedFunctionNum) {
1247596f483aSJessica Paquette 
1248596f483aSJessica Paquette   bool OutlinedSomething = false;
1249a3eb0facSJessica Paquette 
1250962b3ae6SJessica Paquette   // Sort by benefit. The most beneficial functions should be outlined first.
1251efd94c56SFangrui Song   llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
1252efd94c56SFangrui Song                                      const OutlinedFunction &RHS) {
1253962b3ae6SJessica Paquette     return LHS.getBenefit() > RHS.getBenefit();
1254962b3ae6SJessica Paquette   });
1255596f483aSJessica Paquette 
1256962b3ae6SJessica Paquette   // Walk over each function, outlining them as we go along. Functions are
1257962b3ae6SJessica Paquette   // outlined greedily, based off the sort above.
1258962b3ae6SJessica Paquette   for (OutlinedFunction &OF : FunctionList) {
1259962b3ae6SJessica Paquette     // If we outlined something that overlapped with a candidate in a previous
1260962b3ae6SJessica Paquette     // step, then we can't outline from it.
1261e18d6ff0SJessica Paquette     erase_if(OF.Candidates, [&Mapper](Candidate &C) {
1262d9d9309bSJessica Paquette       return std::any_of(
1263e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getStartIdx(),
1264e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1265d9d9309bSJessica Paquette           [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
1266235d877eSJessica Paquette     });
1267596f483aSJessica Paquette 
1268962b3ae6SJessica Paquette     // If we made it unbeneficial to outline this function, skip it.
126985af63d0SJessica Paquette     if (OF.getBenefit() < 1)
1270596f483aSJessica Paquette       continue;
1271596f483aSJessica Paquette 
1272962b3ae6SJessica Paquette     // It's beneficial. Create the function and outline its sequence's
1273962b3ae6SJessica Paquette     // occurrences.
1274a3eb0facSJessica Paquette     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
127558e706a6SJessica Paquette     emitOutlinedFunctionRemark(OF);
1276acffa28cSJessica Paquette     FunctionsCreated++;
1277a3eb0facSJessica Paquette     OutlinedFunctionNum++; // Created a function, move to the next name.
1278596f483aSJessica Paquette     MachineFunction *MF = OF.MF;
1279596f483aSJessica Paquette     const TargetSubtargetInfo &STI = MF->getSubtarget();
1280596f483aSJessica Paquette     const TargetInstrInfo &TII = *STI.getInstrInfo();
1281596f483aSJessica Paquette 
1282962b3ae6SJessica Paquette     // Replace occurrences of the sequence with calls to the new function.
1283e18d6ff0SJessica Paquette     for (Candidate &C : OF.Candidates) {
1284962b3ae6SJessica Paquette       MachineBasicBlock &MBB = *C.getMBB();
1285962b3ae6SJessica Paquette       MachineBasicBlock::iterator StartIt = C.front();
1286962b3ae6SJessica Paquette       MachineBasicBlock::iterator EndIt = C.back();
1287596f483aSJessica Paquette 
1288962b3ae6SJessica Paquette       // Insert the call.
1289962b3ae6SJessica Paquette       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
1290962b3ae6SJessica Paquette 
1291962b3ae6SJessica Paquette       // If the caller tracks liveness, then we need to make sure that
1292962b3ae6SJessica Paquette       // anything we outline doesn't break liveness assumptions. The outlined
1293962b3ae6SJessica Paquette       // functions themselves currently don't track liveness, but we should
1294962b3ae6SJessica Paquette       // make sure that the ranges we yank things out of aren't wrong.
1295aa087327SJessica Paquette       if (MBB.getParent()->getProperties().hasProperty(
12960b672491SJessica Paquette               MachineFunctionProperties::Property::TracksLiveness)) {
1297fc6fda90SJin Lin         // The following code is to add implicit def operands to the call
129871d3869fSDjordje Todorovic         // instruction. It also updates call site information for moved
129971d3869fSDjordje Todorovic         // code.
1300fc6fda90SJin Lin         SmallSet<Register, 2> UseRegs, DefRegs;
13010b672491SJessica Paquette         // Copy over the defs in the outlined range.
13020b672491SJessica Paquette         // First inst in outlined range <-- Anything that's defined in this
1303962b3ae6SJessica Paquette         // ...                           .. range has to be added as an
1304962b3ae6SJessica Paquette         // implicit Last inst in outlined range  <-- def to the call
130571d3869fSDjordje Todorovic         // instruction. Also remove call site information for outlined block
1306fc6fda90SJin Lin         // of code. The exposed uses need to be copied in the outlined range.
1307*ffd5e121SPuyan Lotfi         for (MachineBasicBlock::reverse_iterator
1308*ffd5e121SPuyan Lotfi                  Iter = EndIt.getReverse(),
1309fc6fda90SJin Lin                  Last = std::next(CallInst.getReverse());
1310fc6fda90SJin Lin              Iter != Last; Iter++) {
1311fc6fda90SJin Lin           MachineInstr *MI = &*Iter;
1312fc6fda90SJin Lin           for (MachineOperand &MOP : MI->operands()) {
1313fc6fda90SJin Lin             // Skip over anything that isn't a register.
1314fc6fda90SJin Lin             if (!MOP.isReg())
1315fc6fda90SJin Lin               continue;
1316fc6fda90SJin Lin 
1317fc6fda90SJin Lin             if (MOP.isDef()) {
1318fc6fda90SJin Lin               // Introduce DefRegs set to skip the redundant register.
1319fc6fda90SJin Lin               DefRegs.insert(MOP.getReg());
1320fc6fda90SJin Lin               if (UseRegs.count(MOP.getReg()))
1321fc6fda90SJin Lin                 // Since the regiester is modeled as defined,
1322fc6fda90SJin Lin                 // it is not necessary to be put in use register set.
1323fc6fda90SJin Lin                 UseRegs.erase(MOP.getReg());
1324fc6fda90SJin Lin             } else if (!MOP.isUndef()) {
1325fc6fda90SJin Lin               // Any register which is not undefined should
1326fc6fda90SJin Lin               // be put in the use register set.
1327fc6fda90SJin Lin               UseRegs.insert(MOP.getReg());
1328fc6fda90SJin Lin             }
1329fc6fda90SJin Lin           }
1330fc6fda90SJin Lin           if (MI->isCandidateForCallSiteEntry())
1331fc6fda90SJin Lin             MI->getMF()->eraseCallSiteInfo(MI);
1332fc6fda90SJin Lin         }
1333fc6fda90SJin Lin 
1334fc6fda90SJin Lin         for (const Register &I : DefRegs)
1335fc6fda90SJin Lin           // If it's a def, add it to the call instruction.
1336*ffd5e121SPuyan Lotfi           CallInst->addOperand(
1337*ffd5e121SPuyan Lotfi               MachineOperand::CreateReg(I, true, /* isDef = true */
1338fc6fda90SJin Lin                                         true /* isImp = true */));
1339fc6fda90SJin Lin 
1340fc6fda90SJin Lin         for (const Register &I : UseRegs)
1341fc6fda90SJin Lin           // If it's a exposed use, add it to the call instruction.
1342fc6fda90SJin Lin           CallInst->addOperand(
1343fc6fda90SJin Lin               MachineOperand::CreateReg(I, false, /* isDef = false */
1344fc6fda90SJin Lin                                         true /* isImp = true */));
13450b672491SJessica Paquette       }
13460b672491SJessica Paquette 
1347aa087327SJessica Paquette       // Erase from the point after where the call was inserted up to, and
1348aa087327SJessica Paquette       // including, the final instruction in the sequence.
1349aa087327SJessica Paquette       // Erase needs one past the end, so we need std::next there too.
1350aa087327SJessica Paquette       MBB.erase(std::next(StartIt), std::next(EndIt));
1351235d877eSJessica Paquette 
1352d9d9309bSJessica Paquette       // Keep track of what we removed by marking them all as -1.
1353235d877eSJessica Paquette       std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1354235d877eSJessica Paquette                     Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1355d9d9309bSJessica Paquette                     [](unsigned &I) { I = static_cast<unsigned>(-1); });
1356596f483aSJessica Paquette       OutlinedSomething = true;
1357596f483aSJessica Paquette 
1358596f483aSJessica Paquette       // Statistics.
1359596f483aSJessica Paquette       NumOutlined++;
1360596f483aSJessica Paquette     }
1361962b3ae6SJessica Paquette   }
1362596f483aSJessica Paquette 
1363d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
1364596f483aSJessica Paquette   return OutlinedSomething;
1365596f483aSJessica Paquette }
1366596f483aSJessica Paquette 
1367050d1ac4SJessica Paquette void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1368050d1ac4SJessica Paquette                                      MachineModuleInfo &MMI) {
1369df82274fSJessica Paquette   // Build instruction mappings for each function in the module. Start by
1370df82274fSJessica Paquette   // iterating over each Function in M.
1371596f483aSJessica Paquette   for (Function &F : M) {
1372596f483aSJessica Paquette 
1373df82274fSJessica Paquette     // If there's nothing in F, then there's no reason to try and outline from
1374df82274fSJessica Paquette     // it.
1375df82274fSJessica Paquette     if (F.empty())
1376596f483aSJessica Paquette       continue;
1377596f483aSJessica Paquette 
1378df82274fSJessica Paquette     // There's something in F. Check if it has a MachineFunction associated with
1379df82274fSJessica Paquette     // it.
1380df82274fSJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
1381596f483aSJessica Paquette 
1382df82274fSJessica Paquette     // If it doesn't, then there's nothing to outline from. Move to the next
1383df82274fSJessica Paquette     // Function.
1384df82274fSJessica Paquette     if (!MF)
1385596f483aSJessica Paquette       continue;
1386596f483aSJessica Paquette 
1387da08078fSEli Friedman     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1388da08078fSEli Friedman 
13898bda1881SJessica Paquette     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
13908bda1881SJessica Paquette       continue;
13918bda1881SJessica Paquette 
1392df82274fSJessica Paquette     // We have a MachineFunction. Ask the target if it's suitable for outlining.
1393df82274fSJessica Paquette     // If it isn't, then move on to the next Function in the module.
1394df82274fSJessica Paquette     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1395df82274fSJessica Paquette       continue;
1396df82274fSJessica Paquette 
1397df82274fSJessica Paquette     // We have a function suitable for outlining. Iterate over every
1398df82274fSJessica Paquette     // MachineBasicBlock in MF and try to map its instructions to a list of
1399df82274fSJessica Paquette     // unsigned integers.
1400df82274fSJessica Paquette     for (MachineBasicBlock &MBB : *MF) {
1401df82274fSJessica Paquette       // If there isn't anything in MBB, then there's no point in outlining from
1402df82274fSJessica Paquette       // it.
1403b320ca26SJessica Paquette       // If there are fewer than 2 instructions in the MBB, then it can't ever
1404b320ca26SJessica Paquette       // contain something worth outlining.
1405b320ca26SJessica Paquette       // FIXME: This should be based off of the maximum size in B of an outlined
1406b320ca26SJessica Paquette       // call versus the size in B of the MBB.
1407b320ca26SJessica Paquette       if (MBB.empty() || MBB.size() < 2)
1408df82274fSJessica Paquette         continue;
1409df82274fSJessica Paquette 
1410df82274fSJessica Paquette       // Check if MBB could be the target of an indirect branch. If it is, then
1411df82274fSJessica Paquette       // we don't want to outline from it.
1412df82274fSJessica Paquette       if (MBB.hasAddressTaken())
1413df82274fSJessica Paquette         continue;
1414df82274fSJessica Paquette 
1415df82274fSJessica Paquette       // MBB is suitable for outlining. Map it to a list of unsigneds.
1416da08078fSEli Friedman       Mapper.convertToUnsignedVec(MBB, *TII);
1417596f483aSJessica Paquette     }
1418596f483aSJessica Paquette   }
1419050d1ac4SJessica Paquette }
1420050d1ac4SJessica Paquette 
14212386eab3SJessica Paquette void MachineOutliner::initSizeRemarkInfo(
14222386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
14232386eab3SJessica Paquette     StringMap<unsigned> &FunctionToInstrCount) {
14242386eab3SJessica Paquette   // Collect instruction counts for every function. We'll use this to emit
14252386eab3SJessica Paquette   // per-function size remarks later.
14262386eab3SJessica Paquette   for (const Function &F : M) {
14272386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
14282386eab3SJessica Paquette 
14292386eab3SJessica Paquette     // We only care about MI counts here. If there's no MachineFunction at this
14302386eab3SJessica Paquette     // point, then there won't be after the outliner runs, so let's move on.
14312386eab3SJessica Paquette     if (!MF)
14322386eab3SJessica Paquette       continue;
14332386eab3SJessica Paquette     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
14342386eab3SJessica Paquette   }
14352386eab3SJessica Paquette }
14362386eab3SJessica Paquette 
14372386eab3SJessica Paquette void MachineOutliner::emitInstrCountChangedRemark(
14382386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
14392386eab3SJessica Paquette     const StringMap<unsigned> &FunctionToInstrCount) {
14402386eab3SJessica Paquette   // Iterate over each function in the module and emit remarks.
14412386eab3SJessica Paquette   // Note that we won't miss anything by doing this, because the outliner never
14422386eab3SJessica Paquette   // deletes functions.
14432386eab3SJessica Paquette   for (const Function &F : M) {
14442386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
14452386eab3SJessica Paquette 
14462386eab3SJessica Paquette     // The outliner never deletes functions. If we don't have a MF here, then we
14472386eab3SJessica Paquette     // didn't have one prior to outlining either.
14482386eab3SJessica Paquette     if (!MF)
14492386eab3SJessica Paquette       continue;
14502386eab3SJessica Paquette 
1451adcd0268SBenjamin Kramer     std::string Fname = std::string(F.getName());
14522386eab3SJessica Paquette     unsigned FnCountAfter = MF->getInstructionCount();
14532386eab3SJessica Paquette     unsigned FnCountBefore = 0;
14542386eab3SJessica Paquette 
14552386eab3SJessica Paquette     // Check if the function was recorded before.
14562386eab3SJessica Paquette     auto It = FunctionToInstrCount.find(Fname);
14572386eab3SJessica Paquette 
14582386eab3SJessica Paquette     // Did we have a previously-recorded size? If yes, then set FnCountBefore
14592386eab3SJessica Paquette     // to that.
14602386eab3SJessica Paquette     if (It != FunctionToInstrCount.end())
14612386eab3SJessica Paquette       FnCountBefore = It->second;
14622386eab3SJessica Paquette 
14632386eab3SJessica Paquette     // Compute the delta and emit a remark if there was a change.
14642386eab3SJessica Paquette     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
14652386eab3SJessica Paquette                       static_cast<int64_t>(FnCountBefore);
14662386eab3SJessica Paquette     if (FnDelta == 0)
14672386eab3SJessica Paquette       continue;
14682386eab3SJessica Paquette 
14692386eab3SJessica Paquette     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
14702386eab3SJessica Paquette     MORE.emit([&]() {
14712386eab3SJessica Paquette       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
14726b7615aeSPuyan Lotfi                                           DiagnosticLocation(), &MF->front());
14732386eab3SJessica Paquette       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
14742386eab3SJessica Paquette         << ": Function: "
14752386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
14762386eab3SJessica Paquette         << ": MI instruction count changed from "
14772386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
14782386eab3SJessica Paquette                                                     FnCountBefore)
14792386eab3SJessica Paquette         << " to "
14802386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
14812386eab3SJessica Paquette                                                     FnCountAfter)
14822386eab3SJessica Paquette         << "; Delta: "
14832386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
14842386eab3SJessica Paquette       return R;
14852386eab3SJessica Paquette     });
14862386eab3SJessica Paquette   }
14872386eab3SJessica Paquette }
14882386eab3SJessica Paquette 
1489*ffd5e121SPuyan Lotfi bool MachineOutliner::runOnModule(Module &M) {
1490050d1ac4SJessica Paquette   // Check if there's anything in the module. If it's empty, then there's
1491050d1ac4SJessica Paquette   // nothing to outline.
1492050d1ac4SJessica Paquette   if (M.empty())
1493050d1ac4SJessica Paquette     return false;
1494050d1ac4SJessica Paquette 
1495a51fc8ddSPuyan Lotfi   // Number to append to the current outlined function.
1496a51fc8ddSPuyan Lotfi   unsigned OutlinedFunctionNum = 0;
1497a51fc8ddSPuyan Lotfi 
1498*ffd5e121SPuyan Lotfi   OutlineRepeatedNum = 0;
1499a51fc8ddSPuyan Lotfi   if (!doOutline(M, OutlinedFunctionNum))
1500a51fc8ddSPuyan Lotfi     return false;
1501*ffd5e121SPuyan Lotfi 
1502*ffd5e121SPuyan Lotfi   for (unsigned I = 0; I < OutlinerReruns; ++I) {
1503*ffd5e121SPuyan Lotfi     OutlinedFunctionNum = 0;
1504*ffd5e121SPuyan Lotfi     OutlineRepeatedNum++;
1505*ffd5e121SPuyan Lotfi     if (!doOutline(M, OutlinedFunctionNum)) {
1506*ffd5e121SPuyan Lotfi       LLVM_DEBUG({
1507*ffd5e121SPuyan Lotfi         dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1508*ffd5e121SPuyan Lotfi                << OutlinerReruns + 1 << "\n";
1509*ffd5e121SPuyan Lotfi       });
1510*ffd5e121SPuyan Lotfi       break;
1511*ffd5e121SPuyan Lotfi     }
1512*ffd5e121SPuyan Lotfi   }
1513*ffd5e121SPuyan Lotfi 
1514a51fc8ddSPuyan Lotfi   return true;
1515a51fc8ddSPuyan Lotfi }
1516a51fc8ddSPuyan Lotfi 
1517a51fc8ddSPuyan Lotfi bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1518cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1519050d1ac4SJessica Paquette 
1520050d1ac4SJessica Paquette   // If the user passed -enable-machine-outliner=always or
1521050d1ac4SJessica Paquette   // -enable-machine-outliner, the pass will run on all functions in the module.
1522050d1ac4SJessica Paquette   // Otherwise, if the target supports default outlining, it will run on all
1523050d1ac4SJessica Paquette   // functions deemed by the target to be worth outlining from by default. Tell
1524050d1ac4SJessica Paquette   // the user how the outliner is running.
15256b7615aeSPuyan Lotfi   LLVM_DEBUG({
1526050d1ac4SJessica Paquette     dbgs() << "Machine Outliner: Running on ";
1527050d1ac4SJessica Paquette     if (RunOnAllFunctions)
1528050d1ac4SJessica Paquette       dbgs() << "all functions";
1529050d1ac4SJessica Paquette     else
1530050d1ac4SJessica Paquette       dbgs() << "target-default functions";
15316b7615aeSPuyan Lotfi     dbgs() << "\n";
15326b7615aeSPuyan Lotfi   });
1533050d1ac4SJessica Paquette 
1534050d1ac4SJessica Paquette   // If the user specifies that they want to outline from linkonceodrs, set
1535050d1ac4SJessica Paquette   // it here.
1536050d1ac4SJessica Paquette   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1537050d1ac4SJessica Paquette   InstructionMapper Mapper;
1538050d1ac4SJessica Paquette 
1539050d1ac4SJessica Paquette   // Prepare instruction mappings for the suffix tree.
1540050d1ac4SJessica Paquette   populateMapper(Mapper, M, MMI);
1541596f483aSJessica Paquette   std::vector<OutlinedFunction> FunctionList;
1542596f483aSJessica Paquette 
1543acffa28cSJessica Paquette   // Find all of the outlining candidates.
1544ce3a2dcfSJessica Paquette   findCandidates(Mapper, FunctionList);
1545596f483aSJessica Paquette 
15462386eab3SJessica Paquette   // If we've requested size remarks, then collect the MI counts of every
15472386eab3SJessica Paquette   // function before outlining, and the MI counts after outlining.
15482386eab3SJessica Paquette   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
15492386eab3SJessica Paquette   // the pass manager's responsibility.
15502386eab3SJessica Paquette   // This could pretty easily be placed in outline instead, but because we
15512386eab3SJessica Paquette   // really ultimately *don't* want this here, it's done like this for now
15522386eab3SJessica Paquette   // instead.
15532386eab3SJessica Paquette 
15542386eab3SJessica Paquette   // Check if we want size remarks.
15552386eab3SJessica Paquette   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
15562386eab3SJessica Paquette   StringMap<unsigned> FunctionToInstrCount;
15572386eab3SJessica Paquette   if (ShouldEmitSizeRemarks)
15582386eab3SJessica Paquette     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
15592386eab3SJessica Paquette 
1560acffa28cSJessica Paquette   // Outline each of the candidates and return true if something was outlined.
1561a51fc8ddSPuyan Lotfi   bool OutlinedSomething =
1562a51fc8ddSPuyan Lotfi       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1563729e6869SJessica Paquette 
15642386eab3SJessica Paquette   // If we outlined something, we definitely changed the MI count of the
15652386eab3SJessica Paquette   // module. If we've asked for size remarks, then output them.
15662386eab3SJessica Paquette   // FIXME: This should be in the pass manager.
15672386eab3SJessica Paquette   if (ShouldEmitSizeRemarks && OutlinedSomething)
15682386eab3SJessica Paquette     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
15692386eab3SJessica Paquette 
1570*ffd5e121SPuyan Lotfi   LLVM_DEBUG({
1571*ffd5e121SPuyan Lotfi     if (!OutlinedSomething)
1572*ffd5e121SPuyan Lotfi       dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1573*ffd5e121SPuyan Lotfi              << " because no changes were found.\n";
1574*ffd5e121SPuyan Lotfi   });
1575*ffd5e121SPuyan Lotfi 
1576729e6869SJessica Paquette   return OutlinedSomething;
1577596f483aSJessica Paquette }
1578