blob: 8e6e0b12409eafe034e0d63842aaea2e80012f30 [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 {
95
96 /// Set to false if the candidate overlapped with another candidate.
97 bool InCandidateList = true;
98
99 /// The start index of this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000100 unsigned StartIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000101
102 /// The number of instructions in this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000103 unsigned Len;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000104
105 /// The index of this \p Candidate's \p OutlinedFunction in the list of
106 /// \p OutlinedFunctions.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000107 unsigned FunctionIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000108
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000109 /// Contains all target-specific information for this \p Candidate.
110 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000111
Jessica Paquetteacffa282017-03-23 21:27:38 +0000112 /// \brief The number of instructions that would be saved by outlining every
113 /// candidate of this type.
114 ///
115 /// This is a fixed value which is not updated during the candidate pruning
116 /// process. It is only used for deciding which candidate to keep if two
117 /// candidates overlap. The true benefit is stored in the OutlinedFunction
118 /// for some given candidate.
119 unsigned Benefit = 0;
120
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000121 Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx)
122 : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000123
124 Candidate() {}
125
126 /// \brief Used to ensure that \p Candidates are outlined in an order that
127 /// preserves the start and end indices of other \p Candidates.
128 bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; }
129};
130
131/// \brief The information necessary to create an outlined function for some
132/// class of candidate.
133struct OutlinedFunction {
134
135 /// The actual outlined function created.
136 /// This is initialized after we go through and create the actual function.
137 MachineFunction *MF = nullptr;
138
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000139 /// A number assigned to this function which appears at the end of its name.
140 unsigned Name;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000141
142 /// The number of candidates for this OutlinedFunction.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000143 unsigned OccurrenceCount = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000144
145 /// \brief The sequence of integers corresponding to the instructions in this
146 /// function.
147 std::vector<unsigned> Sequence;
148
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000149 /// Contains all target-specific information for this \p OutlinedFunction.
150 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000151
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000152 /// \brief Return the number of instructions it would take to outline this
153 /// function.
154 unsigned getOutliningCost() {
155 return (OccurrenceCount * MInfo.CallOverhead) + Sequence.size() +
156 MInfo.FrameOverhead;
157 }
158
159 /// \brief Return the number of instructions that would be saved by outlining
160 /// this function.
161 unsigned getBenefit() {
162 unsigned NotOutlinedCost = OccurrenceCount * Sequence.size();
163 unsigned OutlinedCost = getOutliningCost();
164 return (NotOutlinedCost < OutlinedCost) ? 0
165 : NotOutlinedCost - OutlinedCost;
166 }
167
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000168 OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000169 const std::vector<unsigned> &Sequence,
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000170 TargetInstrInfo::MachineOutlinerInfo &MInfo)
Jessica Paquetteacffa282017-03-23 21:27:38 +0000171 : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence),
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000172 MInfo(MInfo) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000173};
174
Jessica Paquette596f4832017-03-06 21:31:18 +0000175/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000176const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000177
178/// A node in a suffix tree which represents a substring or suffix.
179///
180/// Each node has either no children or at least two children, with the root
181/// being a exception in the empty tree.
182///
183/// Children are represented as a map between unsigned integers and nodes. If
184/// a node N has a child M on unsigned integer k, then the mapping represented
185/// by N is a proper prefix of the mapping represented by M. Note that this,
186/// although similar to a trie is somewhat different: each node stores a full
187/// substring of the full mapping rather than a single character state.
188///
189/// Each internal node contains a pointer to the internal node representing
190/// the same string, but with the first character chopped off. This is stored
191/// in \p Link. Each leaf node stores the start index of its respective
192/// suffix in \p SuffixIdx.
193struct SuffixTreeNode {
194
195 /// The children of this node.
196 ///
197 /// A child existing on an unsigned integer implies that from the mapping
198 /// represented by the current node, there is a way to reach another
199 /// mapping by tacking that character on the end of the current string.
200 DenseMap<unsigned, SuffixTreeNode *> Children;
201
202 /// A flag set to false if the node has been pruned from the tree.
203 bool IsInTree = true;
204
205 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000206 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000207
208 /// The end index of this node's substring in the main string.
209 ///
210 /// Every leaf node must have its \p EndIdx incremented at the end of every
211 /// step in the construction algorithm. To avoid having to update O(N)
212 /// nodes individually at the end of every step, the end index is stored
213 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000214 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000215
216 /// For leaves, the start index of the suffix represented by this node.
217 ///
218 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000219 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000220
221 /// \brief For internal nodes, a pointer to the internal node representing
222 /// the same sequence with the first character chopped off.
223 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000224 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000225 /// Ukkonen's algorithm does to achieve linear-time construction is
226 /// keep track of which node the next insert should be at. This makes each
227 /// insert O(1), and there are a total of O(N) inserts. The suffix link
228 /// helps with inserting children of internal nodes.
229 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000230 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000231 /// next insertion must be at the node representing S - its first character.
232 /// This is given by the way that we iteratively build the tree in Ukkonen's
233 /// algorithm. The main idea is to look at the suffixes of each prefix in the
234 /// string, starting with the longest suffix of the prefix, and ending with
235 /// the shortest. Therefore, if we keep pointers between such nodes, we can
236 /// move to the next insertion point in O(1) time. If we don't, then we'd
237 /// have to query from the root, which takes O(N) time. This would make the
238 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000239 SuffixTreeNode *Link = nullptr;
240
241 /// The parent of this node. Every node except for the root has a parent.
242 SuffixTreeNode *Parent = nullptr;
243
244 /// The number of times this node's string appears in the tree.
245 ///
246 /// This is equal to the number of leaf children of the string. It represents
247 /// the number of suffixes that the node's string is a prefix of.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000248 unsigned OccurrenceCount = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000249
Jessica Paquetteacffa282017-03-23 21:27:38 +0000250 /// The length of the string formed by concatenating the edge labels from the
251 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000252 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000253
Jessica Paquette596f4832017-03-06 21:31:18 +0000254 /// Returns true if this node is a leaf.
255 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
256
257 /// Returns true if this node is the root of its owning \p SuffixTree.
258 bool isRoot() const { return StartIdx == EmptyIdx; }
259
260 /// Return the number of elements in the substring associated with this node.
261 size_t size() const {
262
263 // Is it the root? If so, it's the empty string so return 0.
264 if (isRoot())
265 return 0;
266
267 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
268
269 // Size = the number of elements in the string.
270 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
271 return *EndIdx - StartIdx + 1;
272 }
273
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000274 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000275 SuffixTreeNode *Parent)
276 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
277
278 SuffixTreeNode() {}
279};
280
281/// A data structure for fast substring queries.
282///
283/// Suffix trees represent the suffixes of their input strings in their leaves.
284/// A suffix tree is a type of compressed trie structure where each node
285/// represents an entire substring rather than a single character. Each leaf
286/// of the tree is a suffix.
287///
288/// A suffix tree can be seen as a type of state machine where each state is a
289/// substring of the full string. The tree is structured so that, for a string
290/// of length N, there are exactly N leaves in the tree. This structure allows
291/// us to quickly find repeated substrings of the input string.
292///
293/// In this implementation, a "string" is a vector of unsigned integers.
294/// These integers may result from hashing some data type. A suffix tree can
295/// contain 1 or many strings, which can then be queried as one large string.
296///
297/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
298/// suffix tree construction. Ukkonen's algorithm is explained in more detail
299/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
300/// paper is available at
301///
302/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
303class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000304public:
305 /// Stores each leaf node in the tree.
306 ///
307 /// This is used for finding outlining candidates.
308 std::vector<SuffixTreeNode *> LeafVector;
309
Jessica Paquette596f4832017-03-06 21:31:18 +0000310 /// Each element is an integer representing an instruction in the module.
311 ArrayRef<unsigned> Str;
312
Jessica Paquette78681be2017-07-27 23:24:43 +0000313private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000314 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000315 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000316
317 /// The root of the suffix tree.
318 ///
319 /// The root represents the empty string. It is maintained by the
320 /// \p NodeAllocator like every other node in the tree.
321 SuffixTreeNode *Root = nullptr;
322
Jessica Paquette596f4832017-03-06 21:31:18 +0000323 /// Maintains the end indices of the internal nodes in the tree.
324 ///
325 /// Each internal node is guaranteed to never have its end index change
326 /// during the construction algorithm; however, leaves must be updated at
327 /// every step. Therefore, we need to store leaf end indices by reference
328 /// to avoid updating O(N) leaves at every step of construction. Thus,
329 /// every internal node must be allocated its own end index.
330 BumpPtrAllocator InternalEndIdxAllocator;
331
332 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000333 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000334
335 /// \brief Helper struct which keeps track of the next insertion point in
336 /// Ukkonen's algorithm.
337 struct ActiveState {
338 /// The next node to insert at.
339 SuffixTreeNode *Node;
340
341 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000342 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000343
344 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000345 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000346 };
347
348 /// \brief The point the next insertion will take place at in the
349 /// construction algorithm.
350 ActiveState Active;
351
352 /// Allocate a leaf node and add it to the tree.
353 ///
354 /// \param Parent The parent of this node.
355 /// \param StartIdx The start index of this node's associated string.
356 /// \param Edge The label on the edge leaving \p Parent to this node.
357 ///
358 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000359 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000360 unsigned Edge) {
361
362 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
363
Jessica Paquette78681be2017-07-27 23:24:43 +0000364 SuffixTreeNode *N = new (NodeAllocator.Allocate())
365 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000366 Parent.Children[Edge] = N;
367
368 return N;
369 }
370
371 /// Allocate an internal node and add it to the tree.
372 ///
373 /// \param Parent The parent of this node. Only null when allocating the root.
374 /// \param StartIdx The start index of this node's associated string.
375 /// \param EndIdx The end index of this node's associated string.
376 /// \param Edge The label on the edge leaving \p Parent to this node.
377 ///
378 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000379 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
380 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000381
382 assert(StartIdx <= EndIdx && "String can't start after it ends!");
383 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000384 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000385
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000386 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000387 SuffixTreeNode *N = new (NodeAllocator.Allocate())
388 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000389 if (Parent)
390 Parent->Children[Edge] = N;
391
392 return N;
393 }
394
395 /// \brief Set the suffix indices of the leaves to the start indices of their
396 /// respective suffixes. Also stores each leaf in \p LeafVector at its
397 /// respective suffix index.
398 ///
399 /// \param[in] CurrNode The node currently being visited.
400 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000401 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000402
403 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
404
Jessica Paquetteacffa282017-03-23 21:27:38 +0000405 // Store the length of the concatenation of all strings from the root to
406 // this node.
407 if (!CurrNode.isRoot()) {
408 if (CurrNode.ConcatLen == 0)
409 CurrNode.ConcatLen = CurrNode.size();
410
411 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000412 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000413 }
414
Jessica Paquette596f4832017-03-06 21:31:18 +0000415 // Traverse the tree depth-first.
416 for (auto &ChildPair : CurrNode.Children) {
417 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000418 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000419 }
420
421 // Is this node a leaf?
422 if (IsLeaf) {
423 // If yes, give it a suffix index and bump its parent's occurrence count.
424 CurrNode.SuffixIdx = Str.size() - CurrIdx;
425 assert(CurrNode.Parent && "CurrNode had no parent!");
426 CurrNode.Parent->OccurrenceCount++;
427
428 // Store the leaf in the leaf vector for pruning later.
429 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
430 }
431 }
432
433 /// \brief Construct the suffix tree for the prefix of the input ending at
434 /// \p EndIdx.
435 ///
436 /// Used to construct the full suffix tree iteratively. At the end of each
437 /// step, the constructed suffix tree is either a valid suffix tree, or a
438 /// suffix tree with implicit suffixes. At the end of the final step, the
439 /// suffix tree is a valid tree.
440 ///
441 /// \param EndIdx The end index of the current prefix in the main string.
442 /// \param SuffixesToAdd The number of suffixes that must be added
443 /// to complete the suffix tree at the current phase.
444 ///
445 /// \returns The number of suffixes that have not been added at the end of
446 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000447 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000448 SuffixTreeNode *NeedsLink = nullptr;
449
450 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000451
Jessica Paquette596f4832017-03-06 21:31:18 +0000452 // Are we waiting to add anything other than just the last character?
453 if (Active.Len == 0) {
454 // If not, then say the active index is the end index.
455 Active.Idx = EndIdx;
456 }
457
458 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
459
460 // The first character in the current substring we're looking at.
461 unsigned FirstChar = Str[Active.Idx];
462
463 // Have we inserted anything starting with FirstChar at the current node?
464 if (Active.Node->Children.count(FirstChar) == 0) {
465 // If not, then we can just insert a leaf and move too the next step.
466 insertLeaf(*Active.Node, EndIdx, FirstChar);
467
468 // The active node is an internal node, and we visited it, so it must
469 // need a link if it doesn't have one.
470 if (NeedsLink) {
471 NeedsLink->Link = Active.Node;
472 NeedsLink = nullptr;
473 }
474 } else {
475 // There's a match with FirstChar, so look for the point in the tree to
476 // insert a new node.
477 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
478
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000479 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000480
481 // Is the current suffix we're trying to insert longer than the size of
482 // the child we want to move to?
483 if (Active.Len >= SubstringLen) {
484 // If yes, then consume the characters we've seen and move to the next
485 // node.
486 Active.Idx += SubstringLen;
487 Active.Len -= SubstringLen;
488 Active.Node = NextNode;
489 continue;
490 }
491
492 // Otherwise, the suffix we're trying to insert must be contained in the
493 // next node we want to move to.
494 unsigned LastChar = Str[EndIdx];
495
496 // Is the string we're trying to insert a substring of the next node?
497 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
498 // If yes, then we're done for this step. Remember our insertion point
499 // and move to the next end index. At this point, we have an implicit
500 // suffix tree.
501 if (NeedsLink && !Active.Node->isRoot()) {
502 NeedsLink->Link = Active.Node;
503 NeedsLink = nullptr;
504 }
505
506 Active.Len++;
507 break;
508 }
509
510 // The string we're trying to insert isn't a substring of the next node,
511 // but matches up to a point. Split the node.
512 //
513 // For example, say we ended our search at a node n and we're trying to
514 // insert ABD. Then we'll create a new node s for AB, reduce n to just
515 // representing C, and insert a new leaf node l to represent d. This
516 // allows us to ensure that if n was a leaf, it remains a leaf.
517 //
518 // | ABC ---split---> | AB
519 // n s
520 // C / \ D
521 // n l
522
523 // The node s from the diagram
524 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000525 insertInternalNode(Active.Node, NextNode->StartIdx,
526 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000527
528 // Insert the new node representing the new substring into the tree as
529 // a child of the split node. This is the node l from the diagram.
530 insertLeaf(*SplitNode, EndIdx, LastChar);
531
532 // Make the old node a child of the split node and update its start
533 // index. This is the node n from the diagram.
534 NextNode->StartIdx += Active.Len;
535 NextNode->Parent = SplitNode;
536 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
537
538 // SplitNode is an internal node, update the suffix link.
539 if (NeedsLink)
540 NeedsLink->Link = SplitNode;
541
542 NeedsLink = SplitNode;
543 }
544
545 // We've added something new to the tree, so there's one less suffix to
546 // add.
547 SuffixesToAdd--;
548
549 if (Active.Node->isRoot()) {
550 if (Active.Len > 0) {
551 Active.Len--;
552 Active.Idx = EndIdx - SuffixesToAdd + 1;
553 }
554 } else {
555 // Start the next phase at the next smallest suffix.
556 Active.Node = Active.Node->Link;
557 }
558 }
559
560 return SuffixesToAdd;
561 }
562
Jessica Paquette596f4832017-03-06 21:31:18 +0000563public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000564 /// Construct a suffix tree from a sequence of unsigned integers.
565 ///
566 /// \param Str The string to construct the suffix tree for.
567 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
568 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
569 Root->IsInTree = true;
570 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000571 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000572
573 // Keep track of the number of suffixes we have to add of the current
574 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000575 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000576 Active.Node = Root;
577
578 // Construct the suffix tree iteratively on each prefix of the string.
579 // PfxEndIdx is the end index of the current prefix.
580 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000581 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
582 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000583 SuffixesToAdd++;
584 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
585 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
586 }
587
588 // Set the suffix indices of each leaf.
589 assert(Root && "Root node can't be nullptr!");
590 setSuffixIndices(*Root, 0);
591 }
592};
593
Jessica Paquette596f4832017-03-06 21:31:18 +0000594/// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
595struct InstructionMapper {
596
597 /// \brief The next available integer to assign to a \p MachineInstr that
598 /// cannot be outlined.
599 ///
600 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
601 unsigned IllegalInstrNumber = -3;
602
603 /// \brief The next available integer to assign to a \p MachineInstr that can
604 /// be outlined.
605 unsigned LegalInstrNumber = 0;
606
607 /// Correspondence from \p MachineInstrs to unsigned integers.
608 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
609 InstructionIntegerMap;
610
611 /// Corresponcence from unsigned integers to \p MachineInstrs.
612 /// Inverse of \p InstructionIntegerMap.
613 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
614
615 /// The vector of unsigned integers that the module is mapped to.
616 std::vector<unsigned> UnsignedVec;
617
618 /// \brief Stores the location of the instruction associated with the integer
619 /// at index i in \p UnsignedVec for each index i.
620 std::vector<MachineBasicBlock::iterator> InstrList;
621
622 /// \brief Maps \p *It to a legal integer.
623 ///
624 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
625 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
626 ///
627 /// \returns The integer that \p *It was mapped to.
628 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
629
630 // Get the integer for this instruction or give it the current
631 // LegalInstrNumber.
632 InstrList.push_back(It);
633 MachineInstr &MI = *It;
634 bool WasInserted;
635 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000636 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000637 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000638 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000639 unsigned MINumber = ResultIt->second;
640
641 // There was an insertion.
642 if (WasInserted) {
643 LegalInstrNumber++;
644 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
645 }
646
647 UnsignedVec.push_back(MINumber);
648
649 // Make sure we don't overflow or use any integers reserved by the DenseMap.
650 if (LegalInstrNumber >= IllegalInstrNumber)
651 report_fatal_error("Instruction mapping overflow!");
652
Jessica Paquette78681be2017-07-27 23:24:43 +0000653 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
654 "Tried to assign DenseMap tombstone or empty key to instruction.");
655 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
656 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000657
658 return MINumber;
659 }
660
661 /// Maps \p *It to an illegal integer.
662 ///
663 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
664 ///
665 /// \returns The integer that \p *It was mapped to.
666 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
667 unsigned MINumber = IllegalInstrNumber;
668
669 InstrList.push_back(It);
670 UnsignedVec.push_back(IllegalInstrNumber);
671 IllegalInstrNumber--;
672
673 assert(LegalInstrNumber < IllegalInstrNumber &&
674 "Instruction mapping overflow!");
675
Jessica Paquette78681be2017-07-27 23:24:43 +0000676 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
677 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000678
Jessica Paquette78681be2017-07-27 23:24:43 +0000679 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
680 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000681
682 return MINumber;
683 }
684
685 /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
686 /// and appends it to \p UnsignedVec and \p InstrList.
687 ///
688 /// Two instructions are assigned the same integer if they are identical.
689 /// If an instruction is deemed unsafe to outline, then it will be assigned an
690 /// unique integer. The resulting mapping is placed into a suffix tree and
691 /// queried for candidates.
692 ///
693 /// \param MBB The \p MachineBasicBlock to be translated into integers.
694 /// \param TRI \p TargetRegisterInfo for the module.
695 /// \param TII \p TargetInstrInfo for the module.
696 void convertToUnsignedVec(MachineBasicBlock &MBB,
697 const TargetRegisterInfo &TRI,
698 const TargetInstrInfo &TII) {
699 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
700 It++) {
701
702 // Keep track of where this instruction is in the module.
Jessica Paquette78681be2017-07-27 23:24:43 +0000703 switch (TII.getOutliningType(*It)) {
704 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
705 mapToIllegalUnsigned(It);
706 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000707
Jessica Paquette78681be2017-07-27 23:24:43 +0000708 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
709 mapToLegalUnsigned(It);
710 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000711
Jessica Paquette78681be2017-07-27 23:24:43 +0000712 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
713 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000714 }
715 }
716
717 // After we're done every insertion, uniquely terminate this part of the
718 // "string". This makes sure we won't match across basic block or function
719 // boundaries since the "end" is encoded uniquely and thus appears in no
720 // repeated substring.
721 InstrList.push_back(MBB.end());
722 UnsignedVec.push_back(IllegalInstrNumber);
723 IllegalInstrNumber--;
724 }
725
726 InstructionMapper() {
727 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
728 // changed.
729 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000730 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000731 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000732 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000733 }
734};
735
736/// \brief An interprocedural pass which finds repeated sequences of
737/// instructions and replaces them with calls to functions.
738///
739/// Each instruction is mapped to an unsigned integer and placed in a string.
740/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
741/// is then repeatedly queried for repeated sequences of instructions. Each
742/// non-overlapping repeated sequence is then placed in its own
743/// \p MachineFunction and each instance is then replaced with a call to that
744/// function.
745struct MachineOutliner : public ModulePass {
746
747 static char ID;
748
Jessica Paquette13593842017-10-07 00:16:34 +0000749 /// \brief Set to true if the outliner should consider functions with
750 /// linkonceodr linkage.
751 bool OutlineFromLinkOnceODRs = false;
752
Jessica Paquette596f4832017-03-06 21:31:18 +0000753 StringRef getPassName() const override { return "Machine Outliner"; }
754
755 void getAnalysisUsage(AnalysisUsage &AU) const override {
756 AU.addRequired<MachineModuleInfo>();
757 AU.addPreserved<MachineModuleInfo>();
758 AU.setPreservesAll();
759 ModulePass::getAnalysisUsage(AU);
760 }
761
Jessica Paquette13593842017-10-07 00:16:34 +0000762 MachineOutliner(bool OutlineFromLinkOnceODRs = false) :
763 ModulePass(ID), OutlineFromLinkOnceODRs(OutlineFromLinkOnceODRs) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000764 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
765 }
766
Jessica Paquette78681be2017-07-27 23:24:43 +0000767 /// Find all repeated substrings that satisfy the outlining cost model.
768 ///
769 /// If a substring appears at least twice, then it must be represented by
770 /// an internal node which appears in at least two suffixes. Each suffix is
771 /// represented by a leaf node. To do this, we visit each internal node in
772 /// the tree, using the leaf children of each internal node. If an internal
773 /// node represents a beneficial substring, then we use each of its leaf
774 /// children to find the locations of its substring.
775 ///
776 /// \param ST A suffix tree to query.
777 /// \param TII TargetInstrInfo for the target.
778 /// \param Mapper Contains outlining mapping information.
779 /// \param[out] CandidateList Filled with candidates representing each
780 /// beneficial substring.
781 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
782 /// type of candidate.
783 ///
784 /// \returns The length of the longest candidate found.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000785 unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
786 InstructionMapper &Mapper,
787 std::vector<Candidate> &CandidateList,
788 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000789
Jessica Paquette596f4832017-03-06 21:31:18 +0000790 /// \brief Replace the sequences of instructions represented by the
791 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
792 /// described in \p FunctionList.
793 ///
794 /// \param M The module we are outlining from.
795 /// \param CandidateList A list of candidates to be outlined.
796 /// \param FunctionList A list of functions to be inserted into the module.
797 /// \param Mapper Contains the instruction mappings for the module.
798 bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
799 std::vector<OutlinedFunction> &FunctionList,
800 InstructionMapper &Mapper);
801
802 /// Creates a function for \p OF and inserts it into the module.
803 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
804 InstructionMapper &Mapper);
805
806 /// Find potential outlining candidates and store them in \p CandidateList.
807 ///
808 /// For each type of potential candidate, also build an \p OutlinedFunction
809 /// struct containing the information to build the function for that
810 /// candidate.
811 ///
812 /// \param[out] CandidateList Filled with outlining candidates for the module.
813 /// \param[out] FunctionList Filled with functions corresponding to each type
814 /// of \p Candidate.
815 /// \param ST The suffix tree for the module.
816 /// \param TII TargetInstrInfo for the module.
817 ///
818 /// \returns The length of the longest candidate found. 0 if there are none.
819 unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
820 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +0000821 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquettec984e212017-03-13 18:39:33 +0000822 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000823
824 /// \brief Remove any overlapping candidates that weren't handled by the
825 /// suffix tree's pruning method.
826 ///
827 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
828 /// If a short candidate is chosen for outlining, then a longer candidate
829 /// which has that short candidate as a suffix is chosen, the tree's pruning
830 /// method will not find it. Thus, we need to prune before outlining as well.
831 ///
832 /// \param[in,out] CandidateList A list of outlining candidates.
833 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000834 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000835 /// \param MaxCandidateLen The length of the longest candidate.
836 /// \param TII TargetInstrInfo for the module.
837 void pruneOverlaps(std::vector<Candidate> &CandidateList,
838 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000839 InstructionMapper &Mapper, unsigned MaxCandidateLen,
840 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000841
842 /// Construct a suffix tree on the instructions in \p M and outline repeated
843 /// strings from that tree.
844 bool runOnModule(Module &M) override;
845};
846
847} // Anonymous namespace.
848
849char MachineOutliner::ID = 0;
850
851namespace llvm {
Jessica Paquette13593842017-10-07 00:16:34 +0000852ModulePass *createMachineOutlinerPass(bool OutlineFromLinkOnceODRs) {
853 return new MachineOutliner(OutlineFromLinkOnceODRs);
854}
855
Jessica Paquette78681be2017-07-27 23:24:43 +0000856} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000857
Jessica Paquette78681be2017-07-27 23:24:43 +0000858INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
859 false)
860
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000861unsigned
Jessica Paquette78681be2017-07-27 23:24:43 +0000862MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
863 InstructionMapper &Mapper,
864 std::vector<Candidate> &CandidateList,
865 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000866 CandidateList.clear();
867 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000868 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +0000869
870 // FIXME: Visit internal nodes instead of leaves.
871 for (SuffixTreeNode *Leaf : ST.LeafVector) {
872 assert(Leaf && "Leaves in LeafVector cannot be null!");
873 if (!Leaf->IsInTree)
874 continue;
875
876 assert(Leaf->Parent && "All leaves must have parents!");
877 SuffixTreeNode &Parent = *(Leaf->Parent);
878
879 // If it doesn't appear enough, or we already outlined from it, skip it.
880 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
881 continue;
882
Jessica Paquette809d7082017-07-28 03:21:58 +0000883 // Figure out if this candidate is beneficial.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000884 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
Jessica Paquette95c11072017-08-14 22:57:41 +0000885
886 // Too short to be beneficial; skip it.
887 // FIXME: This isn't necessarily true for, say, X86. If we factor in
888 // instruction lengths we need more information than this.
889 if (StringLen < 2)
890 continue;
891
Jessica Paquetted87f5442017-07-29 02:55:46 +0000892 // If this is a beneficial class of candidate, then every one is stored in
893 // this vector.
894 std::vector<Candidate> CandidatesForRepeatedSeq;
895
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000896 // Describes the start and end point of each candidate. This allows the
897 // target to infer some information about each occurrence of each repeated
898 // sequence.
Jessica Paquetted87f5442017-07-29 02:55:46 +0000899 // FIXME: CandidatesForRepeatedSeq and this should be combined.
900 std::vector<
901 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000902 RepeatedSequenceLocs;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000903
Jessica Paquette809d7082017-07-28 03:21:58 +0000904 // Figure out the call overhead for each instance of the sequence.
905 for (auto &ChildPair : Parent.Children) {
906 SuffixTreeNode *M = ChildPair.second;
Jessica Paquette78681be2017-07-27 23:24:43 +0000907
Jessica Paquette809d7082017-07-28 03:21:58 +0000908 if (M && M->IsInTree && M->isLeaf()) {
909 // Each sequence is over [StartIt, EndIt].
910 MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx];
911 MachineBasicBlock::iterator EndIt =
912 Mapper.InstrList[M->SuffixIdx + StringLen - 1];
Jessica Paquetted87f5442017-07-29 02:55:46 +0000913
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000914 CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen,
915 FunctionList.size());
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000916 RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
Jessica Paquetted87f5442017-07-29 02:55:46 +0000917
918 // Never visit this leaf again.
919 M->IsInTree = false;
Jessica Paquette809d7082017-07-28 03:21:58 +0000920 }
921 }
922
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000923 // We've found something we might want to outline.
924 // Create an OutlinedFunction to store it and check if it'd be beneficial
925 // to outline.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000926 TargetInstrInfo::MachineOutlinerInfo MInfo =
927 TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000928 std::vector<unsigned> Seq;
929 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
930 Seq.push_back(ST.Str[i]);
931 OutlinedFunction OF(FunctionList.size(), Parent.OccurrenceCount, Seq,
932 MInfo);
933 unsigned Benefit = OF.getBenefit();
Jessica Paquette809d7082017-07-28 03:21:58 +0000934
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000935 // Is it better to outline this candidate than not?
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000936 if (Benefit < 1) {
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000937 // Outlining this candidate would take more instructions than not
938 // outlining.
939 // Emit a remark explaining why we didn't outline this candidate.
940 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000941 RepeatedSequenceLocs[0];
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000942 MachineOptimizationRemarkEmitter MORE(
943 *(C.first->getParent()->getParent()), nullptr);
944 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
945 C.first->getDebugLoc(),
946 C.first->getParent());
947 R << "Did not outline " << NV("Length", StringLen) << " instructions"
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000948 << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000949 << " locations."
950 << " Instructions from outlining all occurrences ("
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000951 << NV("OutliningCost", OF.getOutliningCost()) << ")"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000952 << " >= Unoutlined instruction count ("
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000953 << NV("NotOutliningCost", StringLen * OF.OccurrenceCount) << ")"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000954 << " (Also found at: ";
955
956 // Tell the user the other places the candidate was found.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000957 for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000958 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000959 RepeatedSequenceLocs[i].first->getDebugLoc());
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000960 if (i != e - 1)
961 R << ", ";
962 }
963
964 R << ")";
965 MORE.emit(R);
966
967 // Move to the next candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +0000968 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000969 }
Jessica Paquette78681be2017-07-27 23:24:43 +0000970
971 if (StringLen > MaxLen)
972 MaxLen = StringLen;
973
Jessica Paquetted87f5442017-07-29 02:55:46 +0000974 // At this point, the candidate class is seen as beneficial. Set their
975 // benefit values and save them in the candidate list.
976 for (Candidate &C : CandidatesForRepeatedSeq) {
977 C.Benefit = Benefit;
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000978 C.MInfo = MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000979 CandidateList.push_back(C);
Jessica Paquette78681be2017-07-27 23:24:43 +0000980 }
981
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000982 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +0000983
984 // Move to the next function.
Jessica Paquette78681be2017-07-27 23:24:43 +0000985 Parent.IsInTree = false;
986 }
987
988 return MaxLen;
989}
Jessica Paquette596f4832017-03-06 21:31:18 +0000990
991void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
992 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000993 InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +0000994 unsigned MaxCandidateLen,
995 const TargetInstrInfo &TII) {
Jessica Paquette91999162017-09-28 23:39:36 +0000996
997 // Return true if this candidate became unbeneficial for outlining in a
998 // previous step.
999 auto ShouldSkipCandidate = [&FunctionList](Candidate &C) {
1000
1001 // Check if the candidate was removed in a previous step.
1002 if (!C.InCandidateList)
1003 return true;
1004
1005 // Check if C's associated function is still beneficial after previous
1006 // pruning steps.
1007 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1008
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001009 if (F.OccurrenceCount < 2 || F.getBenefit() < 1) {
Jessica Paquette91999162017-09-28 23:39:36 +00001010 assert(F.OccurrenceCount > 0 &&
1011 "Can't remove OutlinedFunction with no occurrences!");
1012 F.OccurrenceCount--;
1013 C.InCandidateList = false;
1014 return true;
1015 }
1016
1017 // C is in the list, and F is still beneficial.
1018 return false;
1019 };
1020
1021 // Remove C from the candidate space, and update its OutlinedFunction.
1022 auto Prune = [&FunctionList](Candidate &C) {
1023
1024 // Get the OutlinedFunction associated with this Candidate.
1025 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1026
1027 // Update C's associated function's occurrence count.
1028 assert(F.OccurrenceCount > 0 &&
1029 "Can't remove OutlinedFunction with no occurrences!");
1030 F.OccurrenceCount--;
1031
Jessica Paquette91999162017-09-28 23:39:36 +00001032 // Remove C from the CandidateList.
1033 C.InCandidateList = false;
1034
1035 DEBUG(dbgs() << "- Removed a Candidate \n";
1036 dbgs() << "--- Num fns left for candidate: " << F.OccurrenceCount
1037 << "\n";
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001038 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
Jessica Paquette91999162017-09-28 23:39:36 +00001039 << "\n";);
1040 };
1041
Jessica Paquetteacffa282017-03-23 21:27:38 +00001042 // TODO: Experiment with interval trees or other interval-checking structures
1043 // to lower the time complexity of this function.
1044 // TODO: Can we do better than the simple greedy choice?
1045 // Check for overlaps in the range.
1046 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001047 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1048 It++) {
1049 Candidate &C1 = *It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001050
Jessica Paquette91999162017-09-28 23:39:36 +00001051 // If C1 was already pruned, or its function is no longer beneficial for
1052 // outlining, move to the next candidate.
1053 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001054 continue;
1055
Jessica Paquette596f4832017-03-06 21:31:18 +00001056 // The minimum start index of any candidate that could overlap with this
1057 // one.
1058 unsigned FarthestPossibleIdx = 0;
1059
1060 // Either the index is 0, or it's at most MaxCandidateLen indices away.
1061 if (C1.StartIdx > MaxCandidateLen)
1062 FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen;
1063
Jessica Paquetteacffa282017-03-23 21:27:38 +00001064 // Compare against the candidates in the list that start at at most
1065 // FarthestPossibleIdx indices away from C1. There are at most
1066 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001067 for (auto Sit = It + 1; Sit != Et; Sit++) {
1068 Candidate &C2 = *Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001069
1070 // Is this candidate too far away to overlap?
Jessica Paquette596f4832017-03-06 21:31:18 +00001071 if (C2.StartIdx < FarthestPossibleIdx)
1072 break;
1073
Jessica Paquette91999162017-09-28 23:39:36 +00001074 // If C2 was already pruned, or its function is no longer beneficial for
1075 // outlining, move to the next candidate.
1076 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001077 continue;
1078
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001079 unsigned C2End = C2.StartIdx + C2.Len - 1;
Jessica Paquette596f4832017-03-06 21:31:18 +00001080
1081 // Do C1 and C2 overlap?
1082 //
1083 // Not overlapping:
1084 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1085 //
1086 // We sorted our candidate list so C2Start <= C1Start. We know that
1087 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1088 // have to check is C2End < C2Start to see if we overlap.
1089 if (C2End < C1.StartIdx)
1090 continue;
1091
Jessica Paquetteacffa282017-03-23 21:27:38 +00001092 // C1 and C2 overlap.
1093 // We need to choose the better of the two.
1094 //
1095 // Approximate this by picking the one which would have saved us the
1096 // most instructions before any pruning.
1097 if (C1.Benefit >= C2.Benefit) {
Jessica Paquette91999162017-09-28 23:39:36 +00001098 Prune(C2);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001099 } else {
Jessica Paquette91999162017-09-28 23:39:36 +00001100 Prune(C1);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001101 // C1 is out, so we don't have to compare it against anyone else.
1102 break;
1103 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001104 }
1105 }
1106}
1107
1108unsigned
1109MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1110 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +00001111 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +00001112 const TargetInstrInfo &TII) {
1113
1114 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001115 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001116
Jessica Paquette78681be2017-07-27 23:24:43 +00001117 MaxCandidateLen =
1118 findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001119
Jessica Paquette596f4832017-03-06 21:31:18 +00001120 // Sort the candidates in decending order. This will simplify the outlining
1121 // process when we have to remove the candidates from the mapping by
1122 // allowing us to cut them out without keeping track of an offset.
1123 std::stable_sort(CandidateList.begin(), CandidateList.end());
1124
1125 return MaxCandidateLen;
1126}
1127
1128MachineFunction *
1129MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001130 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001131
1132 // Create the function name. This should be unique. For now, just hash the
1133 // module name and include it in the function name plus the number of this
1134 // function.
1135 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001136 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001137
1138 // Create the function using an IR-level function.
1139 LLVMContext &C = M.getContext();
1140 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001141 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001142 assert(F && "Function was null!");
1143
1144 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1145 // which gives us better results when we outline from linkonceodr functions.
1146 F->setLinkage(GlobalValue::PrivateLinkage);
1147 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1148
1149 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1150 IRBuilder<> Builder(EntryBB);
1151 Builder.CreateRetVoid();
1152
1153 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001154 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001155 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1156 const TargetSubtargetInfo &STI = MF.getSubtarget();
1157 const TargetInstrInfo &TII = *STI.getInstrInfo();
1158
1159 // Insert the new function into the module.
1160 MF.insert(MF.begin(), &MBB);
1161
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001162 TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001163
1164 // Copy over the instructions for the function using the integer mappings in
1165 // its sequence.
1166 for (unsigned Str : OF.Sequence) {
1167 MachineInstr *NewMI =
1168 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1169 NewMI->dropMemRefs();
1170
1171 // Don't keep debug information for outlined instructions.
1172 // FIXME: This means outlined functions are currently undebuggable.
1173 NewMI->setDebugLoc(DebugLoc());
1174 MBB.insert(MBB.end(), NewMI);
1175 }
1176
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001177 TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001178
1179 return &MF;
1180}
1181
1182bool MachineOutliner::outline(Module &M,
1183 const ArrayRef<Candidate> &CandidateList,
1184 std::vector<OutlinedFunction> &FunctionList,
1185 InstructionMapper &Mapper) {
1186
1187 bool OutlinedSomething = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001188 // Replace the candidates with calls to their respective outlined functions.
1189 for (const Candidate &C : CandidateList) {
1190
1191 // Was the candidate removed during pruneOverlaps?
1192 if (!C.InCandidateList)
1193 continue;
1194
1195 // If not, then look at its OutlinedFunction.
1196 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1197
1198 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001199 if (OF.OccurrenceCount < 2 || OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001200 continue;
1201
1202 // If not, then outline it.
1203 assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1204 MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent();
1205 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx];
1206 unsigned EndIdx = C.StartIdx + C.Len - 1;
1207
1208 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1209 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1210 assert(EndIt != MBB->end() && "EndIt out of bounds!");
1211
1212 EndIt++; // Erase needs one past the end index.
1213
1214 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001215 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001216 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001217 FunctionsCreated++;
1218 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001219
1220 MachineFunction *MF = OF.MF;
1221 const TargetSubtargetInfo &STI = MF->getSubtarget();
1222 const TargetInstrInfo &TII = *STI.getInstrInfo();
1223
1224 // Insert a call to the new function and erase the old sequence.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001225 TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001226 StartIt = Mapper.InstrList[C.StartIdx];
1227 MBB->erase(StartIt, EndIt);
1228
1229 OutlinedSomething = true;
1230
1231 // Statistics.
1232 NumOutlined++;
1233 }
1234
Jessica Paquette78681be2017-07-27 23:24:43 +00001235 DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001236
1237 return OutlinedSomething;
1238}
1239
1240bool MachineOutliner::runOnModule(Module &M) {
1241
1242 // Is there anything in the module at all?
1243 if (M.empty())
1244 return false;
1245
1246 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Jessica Paquette78681be2017-07-27 23:24:43 +00001247 const TargetSubtargetInfo &STI =
1248 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
Jessica Paquette596f4832017-03-06 21:31:18 +00001249 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1250 const TargetInstrInfo *TII = STI.getInstrInfo();
1251
1252 InstructionMapper Mapper;
1253
1254 // Build instruction mappings for each function in the module.
1255 for (Function &F : M) {
Matthias Braun7bda1952017-06-06 00:44:35 +00001256 MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001257
1258 // Is the function empty? Safe to outline from?
Jessica Paquette13593842017-10-07 00:16:34 +00001259 if (F.empty() ||
1260 !TII->isFunctionSafeToOutlineFrom(MF, OutlineFromLinkOnceODRs))
Jessica Paquette596f4832017-03-06 21:31:18 +00001261 continue;
1262
1263 // If it is, look at each MachineBasicBlock in the function.
1264 for (MachineBasicBlock &MBB : MF) {
1265
1266 // Is there anything in MBB?
1267 if (MBB.empty())
1268 continue;
1269
1270 // If yes, map it.
1271 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1272 }
1273 }
1274
1275 // Construct a suffix tree, use it to find candidates, and then outline them.
1276 SuffixTree ST(Mapper.UnsignedVec);
1277 std::vector<Candidate> CandidateList;
1278 std::vector<OutlinedFunction> FunctionList;
1279
Jessica Paquetteacffa282017-03-23 21:27:38 +00001280 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001281 unsigned MaxCandidateLen =
Jessica Paquettec984e212017-03-13 18:39:33 +00001282 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001283
Jessica Paquetteacffa282017-03-23 21:27:38 +00001284 // Remove candidates that overlap with other candidates.
Jessica Paquette809d7082017-07-28 03:21:58 +00001285 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001286
1287 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette596f4832017-03-06 21:31:18 +00001288 return outline(M, CandidateList, FunctionList, Mapper);
1289}