blob: d56f113aa7fd8a16699daa1999d2852869bacba7 [file] [log] [blame]
Jessica Paquette596f4832017-03-06 21:31:18 +00001//===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// Replaces repeated sequences of instructions with function calls.
12///
13/// This works by placing every instruction from every basic block in a
14/// suffix tree, and repeatedly querying that tree for repeated sequences of
15/// instructions. If a sequence of instructions appears often, then it ought
16/// to be beneficial to pull out into a function.
17///
Jessica Paquette4cf187b2017-09-27 20:47:39 +000018/// The MachineOutliner communicates with a given target using hooks defined in
19/// TargetInstrInfo.h. The target supplies the outliner with information on how
20/// a specific sequence of instructions should be outlined. This information
21/// is used to deduce the number of instructions necessary to
22///
23/// * Create an outlined function
24/// * Call that outlined function
25///
26/// Targets must implement
27/// * getOutliningCandidateInfo
28/// * insertOutlinerEpilogue
29/// * insertOutlinedCall
30/// * insertOutlinerPrologue
31/// * isFunctionSafeToOutlineFrom
32///
33/// in order to make use of the MachineOutliner.
34///
Jessica Paquette596f4832017-03-06 21:31:18 +000035/// This was originally presented at the 2016 LLVM Developers' Meeting in the
36/// talk "Reducing Code Size Using Outlining". For a high-level overview of
37/// how this pass works, the talk is available on YouTube at
38///
39/// https://www.youtube.com/watch?v=yorld-WSOeU
40///
41/// The slides for the talk are available at
42///
43/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
44///
45/// The talk provides an overview of how the outliner finds candidates and
46/// ultimately outlines them. It describes how the main data structure for this
47/// pass, the suffix tree, is queried and purged for candidates. It also gives
48/// a simplified suffix tree construction algorithm for suffix trees based off
49/// of the algorithm actually used here, Ukkonen's algorithm.
50///
51/// For the original RFC for this pass, please see
52///
53/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
54///
55/// For more information on the suffix tree data structure, please see
56/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
57///
58//===----------------------------------------------------------------------===//
59#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/Statistic.h"
61#include "llvm/ADT/Twine.h"
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/TargetRegisterInfo.h"
69#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jessica Paquette729e6862018-01-18 00:00:58 +000070#include "llvm/IR/DIBuilder.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000071#include "llvm/IR/IRBuilder.h"
Jessica Paquettea499c3c2018-01-19 21:21:49 +000072#include "llvm/IR/Mangler.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000073#include "llvm/Support/Allocator.h"
Jessica Paquette1eca23b2018-04-19 22:17:07 +000074#include "llvm/Support/CommandLine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000075#include "llvm/Support/Debug.h"
76#include "llvm/Support/raw_ostream.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000077#include <functional>
78#include <map>
79#include <sstream>
80#include <tuple>
81#include <vector>
82
83#define DEBUG_TYPE "machine-outliner"
84
85using namespace llvm;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000086using namespace ore;
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
Jessica Paquetteacffa282017-03-23 21:27:38 +0000104/// \brief An individual sequence of instructions to be replaced with a call to
105/// an outlined function.
106struct Candidate {
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000107private:
108 /// The start index of this \p Candidate in the instruction list.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000109 unsigned StartIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000110
111 /// The number of instructions in this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000112 unsigned Len;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000113
Jessica Paquettea499c3c2018-01-19 21:21:49 +0000114 /// The MachineFunction containing this \p Candidate.
115 MachineFunction *MF = nullptr;
116
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000117public:
118 /// Set to false if the candidate overlapped with another candidate.
119 bool InCandidateList = true;
120
121 /// \brief The index of this \p Candidate's \p OutlinedFunction in the list of
Jessica Paquetteacffa282017-03-23 21:27:38 +0000122 /// \p OutlinedFunctions.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000123 unsigned FunctionIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000124
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000125 /// Contains all target-specific information for this \p Candidate.
126 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000127
Jessica Paquettea499c3c2018-01-19 21:21:49 +0000128 /// If there is a DISubprogram associated with the function that this
129 /// Candidate lives in, return it.
130 DISubprogram *getSubprogramOrNull() const {
131 assert(MF && "Candidate has no MF!");
132 if (DISubprogram *SP = MF->getFunction().getSubprogram())
133 return SP;
134 return nullptr;
135 }
136
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000137 /// Return the number of instructions in this Candidate.
Jessica Paquette1934fd22017-10-23 16:25:53 +0000138 unsigned getLength() const { return Len; }
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000139
140 /// Return the start index of this candidate.
Jessica Paquette1934fd22017-10-23 16:25:53 +0000141 unsigned getStartIdx() const { return StartIdx; }
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000142
143 // Return the end index of this candidate.
Jessica Paquette1934fd22017-10-23 16:25:53 +0000144 unsigned getEndIdx() const { return StartIdx + Len - 1; }
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000145
Jessica Paquetteacffa282017-03-23 21:27:38 +0000146 /// \brief The number of instructions that would be saved by outlining every
147 /// candidate of this type.
148 ///
149 /// This is a fixed value which is not updated during the candidate pruning
150 /// process. It is only used for deciding which candidate to keep if two
151 /// candidates overlap. The true benefit is stored in the OutlinedFunction
152 /// for some given candidate.
153 unsigned Benefit = 0;
154
Jessica Paquettea499c3c2018-01-19 21:21:49 +0000155 Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx,
156 MachineFunction *MF)
157 : StartIdx(StartIdx), Len(Len), MF(MF), FunctionIdx(FunctionIdx) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000158
159 Candidate() {}
160
161 /// \brief Used to ensure that \p Candidates are outlined in an order that
162 /// preserves the start and end indices of other \p Candidates.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000163 bool operator<(const Candidate &RHS) const {
Jessica Paquette1934fd22017-10-23 16:25:53 +0000164 return getStartIdx() > RHS.getStartIdx();
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000165 }
Jessica Paquetteacffa282017-03-23 21:27:38 +0000166};
167
168/// \brief The information necessary to create an outlined function for some
169/// class of candidate.
170struct OutlinedFunction {
171
Jessica Paquette85af63d2017-10-17 19:03:23 +0000172private:
173 /// The number of candidates for this \p OutlinedFunction.
174 unsigned OccurrenceCount = 0;
175
176public:
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000177 std::vector<std::shared_ptr<Candidate>> Candidates;
178
Jessica Paquetteacffa282017-03-23 21:27:38 +0000179 /// The actual outlined function created.
180 /// This is initialized after we go through and create the actual function.
181 MachineFunction *MF = nullptr;
182
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000183 /// A number assigned to this function which appears at the end of its name.
184 unsigned Name;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000185
Jessica Paquetteacffa282017-03-23 21:27:38 +0000186 /// \brief The sequence of integers corresponding to the instructions in this
187 /// function.
188 std::vector<unsigned> Sequence;
189
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000190 /// Contains all target-specific information for this \p OutlinedFunction.
191 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000192
Jessica Paquettea499c3c2018-01-19 21:21:49 +0000193 /// If there is a DISubprogram for any Candidate for this outlined function,
194 /// then return it. Otherwise, return nullptr.
195 DISubprogram *getSubprogramOrNull() const {
196 for (const auto &C : Candidates)
197 if (DISubprogram *SP = C->getSubprogramOrNull())
198 return SP;
199 return nullptr;
200 }
201
Jessica Paquette85af63d2017-10-17 19:03:23 +0000202 /// Return the number of candidates for this \p OutlinedFunction.
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000203 unsigned getOccurrenceCount() { return OccurrenceCount; }
Jessica Paquette85af63d2017-10-17 19:03:23 +0000204
205 /// Decrement the occurrence count of this OutlinedFunction and return the
206 /// new count.
207 unsigned decrement() {
208 assert(OccurrenceCount > 0 && "Can't decrement an empty function!");
209 OccurrenceCount--;
210 return getOccurrenceCount();
211 }
212
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000213 /// \brief Return the number of instructions it would take to outline this
214 /// function.
215 unsigned getOutliningCost() {
216 return (OccurrenceCount * MInfo.CallOverhead) + Sequence.size() +
217 MInfo.FrameOverhead;
218 }
219
220 /// \brief Return the number of instructions that would be saved by outlining
221 /// this function.
222 unsigned getBenefit() {
223 unsigned NotOutlinedCost = OccurrenceCount * Sequence.size();
224 unsigned OutlinedCost = getOutliningCost();
225 return (NotOutlinedCost < OutlinedCost) ? 0
226 : NotOutlinedCost - OutlinedCost;
227 }
228
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000229 OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000230 const std::vector<unsigned> &Sequence,
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000231 TargetInstrInfo::MachineOutlinerInfo &MInfo)
Jessica Paquette85af63d2017-10-17 19:03:23 +0000232 : OccurrenceCount(OccurrenceCount), Name(Name), Sequence(Sequence),
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000233 MInfo(MInfo) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000234};
235
Jessica Paquette596f4832017-03-06 21:31:18 +0000236/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000237const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000238
239/// A node in a suffix tree which represents a substring or suffix.
240///
241/// Each node has either no children or at least two children, with the root
242/// being a exception in the empty tree.
243///
244/// Children are represented as a map between unsigned integers and nodes. If
245/// a node N has a child M on unsigned integer k, then the mapping represented
246/// by N is a proper prefix of the mapping represented by M. Note that this,
247/// although similar to a trie is somewhat different: each node stores a full
248/// substring of the full mapping rather than a single character state.
249///
250/// Each internal node contains a pointer to the internal node representing
251/// the same string, but with the first character chopped off. This is stored
252/// in \p Link. Each leaf node stores the start index of its respective
253/// suffix in \p SuffixIdx.
254struct SuffixTreeNode {
255
256 /// The children of this node.
257 ///
258 /// A child existing on an unsigned integer implies that from the mapping
259 /// represented by the current node, there is a way to reach another
260 /// mapping by tacking that character on the end of the current string.
261 DenseMap<unsigned, SuffixTreeNode *> Children;
262
263 /// A flag set to false if the node has been pruned from the tree.
264 bool IsInTree = true;
265
266 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000267 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000268
269 /// The end index of this node's substring in the main string.
270 ///
271 /// Every leaf node must have its \p EndIdx incremented at the end of every
272 /// step in the construction algorithm. To avoid having to update O(N)
273 /// nodes individually at the end of every step, the end index is stored
274 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000275 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000276
277 /// For leaves, the start index of the suffix represented by this node.
278 ///
279 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000280 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000281
282 /// \brief For internal nodes, a pointer to the internal node representing
283 /// the same sequence with the first character chopped off.
284 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000285 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000286 /// Ukkonen's algorithm does to achieve linear-time construction is
287 /// keep track of which node the next insert should be at. This makes each
288 /// insert O(1), and there are a total of O(N) inserts. The suffix link
289 /// helps with inserting children of internal nodes.
290 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000291 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000292 /// next insertion must be at the node representing S - its first character.
293 /// This is given by the way that we iteratively build the tree in Ukkonen's
294 /// algorithm. The main idea is to look at the suffixes of each prefix in the
295 /// string, starting with the longest suffix of the prefix, and ending with
296 /// the shortest. Therefore, if we keep pointers between such nodes, we can
297 /// move to the next insertion point in O(1) time. If we don't, then we'd
298 /// have to query from the root, which takes O(N) time. This would make the
299 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000300 SuffixTreeNode *Link = nullptr;
301
302 /// The parent of this node. Every node except for the root has a parent.
303 SuffixTreeNode *Parent = nullptr;
304
305 /// The number of times this node's string appears in the tree.
306 ///
307 /// This is equal to the number of leaf children of the string. It represents
308 /// the number of suffixes that the node's string is a prefix of.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000309 unsigned OccurrenceCount = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000310
Jessica Paquetteacffa282017-03-23 21:27:38 +0000311 /// The length of the string formed by concatenating the edge labels from the
312 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000313 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000314
Jessica Paquette596f4832017-03-06 21:31:18 +0000315 /// Returns true if this node is a leaf.
316 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
317
318 /// Returns true if this node is the root of its owning \p SuffixTree.
319 bool isRoot() const { return StartIdx == EmptyIdx; }
320
321 /// Return the number of elements in the substring associated with this node.
322 size_t size() const {
323
324 // Is it the root? If so, it's the empty string so return 0.
325 if (isRoot())
326 return 0;
327
328 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
329
330 // Size = the number of elements in the string.
331 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
332 return *EndIdx - StartIdx + 1;
333 }
334
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000335 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000336 SuffixTreeNode *Parent)
337 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
338
339 SuffixTreeNode() {}
340};
341
342/// A data structure for fast substring queries.
343///
344/// Suffix trees represent the suffixes of their input strings in their leaves.
345/// A suffix tree is a type of compressed trie structure where each node
346/// represents an entire substring rather than a single character. Each leaf
347/// of the tree is a suffix.
348///
349/// A suffix tree can be seen as a type of state machine where each state is a
350/// substring of the full string. The tree is structured so that, for a string
351/// of length N, there are exactly N leaves in the tree. This structure allows
352/// us to quickly find repeated substrings of the input string.
353///
354/// In this implementation, a "string" is a vector of unsigned integers.
355/// These integers may result from hashing some data type. A suffix tree can
356/// contain 1 or many strings, which can then be queried as one large string.
357///
358/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
359/// suffix tree construction. Ukkonen's algorithm is explained in more detail
360/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
361/// paper is available at
362///
363/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
364class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000365public:
366 /// Stores each leaf node in the tree.
367 ///
368 /// This is used for finding outlining candidates.
369 std::vector<SuffixTreeNode *> LeafVector;
370
Jessica Paquette596f4832017-03-06 21:31:18 +0000371 /// Each element is an integer representing an instruction in the module.
372 ArrayRef<unsigned> Str;
373
Jessica Paquette78681be2017-07-27 23:24:43 +0000374private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000375 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000376 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000377
378 /// The root of the suffix tree.
379 ///
380 /// The root represents the empty string. It is maintained by the
381 /// \p NodeAllocator like every other node in the tree.
382 SuffixTreeNode *Root = nullptr;
383
Jessica Paquette596f4832017-03-06 21:31:18 +0000384 /// Maintains the end indices of the internal nodes in the tree.
385 ///
386 /// Each internal node is guaranteed to never have its end index change
387 /// during the construction algorithm; however, leaves must be updated at
388 /// every step. Therefore, we need to store leaf end indices by reference
389 /// to avoid updating O(N) leaves at every step of construction. Thus,
390 /// every internal node must be allocated its own end index.
391 BumpPtrAllocator InternalEndIdxAllocator;
392
393 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000394 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000395
396 /// \brief Helper struct which keeps track of the next insertion point in
397 /// Ukkonen's algorithm.
398 struct ActiveState {
399 /// The next node to insert at.
400 SuffixTreeNode *Node;
401
402 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000403 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000404
405 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000406 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000407 };
408
409 /// \brief The point the next insertion will take place at in the
410 /// construction algorithm.
411 ActiveState Active;
412
413 /// Allocate a leaf node and add it to the tree.
414 ///
415 /// \param Parent The parent of this node.
416 /// \param StartIdx The start index of this node's associated string.
417 /// \param Edge The label on the edge leaving \p Parent to this node.
418 ///
419 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000420 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000421 unsigned Edge) {
422
423 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
424
Jessica Paquette78681be2017-07-27 23:24:43 +0000425 SuffixTreeNode *N = new (NodeAllocator.Allocate())
426 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000427 Parent.Children[Edge] = N;
428
429 return N;
430 }
431
432 /// Allocate an internal node and add it to the tree.
433 ///
434 /// \param Parent The parent of this node. Only null when allocating the root.
435 /// \param StartIdx The start index of this node's associated string.
436 /// \param EndIdx The end index of this node's associated string.
437 /// \param Edge The label on the edge leaving \p Parent to this node.
438 ///
439 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000440 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
441 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000442
443 assert(StartIdx <= EndIdx && "String can't start after it ends!");
444 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000445 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000446
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000447 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000448 SuffixTreeNode *N = new (NodeAllocator.Allocate())
449 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000450 if (Parent)
451 Parent->Children[Edge] = N;
452
453 return N;
454 }
455
456 /// \brief Set the suffix indices of the leaves to the start indices of their
457 /// respective suffixes. Also stores each leaf in \p LeafVector at its
458 /// respective suffix index.
459 ///
460 /// \param[in] CurrNode The node currently being visited.
461 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000462 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000463
464 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
465
Jessica Paquetteacffa282017-03-23 21:27:38 +0000466 // Store the length of the concatenation of all strings from the root to
467 // this node.
468 if (!CurrNode.isRoot()) {
469 if (CurrNode.ConcatLen == 0)
470 CurrNode.ConcatLen = CurrNode.size();
471
472 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000473 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000474 }
475
Jessica Paquette596f4832017-03-06 21:31:18 +0000476 // Traverse the tree depth-first.
477 for (auto &ChildPair : CurrNode.Children) {
478 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000479 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000480 }
481
482 // Is this node a leaf?
483 if (IsLeaf) {
484 // If yes, give it a suffix index and bump its parent's occurrence count.
485 CurrNode.SuffixIdx = Str.size() - CurrIdx;
486 assert(CurrNode.Parent && "CurrNode had no parent!");
487 CurrNode.Parent->OccurrenceCount++;
488
489 // Store the leaf in the leaf vector for pruning later.
490 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
491 }
492 }
493
494 /// \brief Construct the suffix tree for the prefix of the input ending at
495 /// \p EndIdx.
496 ///
497 /// Used to construct the full suffix tree iteratively. At the end of each
498 /// step, the constructed suffix tree is either a valid suffix tree, or a
499 /// suffix tree with implicit suffixes. At the end of the final step, the
500 /// suffix tree is a valid tree.
501 ///
502 /// \param EndIdx The end index of the current prefix in the main string.
503 /// \param SuffixesToAdd The number of suffixes that must be added
504 /// to complete the suffix tree at the current phase.
505 ///
506 /// \returns The number of suffixes that have not been added at the end of
507 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000508 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000509 SuffixTreeNode *NeedsLink = nullptr;
510
511 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000512
Jessica Paquette596f4832017-03-06 21:31:18 +0000513 // Are we waiting to add anything other than just the last character?
514 if (Active.Len == 0) {
515 // If not, then say the active index is the end index.
516 Active.Idx = EndIdx;
517 }
518
519 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
520
521 // The first character in the current substring we're looking at.
522 unsigned FirstChar = Str[Active.Idx];
523
524 // Have we inserted anything starting with FirstChar at the current node?
525 if (Active.Node->Children.count(FirstChar) == 0) {
526 // If not, then we can just insert a leaf and move too the next step.
527 insertLeaf(*Active.Node, EndIdx, FirstChar);
528
529 // The active node is an internal node, and we visited it, so it must
530 // need a link if it doesn't have one.
531 if (NeedsLink) {
532 NeedsLink->Link = Active.Node;
533 NeedsLink = nullptr;
534 }
535 } else {
536 // There's a match with FirstChar, so look for the point in the tree to
537 // insert a new node.
538 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
539
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000540 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000541
542 // Is the current suffix we're trying to insert longer than the size of
543 // the child we want to move to?
544 if (Active.Len >= SubstringLen) {
545 // If yes, then consume the characters we've seen and move to the next
546 // node.
547 Active.Idx += SubstringLen;
548 Active.Len -= SubstringLen;
549 Active.Node = NextNode;
550 continue;
551 }
552
553 // Otherwise, the suffix we're trying to insert must be contained in the
554 // next node we want to move to.
555 unsigned LastChar = Str[EndIdx];
556
557 // Is the string we're trying to insert a substring of the next node?
558 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
559 // If yes, then we're done for this step. Remember our insertion point
560 // and move to the next end index. At this point, we have an implicit
561 // suffix tree.
562 if (NeedsLink && !Active.Node->isRoot()) {
563 NeedsLink->Link = Active.Node;
564 NeedsLink = nullptr;
565 }
566
567 Active.Len++;
568 break;
569 }
570
571 // The string we're trying to insert isn't a substring of the next node,
572 // but matches up to a point. Split the node.
573 //
574 // For example, say we ended our search at a node n and we're trying to
575 // insert ABD. Then we'll create a new node s for AB, reduce n to just
576 // representing C, and insert a new leaf node l to represent d. This
577 // allows us to ensure that if n was a leaf, it remains a leaf.
578 //
579 // | ABC ---split---> | AB
580 // n s
581 // C / \ D
582 // n l
583
584 // The node s from the diagram
585 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000586 insertInternalNode(Active.Node, NextNode->StartIdx,
587 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000588
589 // Insert the new node representing the new substring into the tree as
590 // a child of the split node. This is the node l from the diagram.
591 insertLeaf(*SplitNode, EndIdx, LastChar);
592
593 // Make the old node a child of the split node and update its start
594 // index. This is the node n from the diagram.
595 NextNode->StartIdx += Active.Len;
596 NextNode->Parent = SplitNode;
597 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
598
599 // SplitNode is an internal node, update the suffix link.
600 if (NeedsLink)
601 NeedsLink->Link = SplitNode;
602
603 NeedsLink = SplitNode;
604 }
605
606 // We've added something new to the tree, so there's one less suffix to
607 // add.
608 SuffixesToAdd--;
609
610 if (Active.Node->isRoot()) {
611 if (Active.Len > 0) {
612 Active.Len--;
613 Active.Idx = EndIdx - SuffixesToAdd + 1;
614 }
615 } else {
616 // Start the next phase at the next smallest suffix.
617 Active.Node = Active.Node->Link;
618 }
619 }
620
621 return SuffixesToAdd;
622 }
623
Jessica Paquette596f4832017-03-06 21:31:18 +0000624public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000625 /// Construct a suffix tree from a sequence of unsigned integers.
626 ///
627 /// \param Str The string to construct the suffix tree for.
628 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
629 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
630 Root->IsInTree = true;
631 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000632 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000633
634 // Keep track of the number of suffixes we have to add of the current
635 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000636 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000637 Active.Node = Root;
638
639 // Construct the suffix tree iteratively on each prefix of the string.
640 // PfxEndIdx is the end index of the current prefix.
641 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000642 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
643 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000644 SuffixesToAdd++;
645 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
646 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
647 }
648
649 // Set the suffix indices of each leaf.
650 assert(Root && "Root node can't be nullptr!");
651 setSuffixIndices(*Root, 0);
652 }
653};
654
Jessica Paquette596f4832017-03-06 21:31:18 +0000655/// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
656struct InstructionMapper {
657
658 /// \brief The next available integer to assign to a \p MachineInstr that
659 /// cannot be outlined.
660 ///
661 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
662 unsigned IllegalInstrNumber = -3;
663
664 /// \brief The next available integer to assign to a \p MachineInstr that can
665 /// be outlined.
666 unsigned LegalInstrNumber = 0;
667
668 /// Correspondence from \p MachineInstrs to unsigned integers.
669 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
670 InstructionIntegerMap;
671
672 /// Corresponcence from unsigned integers to \p MachineInstrs.
673 /// Inverse of \p InstructionIntegerMap.
674 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
675
676 /// The vector of unsigned integers that the module is mapped to.
677 std::vector<unsigned> UnsignedVec;
678
679 /// \brief Stores the location of the instruction associated with the integer
680 /// at index i in \p UnsignedVec for each index i.
681 std::vector<MachineBasicBlock::iterator> InstrList;
682
683 /// \brief Maps \p *It to a legal integer.
684 ///
685 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
686 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
687 ///
688 /// \returns The integer that \p *It was mapped to.
689 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
690
691 // Get the integer for this instruction or give it the current
692 // LegalInstrNumber.
693 InstrList.push_back(It);
694 MachineInstr &MI = *It;
695 bool WasInserted;
696 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000697 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000698 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000699 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000700 unsigned MINumber = ResultIt->second;
701
702 // There was an insertion.
703 if (WasInserted) {
704 LegalInstrNumber++;
705 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
706 }
707
708 UnsignedVec.push_back(MINumber);
709
710 // Make sure we don't overflow or use any integers reserved by the DenseMap.
711 if (LegalInstrNumber >= IllegalInstrNumber)
712 report_fatal_error("Instruction mapping overflow!");
713
Jessica Paquette78681be2017-07-27 23:24:43 +0000714 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
715 "Tried to assign DenseMap tombstone or empty key to instruction.");
716 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
717 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000718
719 return MINumber;
720 }
721
722 /// Maps \p *It to an illegal integer.
723 ///
724 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
725 ///
726 /// \returns The integer that \p *It was mapped to.
727 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
728 unsigned MINumber = IllegalInstrNumber;
729
730 InstrList.push_back(It);
731 UnsignedVec.push_back(IllegalInstrNumber);
732 IllegalInstrNumber--;
733
734 assert(LegalInstrNumber < IllegalInstrNumber &&
735 "Instruction mapping overflow!");
736
Jessica Paquette78681be2017-07-27 23:24:43 +0000737 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
738 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000739
Jessica Paquette78681be2017-07-27 23:24:43 +0000740 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
741 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000742
743 return MINumber;
744 }
745
746 /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
747 /// and appends it to \p UnsignedVec and \p InstrList.
748 ///
749 /// Two instructions are assigned the same integer if they are identical.
750 /// If an instruction is deemed unsafe to outline, then it will be assigned an
751 /// unique integer. The resulting mapping is placed into a suffix tree and
752 /// queried for candidates.
753 ///
754 /// \param MBB The \p MachineBasicBlock to be translated into integers.
755 /// \param TRI \p TargetRegisterInfo for the module.
756 /// \param TII \p TargetInstrInfo for the module.
757 void convertToUnsignedVec(MachineBasicBlock &MBB,
758 const TargetRegisterInfo &TRI,
759 const TargetInstrInfo &TII) {
Jessica Paquette3291e732018-01-09 00:26:18 +0000760 unsigned Flags = TII.getMachineOutlinerMBBFlags(MBB);
761
Jessica Paquette596f4832017-03-06 21:31:18 +0000762 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
763 It++) {
764
765 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000766 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000767 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
768 mapToIllegalUnsigned(It);
769 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000770
Jessica Paquette78681be2017-07-27 23:24:43 +0000771 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
772 mapToLegalUnsigned(It);
773 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000774
Jessica Paquette78681be2017-07-27 23:24:43 +0000775 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
776 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000777 }
778 }
779
780 // After we're done every insertion, uniquely terminate this part of the
781 // "string". This makes sure we won't match across basic block or function
782 // boundaries since the "end" is encoded uniquely and thus appears in no
783 // repeated substring.
784 InstrList.push_back(MBB.end());
785 UnsignedVec.push_back(IllegalInstrNumber);
786 IllegalInstrNumber--;
787 }
788
789 InstructionMapper() {
790 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
791 // changed.
792 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000793 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000794 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000795 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000796 }
797};
798
799/// \brief An interprocedural pass which finds repeated sequences of
800/// instructions and replaces them with calls to functions.
801///
802/// Each instruction is mapped to an unsigned integer and placed in a string.
803/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
804/// is then repeatedly queried for repeated sequences of instructions. Each
805/// non-overlapping repeated sequence is then placed in its own
806/// \p MachineFunction and each instance is then replaced with a call to that
807/// function.
808struct MachineOutliner : public ModulePass {
809
810 static char ID;
811
Jessica Paquette13593842017-10-07 00:16:34 +0000812 /// \brief Set to true if the outliner should consider functions with
813 /// linkonceodr linkage.
814 bool OutlineFromLinkOnceODRs = false;
815
Jessica Paquette729e6862018-01-18 00:00:58 +0000816 // Collection of IR functions created by the outliner.
817 std::vector<Function *> CreatedIRFunctions;
818
Jessica Paquette596f4832017-03-06 21:31:18 +0000819 StringRef getPassName() const override { return "Machine Outliner"; }
820
821 void getAnalysisUsage(AnalysisUsage &AU) const override {
822 AU.addRequired<MachineModuleInfo>();
823 AU.addPreserved<MachineModuleInfo>();
824 AU.setPreservesAll();
825 ModulePass::getAnalysisUsage(AU);
826 }
827
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000828 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000829 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
830 }
831
Jessica Paquette78681be2017-07-27 23:24:43 +0000832 /// Find all repeated substrings that satisfy the outlining cost model.
833 ///
834 /// If a substring appears at least twice, then it must be represented by
835 /// an internal node which appears in at least two suffixes. Each suffix is
836 /// represented by a leaf node. To do this, we visit each internal node in
837 /// the tree, using the leaf children of each internal node. If an internal
838 /// node represents a beneficial substring, then we use each of its leaf
839 /// children to find the locations of its substring.
840 ///
841 /// \param ST A suffix tree to query.
842 /// \param TII TargetInstrInfo for the target.
843 /// \param Mapper Contains outlining mapping information.
844 /// \param[out] CandidateList Filled with candidates representing each
845 /// beneficial substring.
846 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
847 /// type of candidate.
848 ///
849 /// \returns The length of the longest candidate found.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000850 unsigned
851 findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
852 InstructionMapper &Mapper,
853 std::vector<std::shared_ptr<Candidate>> &CandidateList,
854 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000855
Jessica Paquette596f4832017-03-06 21:31:18 +0000856 /// \brief Replace the sequences of instructions represented by the
857 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
858 /// described in \p FunctionList.
859 ///
860 /// \param M The module we are outlining from.
861 /// \param CandidateList A list of candidates to be outlined.
862 /// \param FunctionList A list of functions to be inserted into the module.
863 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000864 bool outline(Module &M,
865 const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000866 std::vector<OutlinedFunction> &FunctionList,
867 InstructionMapper &Mapper);
868
869 /// Creates a function for \p OF and inserts it into the module.
870 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
871 InstructionMapper &Mapper);
872
873 /// Find potential outlining candidates and store them in \p CandidateList.
874 ///
875 /// For each type of potential candidate, also build an \p OutlinedFunction
876 /// struct containing the information to build the function for that
877 /// candidate.
878 ///
879 /// \param[out] CandidateList Filled with outlining candidates for the module.
880 /// \param[out] FunctionList Filled with functions corresponding to each type
881 /// of \p Candidate.
882 /// \param ST The suffix tree for the module.
883 /// \param TII TargetInstrInfo for the module.
884 ///
885 /// \returns The length of the longest candidate found. 0 if there are none.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000886 unsigned
887 buildCandidateList(std::vector<std::shared_ptr<Candidate>> &CandidateList,
888 std::vector<OutlinedFunction> &FunctionList,
889 SuffixTree &ST, InstructionMapper &Mapper,
890 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000891
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000892 /// Helper function for pruneOverlaps.
893 /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
894 void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
895
Jessica Paquette596f4832017-03-06 21:31:18 +0000896 /// \brief Remove any overlapping candidates that weren't handled by the
897 /// suffix tree's pruning method.
898 ///
899 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
900 /// If a short candidate is chosen for outlining, then a longer candidate
901 /// which has that short candidate as a suffix is chosen, the tree's pruning
902 /// method will not find it. Thus, we need to prune before outlining as well.
903 ///
904 /// \param[in,out] CandidateList A list of outlining candidates.
905 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000906 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000907 /// \param MaxCandidateLen The length of the longest candidate.
908 /// \param TII TargetInstrInfo for the module.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000909 void pruneOverlaps(std::vector<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000910 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000911 InstructionMapper &Mapper, unsigned MaxCandidateLen,
912 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000913
914 /// Construct a suffix tree on the instructions in \p M and outline repeated
915 /// strings from that tree.
916 bool runOnModule(Module &M) override;
917};
918
919} // Anonymous namespace.
920
921char MachineOutliner::ID = 0;
922
923namespace llvm {
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000924ModulePass *createMachineOutlinerPass() {
925 return new MachineOutliner();
Jessica Paquette13593842017-10-07 00:16:34 +0000926}
927
Jessica Paquette78681be2017-07-27 23:24:43 +0000928} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000929
Jessica Paquette78681be2017-07-27 23:24:43 +0000930INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
931 false)
932
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000933unsigned MachineOutliner::findCandidates(
934 SuffixTree &ST, const TargetInstrInfo &TII, InstructionMapper &Mapper,
935 std::vector<std::shared_ptr<Candidate>> &CandidateList,
936 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000937 CandidateList.clear();
938 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000939 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +0000940
941 // FIXME: Visit internal nodes instead of leaves.
942 for (SuffixTreeNode *Leaf : ST.LeafVector) {
943 assert(Leaf && "Leaves in LeafVector cannot be null!");
944 if (!Leaf->IsInTree)
945 continue;
946
947 assert(Leaf->Parent && "All leaves must have parents!");
948 SuffixTreeNode &Parent = *(Leaf->Parent);
949
950 // If it doesn't appear enough, or we already outlined from it, skip it.
951 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
952 continue;
953
Jessica Paquette809d7082017-07-28 03:21:58 +0000954 // Figure out if this candidate is beneficial.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000955 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
Jessica Paquette95c11072017-08-14 22:57:41 +0000956
957 // Too short to be beneficial; skip it.
958 // FIXME: This isn't necessarily true for, say, X86. If we factor in
959 // instruction lengths we need more information than this.
960 if (StringLen < 2)
961 continue;
962
Jessica Paquetted87f5442017-07-29 02:55:46 +0000963 // If this is a beneficial class of candidate, then every one is stored in
964 // this vector.
965 std::vector<Candidate> CandidatesForRepeatedSeq;
966
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000967 // Describes the start and end point of each candidate. This allows the
968 // target to infer some information about each occurrence of each repeated
969 // sequence.
Jessica Paquetted87f5442017-07-29 02:55:46 +0000970 // FIXME: CandidatesForRepeatedSeq and this should be combined.
971 std::vector<
972 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000973 RepeatedSequenceLocs;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000974
Jessica Paquette809d7082017-07-28 03:21:58 +0000975 // Figure out the call overhead for each instance of the sequence.
976 for (auto &ChildPair : Parent.Children) {
977 SuffixTreeNode *M = ChildPair.second;
Jessica Paquette78681be2017-07-27 23:24:43 +0000978
Jessica Paquette809d7082017-07-28 03:21:58 +0000979 if (M && M->IsInTree && M->isLeaf()) {
Jessica Paquetted87f5442017-07-29 02:55:46 +0000980 // Never visit this leaf again.
981 M->IsInTree = false;
Jessica Paquette52df8012017-12-01 21:56:56 +0000982 unsigned StartIdx = M->SuffixIdx;
983 unsigned EndIdx = StartIdx + StringLen - 1;
984
985 // Trick: Discard some candidates that would be incompatible with the
986 // ones we've already found for this sequence. This will save us some
987 // work in candidate selection.
988 //
989 // If two candidates overlap, then we can't outline them both. This
990 // happens when we have candidates that look like, say
991 //
992 // AA (where each "A" is an instruction).
993 //
994 // We might have some portion of the module that looks like this:
995 // AAAAAA (6 A's)
996 //
997 // In this case, there are 5 different copies of "AA" in this range, but
998 // at most 3 can be outlined. If only outlining 3 of these is going to
999 // be unbeneficial, then we ought to not bother.
1000 //
1001 // Note that two things DON'T overlap when they look like this:
1002 // start1...end1 .... start2...end2
1003 // That is, one must either
1004 // * End before the other starts
1005 // * Start after the other ends
1006 if (std::all_of(CandidatesForRepeatedSeq.begin(),
1007 CandidatesForRepeatedSeq.end(),
1008 [&StartIdx, &EndIdx](const Candidate &C) {
1009 return (EndIdx < C.getStartIdx() ||
1010 StartIdx > C.getEndIdx());
1011 })) {
1012 // It doesn't overlap with anything, so we can outline it.
1013 // Each sequence is over [StartIt, EndIt].
1014 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1015 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1016
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001017 // Save the MachineFunction containing the Candidate.
1018 MachineFunction *MF = StartIt->getParent()->getParent();
1019 assert(MF && "Candidate doesn't have a MF?");
1020
Jessica Paquette52df8012017-12-01 21:56:56 +00001021 // Save the candidate and its location.
1022 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen,
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001023 FunctionList.size(), MF);
Jessica Paquette52df8012017-12-01 21:56:56 +00001024 RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
1025 }
Jessica Paquette809d7082017-07-28 03:21:58 +00001026 }
1027 }
1028
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001029 // We've found something we might want to outline.
1030 // Create an OutlinedFunction to store it and check if it'd be beneficial
1031 // to outline.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001032 TargetInstrInfo::MachineOutlinerInfo MInfo =
1033 TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001034 std::vector<unsigned> Seq;
1035 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
1036 Seq.push_back(ST.Str[i]);
Jessica Paquette52df8012017-12-01 21:56:56 +00001037 OutlinedFunction OF(FunctionList.size(), CandidatesForRepeatedSeq.size(),
1038 Seq, MInfo);
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001039 unsigned Benefit = OF.getBenefit();
Jessica Paquette809d7082017-07-28 03:21:58 +00001040
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001041 // Is it better to outline this candidate than not?
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001042 if (Benefit < 1) {
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001043 // Outlining this candidate would take more instructions than not
1044 // outlining.
1045 // Emit a remark explaining why we didn't outline this candidate.
1046 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001047 RepeatedSequenceLocs[0];
Vivek Pandya95906582017-10-11 17:12:59 +00001048 MachineOptimizationRemarkEmitter MORE(
1049 *(C.first->getParent()->getParent()), nullptr);
1050 MORE.emit([&]() {
1051 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
1052 C.first->getDebugLoc(),
1053 C.first->getParent());
1054 R << "Did not outline " << NV("Length", StringLen) << " instructions"
1055 << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
1056 << " locations."
1057 << " Instructions from outlining all occurrences ("
1058 << NV("OutliningCost", OF.getOutliningCost()) << ")"
1059 << " >= Unoutlined instruction count ("
Jessica Paquette85af63d2017-10-17 19:03:23 +00001060 << NV("NotOutliningCost", StringLen * OF.getOccurrenceCount()) << ")"
Vivek Pandya95906582017-10-11 17:12:59 +00001061 << " (Also found at: ";
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001062
Vivek Pandya95906582017-10-11 17:12:59 +00001063 // Tell the user the other places the candidate was found.
1064 for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
1065 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
1066 RepeatedSequenceLocs[i].first->getDebugLoc());
1067 if (i != e - 1)
1068 R << ", ";
1069 }
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001070
Vivek Pandya95906582017-10-11 17:12:59 +00001071 R << ")";
1072 return R;
1073 });
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001074
1075 // Move to the next candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +00001076 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001077 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001078
1079 if (StringLen > MaxLen)
1080 MaxLen = StringLen;
1081
Jessica Paquetted87f5442017-07-29 02:55:46 +00001082 // At this point, the candidate class is seen as beneficial. Set their
1083 // benefit values and save them in the candidate list.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001084 std::vector<std::shared_ptr<Candidate>> CandidatesForFn;
Jessica Paquetted87f5442017-07-29 02:55:46 +00001085 for (Candidate &C : CandidatesForRepeatedSeq) {
1086 C.Benefit = Benefit;
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001087 C.MInfo = MInfo;
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001088 std::shared_ptr<Candidate> Cptr = std::make_shared<Candidate>(C);
1089 CandidateList.push_back(Cptr);
1090 CandidatesForFn.push_back(Cptr);
Jessica Paquette78681be2017-07-27 23:24:43 +00001091 }
1092
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001093 FunctionList.push_back(OF);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001094 FunctionList.back().Candidates = CandidatesForFn;
Jessica Paquette78681be2017-07-27 23:24:43 +00001095
1096 // Move to the next function.
Jessica Paquette78681be2017-07-27 23:24:43 +00001097 Parent.IsInTree = false;
1098 }
1099
1100 return MaxLen;
1101}
Jessica Paquette596f4832017-03-06 21:31:18 +00001102
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001103// Remove C from the candidate space, and update its OutlinedFunction.
1104void MachineOutliner::prune(Candidate &C,
1105 std::vector<OutlinedFunction> &FunctionList) {
1106 // Get the OutlinedFunction associated with this Candidate.
1107 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1108
1109 // Update C's associated function's occurrence count.
1110 F.decrement();
1111
1112 // Remove C from the CandidateList.
1113 C.InCandidateList = false;
1114
1115 DEBUG(dbgs() << "- Removed a Candidate \n";
1116 dbgs() << "--- Num fns left for candidate: " << F.getOccurrenceCount()
1117 << "\n";
1118 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1119 << "\n";);
1120}
1121
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001122void MachineOutliner::pruneOverlaps(
1123 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1124 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper,
1125 unsigned MaxCandidateLen, const TargetInstrInfo &TII) {
Jessica Paquette91999162017-09-28 23:39:36 +00001126
1127 // Return true if this candidate became unbeneficial for outlining in a
1128 // previous step.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001129 auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
Jessica Paquette91999162017-09-28 23:39:36 +00001130
1131 // Check if the candidate was removed in a previous step.
1132 if (!C.InCandidateList)
1133 return true;
1134
Jessica Paquette85af63d2017-10-17 19:03:23 +00001135 // C must be alive. Check if we should remove it.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001136 if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1137 prune(C, FunctionList);
Jessica Paquette91999162017-09-28 23:39:36 +00001138 return true;
1139 }
1140
1141 // C is in the list, and F is still beneficial.
1142 return false;
1143 };
1144
Jessica Paquetteacffa282017-03-23 21:27:38 +00001145 // TODO: Experiment with interval trees or other interval-checking structures
1146 // to lower the time complexity of this function.
1147 // TODO: Can we do better than the simple greedy choice?
1148 // Check for overlaps in the range.
1149 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001150 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1151 It++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001152 Candidate &C1 = **It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001153
Jessica Paquette91999162017-09-28 23:39:36 +00001154 // If C1 was already pruned, or its function is no longer beneficial for
1155 // outlining, move to the next candidate.
1156 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001157 continue;
1158
Jessica Paquette596f4832017-03-06 21:31:18 +00001159 // The minimum start index of any candidate that could overlap with this
1160 // one.
1161 unsigned FarthestPossibleIdx = 0;
1162
1163 // Either the index is 0, or it's at most MaxCandidateLen indices away.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001164 if (C1.getStartIdx() > MaxCandidateLen)
1165 FarthestPossibleIdx = C1.getStartIdx() - MaxCandidateLen;
Jessica Paquette596f4832017-03-06 21:31:18 +00001166
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001167 // Compare against the candidates in the list that start at most
Jessica Paquetteacffa282017-03-23 21:27:38 +00001168 // FarthestPossibleIdx indices away from C1. There are at most
1169 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001170 for (auto Sit = It + 1; Sit != Et; Sit++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001171 Candidate &C2 = **Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001172
1173 // Is this candidate too far away to overlap?
Jessica Paquette1934fd22017-10-23 16:25:53 +00001174 if (C2.getStartIdx() < FarthestPossibleIdx)
Jessica Paquette596f4832017-03-06 21:31:18 +00001175 break;
1176
Jessica Paquette91999162017-09-28 23:39:36 +00001177 // If C2 was already pruned, or its function is no longer beneficial for
1178 // outlining, move to the next candidate.
1179 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001180 continue;
1181
Jessica Paquette596f4832017-03-06 21:31:18 +00001182 // Do C1 and C2 overlap?
1183 //
1184 // Not overlapping:
1185 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1186 //
1187 // We sorted our candidate list so C2Start <= C1Start. We know that
1188 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1189 // have to check is C2End < C2Start to see if we overlap.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001190 if (C2.getEndIdx() < C1.getStartIdx())
Jessica Paquette596f4832017-03-06 21:31:18 +00001191 continue;
1192
Jessica Paquetteacffa282017-03-23 21:27:38 +00001193 // C1 and C2 overlap.
1194 // We need to choose the better of the two.
1195 //
1196 // Approximate this by picking the one which would have saved us the
1197 // most instructions before any pruning.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001198
1199 // Is C2 a better candidate?
1200 if (C2.Benefit > C1.Benefit) {
1201 // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1202 // against anything anymore, so break.
1203 prune(C1, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001204 break;
1205 }
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001206
1207 // Prune C2 and move on to the next candidate.
1208 prune(C2, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001209 }
1210 }
1211}
1212
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001213unsigned MachineOutliner::buildCandidateList(
1214 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1215 std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST,
1216 InstructionMapper &Mapper, const TargetInstrInfo &TII) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001217
1218 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001219 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001220
Jessica Paquette78681be2017-07-27 23:24:43 +00001221 MaxCandidateLen =
1222 findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001223
Jessica Paquette596f4832017-03-06 21:31:18 +00001224 // Sort the candidates in decending order. This will simplify the outlining
1225 // process when we have to remove the candidates from the mapping by
1226 // allowing us to cut them out without keeping track of an offset.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001227 std::stable_sort(
1228 CandidateList.begin(), CandidateList.end(),
1229 [](const std::shared_ptr<Candidate> &LHS,
1230 const std::shared_ptr<Candidate> &RHS) { return *LHS < *RHS; });
Jessica Paquette596f4832017-03-06 21:31:18 +00001231
1232 return MaxCandidateLen;
1233}
1234
1235MachineFunction *
1236MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001237 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001238
1239 // Create the function name. This should be unique. For now, just hash the
1240 // module name and include it in the function name plus the number of this
1241 // function.
1242 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001243 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001244
1245 // Create the function using an IR-level function.
1246 LLVMContext &C = M.getContext();
1247 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001248 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001249 assert(F && "Function was null!");
1250
1251 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1252 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001253 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001254 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1255
Jessica Paquette729e6862018-01-18 00:00:58 +00001256 // Save F so that we can add debug info later if we need to.
1257 CreatedIRFunctions.push_back(F);
1258
Jessica Paquette596f4832017-03-06 21:31:18 +00001259 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1260 IRBuilder<> Builder(EntryBB);
1261 Builder.CreateRetVoid();
1262
1263 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001264 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001265 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1266 const TargetSubtargetInfo &STI = MF.getSubtarget();
1267 const TargetInstrInfo &TII = *STI.getInstrInfo();
1268
1269 // Insert the new function into the module.
1270 MF.insert(MF.begin(), &MBB);
1271
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001272 TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001273
1274 // Copy over the instructions for the function using the integer mappings in
1275 // its sequence.
1276 for (unsigned Str : OF.Sequence) {
1277 MachineInstr *NewMI =
1278 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1279 NewMI->dropMemRefs();
1280
1281 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001282 NewMI->setDebugLoc(DebugLoc());
1283 MBB.insert(MBB.end(), NewMI);
1284 }
1285
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001286 TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
Jessica Paquette729e6862018-01-18 00:00:58 +00001287
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001288 // If there's a DISubprogram associated with this outlined function, then
1289 // emit debug info for the outlined function.
1290 if (DISubprogram *SP = OF.getSubprogramOrNull()) {
1291 // We have a DISubprogram. Get its DICompileUnit.
1292 DICompileUnit *CU = SP->getUnit();
1293 DIBuilder DB(M, true, CU);
1294 DIFile *Unit = SP->getFile();
1295 Mangler Mg;
1296
1297 // Walk over each IR function we created in the outliner and create
1298 // DISubprograms for each function.
1299 for (Function *F : CreatedIRFunctions) {
1300 // Get the mangled name of the function for the linkage name.
1301 std::string Dummy;
1302 llvm::raw_string_ostream MangledNameStream(Dummy);
1303 Mg.getNameWithPrefix(MangledNameStream, F, false);
1304
1305 DISubprogram *SP = DB.createFunction(
1306 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1307 Unit /* File */,
1308 0 /* Line 0 is reserved for compiler-generated code. */,
1309 DB.createSubroutineType(
1310 DB.getOrCreateTypeArray(None)), /* void type */
1311 false, true, 0, /* Line 0 is reserved for compiler-generated code. */
1312 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1313 true /* Outlined code is optimized code by definition. */);
1314
1315 // Don't add any new variables to the subprogram.
1316 DB.finalizeSubprogram(SP);
1317
1318 // Attach subprogram to the function.
1319 F->setSubprogram(SP);
1320 }
1321
1322 // We're done with the DIBuilder.
1323 DB.finalize();
1324 }
1325
Geoff Berry82203c42018-01-31 20:15:16 +00001326 MF.getRegInfo().freezeReservedRegs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001327 return &MF;
1328}
1329
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001330bool MachineOutliner::outline(
1331 Module &M, const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
1332 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001333
1334 bool OutlinedSomething = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001335 // Replace the candidates with calls to their respective outlined functions.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001336 for (const std::shared_ptr<Candidate> &Cptr : CandidateList) {
1337 Candidate &C = *Cptr;
Jessica Paquette596f4832017-03-06 21:31:18 +00001338 // Was the candidate removed during pruneOverlaps?
1339 if (!C.InCandidateList)
1340 continue;
1341
1342 // If not, then look at its OutlinedFunction.
1343 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1344
1345 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquette85af63d2017-10-17 19:03:23 +00001346 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001347 continue;
1348
1349 // If not, then outline it.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001350 assert(C.getStartIdx() < Mapper.InstrList.size() &&
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001351 "Candidate out of bounds!");
Jessica Paquette1934fd22017-10-23 16:25:53 +00001352 MachineBasicBlock *MBB = (*Mapper.InstrList[C.getStartIdx()]).getParent();
1353 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.getStartIdx()];
1354 unsigned EndIdx = C.getEndIdx();
Jessica Paquette596f4832017-03-06 21:31:18 +00001355
1356 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1357 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1358 assert(EndIt != MBB->end() && "EndIt out of bounds!");
1359
1360 EndIt++; // Erase needs one past the end index.
1361
1362 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001363 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001364 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001365 MachineBasicBlock *MBB = &*OF.MF->begin();
1366
1367 // Output a remark telling the user that an outlined function was created,
1368 // and explaining where it came from.
1369 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
1370 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
1371 MBB->findDebugLoc(MBB->begin()), MBB);
1372 R << "Saved " << NV("OutliningBenefit", OF.getBenefit())
1373 << " instructions by "
1374 << "outlining " << NV("Length", OF.Sequence.size()) << " instructions "
1375 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
1376 << " locations. "
1377 << "(Found at: ";
1378
1379 // Tell the user the other places the candidate was found.
1380 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
1381
1382 // Skip over things that were pruned.
1383 if (!OF.Candidates[i]->InCandidateList)
1384 continue;
1385
1386 R << NV(
1387 (Twine("StartLoc") + Twine(i)).str(),
1388 Mapper.InstrList[OF.Candidates[i]->getStartIdx()]->getDebugLoc());
1389 if (i != e - 1)
1390 R << ", ";
1391 }
1392
1393 R << ")";
1394
1395 MORE.emit(R);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001396 FunctionsCreated++;
1397 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001398
1399 MachineFunction *MF = OF.MF;
1400 const TargetSubtargetInfo &STI = MF->getSubtarget();
1401 const TargetInstrInfo &TII = *STI.getInstrInfo();
1402
1403 // Insert a call to the new function and erase the old sequence.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001404 TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
Jessica Paquette1934fd22017-10-23 16:25:53 +00001405 StartIt = Mapper.InstrList[C.getStartIdx()];
Jessica Paquette596f4832017-03-06 21:31:18 +00001406 MBB->erase(StartIt, EndIt);
1407
1408 OutlinedSomething = true;
1409
1410 // Statistics.
1411 NumOutlined++;
1412 }
1413
Jessica Paquette78681be2017-07-27 23:24:43 +00001414 DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001415
1416 return OutlinedSomething;
1417}
1418
1419bool MachineOutliner::runOnModule(Module &M) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001420 // Check if there's anything in the module. If it's empty, then there's
1421 // nothing to outline.
Jessica Paquette596f4832017-03-06 21:31:18 +00001422 if (M.empty())
1423 return false;
1424
1425 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Jessica Paquette78681be2017-07-27 23:24:43 +00001426 const TargetSubtargetInfo &STI =
1427 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
Jessica Paquette596f4832017-03-06 21:31:18 +00001428 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1429 const TargetInstrInfo *TII = STI.getInstrInfo();
Jessica Paquettebccd18b2018-04-04 19:13:31 +00001430
1431 // Does the target implement the MachineOutliner? If it doesn't, quit here.
1432 if (!TII->useMachineOutliner()) {
1433 // No. So we're done.
1434 DEBUG(dbgs()
1435 << "Skipping pass: Target does not support the MachineOutliner.\n");
1436 return false;
1437 }
1438
Jessica Paquette1eca23b2018-04-19 22:17:07 +00001439 // If the user specifies that they want to outline from linkonceodrs, set
1440 // it here.
1441 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1442
Jessica Paquette596f4832017-03-06 21:31:18 +00001443 InstructionMapper Mapper;
1444
Jessica Paquettedf822742018-03-22 21:07:09 +00001445 // Build instruction mappings for each function in the module. Start by
1446 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001447 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001448
Jessica Paquettedf822742018-03-22 21:07:09 +00001449 // If there's nothing in F, then there's no reason to try and outline from
1450 // it.
1451 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001452 continue;
1453
Jessica Paquettedf822742018-03-22 21:07:09 +00001454 // There's something in F. Check if it has a MachineFunction associated with
1455 // it.
1456 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001457
Jessica Paquettedf822742018-03-22 21:07:09 +00001458 // If it doesn't, then there's nothing to outline from. Move to the next
1459 // Function.
1460 if (!MF)
1461 continue;
1462
1463 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1464 // If it isn't, then move on to the next Function in the module.
1465 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1466 continue;
1467
1468 // We have a function suitable for outlining. Iterate over every
1469 // MachineBasicBlock in MF and try to map its instructions to a list of
1470 // unsigned integers.
1471 for (MachineBasicBlock &MBB : *MF) {
1472 // If there isn't anything in MBB, then there's no point in outlining from
1473 // it.
1474 if (MBB.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001475 continue;
1476
Jessica Paquettedf822742018-03-22 21:07:09 +00001477 // Check if MBB could be the target of an indirect branch. If it is, then
1478 // we don't want to outline from it.
1479 if (MBB.hasAddressTaken())
1480 continue;
1481
1482 // MBB is suitable for outlining. Map it to a list of unsigneds.
Jessica Paquette596f4832017-03-06 21:31:18 +00001483 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1484 }
1485 }
1486
1487 // Construct a suffix tree, use it to find candidates, and then outline them.
1488 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001489 std::vector<std::shared_ptr<Candidate>> CandidateList;
Jessica Paquette596f4832017-03-06 21:31:18 +00001490 std::vector<OutlinedFunction> FunctionList;
1491
Jessica Paquetteacffa282017-03-23 21:27:38 +00001492 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001493 unsigned MaxCandidateLen =
Jessica Paquettec984e212017-03-13 18:39:33 +00001494 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001495
Jessica Paquetteacffa282017-03-23 21:27:38 +00001496 // Remove candidates that overlap with other candidates.
Jessica Paquette809d7082017-07-28 03:21:58 +00001497 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001498
1499 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette729e6862018-01-18 00:00:58 +00001500 bool OutlinedSomething = outline(M, CandidateList, FunctionList, Mapper);
1501
Jessica Paquette729e6862018-01-18 00:00:58 +00001502 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001503}