blob: ff334a3a310649b90e6f241a565c7de2bdfe7ac8 [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///
18/// This was originally presented at the 2016 LLVM Developers' Meeting in the
19/// talk "Reducing Code Size Using Outlining". For a high-level overview of
20/// how this pass works, the talk is available on YouTube at
21///
22/// https://www.youtube.com/watch?v=yorld-WSOeU
23///
24/// The slides for the talk are available at
25///
26/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
27///
28/// The talk provides an overview of how the outliner finds candidates and
29/// ultimately outlines them. It describes how the main data structure for this
30/// pass, the suffix tree, is queried and purged for candidates. It also gives
31/// a simplified suffix tree construction algorithm for suffix trees based off
32/// of the algorithm actually used here, Ukkonen's algorithm.
33///
34/// For the original RFC for this pass, please see
35///
36/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
37///
38/// For more information on the suffix tree data structure, please see
39/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
40///
41//===----------------------------------------------------------------------===//
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/Twine.h"
45#include "llvm/CodeGen/MachineFrameInfo.h"
46#include "llvm/CodeGen/MachineFunction.h"
47#include "llvm/CodeGen/MachineInstrBuilder.h"
48#include "llvm/CodeGen/MachineModuleInfo.h"
49#include "llvm/CodeGen/Passes.h"
50#include "llvm/IR/IRBuilder.h"
51#include "llvm/Support/Allocator.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetInstrInfo.h"
55#include "llvm/Target/TargetMachine.h"
56#include "llvm/Target/TargetRegisterInfo.h"
57#include "llvm/Target/TargetSubtargetInfo.h"
58#include <functional>
59#include <map>
60#include <sstream>
61#include <tuple>
62#include <vector>
63
64#define DEBUG_TYPE "machine-outliner"
65
66using namespace llvm;
67
68STATISTIC(NumOutlined, "Number of candidates outlined");
69STATISTIC(FunctionsCreated, "Number of functions created");
70
71namespace {
72
Jessica Paquetteacffa282017-03-23 21:27:38 +000073/// \brief An individual sequence of instructions to be replaced with a call to
74/// an outlined function.
75struct Candidate {
76
77 /// Set to false if the candidate overlapped with another candidate.
78 bool InCandidateList = true;
79
80 /// The start index of this \p Candidate.
81 size_t StartIdx;
82
83 /// The number of instructions in this \p Candidate.
84 size_t Len;
85
86 /// The index of this \p Candidate's \p OutlinedFunction in the list of
87 /// \p OutlinedFunctions.
88 size_t FunctionIdx;
89
90 /// \brief The number of instructions that would be saved by outlining every
91 /// candidate of this type.
92 ///
93 /// This is a fixed value which is not updated during the candidate pruning
94 /// process. It is only used for deciding which candidate to keep if two
95 /// candidates overlap. The true benefit is stored in the OutlinedFunction
96 /// for some given candidate.
97 unsigned Benefit = 0;
98
99 Candidate(size_t StartIdx, size_t Len, size_t FunctionIdx)
100 : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
101
102 Candidate() {}
103
104 /// \brief Used to ensure that \p Candidates are outlined in an order that
105 /// preserves the start and end indices of other \p Candidates.
106 bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; }
107};
108
109/// \brief The information necessary to create an outlined function for some
110/// class of candidate.
111struct OutlinedFunction {
112
113 /// The actual outlined function created.
114 /// This is initialized after we go through and create the actual function.
115 MachineFunction *MF = nullptr;
116
117 /// A number assigned to this function which appears at the end of its name.
118 size_t Name;
119
120 /// The number of candidates for this OutlinedFunction.
121 size_t OccurrenceCount = 0;
122
123 /// \brief The sequence of integers corresponding to the instructions in this
124 /// function.
125 std::vector<unsigned> Sequence;
126
127 /// The number of instructions this function would save.
128 unsigned Benefit = 0;
129
130 /// \brief Set to true if candidates for this outlined function should be
131 /// replaced with tail calls to this OutlinedFunction.
132 bool IsTailCall = false;
133
134 OutlinedFunction(size_t Name, size_t OccurrenceCount,
Jessica Paquette78681be2017-07-27 23:24:43 +0000135 const std::vector<unsigned> &Sequence, unsigned Benefit,
136 bool IsTailCall)
Jessica Paquetteacffa282017-03-23 21:27:38 +0000137 : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence),
Jessica Paquette78681be2017-07-27 23:24:43 +0000138 Benefit(Benefit), IsTailCall(IsTailCall) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000139};
140
Jessica Paquette596f4832017-03-06 21:31:18 +0000141/// Represents an undefined index in the suffix tree.
142const size_t EmptyIdx = -1;
143
144/// A node in a suffix tree which represents a substring or suffix.
145///
146/// Each node has either no children or at least two children, with the root
147/// being a exception in the empty tree.
148///
149/// Children are represented as a map between unsigned integers and nodes. If
150/// a node N has a child M on unsigned integer k, then the mapping represented
151/// by N is a proper prefix of the mapping represented by M. Note that this,
152/// although similar to a trie is somewhat different: each node stores a full
153/// substring of the full mapping rather than a single character state.
154///
155/// Each internal node contains a pointer to the internal node representing
156/// the same string, but with the first character chopped off. This is stored
157/// in \p Link. Each leaf node stores the start index of its respective
158/// suffix in \p SuffixIdx.
159struct SuffixTreeNode {
160
161 /// The children of this node.
162 ///
163 /// A child existing on an unsigned integer implies that from the mapping
164 /// represented by the current node, there is a way to reach another
165 /// mapping by tacking that character on the end of the current string.
166 DenseMap<unsigned, SuffixTreeNode *> Children;
167
168 /// A flag set to false if the node has been pruned from the tree.
169 bool IsInTree = true;
170
171 /// The start index of this node's substring in the main string.
172 size_t StartIdx = EmptyIdx;
173
174 /// The end index of this node's substring in the main string.
175 ///
176 /// Every leaf node must have its \p EndIdx incremented at the end of every
177 /// step in the construction algorithm. To avoid having to update O(N)
178 /// nodes individually at the end of every step, the end index is stored
179 /// as a pointer.
180 size_t *EndIdx = nullptr;
181
182 /// For leaves, the start index of the suffix represented by this node.
183 ///
184 /// For all other nodes, this is ignored.
185 size_t SuffixIdx = EmptyIdx;
186
187 /// \brief For internal nodes, a pointer to the internal node representing
188 /// the same sequence with the first character chopped off.
189 ///
190 /// This has two major purposes in the suffix tree. The first is as a
191 /// shortcut in Ukkonen's construction algorithm. One of the things that
192 /// Ukkonen's algorithm does to achieve linear-time construction is
193 /// keep track of which node the next insert should be at. This makes each
194 /// insert O(1), and there are a total of O(N) inserts. The suffix link
195 /// helps with inserting children of internal nodes.
196 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000197 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000198 /// next insertion must be at the node representing S - its first character.
199 /// This is given by the way that we iteratively build the tree in Ukkonen's
200 /// algorithm. The main idea is to look at the suffixes of each prefix in the
201 /// string, starting with the longest suffix of the prefix, and ending with
202 /// the shortest. Therefore, if we keep pointers between such nodes, we can
203 /// move to the next insertion point in O(1) time. If we don't, then we'd
204 /// have to query from the root, which takes O(N) time. This would make the
205 /// construction algorithm O(N^2) rather than O(N).
206 ///
207 /// The suffix link is also used during the tree pruning process to let us
208 /// quickly throw out a bunch of potential overlaps. Say we have a sequence
209 /// S we want to outline. Then each of its suffixes contribute to at least
210 /// one overlapping case. Therefore, we can follow the suffix links
211 /// starting at the node associated with S to the root and "delete" those
212 /// nodes, save for the root. For each candidate, this removes
213 /// O(|candidate|) overlaps from the search space. We don't actually
214 /// completely invalidate these nodes though; doing that is far too
215 /// aggressive. Consider the following pathological string:
216 ///
217 /// 1 2 3 1 2 3 2 3 2 3 2 3 2 3 2 3 2 3
218 ///
219 /// If we, for the sake of example, outlined 1 2 3, then we would throw
220 /// out all instances of 2 3. This isn't desirable. To get around this,
221 /// when we visit a link node, we decrement its occurrence count by the
222 /// number of sequences we outlined in the current step. In the pathological
223 /// example, the 2 3 node would have an occurrence count of 8, while the
224 /// 1 2 3 node would have an occurrence count of 2. Thus, the 2 3 node
225 /// would survive to the next round allowing us to outline the extra
226 /// instances of 2 3.
227 SuffixTreeNode *Link = nullptr;
228
229 /// The parent of this node. Every node except for the root has a parent.
230 SuffixTreeNode *Parent = nullptr;
231
232 /// The number of times this node's string appears in the tree.
233 ///
234 /// This is equal to the number of leaf children of the string. It represents
235 /// the number of suffixes that the node's string is a prefix of.
236 size_t OccurrenceCount = 0;
237
Jessica Paquetteacffa282017-03-23 21:27:38 +0000238 /// The length of the string formed by concatenating the edge labels from the
239 /// root to this node.
240 size_t ConcatLen = 0;
241
Jessica Paquette596f4832017-03-06 21:31:18 +0000242 /// Returns true if this node is a leaf.
243 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
244
245 /// Returns true if this node is the root of its owning \p SuffixTree.
246 bool isRoot() const { return StartIdx == EmptyIdx; }
247
248 /// Return the number of elements in the substring associated with this node.
249 size_t size() const {
250
251 // Is it the root? If so, it's the empty string so return 0.
252 if (isRoot())
253 return 0;
254
255 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
256
257 // Size = the number of elements in the string.
258 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
259 return *EndIdx - StartIdx + 1;
260 }
261
262 SuffixTreeNode(size_t StartIdx, size_t *EndIdx, SuffixTreeNode *Link,
263 SuffixTreeNode *Parent)
264 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
265
266 SuffixTreeNode() {}
267};
268
269/// A data structure for fast substring queries.
270///
271/// Suffix trees represent the suffixes of their input strings in their leaves.
272/// A suffix tree is a type of compressed trie structure where each node
273/// represents an entire substring rather than a single character. Each leaf
274/// of the tree is a suffix.
275///
276/// A suffix tree can be seen as a type of state machine where each state is a
277/// substring of the full string. The tree is structured so that, for a string
278/// of length N, there are exactly N leaves in the tree. This structure allows
279/// us to quickly find repeated substrings of the input string.
280///
281/// In this implementation, a "string" is a vector of unsigned integers.
282/// These integers may result from hashing some data type. A suffix tree can
283/// contain 1 or many strings, which can then be queried as one large string.
284///
285/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
286/// suffix tree construction. Ukkonen's algorithm is explained in more detail
287/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
288/// paper is available at
289///
290/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
291class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000292public:
293 /// Stores each leaf node in the tree.
294 ///
295 /// This is used for finding outlining candidates.
296 std::vector<SuffixTreeNode *> LeafVector;
297
Jessica Paquette596f4832017-03-06 21:31:18 +0000298 /// Each element is an integer representing an instruction in the module.
299 ArrayRef<unsigned> Str;
300
Jessica Paquette78681be2017-07-27 23:24:43 +0000301private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000302 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000303 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000304
305 /// The root of the suffix tree.
306 ///
307 /// The root represents the empty string. It is maintained by the
308 /// \p NodeAllocator like every other node in the tree.
309 SuffixTreeNode *Root = nullptr;
310
Jessica Paquette596f4832017-03-06 21:31:18 +0000311 /// Maintains the end indices of the internal nodes in the tree.
312 ///
313 /// Each internal node is guaranteed to never have its end index change
314 /// during the construction algorithm; however, leaves must be updated at
315 /// every step. Therefore, we need to store leaf end indices by reference
316 /// to avoid updating O(N) leaves at every step of construction. Thus,
317 /// every internal node must be allocated its own end index.
318 BumpPtrAllocator InternalEndIdxAllocator;
319
320 /// The end index of each leaf in the tree.
321 size_t LeafEndIdx = -1;
322
323 /// \brief Helper struct which keeps track of the next insertion point in
324 /// Ukkonen's algorithm.
325 struct ActiveState {
326 /// The next node to insert at.
327 SuffixTreeNode *Node;
328
329 /// The index of the first character in the substring currently being added.
330 size_t Idx = EmptyIdx;
331
332 /// The length of the substring we have to add at the current step.
333 size_t Len = 0;
334 };
335
336 /// \brief The point the next insertion will take place at in the
337 /// construction algorithm.
338 ActiveState Active;
339
340 /// Allocate a leaf node and add it to the tree.
341 ///
342 /// \param Parent The parent of this node.
343 /// \param StartIdx The start index of this node's associated string.
344 /// \param Edge The label on the edge leaving \p Parent to this node.
345 ///
346 /// \returns A pointer to the allocated leaf node.
347 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, size_t StartIdx,
348 unsigned Edge) {
349
350 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
351
Jessica Paquette78681be2017-07-27 23:24:43 +0000352 SuffixTreeNode *N = new (NodeAllocator.Allocate())
353 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000354 Parent.Children[Edge] = N;
355
356 return N;
357 }
358
359 /// Allocate an internal node and add it to the tree.
360 ///
361 /// \param Parent The parent of this node. Only null when allocating the root.
362 /// \param StartIdx The start index of this node's associated string.
363 /// \param EndIdx The end index of this node's associated string.
364 /// \param Edge The label on the edge leaving \p Parent to this node.
365 ///
366 /// \returns A pointer to the allocated internal node.
367 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, size_t StartIdx,
368 size_t EndIdx, unsigned Edge) {
369
370 assert(StartIdx <= EndIdx && "String can't start after it ends!");
371 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000372 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000373
374 size_t *E = new (InternalEndIdxAllocator) size_t(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000375 SuffixTreeNode *N = new (NodeAllocator.Allocate())
376 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000377 if (Parent)
378 Parent->Children[Edge] = N;
379
380 return N;
381 }
382
383 /// \brief Set the suffix indices of the leaves to the start indices of their
384 /// respective suffixes. Also stores each leaf in \p LeafVector at its
385 /// respective suffix index.
386 ///
387 /// \param[in] CurrNode The node currently being visited.
388 /// \param CurrIdx The current index of the string being visited.
389 void setSuffixIndices(SuffixTreeNode &CurrNode, size_t CurrIdx) {
390
391 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
392
Jessica Paquetteacffa282017-03-23 21:27:38 +0000393 // Store the length of the concatenation of all strings from the root to
394 // this node.
395 if (!CurrNode.isRoot()) {
396 if (CurrNode.ConcatLen == 0)
397 CurrNode.ConcatLen = CurrNode.size();
398
399 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000400 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000401 }
402
Jessica Paquette596f4832017-03-06 21:31:18 +0000403 // Traverse the tree depth-first.
404 for (auto &ChildPair : CurrNode.Children) {
405 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000406 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000407 }
408
409 // Is this node a leaf?
410 if (IsLeaf) {
411 // If yes, give it a suffix index and bump its parent's occurrence count.
412 CurrNode.SuffixIdx = Str.size() - CurrIdx;
413 assert(CurrNode.Parent && "CurrNode had no parent!");
414 CurrNode.Parent->OccurrenceCount++;
415
416 // Store the leaf in the leaf vector for pruning later.
417 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
418 }
419 }
420
421 /// \brief Construct the suffix tree for the prefix of the input ending at
422 /// \p EndIdx.
423 ///
424 /// Used to construct the full suffix tree iteratively. At the end of each
425 /// step, the constructed suffix tree is either a valid suffix tree, or a
426 /// suffix tree with implicit suffixes. At the end of the final step, the
427 /// suffix tree is a valid tree.
428 ///
429 /// \param EndIdx The end index of the current prefix in the main string.
430 /// \param SuffixesToAdd The number of suffixes that must be added
431 /// to complete the suffix tree at the current phase.
432 ///
433 /// \returns The number of suffixes that have not been added at the end of
434 /// this step.
435 unsigned extend(size_t EndIdx, size_t SuffixesToAdd) {
436 SuffixTreeNode *NeedsLink = nullptr;
437
438 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000439
Jessica Paquette596f4832017-03-06 21:31:18 +0000440 // Are we waiting to add anything other than just the last character?
441 if (Active.Len == 0) {
442 // If not, then say the active index is the end index.
443 Active.Idx = EndIdx;
444 }
445
446 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
447
448 // The first character in the current substring we're looking at.
449 unsigned FirstChar = Str[Active.Idx];
450
451 // Have we inserted anything starting with FirstChar at the current node?
452 if (Active.Node->Children.count(FirstChar) == 0) {
453 // If not, then we can just insert a leaf and move too the next step.
454 insertLeaf(*Active.Node, EndIdx, FirstChar);
455
456 // The active node is an internal node, and we visited it, so it must
457 // need a link if it doesn't have one.
458 if (NeedsLink) {
459 NeedsLink->Link = Active.Node;
460 NeedsLink = nullptr;
461 }
462 } else {
463 // There's a match with FirstChar, so look for the point in the tree to
464 // insert a new node.
465 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
466
467 size_t SubstringLen = NextNode->size();
468
469 // Is the current suffix we're trying to insert longer than the size of
470 // the child we want to move to?
471 if (Active.Len >= SubstringLen) {
472 // If yes, then consume the characters we've seen and move to the next
473 // node.
474 Active.Idx += SubstringLen;
475 Active.Len -= SubstringLen;
476 Active.Node = NextNode;
477 continue;
478 }
479
480 // Otherwise, the suffix we're trying to insert must be contained in the
481 // next node we want to move to.
482 unsigned LastChar = Str[EndIdx];
483
484 // Is the string we're trying to insert a substring of the next node?
485 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
486 // If yes, then we're done for this step. Remember our insertion point
487 // and move to the next end index. At this point, we have an implicit
488 // suffix tree.
489 if (NeedsLink && !Active.Node->isRoot()) {
490 NeedsLink->Link = Active.Node;
491 NeedsLink = nullptr;
492 }
493
494 Active.Len++;
495 break;
496 }
497
498 // The string we're trying to insert isn't a substring of the next node,
499 // but matches up to a point. Split the node.
500 //
501 // For example, say we ended our search at a node n and we're trying to
502 // insert ABD. Then we'll create a new node s for AB, reduce n to just
503 // representing C, and insert a new leaf node l to represent d. This
504 // allows us to ensure that if n was a leaf, it remains a leaf.
505 //
506 // | ABC ---split---> | AB
507 // n s
508 // C / \ D
509 // n l
510
511 // The node s from the diagram
512 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000513 insertInternalNode(Active.Node, NextNode->StartIdx,
514 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000515
516 // Insert the new node representing the new substring into the tree as
517 // a child of the split node. This is the node l from the diagram.
518 insertLeaf(*SplitNode, EndIdx, LastChar);
519
520 // Make the old node a child of the split node and update its start
521 // index. This is the node n from the diagram.
522 NextNode->StartIdx += Active.Len;
523 NextNode->Parent = SplitNode;
524 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
525
526 // SplitNode is an internal node, update the suffix link.
527 if (NeedsLink)
528 NeedsLink->Link = SplitNode;
529
530 NeedsLink = SplitNode;
531 }
532
533 // We've added something new to the tree, so there's one less suffix to
534 // add.
535 SuffixesToAdd--;
536
537 if (Active.Node->isRoot()) {
538 if (Active.Len > 0) {
539 Active.Len--;
540 Active.Idx = EndIdx - SuffixesToAdd + 1;
541 }
542 } else {
543 // Start the next phase at the next smallest suffix.
544 Active.Node = Active.Node->Link;
545 }
546 }
547
548 return SuffixesToAdd;
549 }
550
Jessica Paquette596f4832017-03-06 21:31:18 +0000551public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000552 /// Construct a suffix tree from a sequence of unsigned integers.
553 ///
554 /// \param Str The string to construct the suffix tree for.
555 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
556 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
557 Root->IsInTree = true;
558 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000559 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000560
561 // Keep track of the number of suffixes we have to add of the current
562 // prefix.
563 size_t SuffixesToAdd = 0;
564 Active.Node = Root;
565
566 // Construct the suffix tree iteratively on each prefix of the string.
567 // PfxEndIdx is the end index of the current prefix.
568 // End is one past the last element in the string.
569 for (size_t PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; PfxEndIdx++) {
570 SuffixesToAdd++;
571 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
572 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
573 }
574
575 // Set the suffix indices of each leaf.
576 assert(Root && "Root node can't be nullptr!");
577 setSuffixIndices(*Root, 0);
578 }
579};
580
Jessica Paquette596f4832017-03-06 21:31:18 +0000581/// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
582struct InstructionMapper {
583
584 /// \brief The next available integer to assign to a \p MachineInstr that
585 /// cannot be outlined.
586 ///
587 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
588 unsigned IllegalInstrNumber = -3;
589
590 /// \brief The next available integer to assign to a \p MachineInstr that can
591 /// be outlined.
592 unsigned LegalInstrNumber = 0;
593
594 /// Correspondence from \p MachineInstrs to unsigned integers.
595 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
596 InstructionIntegerMap;
597
598 /// Corresponcence from unsigned integers to \p MachineInstrs.
599 /// Inverse of \p InstructionIntegerMap.
600 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
601
602 /// The vector of unsigned integers that the module is mapped to.
603 std::vector<unsigned> UnsignedVec;
604
605 /// \brief Stores the location of the instruction associated with the integer
606 /// at index i in \p UnsignedVec for each index i.
607 std::vector<MachineBasicBlock::iterator> InstrList;
608
609 /// \brief Maps \p *It to a legal integer.
610 ///
611 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
612 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
613 ///
614 /// \returns The integer that \p *It was mapped to.
615 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
616
617 // Get the integer for this instruction or give it the current
618 // LegalInstrNumber.
619 InstrList.push_back(It);
620 MachineInstr &MI = *It;
621 bool WasInserted;
622 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000623 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000624 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000625 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000626 unsigned MINumber = ResultIt->second;
627
628 // There was an insertion.
629 if (WasInserted) {
630 LegalInstrNumber++;
631 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
632 }
633
634 UnsignedVec.push_back(MINumber);
635
636 // Make sure we don't overflow or use any integers reserved by the DenseMap.
637 if (LegalInstrNumber >= IllegalInstrNumber)
638 report_fatal_error("Instruction mapping overflow!");
639
Jessica Paquette78681be2017-07-27 23:24:43 +0000640 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
641 "Tried to assign DenseMap tombstone or empty key to instruction.");
642 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
643 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000644
645 return MINumber;
646 }
647
648 /// Maps \p *It to an illegal integer.
649 ///
650 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
651 ///
652 /// \returns The integer that \p *It was mapped to.
653 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
654 unsigned MINumber = IllegalInstrNumber;
655
656 InstrList.push_back(It);
657 UnsignedVec.push_back(IllegalInstrNumber);
658 IllegalInstrNumber--;
659
660 assert(LegalInstrNumber < IllegalInstrNumber &&
661 "Instruction mapping overflow!");
662
Jessica Paquette78681be2017-07-27 23:24:43 +0000663 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
664 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000665
Jessica Paquette78681be2017-07-27 23:24:43 +0000666 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
667 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000668
669 return MINumber;
670 }
671
672 /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
673 /// and appends it to \p UnsignedVec and \p InstrList.
674 ///
675 /// Two instructions are assigned the same integer if they are identical.
676 /// If an instruction is deemed unsafe to outline, then it will be assigned an
677 /// unique integer. The resulting mapping is placed into a suffix tree and
678 /// queried for candidates.
679 ///
680 /// \param MBB The \p MachineBasicBlock to be translated into integers.
681 /// \param TRI \p TargetRegisterInfo for the module.
682 /// \param TII \p TargetInstrInfo for the module.
683 void convertToUnsignedVec(MachineBasicBlock &MBB,
684 const TargetRegisterInfo &TRI,
685 const TargetInstrInfo &TII) {
686 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
687 It++) {
688
689 // Keep track of where this instruction is in the module.
Jessica Paquette78681be2017-07-27 23:24:43 +0000690 switch (TII.getOutliningType(*It)) {
691 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
692 mapToIllegalUnsigned(It);
693 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000694
Jessica Paquette78681be2017-07-27 23:24:43 +0000695 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
696 mapToLegalUnsigned(It);
697 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000698
Jessica Paquette78681be2017-07-27 23:24:43 +0000699 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
700 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000701 }
702 }
703
704 // After we're done every insertion, uniquely terminate this part of the
705 // "string". This makes sure we won't match across basic block or function
706 // boundaries since the "end" is encoded uniquely and thus appears in no
707 // repeated substring.
708 InstrList.push_back(MBB.end());
709 UnsignedVec.push_back(IllegalInstrNumber);
710 IllegalInstrNumber--;
711 }
712
713 InstructionMapper() {
714 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
715 // changed.
716 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000717 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000718 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000719 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000720 }
721};
722
723/// \brief An interprocedural pass which finds repeated sequences of
724/// instructions and replaces them with calls to functions.
725///
726/// Each instruction is mapped to an unsigned integer and placed in a string.
727/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
728/// is then repeatedly queried for repeated sequences of instructions. Each
729/// non-overlapping repeated sequence is then placed in its own
730/// \p MachineFunction and each instance is then replaced with a call to that
731/// function.
732struct MachineOutliner : public ModulePass {
733
734 static char ID;
735
736 StringRef getPassName() const override { return "Machine Outliner"; }
737
738 void getAnalysisUsage(AnalysisUsage &AU) const override {
739 AU.addRequired<MachineModuleInfo>();
740 AU.addPreserved<MachineModuleInfo>();
741 AU.setPreservesAll();
742 ModulePass::getAnalysisUsage(AU);
743 }
744
745 MachineOutliner() : ModulePass(ID) {
746 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
747 }
748
Jessica Paquette78681be2017-07-27 23:24:43 +0000749 /// Find all repeated substrings that satisfy the outlining cost model.
750 ///
751 /// If a substring appears at least twice, then it must be represented by
752 /// an internal node which appears in at least two suffixes. Each suffix is
753 /// represented by a leaf node. To do this, we visit each internal node in
754 /// the tree, using the leaf children of each internal node. If an internal
755 /// node represents a beneficial substring, then we use each of its leaf
756 /// children to find the locations of its substring.
757 ///
758 /// \param ST A suffix tree to query.
759 /// \param TII TargetInstrInfo for the target.
760 /// \param Mapper Contains outlining mapping information.
761 /// \param[out] CandidateList Filled with candidates representing each
762 /// beneficial substring.
763 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
764 /// type of candidate.
765 ///
766 /// \returns The length of the longest candidate found.
767 size_t findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
768 InstructionMapper &Mapper,
769 std::vector<Candidate> &CandidateList,
770 std::vector<OutlinedFunction> &FunctionList);
771
Jessica Paquette596f4832017-03-06 21:31:18 +0000772 /// \brief Replace the sequences of instructions represented by the
773 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
774 /// described in \p FunctionList.
775 ///
776 /// \param M The module we are outlining from.
777 /// \param CandidateList A list of candidates to be outlined.
778 /// \param FunctionList A list of functions to be inserted into the module.
779 /// \param Mapper Contains the instruction mappings for the module.
780 bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
781 std::vector<OutlinedFunction> &FunctionList,
782 InstructionMapper &Mapper);
783
784 /// Creates a function for \p OF and inserts it into the module.
785 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
786 InstructionMapper &Mapper);
787
788 /// Find potential outlining candidates and store them in \p CandidateList.
789 ///
790 /// For each type of potential candidate, also build an \p OutlinedFunction
791 /// struct containing the information to build the function for that
792 /// candidate.
793 ///
794 /// \param[out] CandidateList Filled with outlining candidates for the module.
795 /// \param[out] FunctionList Filled with functions corresponding to each type
796 /// of \p Candidate.
797 /// \param ST The suffix tree for the module.
798 /// \param TII TargetInstrInfo for the module.
799 ///
800 /// \returns The length of the longest candidate found. 0 if there are none.
801 unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
802 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +0000803 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquettec984e212017-03-13 18:39:33 +0000804 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000805
806 /// \brief Remove any overlapping candidates that weren't handled by the
807 /// suffix tree's pruning method.
808 ///
809 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
810 /// If a short candidate is chosen for outlining, then a longer candidate
811 /// which has that short candidate as a suffix is chosen, the tree's pruning
812 /// method will not find it. Thus, we need to prune before outlining as well.
813 ///
814 /// \param[in,out] CandidateList A list of outlining candidates.
815 /// \param[in,out] FunctionList A list of functions to be outlined.
816 /// \param MaxCandidateLen The length of the longest candidate.
817 /// \param TII TargetInstrInfo for the module.
818 void pruneOverlaps(std::vector<Candidate> &CandidateList,
819 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +0000820 unsigned MaxCandidateLen, const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000821
822 /// Construct a suffix tree on the instructions in \p M and outline repeated
823 /// strings from that tree.
824 bool runOnModule(Module &M) override;
825};
826
827} // Anonymous namespace.
828
829char MachineOutliner::ID = 0;
830
831namespace llvm {
832ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); }
Jessica Paquette78681be2017-07-27 23:24:43 +0000833} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000834
Jessica Paquette78681be2017-07-27 23:24:43 +0000835INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
836 false)
837
838size_t
839MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
840 InstructionMapper &Mapper,
841 std::vector<Candidate> &CandidateList,
842 std::vector<OutlinedFunction> &FunctionList) {
843
844 CandidateList.clear();
845 FunctionList.clear();
846 size_t FnIdx = 0;
847 size_t MaxLen = 0;
848
849 // FIXME: Visit internal nodes instead of leaves.
850 for (SuffixTreeNode *Leaf : ST.LeafVector) {
851 assert(Leaf && "Leaves in LeafVector cannot be null!");
852 if (!Leaf->IsInTree)
853 continue;
854
855 assert(Leaf->Parent && "All leaves must have parents!");
856 SuffixTreeNode &Parent = *(Leaf->Parent);
857
858 // If it doesn't appear enough, or we already outlined from it, skip it.
859 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
860 continue;
861
862 // How many instructions would outlining this string save?
863 size_t StringLen = Leaf->ConcatLen - Leaf->size();
864 unsigned EndVal = ST.Str[Leaf->SuffixIdx + StringLen - 1];
865
866 // Determine if this is going to be tail called.
867 // FIXME: The target should decide this. The outlining pass shouldn't care
868 // about things like tail calling. It should be representation-agnostic.
869 MachineInstr *LastInstr = Mapper.IntegerInstructionMap[EndVal];
870 assert(LastInstr && "Last instruction in sequence was unmapped!");
871 bool IsTailCall = LastInstr->isTerminator();
872 unsigned Benefit =
873 TII.getOutliningBenefit(StringLen, Parent.OccurrenceCount, IsTailCall);
874
875 // If it's not beneficial, skip it.
876 if (Benefit < 1)
877 continue;
878
879 if (StringLen > MaxLen)
880 MaxLen = StringLen;
881
882 unsigned OccurrenceCount = 0;
883 for (auto &ChildPair : Parent.Children) {
884 SuffixTreeNode *M = ChildPair.second;
885
886 // Is it a leaf? If so, we have an occurrence of this candidate.
887 if (M && M->IsInTree && M->isLeaf()) {
888 OccurrenceCount++;
889 CandidateList.emplace_back(M->SuffixIdx, StringLen, FnIdx);
890 CandidateList.back().Benefit = Benefit;
891 M->IsInTree = false;
892 }
893 }
894
895 // Save the function for the new candidate sequence.
896 std::vector<unsigned> CandidateSequence;
897 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
898 CandidateSequence.push_back(ST.Str[i]);
899
900 FunctionList.emplace_back(FnIdx, OccurrenceCount, CandidateSequence,
901 Benefit, false);
902
903 // Move to the next function.
904 FnIdx++;
905 Parent.IsInTree = false;
906 }
907
908 return MaxLen;
909}
Jessica Paquette596f4832017-03-06 21:31:18 +0000910
911void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
912 std::vector<OutlinedFunction> &FunctionList,
913 unsigned MaxCandidateLen,
914 const TargetInstrInfo &TII) {
Jessica Paquetteacffa282017-03-23 21:27:38 +0000915 // TODO: Experiment with interval trees or other interval-checking structures
916 // to lower the time complexity of this function.
917 // TODO: Can we do better than the simple greedy choice?
918 // Check for overlaps in the range.
919 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +0000920 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
921 It++) {
922 Candidate &C1 = *It;
923 OutlinedFunction &F1 = FunctionList[C1.FunctionIdx];
924
925 // If we removed this candidate, skip it.
926 if (!C1.InCandidateList)
927 continue;
928
Jessica Paquetteacffa282017-03-23 21:27:38 +0000929 // Is it still worth it to outline C1?
930 if (F1.Benefit < 1 || F1.OccurrenceCount < 2) {
931 assert(F1.OccurrenceCount > 0 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000932 "Can't remove OutlinedFunction with no occurrences!");
Jessica Paquetteacffa282017-03-23 21:27:38 +0000933 F1.OccurrenceCount--;
Jessica Paquette596f4832017-03-06 21:31:18 +0000934 C1.InCandidateList = false;
935 continue;
936 }
937
938 // The minimum start index of any candidate that could overlap with this
939 // one.
940 unsigned FarthestPossibleIdx = 0;
941
942 // Either the index is 0, or it's at most MaxCandidateLen indices away.
943 if (C1.StartIdx > MaxCandidateLen)
944 FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen;
945
Jessica Paquetteacffa282017-03-23 21:27:38 +0000946 // Compare against the candidates in the list that start at at most
947 // FarthestPossibleIdx indices away from C1. There are at most
948 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +0000949 for (auto Sit = It + 1; Sit != Et; Sit++) {
950 Candidate &C2 = *Sit;
951 OutlinedFunction &F2 = FunctionList[C2.FunctionIdx];
952
953 // Is this candidate too far away to overlap?
Jessica Paquette596f4832017-03-06 21:31:18 +0000954 if (C2.StartIdx < FarthestPossibleIdx)
955 break;
956
957 // Did we already remove this candidate in a previous step?
958 if (!C2.InCandidateList)
959 continue;
960
961 // Is the function beneficial to outline?
962 if (F2.OccurrenceCount < 2 || F2.Benefit < 1) {
963 // If not, remove this candidate and move to the next one.
Jessica Paquetteacffa282017-03-23 21:27:38 +0000964 assert(F2.OccurrenceCount > 0 &&
965 "Can't remove OutlinedFunction with no occurrences!");
966 F2.OccurrenceCount--;
Jessica Paquette596f4832017-03-06 21:31:18 +0000967 C2.InCandidateList = false;
968 continue;
969 }
970
971 size_t C2End = C2.StartIdx + C2.Len - 1;
972
973 // Do C1 and C2 overlap?
974 //
975 // Not overlapping:
976 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
977 //
978 // We sorted our candidate list so C2Start <= C1Start. We know that
979 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
980 // have to check is C2End < C2Start to see if we overlap.
981 if (C2End < C1.StartIdx)
982 continue;
983
Jessica Paquetteacffa282017-03-23 21:27:38 +0000984 // C1 and C2 overlap.
985 // We need to choose the better of the two.
986 //
987 // Approximate this by picking the one which would have saved us the
988 // most instructions before any pruning.
989 if (C1.Benefit >= C2.Benefit) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000990
Jessica Paquetteacffa282017-03-23 21:27:38 +0000991 // C1 is better, so remove C2 and update C2's OutlinedFunction to
992 // reflect the removal.
993 assert(F2.OccurrenceCount > 0 &&
994 "Can't remove OutlinedFunction with no occurrences!");
995 F2.OccurrenceCount--;
996 F2.Benefit = TII.getOutliningBenefit(F2.Sequence.size(),
Jessica Paquette78681be2017-07-27 23:24:43 +0000997 F2.OccurrenceCount, F2.IsTailCall);
Jessica Paquette596f4832017-03-06 21:31:18 +0000998
Jessica Paquetteacffa282017-03-23 21:27:38 +0000999 C2.InCandidateList = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001000
Jessica Paquette78681be2017-07-27 23:24:43 +00001001 DEBUG(dbgs() << "- Removed C2. \n";
1002 dbgs() << "--- Num fns left for C2: " << F2.OccurrenceCount
1003 << "\n";
1004 dbgs() << "--- C2's benefit: " << F2.Benefit << "\n";);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001005
1006 } else {
1007 // C2 is better, so remove C1 and update C1's OutlinedFunction to
1008 // reflect the removal.
1009 assert(F1.OccurrenceCount > 0 &&
1010 "Can't remove OutlinedFunction with no occurrences!");
1011 F1.OccurrenceCount--;
1012 F1.Benefit = TII.getOutliningBenefit(F1.Sequence.size(),
Jessica Paquette78681be2017-07-27 23:24:43 +00001013 F1.OccurrenceCount, F1.IsTailCall);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001014 C1.InCandidateList = false;
1015
Jessica Paquette78681be2017-07-27 23:24:43 +00001016 DEBUG(dbgs() << "- Removed C1. \n";
1017 dbgs() << "--- Num fns left for C1: " << F1.OccurrenceCount
1018 << "\n";
1019 dbgs() << "--- C1's benefit: " << F1.Benefit << "\n";);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001020
1021 // C1 is out, so we don't have to compare it against anyone else.
1022 break;
1023 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001024 }
1025 }
1026}
1027
1028unsigned
1029MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1030 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +00001031 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +00001032 const TargetInstrInfo &TII) {
1033
1034 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +00001035 size_t MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001036
Jessica Paquette78681be2017-07-27 23:24:43 +00001037 MaxCandidateLen =
1038 findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001039
Jessica Paquetteacffa282017-03-23 21:27:38 +00001040 for (auto &OF : FunctionList)
Jessica Paquette78681be2017-07-27 23:24:43 +00001041 OF.IsTailCall =
1042 Mapper.IntegerInstructionMap[OF.Sequence.back()]->isTerminator();
Jessica Paquette596f4832017-03-06 21:31:18 +00001043
1044 // Sort the candidates in decending order. This will simplify the outlining
1045 // process when we have to remove the candidates from the mapping by
1046 // allowing us to cut them out without keeping track of an offset.
1047 std::stable_sort(CandidateList.begin(), CandidateList.end());
1048
1049 return MaxCandidateLen;
1050}
1051
1052MachineFunction *
1053MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001054 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001055
1056 // Create the function name. This should be unique. For now, just hash the
1057 // module name and include it in the function name plus the number of this
1058 // function.
1059 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001060 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001061
1062 // Create the function using an IR-level function.
1063 LLVMContext &C = M.getContext();
1064 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001065 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001066 assert(F && "Function was null!");
1067
1068 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1069 // which gives us better results when we outline from linkonceodr functions.
1070 F->setLinkage(GlobalValue::PrivateLinkage);
1071 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1072
1073 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1074 IRBuilder<> Builder(EntryBB);
1075 Builder.CreateRetVoid();
1076
1077 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001078 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001079 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1080 const TargetSubtargetInfo &STI = MF.getSubtarget();
1081 const TargetInstrInfo &TII = *STI.getInstrInfo();
1082
1083 // Insert the new function into the module.
1084 MF.insert(MF.begin(), &MBB);
1085
Jessica Paquettec984e212017-03-13 18:39:33 +00001086 TII.insertOutlinerPrologue(MBB, MF, OF.IsTailCall);
Jessica Paquette596f4832017-03-06 21:31:18 +00001087
1088 // Copy over the instructions for the function using the integer mappings in
1089 // its sequence.
1090 for (unsigned Str : OF.Sequence) {
1091 MachineInstr *NewMI =
1092 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1093 NewMI->dropMemRefs();
1094
1095 // Don't keep debug information for outlined instructions.
1096 // FIXME: This means outlined functions are currently undebuggable.
1097 NewMI->setDebugLoc(DebugLoc());
1098 MBB.insert(MBB.end(), NewMI);
1099 }
1100
Jessica Paquettec984e212017-03-13 18:39:33 +00001101 TII.insertOutlinerEpilogue(MBB, MF, OF.IsTailCall);
Jessica Paquette596f4832017-03-06 21:31:18 +00001102
1103 return &MF;
1104}
1105
1106bool MachineOutliner::outline(Module &M,
1107 const ArrayRef<Candidate> &CandidateList,
1108 std::vector<OutlinedFunction> &FunctionList,
1109 InstructionMapper &Mapper) {
1110
1111 bool OutlinedSomething = false;
1112
1113 // Replace the candidates with calls to their respective outlined functions.
1114 for (const Candidate &C : CandidateList) {
1115
1116 // Was the candidate removed during pruneOverlaps?
1117 if (!C.InCandidateList)
1118 continue;
1119
1120 // If not, then look at its OutlinedFunction.
1121 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1122
1123 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
1124 if (OF.OccurrenceCount < 2 || OF.Benefit < 1)
1125 continue;
1126
1127 // If not, then outline it.
1128 assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1129 MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent();
1130 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx];
1131 unsigned EndIdx = C.StartIdx + C.Len - 1;
1132
1133 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1134 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1135 assert(EndIt != MBB->end() && "EndIt out of bounds!");
1136
1137 EndIt++; // Erase needs one past the end index.
1138
1139 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001140 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001141 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001142 FunctionsCreated++;
1143 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001144
1145 MachineFunction *MF = OF.MF;
1146 const TargetSubtargetInfo &STI = MF->getSubtarget();
1147 const TargetInstrInfo &TII = *STI.getInstrInfo();
1148
1149 // Insert a call to the new function and erase the old sequence.
Jessica Paquettec984e212017-03-13 18:39:33 +00001150 TII.insertOutlinedCall(M, *MBB, StartIt, *MF, OF.IsTailCall);
Jessica Paquette596f4832017-03-06 21:31:18 +00001151 StartIt = Mapper.InstrList[C.StartIdx];
1152 MBB->erase(StartIt, EndIt);
1153
1154 OutlinedSomething = true;
1155
1156 // Statistics.
1157 NumOutlined++;
1158 }
1159
Jessica Paquette78681be2017-07-27 23:24:43 +00001160 DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001161
1162 return OutlinedSomething;
1163}
1164
1165bool MachineOutliner::runOnModule(Module &M) {
1166
1167 // Is there anything in the module at all?
1168 if (M.empty())
1169 return false;
1170
1171 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Jessica Paquette78681be2017-07-27 23:24:43 +00001172 const TargetSubtargetInfo &STI =
1173 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
Jessica Paquette596f4832017-03-06 21:31:18 +00001174 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1175 const TargetInstrInfo *TII = STI.getInstrInfo();
1176
1177 InstructionMapper Mapper;
1178
1179 // Build instruction mappings for each function in the module.
1180 for (Function &F : M) {
Matthias Braun7bda1952017-06-06 00:44:35 +00001181 MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001182
1183 // Is the function empty? Safe to outline from?
1184 if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF))
1185 continue;
1186
1187 // If it is, look at each MachineBasicBlock in the function.
1188 for (MachineBasicBlock &MBB : MF) {
1189
1190 // Is there anything in MBB?
1191 if (MBB.empty())
1192 continue;
1193
1194 // If yes, map it.
1195 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1196 }
1197 }
1198
1199 // Construct a suffix tree, use it to find candidates, and then outline them.
1200 SuffixTree ST(Mapper.UnsignedVec);
1201 std::vector<Candidate> CandidateList;
1202 std::vector<OutlinedFunction> FunctionList;
1203
Jessica Paquetteacffa282017-03-23 21:27:38 +00001204 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001205 unsigned MaxCandidateLen =
Jessica Paquettec984e212017-03-13 18:39:33 +00001206 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001207
Jessica Paquetteacffa282017-03-23 21:27:38 +00001208 // Remove candidates that overlap with other candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001209 pruneOverlaps(CandidateList, FunctionList, MaxCandidateLen, *TII);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001210
1211 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette596f4832017-03-06 21:31:18 +00001212 return outline(M, CandidateList, FunctionList, Mapper);
1213}