blob: 250f3984fdbb71c7a5ccd5d24cc673d84464adb6 [file] [log] [blame]
Jessica Paquette596f4832017-03-06 21:31:18 +00001//===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jessica Paquette596f4832017-03-06 21:31:18 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Replaces repeated sequences of instructions with function calls.
11///
12/// This works by placing every instruction from every basic block in a
13/// suffix tree, and repeatedly querying that tree for repeated sequences of
14/// instructions. If a sequence of instructions appears often, then it ought
15/// to be beneficial to pull out into a function.
16///
Jessica Paquette4cf187b2017-09-27 20:47:39 +000017/// The MachineOutliner communicates with a given target using hooks defined in
18/// TargetInstrInfo.h. The target supplies the outliner with information on how
19/// a specific sequence of instructions should be outlined. This information
20/// is used to deduce the number of instructions necessary to
21///
22/// * Create an outlined function
23/// * Call that outlined function
24///
25/// Targets must implement
26/// * getOutliningCandidateInfo
Jessica Paquette32de26d2018-06-19 21:14:48 +000027/// * buildOutlinedFrame
Jessica Paquette4cf187b2017-09-27 20:47:39 +000028/// * insertOutlinedCall
Jessica Paquette4cf187b2017-09-27 20:47:39 +000029/// * isFunctionSafeToOutlineFrom
30///
31/// in order to make use of the MachineOutliner.
32///
Jessica Paquette596f4832017-03-06 21:31:18 +000033/// This was originally presented at the 2016 LLVM Developers' Meeting in the
34/// talk "Reducing Code Size Using Outlining". For a high-level overview of
35/// how this pass works, the talk is available on YouTube at
36///
37/// https://www.youtube.com/watch?v=yorld-WSOeU
38///
39/// The slides for the talk are available at
40///
41/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
42///
43/// The talk provides an overview of how the outliner finds candidates and
44/// ultimately outlines them. It describes how the main data structure for this
45/// pass, the suffix tree, is queried and purged for candidates. It also gives
46/// a simplified suffix tree construction algorithm for suffix trees based off
47/// of the algorithm actually used here, Ukkonen's algorithm.
48///
49/// For the original RFC for this pass, please see
50///
51/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
52///
53/// For more information on the suffix tree data structure, please see
54/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
55///
56//===----------------------------------------------------------------------===//
Jessica Paquetteaa087322018-06-04 21:14:16 +000057#include "llvm/CodeGen/MachineOutliner.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000058#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/Statistic.h"
60#include "llvm/ADT/Twine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000061#include "llvm/CodeGen/MachineFunction.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000062#include "llvm/CodeGen/MachineModuleInfo.h"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000063#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Geoff Berry82203c42018-01-31 20:15:16 +000064#include "llvm/CodeGen/MachineRegisterInfo.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000065#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000066#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000067#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jessica Paquette729e6862018-01-18 00:00:58 +000068#include "llvm/IR/DIBuilder.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000069#include "llvm/IR/IRBuilder.h"
Jessica Paquettea499c3c2018-01-19 21:21:49 +000070#include "llvm/IR/Mangler.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000071#include "llvm/Support/Allocator.h"
Jessica Paquette1eca23b2018-04-19 22:17:07 +000072#include "llvm/Support/CommandLine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000073#include "llvm/Support/Debug.h"
74#include "llvm/Support/raw_ostream.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000075#include <functional>
Jessica Paquette596f4832017-03-06 21:31:18 +000076#include <tuple>
77#include <vector>
78
79#define DEBUG_TYPE "machine-outliner"
80
81using namespace llvm;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000082using namespace ore;
Jessica Paquetteaa087322018-06-04 21:14:16 +000083using namespace outliner;
Jessica Paquette596f4832017-03-06 21:31:18 +000084
85STATISTIC(NumOutlined, "Number of candidates outlined");
86STATISTIC(FunctionsCreated, "Number of functions created");
87
Jessica Paquette1eca23b2018-04-19 22:17:07 +000088// Set to true if the user wants the outliner to run on linkonceodr linkage
89// functions. This is false by default because the linker can dedupe linkonceodr
90// functions. Since the outliner is confined to a single module (modulo LTO),
91// this is off by default. It should, however, be the default behaviour in
92// LTO.
93static cl::opt<bool> EnableLinkOnceODROutlining(
Puyan Lotfi6b7615a2019-10-28 17:57:51 -040094 "enable-linkonceodr-outlining", cl::Hidden,
Jessica Paquette1eca23b2018-04-19 22:17:07 +000095 cl::desc("Enable the machine outliner on linkonceodr functions"),
96 cl::init(false));
97
Jessica Paquette596f4832017-03-06 21:31:18 +000098namespace {
99
100/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000101const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000102
103/// A node in a suffix tree which represents a substring or suffix.
104///
105/// Each node has either no children or at least two children, with the root
106/// being a exception in the empty tree.
107///
108/// Children are represented as a map between unsigned integers and nodes. If
109/// a node N has a child M on unsigned integer k, then the mapping represented
110/// by N is a proper prefix of the mapping represented by M. Note that this,
111/// although similar to a trie is somewhat different: each node stores a full
112/// substring of the full mapping rather than a single character state.
113///
114/// Each internal node contains a pointer to the internal node representing
115/// the same string, but with the first character chopped off. This is stored
116/// in \p Link. Each leaf node stores the start index of its respective
117/// suffix in \p SuffixIdx.
118struct SuffixTreeNode {
119
120 /// The children of this node.
121 ///
122 /// A child existing on an unsigned integer implies that from the mapping
123 /// represented by the current node, there is a way to reach another
124 /// mapping by tacking that character on the end of the current string.
125 DenseMap<unsigned, SuffixTreeNode *> Children;
126
Jessica Paquette596f4832017-03-06 21:31:18 +0000127 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000128 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000129
130 /// The end index of this node's substring in the main string.
131 ///
132 /// Every leaf node must have its \p EndIdx incremented at the end of every
133 /// step in the construction algorithm. To avoid having to update O(N)
134 /// nodes individually at the end of every step, the end index is stored
135 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000136 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000137
138 /// For leaves, the start index of the suffix represented by this node.
139 ///
140 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000141 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000142
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000143 /// For internal nodes, a pointer to the internal node representing
Jessica Paquette596f4832017-03-06 21:31:18 +0000144 /// the same sequence with the first character chopped off.
145 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000146 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000147 /// Ukkonen's algorithm does to achieve linear-time construction is
148 /// keep track of which node the next insert should be at. This makes each
149 /// insert O(1), and there are a total of O(N) inserts. The suffix link
150 /// helps with inserting children of internal nodes.
151 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000152 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000153 /// next insertion must be at the node representing S - its first character.
154 /// This is given by the way that we iteratively build the tree in Ukkonen's
155 /// algorithm. The main idea is to look at the suffixes of each prefix in the
156 /// string, starting with the longest suffix of the prefix, and ending with
157 /// the shortest. Therefore, if we keep pointers between such nodes, we can
158 /// move to the next insertion point in O(1) time. If we don't, then we'd
159 /// have to query from the root, which takes O(N) time. This would make the
160 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000161 SuffixTreeNode *Link = nullptr;
162
Jessica Paquetteacffa282017-03-23 21:27:38 +0000163 /// The length of the string formed by concatenating the edge labels from the
164 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000165 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000166
Jessica Paquette596f4832017-03-06 21:31:18 +0000167 /// Returns true if this node is a leaf.
168 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
169
170 /// Returns true if this node is the root of its owning \p SuffixTree.
171 bool isRoot() const { return StartIdx == EmptyIdx; }
172
173 /// Return the number of elements in the substring associated with this node.
174 size_t size() const {
175
176 // Is it the root? If so, it's the empty string so return 0.
177 if (isRoot())
178 return 0;
179
180 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
181
182 // Size = the number of elements in the string.
183 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
184 return *EndIdx - StartIdx + 1;
185 }
186
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000187 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
188 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
Jessica Paquette596f4832017-03-06 21:31:18 +0000189
190 SuffixTreeNode() {}
191};
192
193/// A data structure for fast substring queries.
194///
195/// Suffix trees represent the suffixes of their input strings in their leaves.
196/// A suffix tree is a type of compressed trie structure where each node
197/// represents an entire substring rather than a single character. Each leaf
198/// of the tree is a suffix.
199///
200/// A suffix tree can be seen as a type of state machine where each state is a
201/// substring of the full string. The tree is structured so that, for a string
202/// of length N, there are exactly N leaves in the tree. This structure allows
203/// us to quickly find repeated substrings of the input string.
204///
205/// In this implementation, a "string" is a vector of unsigned integers.
206/// These integers may result from hashing some data type. A suffix tree can
207/// contain 1 or many strings, which can then be queried as one large string.
208///
209/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
210/// suffix tree construction. Ukkonen's algorithm is explained in more detail
211/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
212/// paper is available at
213///
214/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
215class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000216public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000217 /// Each element is an integer representing an instruction in the module.
218 ArrayRef<unsigned> Str;
219
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000220 /// A repeated substring in the tree.
221 struct RepeatedSubstring {
222 /// The length of the string.
223 unsigned Length;
224
225 /// The start indices of each occurrence.
226 std::vector<unsigned> StartIndices;
227 };
228
Jessica Paquette78681be2017-07-27 23:24:43 +0000229private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000230 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000231 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000232
233 /// The root of the suffix tree.
234 ///
235 /// The root represents the empty string. It is maintained by the
236 /// \p NodeAllocator like every other node in the tree.
237 SuffixTreeNode *Root = nullptr;
238
Jessica Paquette596f4832017-03-06 21:31:18 +0000239 /// Maintains the end indices of the internal nodes in the tree.
240 ///
241 /// Each internal node is guaranteed to never have its end index change
242 /// during the construction algorithm; however, leaves must be updated at
243 /// every step. Therefore, we need to store leaf end indices by reference
244 /// to avoid updating O(N) leaves at every step of construction. Thus,
245 /// every internal node must be allocated its own end index.
246 BumpPtrAllocator InternalEndIdxAllocator;
247
248 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000249 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251 /// Helper struct which keeps track of the next insertion point in
Jessica Paquette596f4832017-03-06 21:31:18 +0000252 /// Ukkonen's algorithm.
253 struct ActiveState {
254 /// The next node to insert at.
Simon Pilgrimc7f127d2019-11-05 15:08:21 +0000255 SuffixTreeNode *Node = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000256
257 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000258 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000259
260 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000261 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000262 };
263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000264 /// The point the next insertion will take place at in the
Jessica Paquette596f4832017-03-06 21:31:18 +0000265 /// construction algorithm.
266 ActiveState Active;
267
268 /// Allocate a leaf node and add it to the tree.
269 ///
270 /// \param Parent The parent of this node.
271 /// \param StartIdx The start index of this node's associated string.
272 /// \param Edge The label on the edge leaving \p Parent to this node.
273 ///
274 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000275 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000276 unsigned Edge) {
277
278 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
279
Jessica Paquette78681be2017-07-27 23:24:43 +0000280 SuffixTreeNode *N = new (NodeAllocator.Allocate())
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000281 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
Jessica Paquette596f4832017-03-06 21:31:18 +0000282 Parent.Children[Edge] = N;
283
284 return N;
285 }
286
287 /// Allocate an internal node and add it to the tree.
288 ///
289 /// \param Parent The parent of this node. Only null when allocating the root.
290 /// \param StartIdx The start index of this node's associated string.
291 /// \param EndIdx The end index of this node's associated string.
292 /// \param Edge The label on the edge leaving \p Parent to this node.
293 ///
294 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000295 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
296 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000297
298 assert(StartIdx <= EndIdx && "String can't start after it ends!");
299 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000300 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000301
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000302 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400303 SuffixTreeNode *N =
304 new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root);
Jessica Paquette596f4832017-03-06 21:31:18 +0000305 if (Parent)
306 Parent->Children[Edge] = N;
307
308 return N;
309 }
310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311 /// Set the suffix indices of the leaves to the start indices of their
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000312 /// respective suffixes.
Jessica Paquette596f4832017-03-06 21:31:18 +0000313 ///
314 /// \param[in] CurrNode The node currently being visited.
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000315 /// \param CurrNodeLen The concatenation of all node sizes from the root to
316 /// this node. Used to produce suffix indices.
317 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrNodeLen) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000318
319 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
320
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000321 // Store the concatenation of lengths down from the root.
322 CurrNode.ConcatLen = CurrNodeLen;
Jessica Paquette596f4832017-03-06 21:31:18 +0000323 // Traverse the tree depth-first.
324 for (auto &ChildPair : CurrNode.Children) {
325 assert(ChildPair.second && "Node had a null child!");
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000326 setSuffixIndices(*ChildPair.second,
327 CurrNodeLen + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000328 }
329
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000330 // Is this node a leaf? If it is, give it a suffix index.
331 if (IsLeaf)
332 CurrNode.SuffixIdx = Str.size() - CurrNodeLen;
Jessica Paquette596f4832017-03-06 21:31:18 +0000333 }
334
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000335 /// Construct the suffix tree for the prefix of the input ending at
Jessica Paquette596f4832017-03-06 21:31:18 +0000336 /// \p EndIdx.
337 ///
338 /// Used to construct the full suffix tree iteratively. At the end of each
339 /// step, the constructed suffix tree is either a valid suffix tree, or a
340 /// suffix tree with implicit suffixes. At the end of the final step, the
341 /// suffix tree is a valid tree.
342 ///
343 /// \param EndIdx The end index of the current prefix in the main string.
344 /// \param SuffixesToAdd The number of suffixes that must be added
345 /// to complete the suffix tree at the current phase.
346 ///
347 /// \returns The number of suffixes that have not been added at the end of
348 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000349 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000350 SuffixTreeNode *NeedsLink = nullptr;
351
352 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000353
Jessica Paquette596f4832017-03-06 21:31:18 +0000354 // Are we waiting to add anything other than just the last character?
355 if (Active.Len == 0) {
356 // If not, then say the active index is the end index.
357 Active.Idx = EndIdx;
358 }
359
360 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
361
362 // The first character in the current substring we're looking at.
363 unsigned FirstChar = Str[Active.Idx];
364
365 // Have we inserted anything starting with FirstChar at the current node?
366 if (Active.Node->Children.count(FirstChar) == 0) {
367 // If not, then we can just insert a leaf and move too the next step.
368 insertLeaf(*Active.Node, EndIdx, FirstChar);
369
370 // The active node is an internal node, and we visited it, so it must
371 // need a link if it doesn't have one.
372 if (NeedsLink) {
373 NeedsLink->Link = Active.Node;
374 NeedsLink = nullptr;
375 }
376 } else {
377 // There's a match with FirstChar, so look for the point in the tree to
378 // insert a new node.
379 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
380
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000381 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000382
383 // Is the current suffix we're trying to insert longer than the size of
384 // the child we want to move to?
385 if (Active.Len >= SubstringLen) {
386 // If yes, then consume the characters we've seen and move to the next
387 // node.
388 Active.Idx += SubstringLen;
389 Active.Len -= SubstringLen;
390 Active.Node = NextNode;
391 continue;
392 }
393
394 // Otherwise, the suffix we're trying to insert must be contained in the
395 // next node we want to move to.
396 unsigned LastChar = Str[EndIdx];
397
398 // Is the string we're trying to insert a substring of the next node?
399 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
400 // If yes, then we're done for this step. Remember our insertion point
401 // and move to the next end index. At this point, we have an implicit
402 // suffix tree.
403 if (NeedsLink && !Active.Node->isRoot()) {
404 NeedsLink->Link = Active.Node;
405 NeedsLink = nullptr;
406 }
407
408 Active.Len++;
409 break;
410 }
411
412 // The string we're trying to insert isn't a substring of the next node,
413 // but matches up to a point. Split the node.
414 //
415 // For example, say we ended our search at a node n and we're trying to
416 // insert ABD. Then we'll create a new node s for AB, reduce n to just
417 // representing C, and insert a new leaf node l to represent d. This
418 // allows us to ensure that if n was a leaf, it remains a leaf.
419 //
420 // | ABC ---split---> | AB
421 // n s
422 // C / \ D
423 // n l
424
425 // The node s from the diagram
426 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000427 insertInternalNode(Active.Node, NextNode->StartIdx,
428 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000429
430 // Insert the new node representing the new substring into the tree as
431 // a child of the split node. This is the node l from the diagram.
432 insertLeaf(*SplitNode, EndIdx, LastChar);
433
434 // Make the old node a child of the split node and update its start
435 // index. This is the node n from the diagram.
436 NextNode->StartIdx += Active.Len;
Jessica Paquette596f4832017-03-06 21:31:18 +0000437 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
438
439 // SplitNode is an internal node, update the suffix link.
440 if (NeedsLink)
441 NeedsLink->Link = SplitNode;
442
443 NeedsLink = SplitNode;
444 }
445
446 // We've added something new to the tree, so there's one less suffix to
447 // add.
448 SuffixesToAdd--;
449
450 if (Active.Node->isRoot()) {
451 if (Active.Len > 0) {
452 Active.Len--;
453 Active.Idx = EndIdx - SuffixesToAdd + 1;
454 }
455 } else {
456 // Start the next phase at the next smallest suffix.
457 Active.Node = Active.Node->Link;
458 }
459 }
460
461 return SuffixesToAdd;
462 }
463
Jessica Paquette596f4832017-03-06 21:31:18 +0000464public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000465 /// Construct a suffix tree from a sequence of unsigned integers.
466 ///
467 /// \param Str The string to construct the suffix tree for.
468 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
469 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
Jessica Paquette596f4832017-03-06 21:31:18 +0000470 Active.Node = Root;
Jessica Paquette596f4832017-03-06 21:31:18 +0000471
472 // Keep track of the number of suffixes we have to add of the current
473 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000474 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000475
476 // Construct the suffix tree iteratively on each prefix of the string.
477 // PfxEndIdx is the end index of the current prefix.
478 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000479 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
480 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000481 SuffixesToAdd++;
482 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
483 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
484 }
485
486 // Set the suffix indices of each leaf.
487 assert(Root && "Root node can't be nullptr!");
488 setSuffixIndices(*Root, 0);
489 }
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000490
Jessica Paquettea409cc92018-11-07 19:20:55 +0000491 /// Iterator for finding all repeated substrings in the suffix tree.
492 struct RepeatedSubstringIterator {
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400493 private:
Jessica Paquettea409cc92018-11-07 19:20:55 +0000494 /// The current node we're visiting.
495 SuffixTreeNode *N = nullptr;
496
497 /// The repeated substring associated with this node.
498 RepeatedSubstring RS;
499
500 /// The nodes left to visit.
501 std::vector<SuffixTreeNode *> ToVisit;
502
503 /// The minimum length of a repeated substring to find.
504 /// Since we're outlining, we want at least two instructions in the range.
505 /// FIXME: This may not be true for targets like X86 which support many
506 /// instruction lengths.
507 const unsigned MinLength = 2;
508
509 /// Move the iterator to the next repeated substring.
510 void advance() {
511 // Clear the current state. If we're at the end of the range, then this
512 // is the state we want to be in.
513 RS = RepeatedSubstring();
514 N = nullptr;
515
Jessica Paquette3cd70b32018-12-06 00:26:21 +0000516 // Each leaf node represents a repeat of a string.
517 std::vector<SuffixTreeNode *> LeafChildren;
518
Jessica Paquettea409cc92018-11-07 19:20:55 +0000519 // Continue visiting nodes until we find one which repeats more than once.
520 while (!ToVisit.empty()) {
521 SuffixTreeNode *Curr = ToVisit.back();
522 ToVisit.pop_back();
Jessica Paquette3cd70b32018-12-06 00:26:21 +0000523 LeafChildren.clear();
Jessica Paquettea409cc92018-11-07 19:20:55 +0000524
525 // Keep track of the length of the string associated with the node. If
526 // it's too short, we'll quit.
527 unsigned Length = Curr->ConcatLen;
528
Jessica Paquettea409cc92018-11-07 19:20:55 +0000529 // Iterate over each child, saving internal nodes for visiting, and
530 // leaf nodes in LeafChildren. Internal nodes represent individual
531 // strings, which may repeat.
532 for (auto &ChildPair : Curr->Children) {
533 // Save all of this node's children for processing.
534 if (!ChildPair.second->isLeaf())
535 ToVisit.push_back(ChildPair.second);
536
537 // It's not an internal node, so it must be a leaf. If we have a
538 // long enough string, then save the leaf children.
539 else if (Length >= MinLength)
540 LeafChildren.push_back(ChildPair.second);
541 }
542
543 // The root never represents a repeated substring. If we're looking at
544 // that, then skip it.
545 if (Curr->isRoot())
546 continue;
547
548 // Do we have any repeated substrings?
549 if (LeafChildren.size() >= 2) {
550 // Yes. Update the state to reflect this, and then bail out.
551 N = Curr;
552 RS.Length = Length;
553 for (SuffixTreeNode *Leaf : LeafChildren)
554 RS.StartIndices.push_back(Leaf->SuffixIdx);
555 break;
556 }
557 }
558
559 // At this point, either NewRS is an empty RepeatedSubstring, or it was
560 // set in the above loop. Similarly, N is either nullptr, or the node
561 // associated with NewRS.
562 }
563
564 public:
565 /// Return the current repeated substring.
566 RepeatedSubstring &operator*() { return RS; }
567
568 RepeatedSubstringIterator &operator++() {
569 advance();
570 return *this;
571 }
572
573 RepeatedSubstringIterator operator++(int I) {
574 RepeatedSubstringIterator It(*this);
575 advance();
576 return It;
577 }
578
579 bool operator==(const RepeatedSubstringIterator &Other) {
580 return N == Other.N;
581 }
582 bool operator!=(const RepeatedSubstringIterator &Other) {
583 return !(*this == Other);
584 }
585
586 RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
587 // Do we have a non-null node?
588 if (N) {
589 // Yes. At the first step, we need to visit all of N's children.
590 // Note: This means that we visit N last.
591 ToVisit.push_back(N);
592 advance();
593 }
594 }
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400595 };
Jessica Paquettea409cc92018-11-07 19:20:55 +0000596
597 typedef RepeatedSubstringIterator iterator;
598 iterator begin() { return iterator(Root); }
599 iterator end() { return iterator(nullptr); }
Jessica Paquette596f4832017-03-06 21:31:18 +0000600};
601
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000602/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
Jessica Paquette596f4832017-03-06 21:31:18 +0000603struct InstructionMapper {
604
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000605 /// The next available integer to assign to a \p MachineInstr that
Jessica Paquette596f4832017-03-06 21:31:18 +0000606 /// cannot be outlined.
607 ///
608 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
609 unsigned IllegalInstrNumber = -3;
610
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000611 /// The next available integer to assign to a \p MachineInstr that can
Jessica Paquette596f4832017-03-06 21:31:18 +0000612 /// be outlined.
613 unsigned LegalInstrNumber = 0;
614
615 /// Correspondence from \p MachineInstrs to unsigned integers.
616 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
617 InstructionIntegerMap;
618
Jessica Paquettecad864d2018-11-13 23:01:34 +0000619 /// Correspondence between \p MachineBasicBlocks and target-defined flags.
620 DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
621
Jessica Paquette596f4832017-03-06 21:31:18 +0000622 /// The vector of unsigned integers that the module is mapped to.
623 std::vector<unsigned> UnsignedVec;
624
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000625 /// Stores the location of the instruction associated with the integer
Jessica Paquette596f4832017-03-06 21:31:18 +0000626 /// at index i in \p UnsignedVec for each index i.
627 std::vector<MachineBasicBlock::iterator> InstrList;
628
Jessica Paquettec991cf32018-11-01 23:09:06 +0000629 // Set if we added an illegal number in the previous step.
630 // Since each illegal number is unique, we only need one of them between
631 // each range of legal numbers. This lets us make sure we don't add more
632 // than one illegal number per range.
633 bool AddedIllegalLastTime = false;
634
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000635 /// Maps \p *It to a legal integer.
Jessica Paquette596f4832017-03-06 21:31:18 +0000636 ///
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000637 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
Jessica Paquetteca3ed962018-12-06 00:01:51 +0000638 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000639 ///
640 /// \returns The integer that \p *It was mapped to.
Jessica Paquette267d2662018-11-08 00:02:11 +0000641 unsigned mapToLegalUnsigned(
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000642 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
643 bool &HaveLegalRange, unsigned &NumLegalInBlock,
Jessica Paquette267d2662018-11-08 00:02:11 +0000644 std::vector<unsigned> &UnsignedVecForMBB,
645 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000646 // We added something legal, so we should unset the AddedLegalLastTime
647 // flag.
648 AddedIllegalLastTime = false;
Jessica Paquette596f4832017-03-06 21:31:18 +0000649
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000650 // If we have at least two adjacent legal instructions (which may have
651 // invisible instructions in between), remember that.
652 if (CanOutlineWithPrevInstr)
653 HaveLegalRange = true;
654 CanOutlineWithPrevInstr = true;
655
Jessica Paquette267d2662018-11-08 00:02:11 +0000656 // Keep track of the number of legal instructions we insert.
657 NumLegalInBlock++;
658
Jessica Paquette596f4832017-03-06 21:31:18 +0000659 // Get the integer for this instruction or give it the current
660 // LegalInstrNumber.
Jessica Paquette267d2662018-11-08 00:02:11 +0000661 InstrListForMBB.push_back(It);
Jessica Paquette596f4832017-03-06 21:31:18 +0000662 MachineInstr &MI = *It;
663 bool WasInserted;
664 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000665 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000666 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000667 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000668 unsigned MINumber = ResultIt->second;
669
670 // There was an insertion.
Jessica Paquetteca3ed962018-12-06 00:01:51 +0000671 if (WasInserted)
Jessica Paquette596f4832017-03-06 21:31:18 +0000672 LegalInstrNumber++;
Jessica Paquette596f4832017-03-06 21:31:18 +0000673
Jessica Paquette267d2662018-11-08 00:02:11 +0000674 UnsignedVecForMBB.push_back(MINumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000675
676 // Make sure we don't overflow or use any integers reserved by the DenseMap.
677 if (LegalInstrNumber >= IllegalInstrNumber)
678 report_fatal_error("Instruction mapping overflow!");
679
Jessica Paquette78681be2017-07-27 23:24:43 +0000680 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
681 "Tried to assign DenseMap tombstone or empty key to instruction.");
682 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
683 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000684
685 return MINumber;
686 }
687
688 /// Maps \p *It to an illegal integer.
689 ///
Jessica Paquette267d2662018-11-08 00:02:11 +0000690 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
691 /// IllegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000692 ///
693 /// \returns The integer that \p *It was mapped to.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400694 unsigned mapToIllegalUnsigned(
695 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
696 std::vector<unsigned> &UnsignedVecForMBB,
697 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000698 // Can't outline an illegal instruction. Set the flag.
699 CanOutlineWithPrevInstr = false;
700
Jessica Paquettec991cf32018-11-01 23:09:06 +0000701 // Only add one illegal number per range of legal numbers.
702 if (AddedIllegalLastTime)
703 return IllegalInstrNumber;
704
705 // Remember that we added an illegal number last time.
706 AddedIllegalLastTime = true;
Jessica Paquette596f4832017-03-06 21:31:18 +0000707 unsigned MINumber = IllegalInstrNumber;
708
Jessica Paquette267d2662018-11-08 00:02:11 +0000709 InstrListForMBB.push_back(It);
710 UnsignedVecForMBB.push_back(IllegalInstrNumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000711 IllegalInstrNumber--;
712
713 assert(LegalInstrNumber < IllegalInstrNumber &&
714 "Instruction mapping overflow!");
715
Jessica Paquette78681be2017-07-27 23:24:43 +0000716 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
717 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000718
Jessica Paquette78681be2017-07-27 23:24:43 +0000719 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
720 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000721
722 return MINumber;
723 }
724
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000725 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
Jessica Paquette596f4832017-03-06 21:31:18 +0000726 /// and appends it to \p UnsignedVec and \p InstrList.
727 ///
728 /// Two instructions are assigned the same integer if they are identical.
729 /// If an instruction is deemed unsafe to outline, then it will be assigned an
730 /// unique integer. The resulting mapping is placed into a suffix tree and
731 /// queried for candidates.
732 ///
733 /// \param MBB The \p MachineBasicBlock to be translated into integers.
Eli Friedmanda080782018-08-01 00:37:20 +0000734 /// \param TII \p TargetInstrInfo for the function.
Jessica Paquette596f4832017-03-06 21:31:18 +0000735 void convertToUnsignedVec(MachineBasicBlock &MBB,
Jessica Paquette596f4832017-03-06 21:31:18 +0000736 const TargetInstrInfo &TII) {
Alexander Kornienko3635c892018-11-13 16:41:05 +0000737 unsigned Flags = 0;
Jessica Paquette82d9c0a2018-11-12 23:51:32 +0000738
739 // Don't even map in this case.
740 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
741 return;
742
Jessica Paquettecad864d2018-11-13 23:01:34 +0000743 // Store info for the MBB for later outlining.
744 MBBFlagsMap[&MBB] = Flags;
745
Jessica Paquettec991cf32018-11-01 23:09:06 +0000746 MachineBasicBlock::iterator It = MBB.begin();
Jessica Paquette267d2662018-11-08 00:02:11 +0000747
748 // The number of instructions in this block that will be considered for
749 // outlining.
750 unsigned NumLegalInBlock = 0;
751
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000752 // True if we have at least two legal instructions which aren't separated
753 // by an illegal instruction.
754 bool HaveLegalRange = false;
755
756 // True if we can perform outlining given the last mapped (non-invisible)
757 // instruction. This lets us know if we have a legal range.
758 bool CanOutlineWithPrevInstr = false;
759
Jessica Paquette267d2662018-11-08 00:02:11 +0000760 // FIXME: Should this all just be handled in the target, rather than using
761 // repeated calls to getOutliningType?
762 std::vector<unsigned> UnsignedVecForMBB;
763 std::vector<MachineBasicBlock::iterator> InstrListForMBB;
764
Simon Pilgrim76166a12019-11-05 16:46:10 +0000765 for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000766 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000767 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquetteaa087322018-06-04 21:14:16 +0000768 case InstrType::Illegal:
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400769 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
770 InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000771 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000772
Jessica Paquetteaa087322018-06-04 21:14:16 +0000773 case InstrType::Legal:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000774 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
775 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000776 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000777
Jessica Paquetteaa087322018-06-04 21:14:16 +0000778 case InstrType::LegalTerminator:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000779 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
780 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquettec991cf32018-11-01 23:09:06 +0000781 // The instruction also acts as a terminator, so we have to record that
782 // in the string.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000783 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400784 InstrListForMBB);
Eli Friedman042dc9e2018-05-22 19:11:06 +0000785 break;
786
Jessica Paquetteaa087322018-06-04 21:14:16 +0000787 case InstrType::Invisible:
Jessica Paquettec991cf32018-11-01 23:09:06 +0000788 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
789 // skip this instruction. So, unset the flag here.
Jessica Paquettebd729882018-09-17 18:40:21 +0000790 AddedIllegalLastTime = false;
Jessica Paquette78681be2017-07-27 23:24:43 +0000791 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000792 }
793 }
794
Jessica Paquette267d2662018-11-08 00:02:11 +0000795 // Are there enough legal instructions in the block for outlining to be
796 // possible?
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000797 if (HaveLegalRange) {
Jessica Paquette267d2662018-11-08 00:02:11 +0000798 // After we're done every insertion, uniquely terminate this part of the
799 // "string". This makes sure we won't match across basic block or function
800 // boundaries since the "end" is encoded uniquely and thus appears in no
801 // repeated substring.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000802 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400803 InstrListForMBB);
Jessica Paquette267d2662018-11-08 00:02:11 +0000804 InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
805 InstrListForMBB.end());
806 UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
807 UnsignedVecForMBB.end());
808 }
Jessica Paquette596f4832017-03-06 21:31:18 +0000809 }
810
811 InstructionMapper() {
812 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
813 // changed.
814 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000815 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000816 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000817 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000818 }
819};
820
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000821/// An interprocedural pass which finds repeated sequences of
Jessica Paquette596f4832017-03-06 21:31:18 +0000822/// instructions and replaces them with calls to functions.
823///
824/// Each instruction is mapped to an unsigned integer and placed in a string.
825/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
826/// is then repeatedly queried for repeated sequences of instructions. Each
827/// non-overlapping repeated sequence is then placed in its own
828/// \p MachineFunction and each instance is then replaced with a call to that
829/// function.
830struct MachineOutliner : public ModulePass {
831
832 static char ID;
833
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000834 /// Set to true if the outliner should consider functions with
Jessica Paquette13593842017-10-07 00:16:34 +0000835 /// linkonceodr linkage.
836 bool OutlineFromLinkOnceODRs = false;
837
Jessica Paquette8bda1882018-06-30 03:56:03 +0000838 /// Set to true if the outliner should run on all functions in the module
839 /// considered safe for outlining.
840 /// Set to true by default for compatibility with llc's -run-pass option.
841 /// Set when the pass is constructed in TargetPassConfig.
842 bool RunOnAllFunctions = true;
843
Jessica Paquette596f4832017-03-06 21:31:18 +0000844 StringRef getPassName() const override { return "Machine Outliner"; }
845
846 void getAnalysisUsage(AnalysisUsage &AU) const override {
Yuanfang Chencc382cf2019-09-30 17:54:50 +0000847 AU.addRequired<MachineModuleInfoWrapperPass>();
848 AU.addPreserved<MachineModuleInfoWrapperPass>();
Jessica Paquette596f4832017-03-06 21:31:18 +0000849 AU.setPreservesAll();
850 ModulePass::getAnalysisUsage(AU);
851 }
852
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000853 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000854 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
855 }
856
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000857 /// Remark output explaining that not outlining a set of candidates would be
858 /// better than outlining that set.
859 void emitNotOutliningCheaperRemark(
860 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
861 OutlinedFunction &OF);
862
Jessica Paquette58e706a2018-07-24 20:20:45 +0000863 /// Remark output explaining that a function was outlined.
864 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
865
Jessica Paquettece3a2dc2018-12-05 23:39:07 +0000866 /// Find all repeated substrings that satisfy the outlining cost model by
867 /// constructing a suffix tree.
Jessica Paquette78681be2017-07-27 23:24:43 +0000868 ///
869 /// If a substring appears at least twice, then it must be represented by
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000870 /// an internal node which appears in at least two suffixes. Each suffix
871 /// is represented by a leaf node. To do this, we visit each internal node
872 /// in the tree, using the leaf children of each internal node. If an
873 /// internal node represents a beneficial substring, then we use each of
874 /// its leaf children to find the locations of its substring.
Jessica Paquette78681be2017-07-27 23:24:43 +0000875 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000876 /// \param Mapper Contains outlining mapping information.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000877 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
878 /// each type of candidate.
Jessica Paquettece3a2dc2018-12-05 23:39:07 +0000879 void findCandidates(InstructionMapper &Mapper,
880 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000881
Jessica Paquette4ae3b712018-12-05 22:50:26 +0000882 /// Replace the sequences of instructions represented by \p OutlinedFunctions
883 /// with calls to functions.
Jessica Paquette596f4832017-03-06 21:31:18 +0000884 ///
885 /// \param M The module we are outlining from.
Jessica Paquette596f4832017-03-06 21:31:18 +0000886 /// \param FunctionList A list of functions to be inserted into the module.
887 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette4ae3b712018-12-05 22:50:26 +0000888 bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400889 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
Jessica Paquette596f4832017-03-06 21:31:18 +0000890
891 /// Creates a function for \p OF and inserts it into the module.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +0000892 MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +0000893 InstructionMapper &Mapper,
894 unsigned Name);
Jessica Paquette596f4832017-03-06 21:31:18 +0000895
Puyan Lotfia51fc8d2019-10-28 15:10:21 -0400896 /// Calls 'doOutline()'.
897 bool runOnModule(Module &M) override;
898
Jessica Paquette596f4832017-03-06 21:31:18 +0000899 /// Construct a suffix tree on the instructions in \p M and outline repeated
900 /// strings from that tree.
Puyan Lotfia51fc8d2019-10-28 15:10:21 -0400901 bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
Jessica Paquetteaa087322018-06-04 21:14:16 +0000902
903 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
904 /// function for remark emission.
905 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
Jessica Paquettee18d6ff2018-12-05 23:24:22 +0000906 for (const Candidate &C : OF.Candidates)
Simon Pilgrim7ad25832019-11-05 15:58:04 +0000907 if (MachineFunction *MF = C.getMF())
908 if (DISubprogram *SP = MF->getFunction().getSubprogram())
909 return SP;
Jessica Paquetteaa087322018-06-04 21:14:16 +0000910 return nullptr;
911 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +0000912
913 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
914 /// These are used to construct a suffix tree.
915 void populateMapper(InstructionMapper &Mapper, Module &M,
916 MachineModuleInfo &MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +0000917
Jessica Paquette2386eab2018-09-11 23:05:34 +0000918 /// Initialize information necessary to output a size remark.
919 /// FIXME: This should be handled by the pass manager, not the outliner.
920 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
921 /// pass manager.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400922 void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
923 StringMap<unsigned> &FunctionToInstrCount);
Jessica Paquette2386eab2018-09-11 23:05:34 +0000924
925 /// Emit the remark.
926 // FIXME: This should be handled by the pass manager, not the outliner.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400927 void
928 emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
929 const StringMap<unsigned> &FunctionToInstrCount);
Jessica Paquette2386eab2018-09-11 23:05:34 +0000930};
Jessica Paquette596f4832017-03-06 21:31:18 +0000931} // Anonymous namespace.
932
933char MachineOutliner::ID = 0;
934
935namespace llvm {
Jessica Paquette8bda1882018-06-30 03:56:03 +0000936ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
937 MachineOutliner *OL = new MachineOutliner();
938 OL->RunOnAllFunctions = RunOnAllFunctions;
939 return OL;
Jessica Paquette13593842017-10-07 00:16:34 +0000940}
941
Jessica Paquette78681be2017-07-27 23:24:43 +0000942} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000943
Jessica Paquette78681be2017-07-27 23:24:43 +0000944INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
945 false)
946
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000947void MachineOutliner::emitNotOutliningCheaperRemark(
948 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
949 OutlinedFunction &OF) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000950 // FIXME: Right now, we arbitrarily choose some Candidate from the
951 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
952 // We should probably sort these by function name or something to make sure
953 // the remarks are stable.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000954 Candidate &C = CandidatesForRepeatedSeq.front();
955 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
956 MORE.emit([&]() {
957 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
958 C.front()->getDebugLoc(), C.getMBB());
959 R << "Did not outline " << NV("Length", StringLen) << " instructions"
960 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
961 << " locations."
962 << " Bytes from outlining all occurrences ("
963 << NV("OutliningCost", OF.getOutliningCost()) << ")"
964 << " >= Unoutlined instruction bytes ("
965 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
966 << " (Also found at: ";
967
968 // Tell the user the other places the candidate was found.
969 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
970 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
971 CandidatesForRepeatedSeq[i].front()->getDebugLoc());
972 if (i != e - 1)
973 R << ", ";
974 }
975
976 R << ")";
977 return R;
978 });
979}
980
Jessica Paquette58e706a2018-07-24 20:20:45 +0000981void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
982 MachineBasicBlock *MBB = &*OF.MF->begin();
983 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
984 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
985 MBB->findDebugLoc(MBB->begin()), MBB);
986 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
Jessica Paquette34b618b2018-12-05 17:57:33 +0000987 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
Jessica Paquette58e706a2018-07-24 20:20:45 +0000988 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
989 << " locations. "
990 << "(Found at: ";
991
992 // Tell the user the other places the candidate was found.
993 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
994
Jessica Paquette58e706a2018-07-24 20:20:45 +0000995 R << NV((Twine("StartLoc") + Twine(i)).str(),
Jessica Paquettee18d6ff2018-12-05 23:24:22 +0000996 OF.Candidates[i].front()->getDebugLoc());
Jessica Paquette58e706a2018-07-24 20:20:45 +0000997 if (i != e - 1)
998 R << ", ";
999 }
1000
1001 R << ")";
1002
1003 MORE.emit(R);
1004}
1005
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001006void MachineOutliner::findCandidates(
1007 InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +00001008 FunctionList.clear();
Jessica Paquettece3a2dc2018-12-05 23:39:07 +00001009 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette78681be2017-07-27 23:24:43 +00001010
David Tellenbachfbe7f5e2019-10-30 16:28:11 +00001011 // First, find all of the repeated substrings in the tree of minimum length
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001012 // 2.
Jessica Paquetted4e7d072018-12-06 00:04:03 +00001013 std::vector<Candidate> CandidatesForRepeatedSeq;
Jessica Paquettea409cc92018-11-07 19:20:55 +00001014 for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
Jessica Paquetted4e7d072018-12-06 00:04:03 +00001015 CandidatesForRepeatedSeq.clear();
Jessica Paquettea409cc92018-11-07 19:20:55 +00001016 SuffixTree::RepeatedSubstring RS = *It;
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001017 unsigned StringLen = RS.Length;
1018 for (const unsigned &StartIdx : RS.StartIndices) {
1019 unsigned EndIdx = StartIdx + StringLen - 1;
1020 // Trick: Discard some candidates that would be incompatible with the
1021 // ones we've already found for this sequence. This will save us some
1022 // work in candidate selection.
1023 //
1024 // If two candidates overlap, then we can't outline them both. This
1025 // happens when we have candidates that look like, say
1026 //
1027 // AA (where each "A" is an instruction).
1028 //
1029 // We might have some portion of the module that looks like this:
1030 // AAAAAA (6 A's)
1031 //
1032 // In this case, there are 5 different copies of "AA" in this range, but
1033 // at most 3 can be outlined. If only outlining 3 of these is going to
1034 // be unbeneficial, then we ought to not bother.
1035 //
1036 // Note that two things DON'T overlap when they look like this:
1037 // start1...end1 .... start2...end2
1038 // That is, one must either
1039 // * End before the other starts
1040 // * Start after the other ends
1041 if (std::all_of(
1042 CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
1043 [&StartIdx, &EndIdx](const Candidate &C) {
1044 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
1045 })) {
1046 // It doesn't overlap with anything, so we can outline it.
1047 // Each sequence is over [StartIt, EndIt].
1048 // Save the candidate and its location.
Jessica Paquetted87f5442017-07-29 02:55:46 +00001049
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001050 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1051 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
Jessica Paquettecad864d2018-11-13 23:01:34 +00001052 MachineBasicBlock *MBB = StartIt->getParent();
Jessica Paquette78681be2017-07-27 23:24:43 +00001053
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001054 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
Jessica Paquettecad864d2018-11-13 23:01:34 +00001055 EndIt, MBB, FunctionList.size(),
1056 Mapper.MBBFlagsMap[MBB]);
Jessica Paquette809d7082017-07-28 03:21:58 +00001057 }
1058 }
1059
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001060 // We've found something we might want to outline.
1061 // Create an OutlinedFunction to store it and check if it'd be beneficial
1062 // to outline.
Jessica Paquetteddb039a2018-11-15 00:02:24 +00001063 if (CandidatesForRepeatedSeq.size() < 2)
Eli Friedmanda080782018-08-01 00:37:20 +00001064 continue;
1065
1066 // Arbitrarily choose a TII from the first candidate.
1067 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1068 const TargetInstrInfo *TII =
1069 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1070
Jessica Paquette9d93c602018-07-27 18:21:57 +00001071 OutlinedFunction OF =
Eli Friedmanda080782018-08-01 00:37:20 +00001072 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
Jessica Paquette9d93c602018-07-27 18:21:57 +00001073
Jessica Paquetteb2d53c52018-11-13 22:16:27 +00001074 // If we deleted too many candidates, then there's nothing worth outlining.
1075 // FIXME: This should take target-specified instruction sizes into account.
1076 if (OF.Candidates.size() < 2)
Jessica Paquette9d93c602018-07-27 18:21:57 +00001077 continue;
1078
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001079 // Is it better to outline this candidate than not?
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001080 if (OF.getBenefit() < 1) {
Jessica Paquette1cc52a02018-07-24 17:37:28 +00001081 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001082 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001083 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001084
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001085 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001086 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001087}
1088
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001089MachineFunction *MachineOutliner::createOutlinedFunction(
1090 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001091
Fangrui Songae6c9402019-04-10 14:52:37 +00001092 // Create the function name. This should be unique.
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001093 // FIXME: We should have a better naming scheme. This should be stable,
1094 // regardless of changes to the outliner's cost model/traversal order.
Fangrui Songae6c9402019-04-10 14:52:37 +00001095 std::string FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str();
Jessica Paquette596f4832017-03-06 21:31:18 +00001096
1097 // Create the function using an IR-level function.
1098 LLVMContext &C = M.getContext();
Fangrui Songae6c9402019-04-10 14:52:37 +00001099 Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1100 Function::ExternalLinkage, FunctionName, M);
Jessica Paquette596f4832017-03-06 21:31:18 +00001101
1102 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1103 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001104 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001105 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1106
Eli Friedman25bef202018-05-15 23:36:46 +00001107 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1108 // necessary.
1109
1110 // Set optsize/minsize, so we don't insert padding between outlined
1111 // functions.
1112 F->addFnAttr(Attribute::OptimizeForSize);
1113 F->addFnAttr(Attribute::MinSize);
1114
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001115 // Include target features from an arbitrary candidate for the outlined
1116 // function. This makes sure the outlined function knows what kinds of
1117 // instructions are going into it. This is fine, since all parent functions
1118 // must necessarily support the instructions that are in the outlined region.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001119 Candidate &FirstCand = OF.Candidates.front();
Jessica Paquette34b618b2018-12-05 17:57:33 +00001120 const Function &ParentFn = FirstCand.getMF()->getFunction();
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001121 if (ParentFn.hasFnAttribute("target-features"))
1122 F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1123
Jessica Paquette596f4832017-03-06 21:31:18 +00001124 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1125 IRBuilder<> Builder(EntryBB);
1126 Builder.CreateRetVoid();
1127
Yuanfang Chencc382cf2019-09-30 17:54:50 +00001128 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
Matthias Braun7bda1952017-06-06 00:44:35 +00001129 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001130 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1131 const TargetSubtargetInfo &STI = MF.getSubtarget();
1132 const TargetInstrInfo &TII = *STI.getInstrInfo();
1133
1134 // Insert the new function into the module.
1135 MF.insert(MF.begin(), &MBB);
1136
Jessica Paquette34b618b2018-12-05 17:57:33 +00001137 for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
1138 ++I) {
1139 MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
Chandler Carruthc73c0302018-08-16 21:30:05 +00001140 NewMI->dropMemRefs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001141
1142 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001143 NewMI->setDebugLoc(DebugLoc());
1144 MBB.insert(MBB.end(), NewMI);
1145 }
1146
Jessica Paquette69f517d2018-07-24 20:13:10 +00001147 TII.buildOutlinedFrame(MBB, MF, OF);
Jessica Paquette729e6862018-01-18 00:00:58 +00001148
Jessica Paquettecc06a782018-09-20 18:53:53 +00001149 // Outlined functions shouldn't preserve liveness.
1150 MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1151 MF.getRegInfo().freezeReservedRegs(MF);
1152
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001153 // If there's a DISubprogram associated with this outlined function, then
1154 // emit debug info for the outlined function.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001155 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001156 // We have a DISubprogram. Get its DICompileUnit.
1157 DICompileUnit *CU = SP->getUnit();
1158 DIBuilder DB(M, true, CU);
1159 DIFile *Unit = SP->getFile();
1160 Mangler Mg;
Jessica Paquettecc06a782018-09-20 18:53:53 +00001161 // Get the mangled name of the function for the linkage name.
1162 std::string Dummy;
1163 llvm::raw_string_ostream MangledNameStream(Dummy);
1164 Mg.getNameWithPrefix(MangledNameStream, F, false);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001165
Jessica Paquettecc06a782018-09-20 18:53:53 +00001166 DISubprogram *OutlinedSP = DB.createFunction(
1167 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1168 Unit /* File */,
1169 0 /* Line 0 is reserved for compiler-generated code. */,
1170 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
Paul Robinsoncda54212018-11-19 18:29:28 +00001171 0, /* Line 0 is reserved for compiler-generated code. */
Jessica Paquettecc06a782018-09-20 18:53:53 +00001172 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
Paul Robinsoncda54212018-11-19 18:29:28 +00001173 /* Outlined code is optimized code by definition. */
1174 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001175
Jessica Paquettecc06a782018-09-20 18:53:53 +00001176 // Don't add any new variables to the subprogram.
1177 DB.finalizeSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001178
Jessica Paquettecc06a782018-09-20 18:53:53 +00001179 // Attach subprogram to the function.
1180 F->setSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001181 // We're done with the DIBuilder.
1182 DB.finalize();
1183 }
1184
Jessica Paquette596f4832017-03-06 21:31:18 +00001185 return &MF;
1186}
1187
Jessica Paquette4ae3b712018-12-05 22:50:26 +00001188bool MachineOutliner::outline(Module &M,
1189 std::vector<OutlinedFunction> &FunctionList,
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001190 InstructionMapper &Mapper,
1191 unsigned &OutlinedFunctionNum) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001192
1193 bool OutlinedSomething = false;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001194
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001195 // Sort by benefit. The most beneficial functions should be outlined first.
Fangrui Songefd94c52019-04-23 14:51:27 +00001196 llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
1197 const OutlinedFunction &RHS) {
1198 return LHS.getBenefit() > RHS.getBenefit();
1199 });
Jessica Paquette596f4832017-03-06 21:31:18 +00001200
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001201 // Walk over each function, outlining them as we go along. Functions are
1202 // outlined greedily, based off the sort above.
1203 for (OutlinedFunction &OF : FunctionList) {
1204 // If we outlined something that overlapped with a candidate in a previous
1205 // step, then we can't outline from it.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001206 erase_if(OF.Candidates, [&Mapper](Candidate &C) {
Jessica Paquetted9d93092018-12-05 22:47:25 +00001207 return std::any_of(
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001208 Mapper.UnsignedVec.begin() + C.getStartIdx(),
1209 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
Jessica Paquetted9d93092018-12-05 22:47:25 +00001210 [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
Jessica Paquette235d8772018-12-05 22:27:38 +00001211 });
Jessica Paquette596f4832017-03-06 21:31:18 +00001212
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001213 // If we made it unbeneficial to outline this function, skip it.
Jessica Paquette85af63d2017-10-17 19:03:23 +00001214 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001215 continue;
1216
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001217 // It's beneficial. Create the function and outline its sequence's
1218 // occurrences.
1219 OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
1220 emitOutlinedFunctionRemark(OF);
1221 FunctionsCreated++;
1222 OutlinedFunctionNum++; // Created a function, move to the next name.
Jessica Paquette596f4832017-03-06 21:31:18 +00001223 MachineFunction *MF = OF.MF;
1224 const TargetSubtargetInfo &STI = MF->getSubtarget();
1225 const TargetInstrInfo &TII = *STI.getInstrInfo();
1226
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001227 // Replace occurrences of the sequence with calls to the new function.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001228 for (Candidate &C : OF.Candidates) {
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001229 MachineBasicBlock &MBB = *C.getMBB();
1230 MachineBasicBlock::iterator StartIt = C.front();
1231 MachineBasicBlock::iterator EndIt = C.back();
Jessica Paquette596f4832017-03-06 21:31:18 +00001232
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001233 // Insert the call.
1234 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
Jessica Paquette0b672492018-04-27 23:36:35 +00001235
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001236 // If the caller tracks liveness, then we need to make sure that
1237 // anything we outline doesn't break liveness assumptions. The outlined
1238 // functions themselves currently don't track liveness, but we should
1239 // make sure that the ranges we yank things out of aren't wrong.
1240 if (MBB.getParent()->getProperties().hasProperty(
1241 MachineFunctionProperties::Property::TracksLiveness)) {
1242 // Helper lambda for adding implicit def operands to the call
Djordje Todorovic71d38692019-06-27 13:10:29 +00001243 // instruction. It also updates call site information for moved
1244 // code.
1245 auto CopyDefsAndUpdateCalls = [&CallInst](MachineInstr &MI) {
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001246 for (MachineOperand &MOP : MI.operands()) {
1247 // Skip over anything that isn't a register.
1248 if (!MOP.isReg())
1249 continue;
Jessica Paquette0b672492018-04-27 23:36:35 +00001250
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001251 // If it's a def, add it to the call instruction.
1252 if (MOP.isDef())
1253 CallInst->addOperand(MachineOperand::CreateReg(
1254 MOP.getReg(), true, /* isDef = true */
1255 true /* isImp = true */));
1256 }
Djordje Todorovic71d38692019-06-27 13:10:29 +00001257 if (MI.isCall())
Nikola Prica98603a82019-10-08 15:43:12 +00001258 MI.getMF()->eraseCallSiteInfo(&MI);
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001259 };
1260 // Copy over the defs in the outlined range.
1261 // First inst in outlined range <-- Anything that's defined in this
1262 // ... .. range has to be added as an
1263 // implicit Last inst in outlined range <-- def to the call
Djordje Todorovic71d38692019-06-27 13:10:29 +00001264 // instruction. Also remove call site information for outlined block
1265 // of code.
1266 std::for_each(CallInst, std::next(EndIt), CopyDefsAndUpdateCalls);
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001267 }
1268
1269 // Erase from the point after where the call was inserted up to, and
1270 // including, the final instruction in the sequence.
1271 // Erase needs one past the end, so we need std::next there too.
1272 MBB.erase(std::next(StartIt), std::next(EndIt));
Jessica Paquette235d8772018-12-05 22:27:38 +00001273
Jessica Paquetted9d93092018-12-05 22:47:25 +00001274 // Keep track of what we removed by marking them all as -1.
Jessica Paquette235d8772018-12-05 22:27:38 +00001275 std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1276 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
Jessica Paquetted9d93092018-12-05 22:47:25 +00001277 [](unsigned &I) { I = static_cast<unsigned>(-1); });
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001278 OutlinedSomething = true;
1279
1280 // Statistics.
1281 NumOutlined++;
Jessica Paquette0b672492018-04-27 23:36:35 +00001282 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001283 }
1284
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001285 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001286
1287 return OutlinedSomething;
1288}
1289
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001290void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1291 MachineModuleInfo &MMI) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001292 // Build instruction mappings for each function in the module. Start by
1293 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001294 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001295
Jessica Paquettedf822742018-03-22 21:07:09 +00001296 // If there's nothing in F, then there's no reason to try and outline from
1297 // it.
1298 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001299 continue;
1300
Jessica Paquette784892c2019-10-04 21:24:12 +00001301 // Disable outlining from noreturn functions right now. Noreturn requires
1302 // special handling for the case where what we are outlining could be a
1303 // tail call.
1304 if (F.hasFnAttribute(Attribute::NoReturn))
1305 continue;
1306
Jessica Paquettedf822742018-03-22 21:07:09 +00001307 // There's something in F. Check if it has a MachineFunction associated with
1308 // it.
1309 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001310
Jessica Paquettedf822742018-03-22 21:07:09 +00001311 // If it doesn't, then there's nothing to outline from. Move to the next
1312 // Function.
1313 if (!MF)
1314 continue;
1315
Eli Friedmanda080782018-08-01 00:37:20 +00001316 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1317
Jessica Paquette8bda1882018-06-30 03:56:03 +00001318 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
1319 continue;
1320
Jessica Paquettedf822742018-03-22 21:07:09 +00001321 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1322 // If it isn't, then move on to the next Function in the module.
1323 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1324 continue;
1325
1326 // We have a function suitable for outlining. Iterate over every
1327 // MachineBasicBlock in MF and try to map its instructions to a list of
1328 // unsigned integers.
1329 for (MachineBasicBlock &MBB : *MF) {
1330 // If there isn't anything in MBB, then there's no point in outlining from
1331 // it.
Jessica Paquetteb320ca22018-09-20 21:53:25 +00001332 // If there are fewer than 2 instructions in the MBB, then it can't ever
1333 // contain something worth outlining.
1334 // FIXME: This should be based off of the maximum size in B of an outlined
1335 // call versus the size in B of the MBB.
1336 if (MBB.empty() || MBB.size() < 2)
Jessica Paquette596f4832017-03-06 21:31:18 +00001337 continue;
1338
Jessica Paquettedf822742018-03-22 21:07:09 +00001339 // Check if MBB could be the target of an indirect branch. If it is, then
1340 // we don't want to outline from it.
1341 if (MBB.hasAddressTaken())
1342 continue;
1343
1344 // MBB is suitable for outlining. Map it to a list of unsigneds.
Eli Friedmanda080782018-08-01 00:37:20 +00001345 Mapper.convertToUnsignedVec(MBB, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001346 }
1347 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001348}
1349
Jessica Paquette2386eab2018-09-11 23:05:34 +00001350void MachineOutliner::initSizeRemarkInfo(
1351 const Module &M, const MachineModuleInfo &MMI,
1352 StringMap<unsigned> &FunctionToInstrCount) {
1353 // Collect instruction counts for every function. We'll use this to emit
1354 // per-function size remarks later.
1355 for (const Function &F : M) {
1356 MachineFunction *MF = MMI.getMachineFunction(F);
1357
1358 // We only care about MI counts here. If there's no MachineFunction at this
1359 // point, then there won't be after the outliner runs, so let's move on.
1360 if (!MF)
1361 continue;
1362 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1363 }
1364}
1365
1366void MachineOutliner::emitInstrCountChangedRemark(
1367 const Module &M, const MachineModuleInfo &MMI,
1368 const StringMap<unsigned> &FunctionToInstrCount) {
1369 // Iterate over each function in the module and emit remarks.
1370 // Note that we won't miss anything by doing this, because the outliner never
1371 // deletes functions.
1372 for (const Function &F : M) {
1373 MachineFunction *MF = MMI.getMachineFunction(F);
1374
1375 // The outliner never deletes functions. If we don't have a MF here, then we
1376 // didn't have one prior to outlining either.
1377 if (!MF)
1378 continue;
1379
1380 std::string Fname = F.getName();
1381 unsigned FnCountAfter = MF->getInstructionCount();
1382 unsigned FnCountBefore = 0;
1383
1384 // Check if the function was recorded before.
1385 auto It = FunctionToInstrCount.find(Fname);
1386
1387 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1388 // to that.
1389 if (It != FunctionToInstrCount.end())
1390 FnCountBefore = It->second;
1391
1392 // Compute the delta and emit a remark if there was a change.
1393 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1394 static_cast<int64_t>(FnCountBefore);
1395 if (FnDelta == 0)
1396 continue;
1397
1398 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1399 MORE.emit([&]() {
1400 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001401 DiagnosticLocation(), &MF->front());
Jessica Paquette2386eab2018-09-11 23:05:34 +00001402 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1403 << ": Function: "
1404 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1405 << ": MI instruction count changed from "
1406 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1407 FnCountBefore)
1408 << " to "
1409 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1410 FnCountAfter)
1411 << "; Delta: "
1412 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1413 return R;
1414 });
1415 }
1416}
1417
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001418bool MachineOutliner::runOnModule(Module &M) {
1419 // Check if there's anything in the module. If it's empty, then there's
1420 // nothing to outline.
1421 if (M.empty())
1422 return false;
1423
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001424 // Number to append to the current outlined function.
1425 unsigned OutlinedFunctionNum = 0;
1426
1427 if (!doOutline(M, OutlinedFunctionNum))
1428 return false;
1429 return true;
1430}
1431
1432bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
Yuanfang Chencc382cf2019-09-30 17:54:50 +00001433 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001434
1435 // If the user passed -enable-machine-outliner=always or
1436 // -enable-machine-outliner, the pass will run on all functions in the module.
1437 // Otherwise, if the target supports default outlining, it will run on all
1438 // functions deemed by the target to be worth outlining from by default. Tell
1439 // the user how the outliner is running.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001440 LLVM_DEBUG({
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001441 dbgs() << "Machine Outliner: Running on ";
1442 if (RunOnAllFunctions)
1443 dbgs() << "all functions";
1444 else
1445 dbgs() << "target-default functions";
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001446 dbgs() << "\n";
1447 });
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001448
1449 // If the user specifies that they want to outline from linkonceodrs, set
1450 // it here.
1451 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1452 InstructionMapper Mapper;
1453
1454 // Prepare instruction mappings for the suffix tree.
1455 populateMapper(Mapper, M, MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +00001456 std::vector<OutlinedFunction> FunctionList;
1457
Jessica Paquetteacffa282017-03-23 21:27:38 +00001458 // Find all of the outlining candidates.
Jessica Paquettece3a2dc2018-12-05 23:39:07 +00001459 findCandidates(Mapper, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001460
Jessica Paquette2386eab2018-09-11 23:05:34 +00001461 // If we've requested size remarks, then collect the MI counts of every
1462 // function before outlining, and the MI counts after outlining.
1463 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1464 // the pass manager's responsibility.
1465 // This could pretty easily be placed in outline instead, but because we
1466 // really ultimately *don't* want this here, it's done like this for now
1467 // instead.
1468
1469 // Check if we want size remarks.
1470 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1471 StringMap<unsigned> FunctionToInstrCount;
1472 if (ShouldEmitSizeRemarks)
1473 initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
1474
Jessica Paquetteacffa282017-03-23 21:27:38 +00001475 // Outline each of the candidates and return true if something was outlined.
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001476 bool OutlinedSomething =
1477 outline(M, FunctionList, Mapper, OutlinedFunctionNum);
Jessica Paquette729e6862018-01-18 00:00:58 +00001478
Jessica Paquette2386eab2018-09-11 23:05:34 +00001479 // If we outlined something, we definitely changed the MI count of the
1480 // module. If we've asked for size remarks, then output them.
1481 // FIXME: This should be in the pass manager.
1482 if (ShouldEmitSizeRemarks && OutlinedSomething)
1483 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
1484
Jessica Paquette729e6862018-01-18 00:00:58 +00001485 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001486}