blob: b60740320b89f791561d70232c9a72b1e824b380 [file] [log] [blame]
Jessica Paquette596f4832017-03-06 21:31:18 +00001//===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// Replaces repeated sequences of instructions with function calls.
12///
13/// This works by placing every instruction from every basic block in a
14/// suffix tree, and repeatedly querying that tree for repeated sequences of
15/// instructions. If a sequence of instructions appears often, then it ought
16/// to be beneficial to pull out into a function.
17///
Jessica Paquette4cf187b2017-09-27 20:47:39 +000018/// The MachineOutliner communicates with a given target using hooks defined in
19/// TargetInstrInfo.h. The target supplies the outliner with information on how
20/// a specific sequence of instructions should be outlined. This information
21/// is used to deduce the number of instructions necessary to
22///
23/// * Create an outlined function
24/// * Call that outlined function
25///
26/// Targets must implement
27/// * getOutliningCandidateInfo
28/// * insertOutlinerEpilogue
29/// * insertOutlinedCall
30/// * insertOutlinerPrologue
31/// * isFunctionSafeToOutlineFrom
32///
33/// in order to make use of the MachineOutliner.
34///
Jessica Paquette596f4832017-03-06 21:31:18 +000035/// This was originally presented at the 2016 LLVM Developers' Meeting in the
36/// talk "Reducing Code Size Using Outlining". For a high-level overview of
37/// how this pass works, the talk is available on YouTube at
38///
39/// https://www.youtube.com/watch?v=yorld-WSOeU
40///
41/// The slides for the talk are available at
42///
43/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
44///
45/// The talk provides an overview of how the outliner finds candidates and
46/// ultimately outlines them. It describes how the main data structure for this
47/// pass, the suffix tree, is queried and purged for candidates. It also gives
48/// a simplified suffix tree construction algorithm for suffix trees based off
49/// of the algorithm actually used here, Ukkonen's algorithm.
50///
51/// For the original RFC for this pass, please see
52///
53/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
54///
55/// For more information on the suffix tree data structure, please see
56/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
57///
58//===----------------------------------------------------------------------===//
59#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/Statistic.h"
61#include "llvm/ADT/Twine.h"
62#include "llvm/CodeGen/MachineFrameInfo.h"
63#include "llvm/CodeGen/MachineFunction.h"
64#include "llvm/CodeGen/MachineInstrBuilder.h"
65#include "llvm/CodeGen/MachineModuleInfo.h"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000066#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000067#include "llvm/CodeGen/Passes.h"
68#include "llvm/IR/IRBuilder.h"
69#include "llvm/Support/Allocator.h"
70#include "llvm/Support/Debug.h"
71#include "llvm/Support/raw_ostream.h"
72#include "llvm/Target/TargetInstrInfo.h"
73#include "llvm/Target/TargetMachine.h"
74#include "llvm/Target/TargetRegisterInfo.h"
75#include "llvm/Target/TargetSubtargetInfo.h"
76#include <functional>
77#include <map>
78#include <sstream>
79#include <tuple>
80#include <vector>
81
82#define DEBUG_TYPE "machine-outliner"
83
84using namespace llvm;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000085using namespace ore;
Jessica Paquette596f4832017-03-06 21:31:18 +000086
87STATISTIC(NumOutlined, "Number of candidates outlined");
88STATISTIC(FunctionsCreated, "Number of functions created");
89
90namespace {
91
Jessica Paquetteacffa282017-03-23 21:27:38 +000092/// \brief An individual sequence of instructions to be replaced with a call to
93/// an outlined function.
94struct Candidate {
Jessica Paquettec9ab4c22017-10-17 18:43:15 +000095private:
96 /// The start index of this \p Candidate in the instruction list.
Jessica Paquette4cf187b2017-09-27 20:47:39 +000097 unsigned StartIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +000098
99 /// The number of instructions in this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000100 unsigned Len;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000101
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000102public:
103 /// Set to false if the candidate overlapped with another candidate.
104 bool InCandidateList = true;
105
106 /// \brief The index of this \p Candidate's \p OutlinedFunction in the list of
Jessica Paquetteacffa282017-03-23 21:27:38 +0000107 /// \p OutlinedFunctions.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000108 unsigned FunctionIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000109
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000110 /// Contains all target-specific information for this \p Candidate.
111 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000112
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000113 /// Return the number of instructions in this Candidate.
114 unsigned length() const { return Len; }
115
116 /// Return the start index of this candidate.
117 unsigned startIdx() const { return StartIdx; }
118
119 // Return the end index of this candidate.
120 unsigned endIdx() const { return StartIdx + Len - 1; }
121
Jessica Paquetteacffa282017-03-23 21:27:38 +0000122 /// \brief The number of instructions that would be saved by outlining every
123 /// candidate of this type.
124 ///
125 /// This is a fixed value which is not updated during the candidate pruning
126 /// process. It is only used for deciding which candidate to keep if two
127 /// candidates overlap. The true benefit is stored in the OutlinedFunction
128 /// for some given candidate.
129 unsigned Benefit = 0;
130
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000131 Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx)
132 : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000133
134 Candidate() {}
135
136 /// \brief Used to ensure that \p Candidates are outlined in an order that
137 /// preserves the start and end indices of other \p Candidates.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000138 bool operator<(const Candidate &RHS) const {
139 return startIdx() > RHS.startIdx();
140 }
Jessica Paquetteacffa282017-03-23 21:27:38 +0000141};
142
143/// \brief The information necessary to create an outlined function for some
144/// class of candidate.
145struct OutlinedFunction {
146
Jessica Paquette85af63d2017-10-17 19:03:23 +0000147private:
148 /// The number of candidates for this \p OutlinedFunction.
149 unsigned OccurrenceCount = 0;
150
151public:
Jessica Paquetteacffa282017-03-23 21:27:38 +0000152 /// The actual outlined function created.
153 /// This is initialized after we go through and create the actual function.
154 MachineFunction *MF = nullptr;
155
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000156 /// A number assigned to this function which appears at the end of its name.
157 unsigned Name;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000158
Jessica Paquetteacffa282017-03-23 21:27:38 +0000159 /// \brief The sequence of integers corresponding to the instructions in this
160 /// function.
161 std::vector<unsigned> Sequence;
162
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000163 /// Contains all target-specific information for this \p OutlinedFunction.
164 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000165
Jessica Paquette85af63d2017-10-17 19:03:23 +0000166 /// Return the number of candidates for this \p OutlinedFunction.
167 unsigned getOccurrenceCount() {
168 return OccurrenceCount;
169 }
170
171 /// Decrement the occurrence count of this OutlinedFunction and return the
172 /// new count.
173 unsigned decrement() {
174 assert(OccurrenceCount > 0 && "Can't decrement an empty function!");
175 OccurrenceCount--;
176 return getOccurrenceCount();
177 }
178
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000179 /// \brief Return the number of instructions it would take to outline this
180 /// function.
181 unsigned getOutliningCost() {
182 return (OccurrenceCount * MInfo.CallOverhead) + Sequence.size() +
183 MInfo.FrameOverhead;
184 }
185
186 /// \brief Return the number of instructions that would be saved by outlining
187 /// this function.
188 unsigned getBenefit() {
189 unsigned NotOutlinedCost = OccurrenceCount * Sequence.size();
190 unsigned OutlinedCost = getOutliningCost();
191 return (NotOutlinedCost < OutlinedCost) ? 0
192 : NotOutlinedCost - OutlinedCost;
193 }
194
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000195 OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000196 const std::vector<unsigned> &Sequence,
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000197 TargetInstrInfo::MachineOutlinerInfo &MInfo)
Jessica Paquette85af63d2017-10-17 19:03:23 +0000198 : OccurrenceCount(OccurrenceCount), Name(Name), Sequence(Sequence),
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000199 MInfo(MInfo) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000200};
201
Jessica Paquette596f4832017-03-06 21:31:18 +0000202/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000203const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000204
205/// A node in a suffix tree which represents a substring or suffix.
206///
207/// Each node has either no children or at least two children, with the root
208/// being a exception in the empty tree.
209///
210/// Children are represented as a map between unsigned integers and nodes. If
211/// a node N has a child M on unsigned integer k, then the mapping represented
212/// by N is a proper prefix of the mapping represented by M. Note that this,
213/// although similar to a trie is somewhat different: each node stores a full
214/// substring of the full mapping rather than a single character state.
215///
216/// Each internal node contains a pointer to the internal node representing
217/// the same string, but with the first character chopped off. This is stored
218/// in \p Link. Each leaf node stores the start index of its respective
219/// suffix in \p SuffixIdx.
220struct SuffixTreeNode {
221
222 /// The children of this node.
223 ///
224 /// A child existing on an unsigned integer implies that from the mapping
225 /// represented by the current node, there is a way to reach another
226 /// mapping by tacking that character on the end of the current string.
227 DenseMap<unsigned, SuffixTreeNode *> Children;
228
229 /// A flag set to false if the node has been pruned from the tree.
230 bool IsInTree = true;
231
232 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000233 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000234
235 /// The end index of this node's substring in the main string.
236 ///
237 /// Every leaf node must have its \p EndIdx incremented at the end of every
238 /// step in the construction algorithm. To avoid having to update O(N)
239 /// nodes individually at the end of every step, the end index is stored
240 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000241 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000242
243 /// For leaves, the start index of the suffix represented by this node.
244 ///
245 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000246 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000247
248 /// \brief For internal nodes, a pointer to the internal node representing
249 /// the same sequence with the first character chopped off.
250 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000251 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000252 /// Ukkonen's algorithm does to achieve linear-time construction is
253 /// keep track of which node the next insert should be at. This makes each
254 /// insert O(1), and there are a total of O(N) inserts. The suffix link
255 /// helps with inserting children of internal nodes.
256 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000257 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000258 /// next insertion must be at the node representing S - its first character.
259 /// This is given by the way that we iteratively build the tree in Ukkonen's
260 /// algorithm. The main idea is to look at the suffixes of each prefix in the
261 /// string, starting with the longest suffix of the prefix, and ending with
262 /// the shortest. Therefore, if we keep pointers between such nodes, we can
263 /// move to the next insertion point in O(1) time. If we don't, then we'd
264 /// have to query from the root, which takes O(N) time. This would make the
265 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000266 SuffixTreeNode *Link = nullptr;
267
268 /// The parent of this node. Every node except for the root has a parent.
269 SuffixTreeNode *Parent = nullptr;
270
271 /// The number of times this node's string appears in the tree.
272 ///
273 /// This is equal to the number of leaf children of the string. It represents
274 /// the number of suffixes that the node's string is a prefix of.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000275 unsigned OccurrenceCount = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000276
Jessica Paquetteacffa282017-03-23 21:27:38 +0000277 /// The length of the string formed by concatenating the edge labels from the
278 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000279 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000280
Jessica Paquette596f4832017-03-06 21:31:18 +0000281 /// Returns true if this node is a leaf.
282 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
283
284 /// Returns true if this node is the root of its owning \p SuffixTree.
285 bool isRoot() const { return StartIdx == EmptyIdx; }
286
287 /// Return the number of elements in the substring associated with this node.
288 size_t size() const {
289
290 // Is it the root? If so, it's the empty string so return 0.
291 if (isRoot())
292 return 0;
293
294 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
295
296 // Size = the number of elements in the string.
297 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
298 return *EndIdx - StartIdx + 1;
299 }
300
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000301 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000302 SuffixTreeNode *Parent)
303 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
304
305 SuffixTreeNode() {}
306};
307
308/// A data structure for fast substring queries.
309///
310/// Suffix trees represent the suffixes of their input strings in their leaves.
311/// A suffix tree is a type of compressed trie structure where each node
312/// represents an entire substring rather than a single character. Each leaf
313/// of the tree is a suffix.
314///
315/// A suffix tree can be seen as a type of state machine where each state is a
316/// substring of the full string. The tree is structured so that, for a string
317/// of length N, there are exactly N leaves in the tree. This structure allows
318/// us to quickly find repeated substrings of the input string.
319///
320/// In this implementation, a "string" is a vector of unsigned integers.
321/// These integers may result from hashing some data type. A suffix tree can
322/// contain 1 or many strings, which can then be queried as one large string.
323///
324/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
325/// suffix tree construction. Ukkonen's algorithm is explained in more detail
326/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
327/// paper is available at
328///
329/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
330class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000331public:
332 /// Stores each leaf node in the tree.
333 ///
334 /// This is used for finding outlining candidates.
335 std::vector<SuffixTreeNode *> LeafVector;
336
Jessica Paquette596f4832017-03-06 21:31:18 +0000337 /// Each element is an integer representing an instruction in the module.
338 ArrayRef<unsigned> Str;
339
Jessica Paquette78681be2017-07-27 23:24:43 +0000340private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000341 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000342 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000343
344 /// The root of the suffix tree.
345 ///
346 /// The root represents the empty string. It is maintained by the
347 /// \p NodeAllocator like every other node in the tree.
348 SuffixTreeNode *Root = nullptr;
349
Jessica Paquette596f4832017-03-06 21:31:18 +0000350 /// Maintains the end indices of the internal nodes in the tree.
351 ///
352 /// Each internal node is guaranteed to never have its end index change
353 /// during the construction algorithm; however, leaves must be updated at
354 /// every step. Therefore, we need to store leaf end indices by reference
355 /// to avoid updating O(N) leaves at every step of construction. Thus,
356 /// every internal node must be allocated its own end index.
357 BumpPtrAllocator InternalEndIdxAllocator;
358
359 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000360 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000361
362 /// \brief Helper struct which keeps track of the next insertion point in
363 /// Ukkonen's algorithm.
364 struct ActiveState {
365 /// The next node to insert at.
366 SuffixTreeNode *Node;
367
368 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000369 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000370
371 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000372 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000373 };
374
375 /// \brief The point the next insertion will take place at in the
376 /// construction algorithm.
377 ActiveState Active;
378
379 /// Allocate a leaf node and add it to the tree.
380 ///
381 /// \param Parent The parent of this node.
382 /// \param StartIdx The start index of this node's associated string.
383 /// \param Edge The label on the edge leaving \p Parent to this node.
384 ///
385 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000386 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000387 unsigned Edge) {
388
389 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
390
Jessica Paquette78681be2017-07-27 23:24:43 +0000391 SuffixTreeNode *N = new (NodeAllocator.Allocate())
392 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000393 Parent.Children[Edge] = N;
394
395 return N;
396 }
397
398 /// Allocate an internal node and add it to the tree.
399 ///
400 /// \param Parent The parent of this node. Only null when allocating the root.
401 /// \param StartIdx The start index of this node's associated string.
402 /// \param EndIdx The end index of this node's associated string.
403 /// \param Edge The label on the edge leaving \p Parent to this node.
404 ///
405 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000406 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
407 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000408
409 assert(StartIdx <= EndIdx && "String can't start after it ends!");
410 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000411 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000412
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000413 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000414 SuffixTreeNode *N = new (NodeAllocator.Allocate())
415 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000416 if (Parent)
417 Parent->Children[Edge] = N;
418
419 return N;
420 }
421
422 /// \brief Set the suffix indices of the leaves to the start indices of their
423 /// respective suffixes. Also stores each leaf in \p LeafVector at its
424 /// respective suffix index.
425 ///
426 /// \param[in] CurrNode The node currently being visited.
427 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000428 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000429
430 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
431
Jessica Paquetteacffa282017-03-23 21:27:38 +0000432 // Store the length of the concatenation of all strings from the root to
433 // this node.
434 if (!CurrNode.isRoot()) {
435 if (CurrNode.ConcatLen == 0)
436 CurrNode.ConcatLen = CurrNode.size();
437
438 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000439 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000440 }
441
Jessica Paquette596f4832017-03-06 21:31:18 +0000442 // Traverse the tree depth-first.
443 for (auto &ChildPair : CurrNode.Children) {
444 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000445 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000446 }
447
448 // Is this node a leaf?
449 if (IsLeaf) {
450 // If yes, give it a suffix index and bump its parent's occurrence count.
451 CurrNode.SuffixIdx = Str.size() - CurrIdx;
452 assert(CurrNode.Parent && "CurrNode had no parent!");
453 CurrNode.Parent->OccurrenceCount++;
454
455 // Store the leaf in the leaf vector for pruning later.
456 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
457 }
458 }
459
460 /// \brief Construct the suffix tree for the prefix of the input ending at
461 /// \p EndIdx.
462 ///
463 /// Used to construct the full suffix tree iteratively. At the end of each
464 /// step, the constructed suffix tree is either a valid suffix tree, or a
465 /// suffix tree with implicit suffixes. At the end of the final step, the
466 /// suffix tree is a valid tree.
467 ///
468 /// \param EndIdx The end index of the current prefix in the main string.
469 /// \param SuffixesToAdd The number of suffixes that must be added
470 /// to complete the suffix tree at the current phase.
471 ///
472 /// \returns The number of suffixes that have not been added at the end of
473 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000474 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000475 SuffixTreeNode *NeedsLink = nullptr;
476
477 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000478
Jessica Paquette596f4832017-03-06 21:31:18 +0000479 // Are we waiting to add anything other than just the last character?
480 if (Active.Len == 0) {
481 // If not, then say the active index is the end index.
482 Active.Idx = EndIdx;
483 }
484
485 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
486
487 // The first character in the current substring we're looking at.
488 unsigned FirstChar = Str[Active.Idx];
489
490 // Have we inserted anything starting with FirstChar at the current node?
491 if (Active.Node->Children.count(FirstChar) == 0) {
492 // If not, then we can just insert a leaf and move too the next step.
493 insertLeaf(*Active.Node, EndIdx, FirstChar);
494
495 // The active node is an internal node, and we visited it, so it must
496 // need a link if it doesn't have one.
497 if (NeedsLink) {
498 NeedsLink->Link = Active.Node;
499 NeedsLink = nullptr;
500 }
501 } else {
502 // There's a match with FirstChar, so look for the point in the tree to
503 // insert a new node.
504 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
505
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000506 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000507
508 // Is the current suffix we're trying to insert longer than the size of
509 // the child we want to move to?
510 if (Active.Len >= SubstringLen) {
511 // If yes, then consume the characters we've seen and move to the next
512 // node.
513 Active.Idx += SubstringLen;
514 Active.Len -= SubstringLen;
515 Active.Node = NextNode;
516 continue;
517 }
518
519 // Otherwise, the suffix we're trying to insert must be contained in the
520 // next node we want to move to.
521 unsigned LastChar = Str[EndIdx];
522
523 // Is the string we're trying to insert a substring of the next node?
524 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
525 // If yes, then we're done for this step. Remember our insertion point
526 // and move to the next end index. At this point, we have an implicit
527 // suffix tree.
528 if (NeedsLink && !Active.Node->isRoot()) {
529 NeedsLink->Link = Active.Node;
530 NeedsLink = nullptr;
531 }
532
533 Active.Len++;
534 break;
535 }
536
537 // The string we're trying to insert isn't a substring of the next node,
538 // but matches up to a point. Split the node.
539 //
540 // For example, say we ended our search at a node n and we're trying to
541 // insert ABD. Then we'll create a new node s for AB, reduce n to just
542 // representing C, and insert a new leaf node l to represent d. This
543 // allows us to ensure that if n was a leaf, it remains a leaf.
544 //
545 // | ABC ---split---> | AB
546 // n s
547 // C / \ D
548 // n l
549
550 // The node s from the diagram
551 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000552 insertInternalNode(Active.Node, NextNode->StartIdx,
553 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000554
555 // Insert the new node representing the new substring into the tree as
556 // a child of the split node. This is the node l from the diagram.
557 insertLeaf(*SplitNode, EndIdx, LastChar);
558
559 // Make the old node a child of the split node and update its start
560 // index. This is the node n from the diagram.
561 NextNode->StartIdx += Active.Len;
562 NextNode->Parent = SplitNode;
563 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
564
565 // SplitNode is an internal node, update the suffix link.
566 if (NeedsLink)
567 NeedsLink->Link = SplitNode;
568
569 NeedsLink = SplitNode;
570 }
571
572 // We've added something new to the tree, so there's one less suffix to
573 // add.
574 SuffixesToAdd--;
575
576 if (Active.Node->isRoot()) {
577 if (Active.Len > 0) {
578 Active.Len--;
579 Active.Idx = EndIdx - SuffixesToAdd + 1;
580 }
581 } else {
582 // Start the next phase at the next smallest suffix.
583 Active.Node = Active.Node->Link;
584 }
585 }
586
587 return SuffixesToAdd;
588 }
589
Jessica Paquette596f4832017-03-06 21:31:18 +0000590public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000591 /// Construct a suffix tree from a sequence of unsigned integers.
592 ///
593 /// \param Str The string to construct the suffix tree for.
594 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
595 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
596 Root->IsInTree = true;
597 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000598 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000599
600 // Keep track of the number of suffixes we have to add of the current
601 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000602 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000603 Active.Node = Root;
604
605 // Construct the suffix tree iteratively on each prefix of the string.
606 // PfxEndIdx is the end index of the current prefix.
607 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000608 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
609 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000610 SuffixesToAdd++;
611 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
612 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
613 }
614
615 // Set the suffix indices of each leaf.
616 assert(Root && "Root node can't be nullptr!");
617 setSuffixIndices(*Root, 0);
618 }
619};
620
Jessica Paquette596f4832017-03-06 21:31:18 +0000621/// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
622struct InstructionMapper {
623
624 /// \brief The next available integer to assign to a \p MachineInstr that
625 /// cannot be outlined.
626 ///
627 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
628 unsigned IllegalInstrNumber = -3;
629
630 /// \brief The next available integer to assign to a \p MachineInstr that can
631 /// be outlined.
632 unsigned LegalInstrNumber = 0;
633
634 /// Correspondence from \p MachineInstrs to unsigned integers.
635 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
636 InstructionIntegerMap;
637
638 /// Corresponcence from unsigned integers to \p MachineInstrs.
639 /// Inverse of \p InstructionIntegerMap.
640 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
641
642 /// The vector of unsigned integers that the module is mapped to.
643 std::vector<unsigned> UnsignedVec;
644
645 /// \brief Stores the location of the instruction associated with the integer
646 /// at index i in \p UnsignedVec for each index i.
647 std::vector<MachineBasicBlock::iterator> InstrList;
648
649 /// \brief Maps \p *It to a legal integer.
650 ///
651 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
652 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
653 ///
654 /// \returns The integer that \p *It was mapped to.
655 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
656
657 // Get the integer for this instruction or give it the current
658 // LegalInstrNumber.
659 InstrList.push_back(It);
660 MachineInstr &MI = *It;
661 bool WasInserted;
662 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000663 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000664 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000665 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000666 unsigned MINumber = ResultIt->second;
667
668 // There was an insertion.
669 if (WasInserted) {
670 LegalInstrNumber++;
671 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
672 }
673
674 UnsignedVec.push_back(MINumber);
675
676 // Make sure we don't overflow or use any integers reserved by the DenseMap.
677 if (LegalInstrNumber >= IllegalInstrNumber)
678 report_fatal_error("Instruction mapping overflow!");
679
Jessica Paquette78681be2017-07-27 23:24:43 +0000680 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
681 "Tried to assign DenseMap tombstone or empty key to instruction.");
682 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
683 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000684
685 return MINumber;
686 }
687
688 /// Maps \p *It to an illegal integer.
689 ///
690 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
691 ///
692 /// \returns The integer that \p *It was mapped to.
693 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
694 unsigned MINumber = IllegalInstrNumber;
695
696 InstrList.push_back(It);
697 UnsignedVec.push_back(IllegalInstrNumber);
698 IllegalInstrNumber--;
699
700 assert(LegalInstrNumber < IllegalInstrNumber &&
701 "Instruction mapping overflow!");
702
Jessica Paquette78681be2017-07-27 23:24:43 +0000703 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
704 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000705
Jessica Paquette78681be2017-07-27 23:24:43 +0000706 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
707 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000708
709 return MINumber;
710 }
711
712 /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
713 /// and appends it to \p UnsignedVec and \p InstrList.
714 ///
715 /// Two instructions are assigned the same integer if they are identical.
716 /// If an instruction is deemed unsafe to outline, then it will be assigned an
717 /// unique integer. The resulting mapping is placed into a suffix tree and
718 /// queried for candidates.
719 ///
720 /// \param MBB The \p MachineBasicBlock to be translated into integers.
721 /// \param TRI \p TargetRegisterInfo for the module.
722 /// \param TII \p TargetInstrInfo for the module.
723 void convertToUnsignedVec(MachineBasicBlock &MBB,
724 const TargetRegisterInfo &TRI,
725 const TargetInstrInfo &TII) {
726 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
727 It++) {
728
729 // Keep track of where this instruction is in the module.
Jessica Paquette78681be2017-07-27 23:24:43 +0000730 switch (TII.getOutliningType(*It)) {
731 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
732 mapToIllegalUnsigned(It);
733 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000734
Jessica Paquette78681be2017-07-27 23:24:43 +0000735 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
736 mapToLegalUnsigned(It);
737 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000738
Jessica Paquette78681be2017-07-27 23:24:43 +0000739 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
740 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000741 }
742 }
743
744 // After we're done every insertion, uniquely terminate this part of the
745 // "string". This makes sure we won't match across basic block or function
746 // boundaries since the "end" is encoded uniquely and thus appears in no
747 // repeated substring.
748 InstrList.push_back(MBB.end());
749 UnsignedVec.push_back(IllegalInstrNumber);
750 IllegalInstrNumber--;
751 }
752
753 InstructionMapper() {
754 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
755 // changed.
756 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000757 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000758 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000759 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000760 }
761};
762
763/// \brief An interprocedural pass which finds repeated sequences of
764/// instructions and replaces them with calls to functions.
765///
766/// Each instruction is mapped to an unsigned integer and placed in a string.
767/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
768/// is then repeatedly queried for repeated sequences of instructions. Each
769/// non-overlapping repeated sequence is then placed in its own
770/// \p MachineFunction and each instance is then replaced with a call to that
771/// function.
772struct MachineOutliner : public ModulePass {
773
774 static char ID;
775
Jessica Paquette13593842017-10-07 00:16:34 +0000776 /// \brief Set to true if the outliner should consider functions with
777 /// linkonceodr linkage.
778 bool OutlineFromLinkOnceODRs = false;
779
Jessica Paquette596f4832017-03-06 21:31:18 +0000780 StringRef getPassName() const override { return "Machine Outliner"; }
781
782 void getAnalysisUsage(AnalysisUsage &AU) const override {
783 AU.addRequired<MachineModuleInfo>();
784 AU.addPreserved<MachineModuleInfo>();
785 AU.setPreservesAll();
786 ModulePass::getAnalysisUsage(AU);
787 }
788
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000789 MachineOutliner(bool OutlineFromLinkOnceODRs = false)
790 : ModulePass(ID), OutlineFromLinkOnceODRs(OutlineFromLinkOnceODRs) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000791 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
792 }
793
Jessica Paquette78681be2017-07-27 23:24:43 +0000794 /// Find all repeated substrings that satisfy the outlining cost model.
795 ///
796 /// If a substring appears at least twice, then it must be represented by
797 /// an internal node which appears in at least two suffixes. Each suffix is
798 /// represented by a leaf node. To do this, we visit each internal node in
799 /// the tree, using the leaf children of each internal node. If an internal
800 /// node represents a beneficial substring, then we use each of its leaf
801 /// children to find the locations of its substring.
802 ///
803 /// \param ST A suffix tree to query.
804 /// \param TII TargetInstrInfo for the target.
805 /// \param Mapper Contains outlining mapping information.
806 /// \param[out] CandidateList Filled with candidates representing each
807 /// beneficial substring.
808 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
809 /// type of candidate.
810 ///
811 /// \returns The length of the longest candidate found.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000812 unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
813 InstructionMapper &Mapper,
814 std::vector<Candidate> &CandidateList,
815 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000816
Jessica Paquette596f4832017-03-06 21:31:18 +0000817 /// \brief Replace the sequences of instructions represented by the
818 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
819 /// described in \p FunctionList.
820 ///
821 /// \param M The module we are outlining from.
822 /// \param CandidateList A list of candidates to be outlined.
823 /// \param FunctionList A list of functions to be inserted into the module.
824 /// \param Mapper Contains the instruction mappings for the module.
825 bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
826 std::vector<OutlinedFunction> &FunctionList,
827 InstructionMapper &Mapper);
828
829 /// Creates a function for \p OF and inserts it into the module.
830 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
831 InstructionMapper &Mapper);
832
833 /// Find potential outlining candidates and store them in \p CandidateList.
834 ///
835 /// For each type of potential candidate, also build an \p OutlinedFunction
836 /// struct containing the information to build the function for that
837 /// candidate.
838 ///
839 /// \param[out] CandidateList Filled with outlining candidates for the module.
840 /// \param[out] FunctionList Filled with functions corresponding to each type
841 /// of \p Candidate.
842 /// \param ST The suffix tree for the module.
843 /// \param TII TargetInstrInfo for the module.
844 ///
845 /// \returns The length of the longest candidate found. 0 if there are none.
846 unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
847 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +0000848 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquettec984e212017-03-13 18:39:33 +0000849 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000850
851 /// \brief Remove any overlapping candidates that weren't handled by the
852 /// suffix tree's pruning method.
853 ///
854 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
855 /// If a short candidate is chosen for outlining, then a longer candidate
856 /// which has that short candidate as a suffix is chosen, the tree's pruning
857 /// method will not find it. Thus, we need to prune before outlining as well.
858 ///
859 /// \param[in,out] CandidateList A list of outlining candidates.
860 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000861 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000862 /// \param MaxCandidateLen The length of the longest candidate.
863 /// \param TII TargetInstrInfo for the module.
864 void pruneOverlaps(std::vector<Candidate> &CandidateList,
865 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000866 InstructionMapper &Mapper, unsigned MaxCandidateLen,
867 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000868
869 /// Construct a suffix tree on the instructions in \p M and outline repeated
870 /// strings from that tree.
871 bool runOnModule(Module &M) override;
872};
873
874} // Anonymous namespace.
875
876char MachineOutliner::ID = 0;
877
878namespace llvm {
Jessica Paquette13593842017-10-07 00:16:34 +0000879ModulePass *createMachineOutlinerPass(bool OutlineFromLinkOnceODRs) {
880 return new MachineOutliner(OutlineFromLinkOnceODRs);
881}
882
Jessica Paquette78681be2017-07-27 23:24:43 +0000883} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000884
Jessica Paquette78681be2017-07-27 23:24:43 +0000885INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
886 false)
887
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000888unsigned
Jessica Paquette78681be2017-07-27 23:24:43 +0000889MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
890 InstructionMapper &Mapper,
891 std::vector<Candidate> &CandidateList,
892 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000893 CandidateList.clear();
894 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000895 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +0000896
897 // FIXME: Visit internal nodes instead of leaves.
898 for (SuffixTreeNode *Leaf : ST.LeafVector) {
899 assert(Leaf && "Leaves in LeafVector cannot be null!");
900 if (!Leaf->IsInTree)
901 continue;
902
903 assert(Leaf->Parent && "All leaves must have parents!");
904 SuffixTreeNode &Parent = *(Leaf->Parent);
905
906 // If it doesn't appear enough, or we already outlined from it, skip it.
907 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
908 continue;
909
Jessica Paquette809d7082017-07-28 03:21:58 +0000910 // Figure out if this candidate is beneficial.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000911 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
Jessica Paquette95c11072017-08-14 22:57:41 +0000912
913 // Too short to be beneficial; skip it.
914 // FIXME: This isn't necessarily true for, say, X86. If we factor in
915 // instruction lengths we need more information than this.
916 if (StringLen < 2)
917 continue;
918
Jessica Paquetted87f5442017-07-29 02:55:46 +0000919 // If this is a beneficial class of candidate, then every one is stored in
920 // this vector.
921 std::vector<Candidate> CandidatesForRepeatedSeq;
922
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000923 // Describes the start and end point of each candidate. This allows the
924 // target to infer some information about each occurrence of each repeated
925 // sequence.
Jessica Paquetted87f5442017-07-29 02:55:46 +0000926 // FIXME: CandidatesForRepeatedSeq and this should be combined.
927 std::vector<
928 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000929 RepeatedSequenceLocs;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000930
Jessica Paquette809d7082017-07-28 03:21:58 +0000931 // Figure out the call overhead for each instance of the sequence.
932 for (auto &ChildPair : Parent.Children) {
933 SuffixTreeNode *M = ChildPair.second;
Jessica Paquette78681be2017-07-27 23:24:43 +0000934
Jessica Paquette809d7082017-07-28 03:21:58 +0000935 if (M && M->IsInTree && M->isLeaf()) {
936 // Each sequence is over [StartIt, EndIt].
937 MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx];
938 MachineBasicBlock::iterator EndIt =
939 Mapper.InstrList[M->SuffixIdx + StringLen - 1];
Jessica Paquetted87f5442017-07-29 02:55:46 +0000940
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000941 CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen,
942 FunctionList.size());
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000943 RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
Jessica Paquetted87f5442017-07-29 02:55:46 +0000944
945 // Never visit this leaf again.
946 M->IsInTree = false;
Jessica Paquette809d7082017-07-28 03:21:58 +0000947 }
948 }
949
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000950 // We've found something we might want to outline.
951 // Create an OutlinedFunction to store it and check if it'd be beneficial
952 // to outline.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000953 TargetInstrInfo::MachineOutlinerInfo MInfo =
954 TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000955 std::vector<unsigned> Seq;
956 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
957 Seq.push_back(ST.Str[i]);
958 OutlinedFunction OF(FunctionList.size(), Parent.OccurrenceCount, Seq,
959 MInfo);
960 unsigned Benefit = OF.getBenefit();
Jessica Paquette809d7082017-07-28 03:21:58 +0000961
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000962 // Is it better to outline this candidate than not?
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000963 if (Benefit < 1) {
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000964 // Outlining this candidate would take more instructions than not
965 // outlining.
966 // Emit a remark explaining why we didn't outline this candidate.
967 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000968 RepeatedSequenceLocs[0];
Vivek Pandya95906582017-10-11 17:12:59 +0000969 MachineOptimizationRemarkEmitter MORE(
970 *(C.first->getParent()->getParent()), nullptr);
971 MORE.emit([&]() {
972 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
973 C.first->getDebugLoc(),
974 C.first->getParent());
975 R << "Did not outline " << NV("Length", StringLen) << " instructions"
976 << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
977 << " locations."
978 << " Instructions from outlining all occurrences ("
979 << NV("OutliningCost", OF.getOutliningCost()) << ")"
980 << " >= Unoutlined instruction count ("
Jessica Paquette85af63d2017-10-17 19:03:23 +0000981 << NV("NotOutliningCost", StringLen * OF.getOccurrenceCount()) << ")"
Vivek Pandya95906582017-10-11 17:12:59 +0000982 << " (Also found at: ";
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000983
Vivek Pandya95906582017-10-11 17:12:59 +0000984 // Tell the user the other places the candidate was found.
985 for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
986 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
987 RepeatedSequenceLocs[i].first->getDebugLoc());
988 if (i != e - 1)
989 R << ", ";
990 }
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000991
Vivek Pandya95906582017-10-11 17:12:59 +0000992 R << ")";
993 return R;
994 });
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000995
996 // Move to the next candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +0000997 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000998 }
Jessica Paquette78681be2017-07-27 23:24:43 +0000999
1000 if (StringLen > MaxLen)
1001 MaxLen = StringLen;
1002
Jessica Paquetted87f5442017-07-29 02:55:46 +00001003 // At this point, the candidate class is seen as beneficial. Set their
1004 // benefit values and save them in the candidate list.
1005 for (Candidate &C : CandidatesForRepeatedSeq) {
1006 C.Benefit = Benefit;
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001007 C.MInfo = MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +00001008 CandidateList.push_back(C);
Jessica Paquette78681be2017-07-27 23:24:43 +00001009 }
1010
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001011 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001012
1013 // Move to the next function.
Jessica Paquette78681be2017-07-27 23:24:43 +00001014 Parent.IsInTree = false;
1015 }
1016
1017 return MaxLen;
1018}
Jessica Paquette596f4832017-03-06 21:31:18 +00001019
1020void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
1021 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +00001022 InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +00001023 unsigned MaxCandidateLen,
1024 const TargetInstrInfo &TII) {
Jessica Paquette91999162017-09-28 23:39:36 +00001025
1026 // Return true if this candidate became unbeneficial for outlining in a
1027 // previous step.
1028 auto ShouldSkipCandidate = [&FunctionList](Candidate &C) {
1029
1030 // Check if the candidate was removed in a previous step.
1031 if (!C.InCandidateList)
1032 return true;
1033
Jessica Paquette85af63d2017-10-17 19:03:23 +00001034 // C must be alive. Check if we should remove it.
Jessica Paquette91999162017-09-28 23:39:36 +00001035 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1036
Jessica Paquette85af63d2017-10-17 19:03:23 +00001037 if (F.getBenefit() < 1) {
1038 F.decrement();
Jessica Paquette91999162017-09-28 23:39:36 +00001039 C.InCandidateList = false;
1040 return true;
1041 }
1042
1043 // C is in the list, and F is still beneficial.
1044 return false;
1045 };
1046
1047 // Remove C from the candidate space, and update its OutlinedFunction.
1048 auto Prune = [&FunctionList](Candidate &C) {
1049
1050 // Get the OutlinedFunction associated with this Candidate.
1051 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1052
1053 // Update C's associated function's occurrence count.
Jessica Paquette85af63d2017-10-17 19:03:23 +00001054 F.decrement();
Jessica Paquette91999162017-09-28 23:39:36 +00001055
Jessica Paquette91999162017-09-28 23:39:36 +00001056 // Remove C from the CandidateList.
1057 C.InCandidateList = false;
1058
1059 DEBUG(dbgs() << "- Removed a Candidate \n";
Jessica Paquette85af63d2017-10-17 19:03:23 +00001060 dbgs() << "--- Num fns left for candidate: " << F.getOccurrenceCount()
Jessica Paquette91999162017-09-28 23:39:36 +00001061 << "\n";
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001062 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
Jessica Paquette91999162017-09-28 23:39:36 +00001063 << "\n";);
1064 };
1065
Jessica Paquetteacffa282017-03-23 21:27:38 +00001066 // TODO: Experiment with interval trees or other interval-checking structures
1067 // to lower the time complexity of this function.
1068 // TODO: Can we do better than the simple greedy choice?
1069 // Check for overlaps in the range.
1070 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001071 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1072 It++) {
1073 Candidate &C1 = *It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001074
Jessica Paquette91999162017-09-28 23:39:36 +00001075 // If C1 was already pruned, or its function is no longer beneficial for
1076 // outlining, move to the next candidate.
1077 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001078 continue;
1079
Jessica Paquette596f4832017-03-06 21:31:18 +00001080 // The minimum start index of any candidate that could overlap with this
1081 // one.
1082 unsigned FarthestPossibleIdx = 0;
1083
1084 // Either the index is 0, or it's at most MaxCandidateLen indices away.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001085 if (C1.startIdx() > MaxCandidateLen)
1086 FarthestPossibleIdx = C1.startIdx() - MaxCandidateLen;
Jessica Paquette596f4832017-03-06 21:31:18 +00001087
Jessica Paquetteacffa282017-03-23 21:27:38 +00001088 // Compare against the candidates in the list that start at at most
1089 // FarthestPossibleIdx indices away from C1. There are at most
1090 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001091 for (auto Sit = It + 1; Sit != Et; Sit++) {
1092 Candidate &C2 = *Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001093
1094 // Is this candidate too far away to overlap?
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001095 if (C2.startIdx() < FarthestPossibleIdx)
Jessica Paquette596f4832017-03-06 21:31:18 +00001096 break;
1097
Jessica Paquette91999162017-09-28 23:39:36 +00001098 // If C2 was already pruned, or its function is no longer beneficial for
1099 // outlining, move to the next candidate.
1100 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001101 continue;
1102
Jessica Paquette596f4832017-03-06 21:31:18 +00001103 // Do C1 and C2 overlap?
1104 //
1105 // Not overlapping:
1106 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1107 //
1108 // We sorted our candidate list so C2Start <= C1Start. We know that
1109 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1110 // have to check is C2End < C2Start to see if we overlap.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001111 if (C2.endIdx() < C1.startIdx())
Jessica Paquette596f4832017-03-06 21:31:18 +00001112 continue;
1113
Jessica Paquetteacffa282017-03-23 21:27:38 +00001114 // C1 and C2 overlap.
1115 // We need to choose the better of the two.
1116 //
1117 // Approximate this by picking the one which would have saved us the
1118 // most instructions before any pruning.
1119 if (C1.Benefit >= C2.Benefit) {
Jessica Paquette91999162017-09-28 23:39:36 +00001120 Prune(C2);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001121 } else {
Jessica Paquette91999162017-09-28 23:39:36 +00001122 Prune(C1);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001123 // C1 is out, so we don't have to compare it against anyone else.
1124 break;
1125 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001126 }
1127 }
1128}
1129
1130unsigned
1131MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1132 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +00001133 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +00001134 const TargetInstrInfo &TII) {
1135
1136 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001137 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001138
Jessica Paquette78681be2017-07-27 23:24:43 +00001139 MaxCandidateLen =
1140 findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001141
Jessica Paquette596f4832017-03-06 21:31:18 +00001142 // Sort the candidates in decending order. This will simplify the outlining
1143 // process when we have to remove the candidates from the mapping by
1144 // allowing us to cut them out without keeping track of an offset.
1145 std::stable_sort(CandidateList.begin(), CandidateList.end());
1146
1147 return MaxCandidateLen;
1148}
1149
1150MachineFunction *
1151MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001152 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001153
1154 // Create the function name. This should be unique. For now, just hash the
1155 // module name and include it in the function name plus the number of this
1156 // function.
1157 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001158 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001159
1160 // Create the function using an IR-level function.
1161 LLVMContext &C = M.getContext();
1162 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001163 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001164 assert(F && "Function was null!");
1165
1166 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1167 // which gives us better results when we outline from linkonceodr functions.
1168 F->setLinkage(GlobalValue::PrivateLinkage);
1169 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1170
1171 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1172 IRBuilder<> Builder(EntryBB);
1173 Builder.CreateRetVoid();
1174
1175 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001176 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001177 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1178 const TargetSubtargetInfo &STI = MF.getSubtarget();
1179 const TargetInstrInfo &TII = *STI.getInstrInfo();
1180
1181 // Insert the new function into the module.
1182 MF.insert(MF.begin(), &MBB);
1183
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001184 TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001185
1186 // Copy over the instructions for the function using the integer mappings in
1187 // its sequence.
1188 for (unsigned Str : OF.Sequence) {
1189 MachineInstr *NewMI =
1190 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1191 NewMI->dropMemRefs();
1192
1193 // Don't keep debug information for outlined instructions.
1194 // FIXME: This means outlined functions are currently undebuggable.
1195 NewMI->setDebugLoc(DebugLoc());
1196 MBB.insert(MBB.end(), NewMI);
1197 }
1198
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001199 TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001200
1201 return &MF;
1202}
1203
1204bool MachineOutliner::outline(Module &M,
1205 const ArrayRef<Candidate> &CandidateList,
1206 std::vector<OutlinedFunction> &FunctionList,
1207 InstructionMapper &Mapper) {
1208
1209 bool OutlinedSomething = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001210 // Replace the candidates with calls to their respective outlined functions.
1211 for (const Candidate &C : CandidateList) {
1212
1213 // Was the candidate removed during pruneOverlaps?
1214 if (!C.InCandidateList)
1215 continue;
1216
1217 // If not, then look at its OutlinedFunction.
1218 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1219
1220 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquette85af63d2017-10-17 19:03:23 +00001221 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001222 continue;
1223
1224 // If not, then outline it.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001225 assert(C.startIdx() < Mapper.InstrList.size() &&
1226 "Candidate out of bounds!");
1227 MachineBasicBlock *MBB = (*Mapper.InstrList[C.startIdx()]).getParent();
1228 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.startIdx()];
1229 unsigned EndIdx = C.endIdx();
Jessica Paquette596f4832017-03-06 21:31:18 +00001230
1231 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1232 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1233 assert(EndIt != MBB->end() && "EndIt out of bounds!");
1234
1235 EndIt++; // Erase needs one past the end index.
1236
1237 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001238 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001239 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001240 FunctionsCreated++;
1241 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001242
1243 MachineFunction *MF = OF.MF;
1244 const TargetSubtargetInfo &STI = MF->getSubtarget();
1245 const TargetInstrInfo &TII = *STI.getInstrInfo();
1246
1247 // Insert a call to the new function and erase the old sequence.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001248 TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001249 StartIt = Mapper.InstrList[C.startIdx()];
Jessica Paquette596f4832017-03-06 21:31:18 +00001250 MBB->erase(StartIt, EndIt);
1251
1252 OutlinedSomething = true;
1253
1254 // Statistics.
1255 NumOutlined++;
1256 }
1257
Jessica Paquette78681be2017-07-27 23:24:43 +00001258 DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001259
1260 return OutlinedSomething;
1261}
1262
1263bool MachineOutliner::runOnModule(Module &M) {
1264
1265 // Is there anything in the module at all?
1266 if (M.empty())
1267 return false;
1268
1269 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Jessica Paquette78681be2017-07-27 23:24:43 +00001270 const TargetSubtargetInfo &STI =
1271 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
Jessica Paquette596f4832017-03-06 21:31:18 +00001272 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1273 const TargetInstrInfo *TII = STI.getInstrInfo();
1274
1275 InstructionMapper Mapper;
1276
1277 // Build instruction mappings for each function in the module.
1278 for (Function &F : M) {
Matthias Braun7bda1952017-06-06 00:44:35 +00001279 MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001280
1281 // Is the function empty? Safe to outline from?
Jessica Paquette13593842017-10-07 00:16:34 +00001282 if (F.empty() ||
1283 !TII->isFunctionSafeToOutlineFrom(MF, OutlineFromLinkOnceODRs))
Jessica Paquette596f4832017-03-06 21:31:18 +00001284 continue;
1285
1286 // If it is, look at each MachineBasicBlock in the function.
1287 for (MachineBasicBlock &MBB : MF) {
1288
1289 // Is there anything in MBB?
1290 if (MBB.empty())
1291 continue;
1292
1293 // If yes, map it.
1294 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1295 }
1296 }
1297
1298 // Construct a suffix tree, use it to find candidates, and then outline them.
1299 SuffixTree ST(Mapper.UnsignedVec);
1300 std::vector<Candidate> CandidateList;
1301 std::vector<OutlinedFunction> FunctionList;
1302
Jessica Paquetteacffa282017-03-23 21:27:38 +00001303 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001304 unsigned MaxCandidateLen =
Jessica Paquettec984e212017-03-13 18:39:33 +00001305 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001306
Jessica Paquetteacffa282017-03-23 21:27:38 +00001307 // Remove candidates that overlap with other candidates.
Jessica Paquette809d7082017-07-28 03:21:58 +00001308 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001309
1310 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette596f4832017-03-06 21:31:18 +00001311 return outline(M, CandidateList, FunctionList, Mapper);
1312}