blob: d1343cbc54cf767747b48053ee7d784684f88abb [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
Jessica Paquette32de26d2018-06-19 21:14:48 +000028/// * buildOutlinedFrame
Jessica Paquette4cf187b2017-09-27 20:47:39 +000029/// * insertOutlinedCall
Jessica Paquette4cf187b2017-09-27 20:47:39 +000030/// * isFunctionSafeToOutlineFrom
31///
32/// in order to make use of the MachineOutliner.
33///
Jessica Paquette596f4832017-03-06 21:31:18 +000034/// This was originally presented at the 2016 LLVM Developers' Meeting in the
35/// talk "Reducing Code Size Using Outlining". For a high-level overview of
36/// how this pass works, the talk is available on YouTube at
37///
38/// https://www.youtube.com/watch?v=yorld-WSOeU
39///
40/// The slides for the talk are available at
41///
42/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
43///
44/// The talk provides an overview of how the outliner finds candidates and
45/// ultimately outlines them. It describes how the main data structure for this
46/// pass, the suffix tree, is queried and purged for candidates. It also gives
47/// a simplified suffix tree construction algorithm for suffix trees based off
48/// of the algorithm actually used here, Ukkonen's algorithm.
49///
50/// For the original RFC for this pass, please see
51///
52/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
53///
54/// For more information on the suffix tree data structure, please see
55/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
56///
57//===----------------------------------------------------------------------===//
Jessica Paquetteaa087322018-06-04 21:14:16 +000058#include "llvm/CodeGen/MachineOutliner.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000059#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/Statistic.h"
61#include "llvm/ADT/Twine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000062#include "llvm/CodeGen/MachineFunction.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000063#include "llvm/CodeGen/MachineModuleInfo.h"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000064#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Geoff Berry82203c42018-01-31 20:15:16 +000065#include "llvm/CodeGen/MachineRegisterInfo.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000066#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000067#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000068#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jessica Paquette729e6862018-01-18 00:00:58 +000069#include "llvm/IR/DIBuilder.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000070#include "llvm/IR/IRBuilder.h"
Jessica Paquettea499c3c2018-01-19 21:21:49 +000071#include "llvm/IR/Mangler.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000072#include "llvm/Support/Allocator.h"
Jessica Paquette1eca23b2018-04-19 22:17:07 +000073#include "llvm/Support/CommandLine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000074#include "llvm/Support/Debug.h"
75#include "llvm/Support/raw_ostream.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000076#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 Paquetteaa087322018-06-04 21:14:16 +000086using namespace outliner;
Jessica Paquette596f4832017-03-06 21:31:18 +000087
88STATISTIC(NumOutlined, "Number of candidates outlined");
89STATISTIC(FunctionsCreated, "Number of functions created");
90
Jessica Paquette1eca23b2018-04-19 22:17:07 +000091// Set to true if the user wants the outliner to run on linkonceodr linkage
92// functions. This is false by default because the linker can dedupe linkonceodr
93// functions. Since the outliner is confined to a single module (modulo LTO),
94// this is off by default. It should, however, be the default behaviour in
95// LTO.
96static cl::opt<bool> EnableLinkOnceODROutlining(
97 "enable-linkonceodr-outlining",
98 cl::Hidden,
99 cl::desc("Enable the machine outliner on linkonceodr functions"),
100 cl::init(false));
101
Jessica Paquette596f4832017-03-06 21:31:18 +0000102namespace {
103
104/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000105const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000106
107/// A node in a suffix tree which represents a substring or suffix.
108///
109/// Each node has either no children or at least two children, with the root
110/// being a exception in the empty tree.
111///
112/// Children are represented as a map between unsigned integers and nodes. If
113/// a node N has a child M on unsigned integer k, then the mapping represented
114/// by N is a proper prefix of the mapping represented by M. Note that this,
115/// although similar to a trie is somewhat different: each node stores a full
116/// substring of the full mapping rather than a single character state.
117///
118/// Each internal node contains a pointer to the internal node representing
119/// the same string, but with the first character chopped off. This is stored
120/// in \p Link. Each leaf node stores the start index of its respective
121/// suffix in \p SuffixIdx.
122struct SuffixTreeNode {
123
124 /// The children of this node.
125 ///
126 /// A child existing on an unsigned integer implies that from the mapping
127 /// represented by the current node, there is a way to reach another
128 /// mapping by tacking that character on the end of the current string.
129 DenseMap<unsigned, SuffixTreeNode *> Children;
130
131 /// A flag set to false if the node has been pruned from the tree.
132 bool IsInTree = true;
133
134 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000135 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000136
137 /// The end index of this node's substring in the main string.
138 ///
139 /// Every leaf node must have its \p EndIdx incremented at the end of every
140 /// step in the construction algorithm. To avoid having to update O(N)
141 /// nodes individually at the end of every step, the end index is stored
142 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000143 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000144
145 /// For leaves, the start index of the suffix represented by this node.
146 ///
147 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000148 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000150 /// For internal nodes, a pointer to the internal node representing
Jessica Paquette596f4832017-03-06 21:31:18 +0000151 /// the same sequence with the first character chopped off.
152 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000153 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000154 /// Ukkonen's algorithm does to achieve linear-time construction is
155 /// keep track of which node the next insert should be at. This makes each
156 /// insert O(1), and there are a total of O(N) inserts. The suffix link
157 /// helps with inserting children of internal nodes.
158 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000159 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000160 /// next insertion must be at the node representing S - its first character.
161 /// This is given by the way that we iteratively build the tree in Ukkonen's
162 /// algorithm. The main idea is to look at the suffixes of each prefix in the
163 /// string, starting with the longest suffix of the prefix, and ending with
164 /// the shortest. Therefore, if we keep pointers between such nodes, we can
165 /// move to the next insertion point in O(1) time. If we don't, then we'd
166 /// have to query from the root, which takes O(N) time. This would make the
167 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000168 SuffixTreeNode *Link = nullptr;
169
170 /// The parent of this node. Every node except for the root has a parent.
171 SuffixTreeNode *Parent = nullptr;
172
173 /// The number of times this node's string appears in the tree.
174 ///
175 /// This is equal to the number of leaf children of the string. It represents
176 /// the number of suffixes that the node's string is a prefix of.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000177 unsigned OccurrenceCount = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000178
Jessica Paquetteacffa282017-03-23 21:27:38 +0000179 /// The length of the string formed by concatenating the edge labels from the
180 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000181 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000182
Jessica Paquette596f4832017-03-06 21:31:18 +0000183 /// Returns true if this node is a leaf.
184 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
185
186 /// Returns true if this node is the root of its owning \p SuffixTree.
187 bool isRoot() const { return StartIdx == EmptyIdx; }
188
189 /// Return the number of elements in the substring associated with this node.
190 size_t size() const {
191
192 // Is it the root? If so, it's the empty string so return 0.
193 if (isRoot())
194 return 0;
195
196 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
197
198 // Size = the number of elements in the string.
199 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
200 return *EndIdx - StartIdx + 1;
201 }
202
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000203 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000204 SuffixTreeNode *Parent)
205 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
206
207 SuffixTreeNode() {}
208};
209
210/// A data structure for fast substring queries.
211///
212/// Suffix trees represent the suffixes of their input strings in their leaves.
213/// A suffix tree is a type of compressed trie structure where each node
214/// represents an entire substring rather than a single character. Each leaf
215/// of the tree is a suffix.
216///
217/// A suffix tree can be seen as a type of state machine where each state is a
218/// substring of the full string. The tree is structured so that, for a string
219/// of length N, there are exactly N leaves in the tree. This structure allows
220/// us to quickly find repeated substrings of the input string.
221///
222/// In this implementation, a "string" is a vector of unsigned integers.
223/// These integers may result from hashing some data type. A suffix tree can
224/// contain 1 or many strings, which can then be queried as one large string.
225///
226/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
227/// suffix tree construction. Ukkonen's algorithm is explained in more detail
228/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
229/// paper is available at
230///
231/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
232class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000233public:
234 /// Stores each leaf node in the tree.
235 ///
236 /// This is used for finding outlining candidates.
237 std::vector<SuffixTreeNode *> LeafVector;
238
Jessica Paquette596f4832017-03-06 21:31:18 +0000239 /// Each element is an integer representing an instruction in the module.
240 ArrayRef<unsigned> Str;
241
Jessica Paquette78681be2017-07-27 23:24:43 +0000242private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000243 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000244 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000245
246 /// The root of the suffix tree.
247 ///
248 /// The root represents the empty string. It is maintained by the
249 /// \p NodeAllocator like every other node in the tree.
250 SuffixTreeNode *Root = nullptr;
251
Jessica Paquette596f4832017-03-06 21:31:18 +0000252 /// Maintains the end indices of the internal nodes in the tree.
253 ///
254 /// Each internal node is guaranteed to never have its end index change
255 /// during the construction algorithm; however, leaves must be updated at
256 /// every step. Therefore, we need to store leaf end indices by reference
257 /// to avoid updating O(N) leaves at every step of construction. Thus,
258 /// every internal node must be allocated its own end index.
259 BumpPtrAllocator InternalEndIdxAllocator;
260
261 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000262 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000264 /// Helper struct which keeps track of the next insertion point in
Jessica Paquette596f4832017-03-06 21:31:18 +0000265 /// Ukkonen's algorithm.
266 struct ActiveState {
267 /// The next node to insert at.
268 SuffixTreeNode *Node;
269
270 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000271 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000272
273 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000274 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000275 };
276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277 /// The point the next insertion will take place at in the
Jessica Paquette596f4832017-03-06 21:31:18 +0000278 /// construction algorithm.
279 ActiveState Active;
280
281 /// Allocate a leaf node and add it to the tree.
282 ///
283 /// \param Parent The parent of this node.
284 /// \param StartIdx The start index of this node's associated string.
285 /// \param Edge The label on the edge leaving \p Parent to this node.
286 ///
287 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000288 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000289 unsigned Edge) {
290
291 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
292
Jessica Paquette78681be2017-07-27 23:24:43 +0000293 SuffixTreeNode *N = new (NodeAllocator.Allocate())
294 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000295 Parent.Children[Edge] = N;
296
297 return N;
298 }
299
300 /// Allocate an internal node and add it to the tree.
301 ///
302 /// \param Parent The parent of this node. Only null when allocating the root.
303 /// \param StartIdx The start index of this node's associated string.
304 /// \param EndIdx The end index of this node's associated string.
305 /// \param Edge The label on the edge leaving \p Parent to this node.
306 ///
307 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000308 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
309 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000310
311 assert(StartIdx <= EndIdx && "String can't start after it ends!");
312 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000313 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000314
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000315 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000316 SuffixTreeNode *N = new (NodeAllocator.Allocate())
317 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000318 if (Parent)
319 Parent->Children[Edge] = N;
320
321 return N;
322 }
323
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000324 /// Set the suffix indices of the leaves to the start indices of their
Jessica Paquette596f4832017-03-06 21:31:18 +0000325 /// respective suffixes. Also stores each leaf in \p LeafVector at its
326 /// respective suffix index.
327 ///
328 /// \param[in] CurrNode The node currently being visited.
329 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000330 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000331
332 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
333
Jessica Paquetteacffa282017-03-23 21:27:38 +0000334 // Store the length of the concatenation of all strings from the root to
335 // this node.
336 if (!CurrNode.isRoot()) {
337 if (CurrNode.ConcatLen == 0)
338 CurrNode.ConcatLen = CurrNode.size();
339
340 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000341 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000342 }
343
Jessica Paquette596f4832017-03-06 21:31:18 +0000344 // Traverse the tree depth-first.
345 for (auto &ChildPair : CurrNode.Children) {
346 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000347 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000348 }
349
350 // Is this node a leaf?
351 if (IsLeaf) {
352 // If yes, give it a suffix index and bump its parent's occurrence count.
353 CurrNode.SuffixIdx = Str.size() - CurrIdx;
354 assert(CurrNode.Parent && "CurrNode had no parent!");
355 CurrNode.Parent->OccurrenceCount++;
356
357 // Store the leaf in the leaf vector for pruning later.
358 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
359 }
360 }
361
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000362 /// Construct the suffix tree for the prefix of the input ending at
Jessica Paquette596f4832017-03-06 21:31:18 +0000363 /// \p EndIdx.
364 ///
365 /// Used to construct the full suffix tree iteratively. At the end of each
366 /// step, the constructed suffix tree is either a valid suffix tree, or a
367 /// suffix tree with implicit suffixes. At the end of the final step, the
368 /// suffix tree is a valid tree.
369 ///
370 /// \param EndIdx The end index of the current prefix in the main string.
371 /// \param SuffixesToAdd The number of suffixes that must be added
372 /// to complete the suffix tree at the current phase.
373 ///
374 /// \returns The number of suffixes that have not been added at the end of
375 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000376 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000377 SuffixTreeNode *NeedsLink = nullptr;
378
379 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000380
Jessica Paquette596f4832017-03-06 21:31:18 +0000381 // Are we waiting to add anything other than just the last character?
382 if (Active.Len == 0) {
383 // If not, then say the active index is the end index.
384 Active.Idx = EndIdx;
385 }
386
387 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
388
389 // The first character in the current substring we're looking at.
390 unsigned FirstChar = Str[Active.Idx];
391
392 // Have we inserted anything starting with FirstChar at the current node?
393 if (Active.Node->Children.count(FirstChar) == 0) {
394 // If not, then we can just insert a leaf and move too the next step.
395 insertLeaf(*Active.Node, EndIdx, FirstChar);
396
397 // The active node is an internal node, and we visited it, so it must
398 // need a link if it doesn't have one.
399 if (NeedsLink) {
400 NeedsLink->Link = Active.Node;
401 NeedsLink = nullptr;
402 }
403 } else {
404 // There's a match with FirstChar, so look for the point in the tree to
405 // insert a new node.
406 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
407
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000408 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000409
410 // Is the current suffix we're trying to insert longer than the size of
411 // the child we want to move to?
412 if (Active.Len >= SubstringLen) {
413 // If yes, then consume the characters we've seen and move to the next
414 // node.
415 Active.Idx += SubstringLen;
416 Active.Len -= SubstringLen;
417 Active.Node = NextNode;
418 continue;
419 }
420
421 // Otherwise, the suffix we're trying to insert must be contained in the
422 // next node we want to move to.
423 unsigned LastChar = Str[EndIdx];
424
425 // Is the string we're trying to insert a substring of the next node?
426 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
427 // If yes, then we're done for this step. Remember our insertion point
428 // and move to the next end index. At this point, we have an implicit
429 // suffix tree.
430 if (NeedsLink && !Active.Node->isRoot()) {
431 NeedsLink->Link = Active.Node;
432 NeedsLink = nullptr;
433 }
434
435 Active.Len++;
436 break;
437 }
438
439 // The string we're trying to insert isn't a substring of the next node,
440 // but matches up to a point. Split the node.
441 //
442 // For example, say we ended our search at a node n and we're trying to
443 // insert ABD. Then we'll create a new node s for AB, reduce n to just
444 // representing C, and insert a new leaf node l to represent d. This
445 // allows us to ensure that if n was a leaf, it remains a leaf.
446 //
447 // | ABC ---split---> | AB
448 // n s
449 // C / \ D
450 // n l
451
452 // The node s from the diagram
453 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000454 insertInternalNode(Active.Node, NextNode->StartIdx,
455 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000456
457 // Insert the new node representing the new substring into the tree as
458 // a child of the split node. This is the node l from the diagram.
459 insertLeaf(*SplitNode, EndIdx, LastChar);
460
461 // Make the old node a child of the split node and update its start
462 // index. This is the node n from the diagram.
463 NextNode->StartIdx += Active.Len;
464 NextNode->Parent = SplitNode;
465 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
466
467 // SplitNode is an internal node, update the suffix link.
468 if (NeedsLink)
469 NeedsLink->Link = SplitNode;
470
471 NeedsLink = SplitNode;
472 }
473
474 // We've added something new to the tree, so there's one less suffix to
475 // add.
476 SuffixesToAdd--;
477
478 if (Active.Node->isRoot()) {
479 if (Active.Len > 0) {
480 Active.Len--;
481 Active.Idx = EndIdx - SuffixesToAdd + 1;
482 }
483 } else {
484 // Start the next phase at the next smallest suffix.
485 Active.Node = Active.Node->Link;
486 }
487 }
488
489 return SuffixesToAdd;
490 }
491
Jessica Paquette596f4832017-03-06 21:31:18 +0000492public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000493 /// Construct a suffix tree from a sequence of unsigned integers.
494 ///
495 /// \param Str The string to construct the suffix tree for.
496 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
497 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
498 Root->IsInTree = true;
499 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000500 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000501
502 // Keep track of the number of suffixes we have to add of the current
503 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000504 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000505 Active.Node = Root;
506
507 // Construct the suffix tree iteratively on each prefix of the string.
508 // PfxEndIdx is the end index of the current prefix.
509 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000510 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
511 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000512 SuffixesToAdd++;
513 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
514 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
515 }
516
517 // Set the suffix indices of each leaf.
518 assert(Root && "Root node can't be nullptr!");
519 setSuffixIndices(*Root, 0);
520 }
521};
522
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000523/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
Jessica Paquette596f4832017-03-06 21:31:18 +0000524struct InstructionMapper {
525
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000526 /// The next available integer to assign to a \p MachineInstr that
Jessica Paquette596f4832017-03-06 21:31:18 +0000527 /// cannot be outlined.
528 ///
529 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
530 unsigned IllegalInstrNumber = -3;
531
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000532 /// The next available integer to assign to a \p MachineInstr that can
Jessica Paquette596f4832017-03-06 21:31:18 +0000533 /// be outlined.
534 unsigned LegalInstrNumber = 0;
535
536 /// Correspondence from \p MachineInstrs to unsigned integers.
537 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
538 InstructionIntegerMap;
539
540 /// Corresponcence from unsigned integers to \p MachineInstrs.
541 /// Inverse of \p InstructionIntegerMap.
542 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
543
544 /// The vector of unsigned integers that the module is mapped to.
545 std::vector<unsigned> UnsignedVec;
546
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000547 /// Stores the location of the instruction associated with the integer
Jessica Paquette596f4832017-03-06 21:31:18 +0000548 /// at index i in \p UnsignedVec for each index i.
549 std::vector<MachineBasicBlock::iterator> InstrList;
550
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000551 /// Maps \p *It to a legal integer.
Jessica Paquette596f4832017-03-06 21:31:18 +0000552 ///
553 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
554 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
555 ///
556 /// \returns The integer that \p *It was mapped to.
557 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
558
559 // Get the integer for this instruction or give it the current
560 // LegalInstrNumber.
561 InstrList.push_back(It);
562 MachineInstr &MI = *It;
563 bool WasInserted;
564 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000565 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000566 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000567 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000568 unsigned MINumber = ResultIt->second;
569
570 // There was an insertion.
571 if (WasInserted) {
572 LegalInstrNumber++;
573 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
574 }
575
576 UnsignedVec.push_back(MINumber);
577
578 // Make sure we don't overflow or use any integers reserved by the DenseMap.
579 if (LegalInstrNumber >= IllegalInstrNumber)
580 report_fatal_error("Instruction mapping overflow!");
581
Jessica Paquette78681be2017-07-27 23:24:43 +0000582 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
583 "Tried to assign DenseMap tombstone or empty key to instruction.");
584 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
585 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000586
587 return MINumber;
588 }
589
590 /// Maps \p *It to an illegal integer.
591 ///
592 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
593 ///
594 /// \returns The integer that \p *It was mapped to.
595 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
596 unsigned MINumber = IllegalInstrNumber;
597
598 InstrList.push_back(It);
599 UnsignedVec.push_back(IllegalInstrNumber);
600 IllegalInstrNumber--;
601
602 assert(LegalInstrNumber < IllegalInstrNumber &&
603 "Instruction mapping overflow!");
604
Jessica Paquette78681be2017-07-27 23:24:43 +0000605 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
606 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000607
Jessica Paquette78681be2017-07-27 23:24:43 +0000608 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
609 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000610
611 return MINumber;
612 }
613
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000614 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
Jessica Paquette596f4832017-03-06 21:31:18 +0000615 /// and appends it to \p UnsignedVec and \p InstrList.
616 ///
617 /// Two instructions are assigned the same integer if they are identical.
618 /// If an instruction is deemed unsafe to outline, then it will be assigned an
619 /// unique integer. The resulting mapping is placed into a suffix tree and
620 /// queried for candidates.
621 ///
622 /// \param MBB The \p MachineBasicBlock to be translated into integers.
Eli Friedmanda080782018-08-01 00:37:20 +0000623 /// \param TII \p TargetInstrInfo for the function.
Jessica Paquette596f4832017-03-06 21:31:18 +0000624 void convertToUnsignedVec(MachineBasicBlock &MBB,
Jessica Paquette596f4832017-03-06 21:31:18 +0000625 const TargetInstrInfo &TII) {
Jessica Paquette3291e732018-01-09 00:26:18 +0000626 unsigned Flags = TII.getMachineOutlinerMBBFlags(MBB);
627
Jessica Paquettebd729882018-09-17 18:40:21 +0000628 // Set to true whenever we map an illegal number.
629 bool AddedIllegalLastTime = false;
Jessica Paquette596f4832017-03-06 21:31:18 +0000630 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
631 It++) {
632
633 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000634 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquetteaa087322018-06-04 21:14:16 +0000635 case InstrType::Illegal:
Jessica Paquettebd729882018-09-17 18:40:21 +0000636 // If we added an illegal number last time, then don't add more of them.
637 // One number is all that is necessary to prevent matches on illegal
638 // instructions.
639 if (AddedIllegalLastTime)
640 break;
641 AddedIllegalLastTime = true;
Jessica Paquette78681be2017-07-27 23:24:43 +0000642 mapToIllegalUnsigned(It);
643 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000644
Jessica Paquetteaa087322018-06-04 21:14:16 +0000645 case InstrType::Legal:
Jessica Paquettebd729882018-09-17 18:40:21 +0000646 AddedIllegalLastTime = false;
Jessica Paquette78681be2017-07-27 23:24:43 +0000647 mapToLegalUnsigned(It);
648 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000649
Jessica Paquetteaa087322018-06-04 21:14:16 +0000650 case InstrType::LegalTerminator:
Eli Friedman042dc9e2018-05-22 19:11:06 +0000651 mapToLegalUnsigned(It);
652 InstrList.push_back(It);
Jessica Paquettebd729882018-09-17 18:40:21 +0000653 AddedIllegalLastTime = true;
Eli Friedman042dc9e2018-05-22 19:11:06 +0000654 UnsignedVec.push_back(IllegalInstrNumber);
655 IllegalInstrNumber--;
656 break;
657
Jessica Paquetteaa087322018-06-04 21:14:16 +0000658 case InstrType::Invisible:
Jessica Paquettebd729882018-09-17 18:40:21 +0000659 AddedIllegalLastTime = false;
Jessica Paquette78681be2017-07-27 23:24:43 +0000660 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000661 }
662 }
663
664 // After we're done every insertion, uniquely terminate this part of the
665 // "string". This makes sure we won't match across basic block or function
666 // boundaries since the "end" is encoded uniquely and thus appears in no
667 // repeated substring.
668 InstrList.push_back(MBB.end());
669 UnsignedVec.push_back(IllegalInstrNumber);
670 IllegalInstrNumber--;
671 }
672
673 InstructionMapper() {
674 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
675 // changed.
676 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000677 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000678 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000679 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000680 }
681};
682
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000683/// An interprocedural pass which finds repeated sequences of
Jessica Paquette596f4832017-03-06 21:31:18 +0000684/// instructions and replaces them with calls to functions.
685///
686/// Each instruction is mapped to an unsigned integer and placed in a string.
687/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
688/// is then repeatedly queried for repeated sequences of instructions. Each
689/// non-overlapping repeated sequence is then placed in its own
690/// \p MachineFunction and each instance is then replaced with a call to that
691/// function.
692struct MachineOutliner : public ModulePass {
693
694 static char ID;
695
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000696 /// Set to true if the outliner should consider functions with
Jessica Paquette13593842017-10-07 00:16:34 +0000697 /// linkonceodr linkage.
698 bool OutlineFromLinkOnceODRs = false;
699
Jessica Paquette8bda1882018-06-30 03:56:03 +0000700 /// Set to true if the outliner should run on all functions in the module
701 /// considered safe for outlining.
702 /// Set to true by default for compatibility with llc's -run-pass option.
703 /// Set when the pass is constructed in TargetPassConfig.
704 bool RunOnAllFunctions = true;
705
Jessica Paquette729e6862018-01-18 00:00:58 +0000706 // Collection of IR functions created by the outliner.
707 std::vector<Function *> CreatedIRFunctions;
708
Jessica Paquette596f4832017-03-06 21:31:18 +0000709 StringRef getPassName() const override { return "Machine Outliner"; }
710
711 void getAnalysisUsage(AnalysisUsage &AU) const override {
712 AU.addRequired<MachineModuleInfo>();
713 AU.addPreserved<MachineModuleInfo>();
714 AU.setPreservesAll();
715 ModulePass::getAnalysisUsage(AU);
716 }
717
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000718 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000719 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
720 }
721
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000722 /// Remark output explaining that not outlining a set of candidates would be
723 /// better than outlining that set.
724 void emitNotOutliningCheaperRemark(
725 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
726 OutlinedFunction &OF);
727
Jessica Paquette58e706a2018-07-24 20:20:45 +0000728 /// Remark output explaining that a function was outlined.
729 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
730
Jessica Paquette78681be2017-07-27 23:24:43 +0000731 /// Find all repeated substrings that satisfy the outlining cost model.
732 ///
733 /// If a substring appears at least twice, then it must be represented by
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000734 /// an internal node which appears in at least two suffixes. Each suffix
735 /// is represented by a leaf node. To do this, we visit each internal node
736 /// in the tree, using the leaf children of each internal node. If an
737 /// internal node represents a beneficial substring, then we use each of
738 /// its leaf children to find the locations of its substring.
Jessica Paquette78681be2017-07-27 23:24:43 +0000739 ///
740 /// \param ST A suffix tree to query.
Jessica Paquette78681be2017-07-27 23:24:43 +0000741 /// \param Mapper Contains outlining mapping information.
742 /// \param[out] CandidateList Filled with candidates representing each
743 /// beneficial substring.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000744 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
745 /// each type of candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +0000746 ///
747 /// \returns The length of the longest candidate found.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000748 unsigned
Eli Friedmanda080782018-08-01 00:37:20 +0000749 findCandidates(SuffixTree &ST,
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000750 InstructionMapper &Mapper,
751 std::vector<std::shared_ptr<Candidate>> &CandidateList,
752 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000753
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000754 /// Replace the sequences of instructions represented by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000755 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
756 /// described in \p FunctionList.
757 ///
758 /// \param M The module we are outlining from.
759 /// \param CandidateList A list of candidates to be outlined.
760 /// \param FunctionList A list of functions to be inserted into the module.
761 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000762 bool outline(Module &M,
763 const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000764 std::vector<OutlinedFunction> &FunctionList,
765 InstructionMapper &Mapper);
766
767 /// Creates a function for \p OF and inserts it into the module.
768 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
769 InstructionMapper &Mapper);
770
771 /// Find potential outlining candidates and store them in \p CandidateList.
772 ///
773 /// For each type of potential candidate, also build an \p OutlinedFunction
774 /// struct containing the information to build the function for that
775 /// candidate.
776 ///
777 /// \param[out] CandidateList Filled with outlining candidates for the module.
778 /// \param[out] FunctionList Filled with functions corresponding to each type
779 /// of \p Candidate.
780 /// \param ST The suffix tree for the module.
Jessica Paquette596f4832017-03-06 21:31:18 +0000781 ///
782 /// \returns The length of the longest candidate found. 0 if there are none.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000783 unsigned
784 buildCandidateList(std::vector<std::shared_ptr<Candidate>> &CandidateList,
785 std::vector<OutlinedFunction> &FunctionList,
Eli Friedmanda080782018-08-01 00:37:20 +0000786 SuffixTree &ST, InstructionMapper &Mapper);
Jessica Paquette596f4832017-03-06 21:31:18 +0000787
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000788 /// Helper function for pruneOverlaps.
789 /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
790 void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
791
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000792 /// Remove any overlapping candidates that weren't handled by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000793 /// suffix tree's pruning method.
794 ///
795 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
796 /// If a short candidate is chosen for outlining, then a longer candidate
797 /// which has that short candidate as a suffix is chosen, the tree's pruning
798 /// method will not find it. Thus, we need to prune before outlining as well.
799 ///
800 /// \param[in,out] CandidateList A list of outlining candidates.
801 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000802 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000803 /// \param MaxCandidateLen The length of the longest candidate.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000804 void pruneOverlaps(std::vector<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000805 std::vector<OutlinedFunction> &FunctionList,
Eli Friedmanda080782018-08-01 00:37:20 +0000806 InstructionMapper &Mapper, unsigned MaxCandidateLen);
Jessica Paquette596f4832017-03-06 21:31:18 +0000807
808 /// Construct a suffix tree on the instructions in \p M and outline repeated
809 /// strings from that tree.
810 bool runOnModule(Module &M) override;
Jessica Paquetteaa087322018-06-04 21:14:16 +0000811
812 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
813 /// function for remark emission.
814 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
815 DISubprogram *SP;
816 for (const std::shared_ptr<Candidate> &C : OF.Candidates)
817 if (C && C->getMF() && (SP = C->getMF()->getFunction().getSubprogram()))
818 return SP;
819 return nullptr;
820 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +0000821
822 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
823 /// These are used to construct a suffix tree.
824 void populateMapper(InstructionMapper &Mapper, Module &M,
825 MachineModuleInfo &MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +0000826
Jessica Paquette2386eab2018-09-11 23:05:34 +0000827 /// Initialize information necessary to output a size remark.
828 /// FIXME: This should be handled by the pass manager, not the outliner.
829 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
830 /// pass manager.
831 void initSizeRemarkInfo(
832 const Module &M, const MachineModuleInfo &MMI,
833 StringMap<unsigned> &FunctionToInstrCount);
834
835 /// Emit the remark.
836 // FIXME: This should be handled by the pass manager, not the outliner.
837 void emitInstrCountChangedRemark(
838 const Module &M, const MachineModuleInfo &MMI,
839 const StringMap<unsigned> &FunctionToInstrCount);
840};
Jessica Paquette596f4832017-03-06 21:31:18 +0000841} // Anonymous namespace.
842
843char MachineOutliner::ID = 0;
844
845namespace llvm {
Jessica Paquette8bda1882018-06-30 03:56:03 +0000846ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
847 MachineOutliner *OL = new MachineOutliner();
848 OL->RunOnAllFunctions = RunOnAllFunctions;
849 return OL;
Jessica Paquette13593842017-10-07 00:16:34 +0000850}
851
Jessica Paquette78681be2017-07-27 23:24:43 +0000852} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000853
Jessica Paquette78681be2017-07-27 23:24:43 +0000854INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
855 false)
856
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000857void MachineOutliner::emitNotOutliningCheaperRemark(
858 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
859 OutlinedFunction &OF) {
860 Candidate &C = CandidatesForRepeatedSeq.front();
861 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
862 MORE.emit([&]() {
863 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
864 C.front()->getDebugLoc(), C.getMBB());
865 R << "Did not outline " << NV("Length", StringLen) << " instructions"
866 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
867 << " locations."
868 << " Bytes from outlining all occurrences ("
869 << NV("OutliningCost", OF.getOutliningCost()) << ")"
870 << " >= Unoutlined instruction bytes ("
871 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
872 << " (Also found at: ";
873
874 // Tell the user the other places the candidate was found.
875 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
876 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
877 CandidatesForRepeatedSeq[i].front()->getDebugLoc());
878 if (i != e - 1)
879 R << ", ";
880 }
881
882 R << ")";
883 return R;
884 });
885}
886
Jessica Paquette58e706a2018-07-24 20:20:45 +0000887void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
888 MachineBasicBlock *MBB = &*OF.MF->begin();
889 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
890 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
891 MBB->findDebugLoc(MBB->begin()), MBB);
892 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
893 << "outlining " << NV("Length", OF.Sequence.size()) << " instructions "
894 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
895 << " locations. "
896 << "(Found at: ";
897
898 // Tell the user the other places the candidate was found.
899 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
900
901 // Skip over things that were pruned.
902 if (!OF.Candidates[i]->InCandidateList)
903 continue;
904
905 R << NV((Twine("StartLoc") + Twine(i)).str(),
906 OF.Candidates[i]->front()->getDebugLoc());
907 if (i != e - 1)
908 R << ", ";
909 }
910
911 R << ")";
912
913 MORE.emit(R);
914}
915
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000916unsigned MachineOutliner::findCandidates(
Eli Friedmanda080782018-08-01 00:37:20 +0000917 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000918 std::vector<std::shared_ptr<Candidate>> &CandidateList,
919 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000920 CandidateList.clear();
921 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000922 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +0000923
924 // FIXME: Visit internal nodes instead of leaves.
925 for (SuffixTreeNode *Leaf : ST.LeafVector) {
926 assert(Leaf && "Leaves in LeafVector cannot be null!");
927 if (!Leaf->IsInTree)
928 continue;
929
930 assert(Leaf->Parent && "All leaves must have parents!");
931 SuffixTreeNode &Parent = *(Leaf->Parent);
932
933 // If it doesn't appear enough, or we already outlined from it, skip it.
934 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
935 continue;
936
Jessica Paquette809d7082017-07-28 03:21:58 +0000937 // Figure out if this candidate is beneficial.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000938 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
Jessica Paquette95c11072017-08-14 22:57:41 +0000939
940 // Too short to be beneficial; skip it.
941 // FIXME: This isn't necessarily true for, say, X86. If we factor in
942 // instruction lengths we need more information than this.
943 if (StringLen < 2)
944 continue;
945
Jessica Paquetted87f5442017-07-29 02:55:46 +0000946 // If this is a beneficial class of candidate, then every one is stored in
947 // this vector.
948 std::vector<Candidate> CandidatesForRepeatedSeq;
949
Jessica Paquette809d7082017-07-28 03:21:58 +0000950 // Figure out the call overhead for each instance of the sequence.
951 for (auto &ChildPair : Parent.Children) {
952 SuffixTreeNode *M = ChildPair.second;
Jessica Paquette78681be2017-07-27 23:24:43 +0000953
Jessica Paquette809d7082017-07-28 03:21:58 +0000954 if (M && M->IsInTree && M->isLeaf()) {
Jessica Paquetted87f5442017-07-29 02:55:46 +0000955 // Never visit this leaf again.
956 M->IsInTree = false;
Jessica Paquette52df8012017-12-01 21:56:56 +0000957 unsigned StartIdx = M->SuffixIdx;
958 unsigned EndIdx = StartIdx + StringLen - 1;
959
960 // Trick: Discard some candidates that would be incompatible with the
961 // ones we've already found for this sequence. This will save us some
962 // work in candidate selection.
963 //
964 // If two candidates overlap, then we can't outline them both. This
965 // happens when we have candidates that look like, say
966 //
967 // AA (where each "A" is an instruction).
968 //
969 // We might have some portion of the module that looks like this:
Fangrui Songf78650a2018-07-30 19:41:25 +0000970 // AAAAAA (6 A's)
Jessica Paquette52df8012017-12-01 21:56:56 +0000971 //
972 // In this case, there are 5 different copies of "AA" in this range, but
973 // at most 3 can be outlined. If only outlining 3 of these is going to
974 // be unbeneficial, then we ought to not bother.
975 //
976 // Note that two things DON'T overlap when they look like this:
977 // start1...end1 .... start2...end2
978 // That is, one must either
979 // * End before the other starts
980 // * Start after the other ends
981 if (std::all_of(CandidatesForRepeatedSeq.begin(),
982 CandidatesForRepeatedSeq.end(),
983 [&StartIdx, &EndIdx](const Candidate &C) {
984 return (EndIdx < C.getStartIdx() ||
Jessica Paquetteaa087322018-06-04 21:14:16 +0000985 StartIdx > C.getEndIdx());
Jessica Paquette52df8012017-12-01 21:56:56 +0000986 })) {
987 // It doesn't overlap with anything, so we can outline it.
988 // Each sequence is over [StartIt, EndIt].
Jessica Paquetteaa087322018-06-04 21:14:16 +0000989 // Save the candidate and its location.
990
Jessica Paquette52df8012017-12-01 21:56:56 +0000991 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
992 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
993
Jessica Paquetteaa087322018-06-04 21:14:16 +0000994 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
995 EndIt, StartIt->getParent(),
996 FunctionList.size());
Jessica Paquette52df8012017-12-01 21:56:56 +0000997 }
Jessica Paquette809d7082017-07-28 03:21:58 +0000998 }
999 }
1000
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001001 // We've found something we might want to outline.
1002 // Create an OutlinedFunction to store it and check if it'd be beneficial
1003 // to outline.
Eli Friedmanda080782018-08-01 00:37:20 +00001004 if (CandidatesForRepeatedSeq.empty())
1005 continue;
1006
1007 // Arbitrarily choose a TII from the first candidate.
1008 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1009 const TargetInstrInfo *TII =
1010 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1011
Jessica Paquette9d93c602018-07-27 18:21:57 +00001012 OutlinedFunction OF =
Eli Friedmanda080782018-08-01 00:37:20 +00001013 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
Jessica Paquette9d93c602018-07-27 18:21:57 +00001014
1015 // If we deleted every candidate, then there's nothing to outline.
1016 if (OF.Candidates.empty())
1017 continue;
1018
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001019 std::vector<unsigned> Seq;
1020 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
1021 Seq.push_back(ST.Str[i]);
Jessica Paquette69f517d2018-07-24 20:13:10 +00001022 OF.Sequence = Seq;
1023 OF.Name = FunctionList.size();
Jessica Paquette809d7082017-07-28 03:21:58 +00001024
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001025 // Is it better to outline this candidate than not?
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001026 if (OF.getBenefit() < 1) {
Jessica Paquette1cc52a02018-07-24 17:37:28 +00001027 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001028 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001029 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001030
1031 if (StringLen > MaxLen)
1032 MaxLen = StringLen;
1033
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001034 // The function is beneficial. Save its candidates to the candidate list
1035 // for pruning.
1036 for (std::shared_ptr<Candidate> &C : OF.Candidates)
1037 CandidateList.push_back(C);
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001038 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001039
1040 // Move to the next function.
Jessica Paquette78681be2017-07-27 23:24:43 +00001041 Parent.IsInTree = false;
1042 }
1043
1044 return MaxLen;
1045}
Jessica Paquette596f4832017-03-06 21:31:18 +00001046
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001047// Remove C from the candidate space, and update its OutlinedFunction.
1048void MachineOutliner::prune(Candidate &C,
1049 std::vector<OutlinedFunction> &FunctionList) {
1050 // Get the OutlinedFunction associated with this Candidate.
1051 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1052
1053 // Update C's associated function's occurrence count.
1054 F.decrement();
1055
1056 // Remove C from the CandidateList.
1057 C.InCandidateList = false;
1058
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001059 LLVM_DEBUG(dbgs() << "- Removed a Candidate \n";
1060 dbgs() << "--- Num fns left for candidate: "
1061 << F.getOccurrenceCount() << "\n";
1062 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1063 << "\n";);
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001064}
1065
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001066void MachineOutliner::pruneOverlaps(
1067 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1068 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper,
Eli Friedmanda080782018-08-01 00:37:20 +00001069 unsigned MaxCandidateLen) {
Jessica Paquette91999162017-09-28 23:39:36 +00001070
1071 // Return true if this candidate became unbeneficial for outlining in a
1072 // previous step.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001073 auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
Jessica Paquette91999162017-09-28 23:39:36 +00001074
1075 // Check if the candidate was removed in a previous step.
1076 if (!C.InCandidateList)
1077 return true;
1078
Jessica Paquette85af63d2017-10-17 19:03:23 +00001079 // C must be alive. Check if we should remove it.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001080 if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1081 prune(C, FunctionList);
Jessica Paquette91999162017-09-28 23:39:36 +00001082 return true;
1083 }
1084
1085 // C is in the list, and F is still beneficial.
1086 return false;
1087 };
1088
Jessica Paquetteacffa282017-03-23 21:27:38 +00001089 // TODO: Experiment with interval trees or other interval-checking structures
1090 // to lower the time complexity of this function.
1091 // TODO: Can we do better than the simple greedy choice?
1092 // Check for overlaps in the range.
1093 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001094 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1095 It++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001096 Candidate &C1 = **It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001097
Jessica Paquette91999162017-09-28 23:39:36 +00001098 // If C1 was already pruned, or its function is no longer beneficial for
1099 // outlining, move to the next candidate.
1100 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001101 continue;
1102
Jessica Paquette596f4832017-03-06 21:31:18 +00001103 // The minimum start index of any candidate that could overlap with this
1104 // one.
1105 unsigned FarthestPossibleIdx = 0;
1106
1107 // Either the index is 0, or it's at most MaxCandidateLen indices away.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001108 if (C1.getStartIdx() > MaxCandidateLen)
1109 FarthestPossibleIdx = C1.getStartIdx() - MaxCandidateLen;
Jessica Paquette596f4832017-03-06 21:31:18 +00001110
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001111 // Compare against the candidates in the list that start at most
Jessica Paquetteacffa282017-03-23 21:27:38 +00001112 // FarthestPossibleIdx indices away from C1. There are at most
1113 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001114 for (auto Sit = It + 1; Sit != Et; Sit++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001115 Candidate &C2 = **Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001116
1117 // Is this candidate too far away to overlap?
Jessica Paquette1934fd22017-10-23 16:25:53 +00001118 if (C2.getStartIdx() < FarthestPossibleIdx)
Jessica Paquette596f4832017-03-06 21:31:18 +00001119 break;
1120
Jessica Paquette91999162017-09-28 23:39:36 +00001121 // If C2 was already pruned, or its function is no longer beneficial for
1122 // outlining, move to the next candidate.
1123 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001124 continue;
1125
Jessica Paquette596f4832017-03-06 21:31:18 +00001126 // Do C1 and C2 overlap?
1127 //
1128 // Not overlapping:
1129 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1130 //
1131 // We sorted our candidate list so C2Start <= C1Start. We know that
1132 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1133 // have to check is C2End < C2Start to see if we overlap.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001134 if (C2.getEndIdx() < C1.getStartIdx())
Jessica Paquette596f4832017-03-06 21:31:18 +00001135 continue;
1136
Jessica Paquetteacffa282017-03-23 21:27:38 +00001137 // C1 and C2 overlap.
1138 // We need to choose the better of the two.
1139 //
1140 // Approximate this by picking the one which would have saved us the
1141 // most instructions before any pruning.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001142
1143 // Is C2 a better candidate?
1144 if (C2.Benefit > C1.Benefit) {
1145 // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1146 // against anything anymore, so break.
1147 prune(C1, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001148 break;
1149 }
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001150
1151 // Prune C2 and move on to the next candidate.
1152 prune(C2, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001153 }
1154 }
1155}
1156
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001157unsigned MachineOutliner::buildCandidateList(
1158 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1159 std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST,
Eli Friedmanda080782018-08-01 00:37:20 +00001160 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001161
1162 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001163 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001164
Jessica Paquette78681be2017-07-27 23:24:43 +00001165 MaxCandidateLen =
Eli Friedmanda080782018-08-01 00:37:20 +00001166 findCandidates(ST, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001167
Jessica Paquette596f4832017-03-06 21:31:18 +00001168 // Sort the candidates in decending order. This will simplify the outlining
1169 // process when we have to remove the candidates from the mapping by
1170 // allowing us to cut them out without keeping track of an offset.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001171 std::stable_sort(
1172 CandidateList.begin(), CandidateList.end(),
1173 [](const std::shared_ptr<Candidate> &LHS,
1174 const std::shared_ptr<Candidate> &RHS) { return *LHS < *RHS; });
Jessica Paquette596f4832017-03-06 21:31:18 +00001175
1176 return MaxCandidateLen;
1177}
1178
1179MachineFunction *
1180MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001181 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001182
1183 // Create the function name. This should be unique. For now, just hash the
1184 // module name and include it in the function name plus the number of this
1185 // function.
1186 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001187 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001188
1189 // Create the function using an IR-level function.
1190 LLVMContext &C = M.getContext();
1191 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001192 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001193 assert(F && "Function was null!");
1194
1195 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1196 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001197 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001198 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1199
Eli Friedman25bef202018-05-15 23:36:46 +00001200 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1201 // necessary.
1202
1203 // Set optsize/minsize, so we don't insert padding between outlined
1204 // functions.
1205 F->addFnAttr(Attribute::OptimizeForSize);
1206 F->addFnAttr(Attribute::MinSize);
1207
Jessica Paquette729e6862018-01-18 00:00:58 +00001208 // Save F so that we can add debug info later if we need to.
1209 CreatedIRFunctions.push_back(F);
1210
Jessica Paquette596f4832017-03-06 21:31:18 +00001211 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1212 IRBuilder<> Builder(EntryBB);
1213 Builder.CreateRetVoid();
1214
1215 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001216 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001217 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1218 const TargetSubtargetInfo &STI = MF.getSubtarget();
1219 const TargetInstrInfo &TII = *STI.getInstrInfo();
1220
1221 // Insert the new function into the module.
1222 MF.insert(MF.begin(), &MBB);
1223
Jessica Paquette596f4832017-03-06 21:31:18 +00001224 // Copy over the instructions for the function using the integer mappings in
1225 // its sequence.
1226 for (unsigned Str : OF.Sequence) {
1227 MachineInstr *NewMI =
1228 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
Chandler Carruthc73c0302018-08-16 21:30:05 +00001229 NewMI->dropMemRefs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001230
1231 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001232 NewMI->setDebugLoc(DebugLoc());
1233 MBB.insert(MBB.end(), NewMI);
1234 }
1235
Jessica Paquette69f517d2018-07-24 20:13:10 +00001236 TII.buildOutlinedFrame(MBB, MF, OF);
Jessica Paquette729e6862018-01-18 00:00:58 +00001237
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001238 // If there's a DISubprogram associated with this outlined function, then
1239 // emit debug info for the outlined function.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001240 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001241 // We have a DISubprogram. Get its DICompileUnit.
1242 DICompileUnit *CU = SP->getUnit();
1243 DIBuilder DB(M, true, CU);
1244 DIFile *Unit = SP->getFile();
1245 Mangler Mg;
1246
1247 // Walk over each IR function we created in the outliner and create
1248 // DISubprograms for each function.
1249 for (Function *F : CreatedIRFunctions) {
1250 // Get the mangled name of the function for the linkage name.
1251 std::string Dummy;
1252 llvm::raw_string_ostream MangledNameStream(Dummy);
1253 Mg.getNameWithPrefix(MangledNameStream, F, false);
1254
1255 DISubprogram *SP = DB.createFunction(
1256 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1257 Unit /* File */,
1258 0 /* Line 0 is reserved for compiler-generated code. */,
1259 DB.createSubroutineType(
1260 DB.getOrCreateTypeArray(None)), /* void type */
1261 false, true, 0, /* Line 0 is reserved for compiler-generated code. */
1262 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1263 true /* Outlined code is optimized code by definition. */);
1264
1265 // Don't add any new variables to the subprogram.
1266 DB.finalizeSubprogram(SP);
1267
1268 // Attach subprogram to the function.
1269 F->setSubprogram(SP);
1270 }
1271
1272 // We're done with the DIBuilder.
1273 DB.finalize();
1274 }
1275
Jessica Paquette0b672492018-04-27 23:36:35 +00001276 // Outlined functions shouldn't preserve liveness.
1277 MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
Geoff Berry82203c42018-01-31 20:15:16 +00001278 MF.getRegInfo().freezeReservedRegs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001279 return &MF;
1280}
1281
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001282bool MachineOutliner::outline(
1283 Module &M, const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
1284 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001285
1286 bool OutlinedSomething = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001287 // Replace the candidates with calls to their respective outlined functions.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001288 for (const std::shared_ptr<Candidate> &Cptr : CandidateList) {
1289 Candidate &C = *Cptr;
Jessica Paquette596f4832017-03-06 21:31:18 +00001290 // Was the candidate removed during pruneOverlaps?
1291 if (!C.InCandidateList)
1292 continue;
1293
1294 // If not, then look at its OutlinedFunction.
1295 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1296
1297 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquette85af63d2017-10-17 19:03:23 +00001298 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001299 continue;
1300
Jessica Paquette596f4832017-03-06 21:31:18 +00001301 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001302 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001303 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquette58e706a2018-07-24 20:20:45 +00001304 emitOutlinedFunctionRemark(OF);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001305 FunctionsCreated++;
1306 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001307
1308 MachineFunction *MF = OF.MF;
Jessica Paquetteaa087322018-06-04 21:14:16 +00001309 MachineBasicBlock &MBB = *C.getMBB();
1310 MachineBasicBlock::iterator StartIt = C.front();
1311 MachineBasicBlock::iterator EndIt = C.back();
1312 assert(StartIt != C.getMBB()->end() && "StartIt out of bounds!");
1313 assert(EndIt != C.getMBB()->end() && "EndIt out of bounds!");
1314
Jessica Paquette596f4832017-03-06 21:31:18 +00001315 const TargetSubtargetInfo &STI = MF->getSubtarget();
1316 const TargetInstrInfo &TII = *STI.getInstrInfo();
1317
1318 // Insert a call to the new function and erase the old sequence.
Jessica Paquettefca55122018-07-24 17:42:11 +00001319 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *OF.MF, C);
Jessica Paquette596f4832017-03-06 21:31:18 +00001320
Jessica Paquette0b672492018-04-27 23:36:35 +00001321 // If the caller tracks liveness, then we need to make sure that anything
1322 // we outline doesn't break liveness assumptions.
1323 // The outlined functions themselves currently don't track liveness, but
1324 // we should make sure that the ranges we yank things out of aren't
1325 // wrong.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001326 if (MBB.getParent()->getProperties().hasProperty(
Jessica Paquette0b672492018-04-27 23:36:35 +00001327 MachineFunctionProperties::Property::TracksLiveness)) {
1328 // Helper lambda for adding implicit def operands to the call instruction.
1329 auto CopyDefs = [&CallInst](MachineInstr &MI) {
1330 for (MachineOperand &MOP : MI.operands()) {
1331 // Skip over anything that isn't a register.
1332 if (!MOP.isReg())
1333 continue;
1334
1335 // If it's a def, add it to the call instruction.
1336 if (MOP.isDef())
1337 CallInst->addOperand(
1338 MachineOperand::CreateReg(MOP.getReg(), true, /* isDef = true */
1339 true /* isImp = true */));
1340 }
1341 };
1342
1343 // Copy over the defs in the outlined range.
1344 // First inst in outlined range <-- Anything that's defined in this
1345 // ... .. range has to be added as an implicit
1346 // Last inst in outlined range <-- def to the call instruction.
Francis Visoiu Mistrihf905bf12018-07-14 09:40:01 +00001347 std::for_each(CallInst, std::next(EndIt), CopyDefs);
Jessica Paquette0b672492018-04-27 23:36:35 +00001348 }
1349
Jessica Paquetteaa087322018-06-04 21:14:16 +00001350 // Erase from the point after where the call was inserted up to, and
1351 // including, the final instruction in the sequence.
1352 // Erase needs one past the end, so we need std::next there too.
1353 MBB.erase(std::next(StartIt), std::next(EndIt));
Jessica Paquette596f4832017-03-06 21:31:18 +00001354 OutlinedSomething = true;
1355
1356 // Statistics.
1357 NumOutlined++;
1358 }
1359
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001360 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001361
1362 return OutlinedSomething;
1363}
1364
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001365void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1366 MachineModuleInfo &MMI) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001367 // Build instruction mappings for each function in the module. Start by
1368 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001369 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001370
Jessica Paquettedf822742018-03-22 21:07:09 +00001371 // If there's nothing in F, then there's no reason to try and outline from
1372 // it.
1373 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001374 continue;
1375
Jessica Paquettedf822742018-03-22 21:07:09 +00001376 // There's something in F. Check if it has a MachineFunction associated with
1377 // it.
1378 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001379
Jessica Paquettedf822742018-03-22 21:07:09 +00001380 // If it doesn't, then there's nothing to outline from. Move to the next
1381 // Function.
1382 if (!MF)
1383 continue;
1384
Eli Friedmanda080782018-08-01 00:37:20 +00001385 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1386
Jessica Paquette8bda1882018-06-30 03:56:03 +00001387 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
1388 continue;
1389
Jessica Paquettedf822742018-03-22 21:07:09 +00001390 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1391 // If it isn't, then move on to the next Function in the module.
1392 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1393 continue;
1394
1395 // We have a function suitable for outlining. Iterate over every
1396 // MachineBasicBlock in MF and try to map its instructions to a list of
1397 // unsigned integers.
1398 for (MachineBasicBlock &MBB : *MF) {
1399 // If there isn't anything in MBB, then there's no point in outlining from
1400 // it.
1401 if (MBB.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001402 continue;
1403
Jessica Paquettedf822742018-03-22 21:07:09 +00001404 // Check if MBB could be the target of an indirect branch. If it is, then
1405 // we don't want to outline from it.
1406 if (MBB.hasAddressTaken())
1407 continue;
1408
1409 // MBB is suitable for outlining. Map it to a list of unsigneds.
Eli Friedmanda080782018-08-01 00:37:20 +00001410 Mapper.convertToUnsignedVec(MBB, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001411 }
1412 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001413}
1414
Jessica Paquette2386eab2018-09-11 23:05:34 +00001415void MachineOutliner::initSizeRemarkInfo(
1416 const Module &M, const MachineModuleInfo &MMI,
1417 StringMap<unsigned> &FunctionToInstrCount) {
1418 // Collect instruction counts for every function. We'll use this to emit
1419 // per-function size remarks later.
1420 for (const Function &F : M) {
1421 MachineFunction *MF = MMI.getMachineFunction(F);
1422
1423 // We only care about MI counts here. If there's no MachineFunction at this
1424 // point, then there won't be after the outliner runs, so let's move on.
1425 if (!MF)
1426 continue;
1427 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1428 }
1429}
1430
1431void MachineOutliner::emitInstrCountChangedRemark(
1432 const Module &M, const MachineModuleInfo &MMI,
1433 const StringMap<unsigned> &FunctionToInstrCount) {
1434 // Iterate over each function in the module and emit remarks.
1435 // Note that we won't miss anything by doing this, because the outliner never
1436 // deletes functions.
1437 for (const Function &F : M) {
1438 MachineFunction *MF = MMI.getMachineFunction(F);
1439
1440 // The outliner never deletes functions. If we don't have a MF here, then we
1441 // didn't have one prior to outlining either.
1442 if (!MF)
1443 continue;
1444
1445 std::string Fname = F.getName();
1446 unsigned FnCountAfter = MF->getInstructionCount();
1447 unsigned FnCountBefore = 0;
1448
1449 // Check if the function was recorded before.
1450 auto It = FunctionToInstrCount.find(Fname);
1451
1452 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1453 // to that.
1454 if (It != FunctionToInstrCount.end())
1455 FnCountBefore = It->second;
1456
1457 // Compute the delta and emit a remark if there was a change.
1458 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1459 static_cast<int64_t>(FnCountBefore);
1460 if (FnDelta == 0)
1461 continue;
1462
1463 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1464 MORE.emit([&]() {
1465 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1466 DiagnosticLocation(),
1467 &MF->front());
1468 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1469 << ": Function: "
1470 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1471 << ": MI instruction count changed from "
1472 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1473 FnCountBefore)
1474 << " to "
1475 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1476 FnCountAfter)
1477 << "; Delta: "
1478 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1479 return R;
1480 });
1481 }
1482}
1483
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001484bool MachineOutliner::runOnModule(Module &M) {
1485 // Check if there's anything in the module. If it's empty, then there's
1486 // nothing to outline.
1487 if (M.empty())
1488 return false;
1489
1490 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1491
1492 // If the user passed -enable-machine-outliner=always or
1493 // -enable-machine-outliner, the pass will run on all functions in the module.
1494 // Otherwise, if the target supports default outlining, it will run on all
1495 // functions deemed by the target to be worth outlining from by default. Tell
1496 // the user how the outliner is running.
1497 LLVM_DEBUG(
1498 dbgs() << "Machine Outliner: Running on ";
1499 if (RunOnAllFunctions)
1500 dbgs() << "all functions";
1501 else
1502 dbgs() << "target-default functions";
1503 dbgs() << "\n"
1504 );
1505
1506 // If the user specifies that they want to outline from linkonceodrs, set
1507 // it here.
1508 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1509 InstructionMapper Mapper;
1510
1511 // Prepare instruction mappings for the suffix tree.
1512 populateMapper(Mapper, M, MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +00001513
1514 // Construct a suffix tree, use it to find candidates, and then outline them.
1515 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001516 std::vector<std::shared_ptr<Candidate>> CandidateList;
Jessica Paquette596f4832017-03-06 21:31:18 +00001517 std::vector<OutlinedFunction> FunctionList;
1518
Jessica Paquetteacffa282017-03-23 21:27:38 +00001519 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001520 unsigned MaxCandidateLen =
Eli Friedmanda080782018-08-01 00:37:20 +00001521 buildCandidateList(CandidateList, FunctionList, ST, Mapper);
Jessica Paquette596f4832017-03-06 21:31:18 +00001522
Jessica Paquetteacffa282017-03-23 21:27:38 +00001523 // Remove candidates that overlap with other candidates.
Eli Friedmanda080782018-08-01 00:37:20 +00001524 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001525
Jessica Paquette2386eab2018-09-11 23:05:34 +00001526 // If we've requested size remarks, then collect the MI counts of every
1527 // function before outlining, and the MI counts after outlining.
1528 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1529 // the pass manager's responsibility.
1530 // This could pretty easily be placed in outline instead, but because we
1531 // really ultimately *don't* want this here, it's done like this for now
1532 // instead.
1533
1534 // Check if we want size remarks.
1535 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1536 StringMap<unsigned> FunctionToInstrCount;
1537 if (ShouldEmitSizeRemarks)
1538 initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
1539
Jessica Paquetteacffa282017-03-23 21:27:38 +00001540 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette729e6862018-01-18 00:00:58 +00001541 bool OutlinedSomething = outline(M, CandidateList, FunctionList, Mapper);
1542
Jessica Paquette2386eab2018-09-11 23:05:34 +00001543 // If we outlined something, we definitely changed the MI count of the
1544 // module. If we've asked for size remarks, then output them.
1545 // FIXME: This should be in the pass manager.
1546 if (ShouldEmitSizeRemarks && OutlinedSomething)
1547 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
1548
Jessica Paquette729e6862018-01-18 00:00:58 +00001549 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001550}