blob: d63f194f7e66201a743787c0c2323aa6304497f4 [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"
Jin Linfc6fda92020-03-05 13:54:58 -080059#include "llvm/ADT/SmallSet.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000060#include "llvm/ADT/Statistic.h"
61#include "llvm/ADT/Twine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000062#include "llvm/CodeGen/MachineFunction.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000063#include "llvm/CodeGen/MachineModuleInfo.h"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000064#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Geoff Berry82203c42018-01-31 20:15:16 +000065#include "llvm/CodeGen/MachineRegisterInfo.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000066#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000067#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000068#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jessica Paquette729e6862018-01-18 00:00:58 +000069#include "llvm/IR/DIBuilder.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000070#include "llvm/IR/IRBuilder.h"
Jessica Paquettea499c3c2018-01-19 21:21:49 +000071#include "llvm/IR/Mangler.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080072#include "llvm/InitializePasses.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>
Jessica Paquette596f4832017-03-06 21:31:18 +000078#include <tuple>
79#include <vector>
80
81#define DEBUG_TYPE "machine-outliner"
82
83using namespace llvm;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000084using namespace ore;
Jessica Paquetteaa087322018-06-04 21:14:16 +000085using namespace outliner;
Jessica Paquette596f4832017-03-06 21:31:18 +000086
87STATISTIC(NumOutlined, "Number of candidates outlined");
88STATISTIC(FunctionsCreated, "Number of functions created");
89
Jessica Paquette1eca23b2018-04-19 22:17:07 +000090// Set to true if the user wants the outliner to run on linkonceodr linkage
91// functions. This is false by default because the linker can dedupe linkonceodr
92// functions. Since the outliner is confined to a single module (modulo LTO),
93// this is off by default. It should, however, be the default behaviour in
94// LTO.
95static cl::opt<bool> EnableLinkOnceODROutlining(
Puyan Lotfi6b7615a2019-10-28 17:57:51 -040096 "enable-linkonceodr-outlining", cl::Hidden,
Jessica Paquette1eca23b2018-04-19 22:17:07 +000097 cl::desc("Enable the machine outliner on linkonceodr functions"),
98 cl::init(false));
99
Jin Lin0d896272020-03-17 15:40:26 -0700100// Set the number of times to repeatedly apply outlining.
101// Defaults to 1, but more repetitions can save additional size.
102static cl::opt<unsigned>
103 NumRepeat("machine-outline-runs", cl::Hidden,
104 cl::desc("The number of times to apply machine outlining"),
105 cl::init(1));
106
Jessica Paquette596f4832017-03-06 21:31:18 +0000107namespace {
108
109/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000110const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000111
112/// A node in a suffix tree which represents a substring or suffix.
113///
114/// Each node has either no children or at least two children, with the root
115/// being a exception in the empty tree.
116///
117/// Children are represented as a map between unsigned integers and nodes. If
118/// a node N has a child M on unsigned integer k, then the mapping represented
119/// by N is a proper prefix of the mapping represented by M. Note that this,
120/// although similar to a trie is somewhat different: each node stores a full
121/// substring of the full mapping rather than a single character state.
122///
123/// Each internal node contains a pointer to the internal node representing
124/// the same string, but with the first character chopped off. This is stored
125/// in \p Link. Each leaf node stores the start index of its respective
126/// suffix in \p SuffixIdx.
127struct SuffixTreeNode {
128
129 /// The children of this node.
130 ///
131 /// A child existing on an unsigned integer implies that from the mapping
132 /// represented by the current node, there is a way to reach another
133 /// mapping by tacking that character on the end of the current string.
134 DenseMap<unsigned, SuffixTreeNode *> Children;
135
Jessica Paquette596f4832017-03-06 21:31:18 +0000136 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000137 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000138
139 /// The end index of this node's substring in the main string.
140 ///
141 /// Every leaf node must have its \p EndIdx incremented at the end of every
142 /// step in the construction algorithm. To avoid having to update O(N)
143 /// nodes individually at the end of every step, the end index is stored
144 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000145 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000146
147 /// For leaves, the start index of the suffix represented by this node.
148 ///
149 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000150 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000151
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000152 /// For internal nodes, a pointer to the internal node representing
Jessica Paquette596f4832017-03-06 21:31:18 +0000153 /// the same sequence with the first character chopped off.
154 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000155 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000156 /// Ukkonen's algorithm does to achieve linear-time construction is
157 /// keep track of which node the next insert should be at. This makes each
158 /// insert O(1), and there are a total of O(N) inserts. The suffix link
159 /// helps with inserting children of internal nodes.
160 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000161 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000162 /// next insertion must be at the node representing S - its first character.
163 /// This is given by the way that we iteratively build the tree in Ukkonen's
164 /// algorithm. The main idea is to look at the suffixes of each prefix in the
165 /// string, starting with the longest suffix of the prefix, and ending with
166 /// the shortest. Therefore, if we keep pointers between such nodes, we can
167 /// move to the next insertion point in O(1) time. If we don't, then we'd
168 /// have to query from the root, which takes O(N) time. This would make the
169 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000170 SuffixTreeNode *Link = nullptr;
171
Jessica Paquetteacffa282017-03-23 21:27:38 +0000172 /// The length of the string formed by concatenating the edge labels from the
173 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000174 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000175
Jessica Paquette596f4832017-03-06 21:31:18 +0000176 /// Returns true if this node is a leaf.
177 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
178
179 /// Returns true if this node is the root of its owning \p SuffixTree.
180 bool isRoot() const { return StartIdx == EmptyIdx; }
181
182 /// Return the number of elements in the substring associated with this node.
183 size_t size() const {
184
185 // Is it the root? If so, it's the empty string so return 0.
186 if (isRoot())
187 return 0;
188
189 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
190
191 // Size = the number of elements in the string.
192 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
193 return *EndIdx - StartIdx + 1;
194 }
195
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000196 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
197 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
Jessica Paquette596f4832017-03-06 21:31:18 +0000198
199 SuffixTreeNode() {}
200};
201
202/// A data structure for fast substring queries.
203///
204/// Suffix trees represent the suffixes of their input strings in their leaves.
205/// A suffix tree is a type of compressed trie structure where each node
206/// represents an entire substring rather than a single character. Each leaf
207/// of the tree is a suffix.
208///
209/// A suffix tree can be seen as a type of state machine where each state is a
210/// substring of the full string. The tree is structured so that, for a string
211/// of length N, there are exactly N leaves in the tree. This structure allows
212/// us to quickly find repeated substrings of the input string.
213///
214/// In this implementation, a "string" is a vector of unsigned integers.
215/// These integers may result from hashing some data type. A suffix tree can
216/// contain 1 or many strings, which can then be queried as one large string.
217///
218/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
219/// suffix tree construction. Ukkonen's algorithm is explained in more detail
220/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
221/// paper is available at
222///
223/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
224class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000225public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000226 /// Each element is an integer representing an instruction in the module.
227 ArrayRef<unsigned> Str;
228
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000229 /// A repeated substring in the tree.
230 struct RepeatedSubstring {
231 /// The length of the string.
232 unsigned Length;
233
234 /// The start indices of each occurrence.
235 std::vector<unsigned> StartIndices;
236 };
237
Jessica Paquette78681be2017-07-27 23:24:43 +0000238private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000239 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000240 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000241
242 /// The root of the suffix tree.
243 ///
244 /// The root represents the empty string. It is maintained by the
245 /// \p NodeAllocator like every other node in the tree.
246 SuffixTreeNode *Root = nullptr;
247
Jessica Paquette596f4832017-03-06 21:31:18 +0000248 /// Maintains the end indices of the internal nodes in the tree.
249 ///
250 /// Each internal node is guaranteed to never have its end index change
251 /// during the construction algorithm; however, leaves must be updated at
252 /// every step. Therefore, we need to store leaf end indices by reference
253 /// to avoid updating O(N) leaves at every step of construction. Thus,
254 /// every internal node must be allocated its own end index.
255 BumpPtrAllocator InternalEndIdxAllocator;
256
257 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000258 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000260 /// Helper struct which keeps track of the next insertion point in
Jessica Paquette596f4832017-03-06 21:31:18 +0000261 /// Ukkonen's algorithm.
262 struct ActiveState {
263 /// The next node to insert at.
Simon Pilgrimc7f127d2019-11-05 15:08:21 +0000264 SuffixTreeNode *Node = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000265
266 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000267 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000268
269 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000270 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000271 };
272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000273 /// The point the next insertion will take place at in the
Jessica Paquette596f4832017-03-06 21:31:18 +0000274 /// construction algorithm.
275 ActiveState Active;
276
277 /// Allocate a leaf node and add it to the tree.
278 ///
279 /// \param Parent The parent of this node.
280 /// \param StartIdx The start index of this node's associated string.
281 /// \param Edge The label on the edge leaving \p Parent to this node.
282 ///
283 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000284 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000285 unsigned Edge) {
286
287 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
288
Jessica Paquette78681be2017-07-27 23:24:43 +0000289 SuffixTreeNode *N = new (NodeAllocator.Allocate())
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000290 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
Jessica Paquette596f4832017-03-06 21:31:18 +0000291 Parent.Children[Edge] = N;
292
293 return N;
294 }
295
296 /// Allocate an internal node and add it to the tree.
297 ///
298 /// \param Parent The parent of this node. Only null when allocating the root.
299 /// \param StartIdx The start index of this node's associated string.
300 /// \param EndIdx The end index of this node's associated string.
301 /// \param Edge The label on the edge leaving \p Parent to this node.
302 ///
303 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000304 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
305 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000306
307 assert(StartIdx <= EndIdx && "String can't start after it ends!");
308 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000309 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000310
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000311 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400312 SuffixTreeNode *N =
313 new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root);
Jessica Paquette596f4832017-03-06 21:31:18 +0000314 if (Parent)
315 Parent->Children[Edge] = N;
316
317 return N;
318 }
319
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000320 /// Set the suffix indices of the leaves to the start indices of their
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000321 /// respective suffixes.
Jessica Paquetted5750772019-12-20 15:57:39 -0800322 void setSuffixIndices() {
323 // List of nodes we need to visit along with the current length of the
324 // string.
325 std::vector<std::pair<SuffixTreeNode *, unsigned>> ToVisit;
Jessica Paquette596f4832017-03-06 21:31:18 +0000326
Jessica Paquetted5750772019-12-20 15:57:39 -0800327 // Current node being visited.
328 SuffixTreeNode *CurrNode = Root;
Jessica Paquette596f4832017-03-06 21:31:18 +0000329
Jessica Paquetted5750772019-12-20 15:57:39 -0800330 // Sum of the lengths of the nodes down the path to the current one.
331 unsigned CurrNodeLen = 0;
332 ToVisit.push_back({CurrNode, CurrNodeLen});
333 while (!ToVisit.empty()) {
334 std::tie(CurrNode, CurrNodeLen) = ToVisit.back();
335 ToVisit.pop_back();
336 CurrNode->ConcatLen = CurrNodeLen;
337 for (auto &ChildPair : CurrNode->Children) {
338 assert(ChildPair.second && "Node had a null child!");
339 ToVisit.push_back(
340 {ChildPair.second, CurrNodeLen + ChildPair.second->size()});
341 }
342
343 // No children, so we are at the end of the string.
344 if (CurrNode->Children.size() == 0 && !CurrNode->isRoot())
345 CurrNode->SuffixIdx = Str.size() - CurrNodeLen;
Jessica Paquette596f4832017-03-06 21:31:18 +0000346 }
Jessica Paquette596f4832017-03-06 21:31:18 +0000347 }
348
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000349 /// Construct the suffix tree for the prefix of the input ending at
Jessica Paquette596f4832017-03-06 21:31:18 +0000350 /// \p EndIdx.
351 ///
352 /// Used to construct the full suffix tree iteratively. At the end of each
353 /// step, the constructed suffix tree is either a valid suffix tree, or a
354 /// suffix tree with implicit suffixes. At the end of the final step, the
355 /// suffix tree is a valid tree.
356 ///
357 /// \param EndIdx The end index of the current prefix in the main string.
358 /// \param SuffixesToAdd The number of suffixes that must be added
359 /// to complete the suffix tree at the current phase.
360 ///
361 /// \returns The number of suffixes that have not been added at the end of
362 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000363 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000364 SuffixTreeNode *NeedsLink = nullptr;
365
366 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000367
Jessica Paquette596f4832017-03-06 21:31:18 +0000368 // Are we waiting to add anything other than just the last character?
369 if (Active.Len == 0) {
370 // If not, then say the active index is the end index.
371 Active.Idx = EndIdx;
372 }
373
374 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
375
376 // The first character in the current substring we're looking at.
377 unsigned FirstChar = Str[Active.Idx];
378
379 // Have we inserted anything starting with FirstChar at the current node?
380 if (Active.Node->Children.count(FirstChar) == 0) {
381 // If not, then we can just insert a leaf and move too the next step.
382 insertLeaf(*Active.Node, EndIdx, FirstChar);
383
384 // The active node is an internal node, and we visited it, so it must
385 // need a link if it doesn't have one.
386 if (NeedsLink) {
387 NeedsLink->Link = Active.Node;
388 NeedsLink = nullptr;
389 }
390 } else {
391 // There's a match with FirstChar, so look for the point in the tree to
392 // insert a new node.
393 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
394
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000395 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000396
397 // Is the current suffix we're trying to insert longer than the size of
398 // the child we want to move to?
399 if (Active.Len >= SubstringLen) {
400 // If yes, then consume the characters we've seen and move to the next
401 // node.
402 Active.Idx += SubstringLen;
403 Active.Len -= SubstringLen;
404 Active.Node = NextNode;
405 continue;
406 }
407
408 // Otherwise, the suffix we're trying to insert must be contained in the
409 // next node we want to move to.
410 unsigned LastChar = Str[EndIdx];
411
412 // Is the string we're trying to insert a substring of the next node?
413 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
414 // If yes, then we're done for this step. Remember our insertion point
415 // and move to the next end index. At this point, we have an implicit
416 // suffix tree.
417 if (NeedsLink && !Active.Node->isRoot()) {
418 NeedsLink->Link = Active.Node;
419 NeedsLink = nullptr;
420 }
421
422 Active.Len++;
423 break;
424 }
425
426 // The string we're trying to insert isn't a substring of the next node,
427 // but matches up to a point. Split the node.
428 //
429 // For example, say we ended our search at a node n and we're trying to
430 // insert ABD. Then we'll create a new node s for AB, reduce n to just
431 // representing C, and insert a new leaf node l to represent d. This
432 // allows us to ensure that if n was a leaf, it remains a leaf.
433 //
434 // | ABC ---split---> | AB
435 // n s
436 // C / \ D
437 // n l
438
439 // The node s from the diagram
440 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000441 insertInternalNode(Active.Node, NextNode->StartIdx,
442 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000443
444 // Insert the new node representing the new substring into the tree as
445 // a child of the split node. This is the node l from the diagram.
446 insertLeaf(*SplitNode, EndIdx, LastChar);
447
448 // Make the old node a child of the split node and update its start
449 // index. This is the node n from the diagram.
450 NextNode->StartIdx += Active.Len;
Jessica Paquette596f4832017-03-06 21:31:18 +0000451 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
452
453 // SplitNode is an internal node, update the suffix link.
454 if (NeedsLink)
455 NeedsLink->Link = SplitNode;
456
457 NeedsLink = SplitNode;
458 }
459
460 // We've added something new to the tree, so there's one less suffix to
461 // add.
462 SuffixesToAdd--;
463
464 if (Active.Node->isRoot()) {
465 if (Active.Len > 0) {
466 Active.Len--;
467 Active.Idx = EndIdx - SuffixesToAdd + 1;
468 }
469 } else {
470 // Start the next phase at the next smallest suffix.
471 Active.Node = Active.Node->Link;
472 }
473 }
474
475 return SuffixesToAdd;
476 }
477
Jessica Paquette596f4832017-03-06 21:31:18 +0000478public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000479 /// Construct a suffix tree from a sequence of unsigned integers.
480 ///
481 /// \param Str The string to construct the suffix tree for.
482 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
483 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
Jessica Paquette596f4832017-03-06 21:31:18 +0000484 Active.Node = Root;
Jessica Paquette596f4832017-03-06 21:31:18 +0000485
486 // Keep track of the number of suffixes we have to add of the current
487 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000488 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000489
490 // Construct the suffix tree iteratively on each prefix of the string.
491 // PfxEndIdx is the end index of the current prefix.
492 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000493 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
494 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000495 SuffixesToAdd++;
496 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
497 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
498 }
499
500 // Set the suffix indices of each leaf.
501 assert(Root && "Root node can't be nullptr!");
Jessica Paquetted5750772019-12-20 15:57:39 -0800502 setSuffixIndices();
Jessica Paquette596f4832017-03-06 21:31:18 +0000503 }
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000504
Jessica Paquettea409cc92018-11-07 19:20:55 +0000505 /// Iterator for finding all repeated substrings in the suffix tree.
506 struct RepeatedSubstringIterator {
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400507 private:
Jessica Paquettea409cc92018-11-07 19:20:55 +0000508 /// The current node we're visiting.
509 SuffixTreeNode *N = nullptr;
510
511 /// The repeated substring associated with this node.
512 RepeatedSubstring RS;
513
514 /// The nodes left to visit.
515 std::vector<SuffixTreeNode *> ToVisit;
516
517 /// The minimum length of a repeated substring to find.
518 /// Since we're outlining, we want at least two instructions in the range.
519 /// FIXME: This may not be true for targets like X86 which support many
520 /// instruction lengths.
521 const unsigned MinLength = 2;
522
523 /// Move the iterator to the next repeated substring.
524 void advance() {
525 // Clear the current state. If we're at the end of the range, then this
526 // is the state we want to be in.
527 RS = RepeatedSubstring();
528 N = nullptr;
529
Jessica Paquette3cd70b32018-12-06 00:26:21 +0000530 // Each leaf node represents a repeat of a string.
531 std::vector<SuffixTreeNode *> LeafChildren;
532
Jessica Paquettea409cc92018-11-07 19:20:55 +0000533 // Continue visiting nodes until we find one which repeats more than once.
534 while (!ToVisit.empty()) {
535 SuffixTreeNode *Curr = ToVisit.back();
536 ToVisit.pop_back();
Jessica Paquette3cd70b32018-12-06 00:26:21 +0000537 LeafChildren.clear();
Jessica Paquettea409cc92018-11-07 19:20:55 +0000538
539 // Keep track of the length of the string associated with the node. If
540 // it's too short, we'll quit.
541 unsigned Length = Curr->ConcatLen;
542
Jessica Paquettea409cc92018-11-07 19:20:55 +0000543 // Iterate over each child, saving internal nodes for visiting, and
544 // leaf nodes in LeafChildren. Internal nodes represent individual
545 // strings, which may repeat.
546 for (auto &ChildPair : Curr->Children) {
547 // Save all of this node's children for processing.
548 if (!ChildPair.second->isLeaf())
549 ToVisit.push_back(ChildPair.second);
550
551 // It's not an internal node, so it must be a leaf. If we have a
552 // long enough string, then save the leaf children.
553 else if (Length >= MinLength)
554 LeafChildren.push_back(ChildPair.second);
555 }
556
557 // The root never represents a repeated substring. If we're looking at
558 // that, then skip it.
559 if (Curr->isRoot())
560 continue;
561
562 // Do we have any repeated substrings?
563 if (LeafChildren.size() >= 2) {
564 // Yes. Update the state to reflect this, and then bail out.
565 N = Curr;
566 RS.Length = Length;
567 for (SuffixTreeNode *Leaf : LeafChildren)
568 RS.StartIndices.push_back(Leaf->SuffixIdx);
569 break;
570 }
571 }
572
573 // At this point, either NewRS is an empty RepeatedSubstring, or it was
574 // set in the above loop. Similarly, N is either nullptr, or the node
575 // associated with NewRS.
576 }
577
578 public:
579 /// Return the current repeated substring.
580 RepeatedSubstring &operator*() { return RS; }
581
582 RepeatedSubstringIterator &operator++() {
583 advance();
584 return *this;
585 }
586
587 RepeatedSubstringIterator operator++(int I) {
588 RepeatedSubstringIterator It(*this);
589 advance();
590 return It;
591 }
592
593 bool operator==(const RepeatedSubstringIterator &Other) {
594 return N == Other.N;
595 }
596 bool operator!=(const RepeatedSubstringIterator &Other) {
597 return !(*this == Other);
598 }
599
600 RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
601 // Do we have a non-null node?
602 if (N) {
603 // Yes. At the first step, we need to visit all of N's children.
604 // Note: This means that we visit N last.
605 ToVisit.push_back(N);
606 advance();
607 }
608 }
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400609 };
Jessica Paquettea409cc92018-11-07 19:20:55 +0000610
611 typedef RepeatedSubstringIterator iterator;
612 iterator begin() { return iterator(Root); }
613 iterator end() { return iterator(nullptr); }
Jessica Paquette596f4832017-03-06 21:31:18 +0000614};
615
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000616/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
Jessica Paquette596f4832017-03-06 21:31:18 +0000617struct InstructionMapper {
618
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000619 /// The next available integer to assign to a \p MachineInstr that
Jessica Paquette596f4832017-03-06 21:31:18 +0000620 /// cannot be outlined.
621 ///
622 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
623 unsigned IllegalInstrNumber = -3;
624
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000625 /// The next available integer to assign to a \p MachineInstr that can
Jessica Paquette596f4832017-03-06 21:31:18 +0000626 /// be outlined.
627 unsigned LegalInstrNumber = 0;
628
629 /// Correspondence from \p MachineInstrs to unsigned integers.
630 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
631 InstructionIntegerMap;
632
Jessica Paquettecad864d2018-11-13 23:01:34 +0000633 /// Correspondence between \p MachineBasicBlocks and target-defined flags.
634 DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
635
Jessica Paquette596f4832017-03-06 21:31:18 +0000636 /// The vector of unsigned integers that the module is mapped to.
637 std::vector<unsigned> UnsignedVec;
638
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000639 /// Stores the location of the instruction associated with the integer
Jessica Paquette596f4832017-03-06 21:31:18 +0000640 /// at index i in \p UnsignedVec for each index i.
641 std::vector<MachineBasicBlock::iterator> InstrList;
642
Jessica Paquettec991cf32018-11-01 23:09:06 +0000643 // Set if we added an illegal number in the previous step.
644 // Since each illegal number is unique, we only need one of them between
645 // each range of legal numbers. This lets us make sure we don't add more
646 // than one illegal number per range.
647 bool AddedIllegalLastTime = false;
648
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000649 /// Maps \p *It to a legal integer.
Jessica Paquette596f4832017-03-06 21:31:18 +0000650 ///
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000651 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
Jessica Paquetteca3ed962018-12-06 00:01:51 +0000652 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000653 ///
654 /// \returns The integer that \p *It was mapped to.
Jessica Paquette267d2662018-11-08 00:02:11 +0000655 unsigned mapToLegalUnsigned(
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000656 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
657 bool &HaveLegalRange, unsigned &NumLegalInBlock,
Jessica Paquette267d2662018-11-08 00:02:11 +0000658 std::vector<unsigned> &UnsignedVecForMBB,
659 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000660 // We added something legal, so we should unset the AddedLegalLastTime
661 // flag.
662 AddedIllegalLastTime = false;
Jessica Paquette596f4832017-03-06 21:31:18 +0000663
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000664 // If we have at least two adjacent legal instructions (which may have
665 // invisible instructions in between), remember that.
666 if (CanOutlineWithPrevInstr)
667 HaveLegalRange = true;
668 CanOutlineWithPrevInstr = true;
669
Jessica Paquette267d2662018-11-08 00:02:11 +0000670 // Keep track of the number of legal instructions we insert.
671 NumLegalInBlock++;
672
Jessica Paquette596f4832017-03-06 21:31:18 +0000673 // Get the integer for this instruction or give it the current
674 // LegalInstrNumber.
Jessica Paquette267d2662018-11-08 00:02:11 +0000675 InstrListForMBB.push_back(It);
Jessica Paquette596f4832017-03-06 21:31:18 +0000676 MachineInstr &MI = *It;
677 bool WasInserted;
678 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000679 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000680 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000681 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000682 unsigned MINumber = ResultIt->second;
683
684 // There was an insertion.
Jessica Paquetteca3ed962018-12-06 00:01:51 +0000685 if (WasInserted)
Jessica Paquette596f4832017-03-06 21:31:18 +0000686 LegalInstrNumber++;
Jessica Paquette596f4832017-03-06 21:31:18 +0000687
Jessica Paquette267d2662018-11-08 00:02:11 +0000688 UnsignedVecForMBB.push_back(MINumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000689
690 // Make sure we don't overflow or use any integers reserved by the DenseMap.
691 if (LegalInstrNumber >= IllegalInstrNumber)
692 report_fatal_error("Instruction mapping overflow!");
693
Jessica Paquette78681be2017-07-27 23:24:43 +0000694 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
695 "Tried to assign DenseMap tombstone or empty key to instruction.");
696 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
697 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000698
699 return MINumber;
700 }
701
702 /// Maps \p *It to an illegal integer.
703 ///
Jessica Paquette267d2662018-11-08 00:02:11 +0000704 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
705 /// IllegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000706 ///
707 /// \returns The integer that \p *It was mapped to.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400708 unsigned mapToIllegalUnsigned(
709 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
710 std::vector<unsigned> &UnsignedVecForMBB,
711 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000712 // Can't outline an illegal instruction. Set the flag.
713 CanOutlineWithPrevInstr = false;
714
Jessica Paquettec991cf32018-11-01 23:09:06 +0000715 // Only add one illegal number per range of legal numbers.
716 if (AddedIllegalLastTime)
717 return IllegalInstrNumber;
718
719 // Remember that we added an illegal number last time.
720 AddedIllegalLastTime = true;
Jessica Paquette596f4832017-03-06 21:31:18 +0000721 unsigned MINumber = IllegalInstrNumber;
722
Jessica Paquette267d2662018-11-08 00:02:11 +0000723 InstrListForMBB.push_back(It);
724 UnsignedVecForMBB.push_back(IllegalInstrNumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000725 IllegalInstrNumber--;
726
727 assert(LegalInstrNumber < IllegalInstrNumber &&
728 "Instruction mapping overflow!");
729
Jessica Paquette78681be2017-07-27 23:24:43 +0000730 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
731 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000732
Jessica Paquette78681be2017-07-27 23:24:43 +0000733 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
734 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000735
736 return MINumber;
737 }
738
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000739 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
Jessica Paquette596f4832017-03-06 21:31:18 +0000740 /// and appends it to \p UnsignedVec and \p InstrList.
741 ///
742 /// Two instructions are assigned the same integer if they are identical.
743 /// If an instruction is deemed unsafe to outline, then it will be assigned an
744 /// unique integer. The resulting mapping is placed into a suffix tree and
745 /// queried for candidates.
746 ///
747 /// \param MBB The \p MachineBasicBlock to be translated into integers.
Eli Friedmanda080782018-08-01 00:37:20 +0000748 /// \param TII \p TargetInstrInfo for the function.
Jessica Paquette596f4832017-03-06 21:31:18 +0000749 void convertToUnsignedVec(MachineBasicBlock &MBB,
Jessica Paquette596f4832017-03-06 21:31:18 +0000750 const TargetInstrInfo &TII) {
Alexander Kornienko3635c892018-11-13 16:41:05 +0000751 unsigned Flags = 0;
Jessica Paquette82d9c0a2018-11-12 23:51:32 +0000752
753 // Don't even map in this case.
754 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
755 return;
756
Jessica Paquettecad864d2018-11-13 23:01:34 +0000757 // Store info for the MBB for later outlining.
758 MBBFlagsMap[&MBB] = Flags;
759
Jessica Paquettec991cf32018-11-01 23:09:06 +0000760 MachineBasicBlock::iterator It = MBB.begin();
Jessica Paquette267d2662018-11-08 00:02:11 +0000761
762 // The number of instructions in this block that will be considered for
763 // outlining.
764 unsigned NumLegalInBlock = 0;
765
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000766 // True if we have at least two legal instructions which aren't separated
767 // by an illegal instruction.
768 bool HaveLegalRange = false;
769
770 // True if we can perform outlining given the last mapped (non-invisible)
771 // instruction. This lets us know if we have a legal range.
772 bool CanOutlineWithPrevInstr = false;
773
Jessica Paquette267d2662018-11-08 00:02:11 +0000774 // FIXME: Should this all just be handled in the target, rather than using
775 // repeated calls to getOutliningType?
776 std::vector<unsigned> UnsignedVecForMBB;
777 std::vector<MachineBasicBlock::iterator> InstrListForMBB;
778
Simon Pilgrim76166a12019-11-05 16:46:10 +0000779 for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000780 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000781 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquetteaa087322018-06-04 21:14:16 +0000782 case InstrType::Illegal:
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400783 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
784 InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000785 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000786
Jessica Paquetteaa087322018-06-04 21:14:16 +0000787 case InstrType::Legal:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000788 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
789 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000790 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000791
Jessica Paquetteaa087322018-06-04 21:14:16 +0000792 case InstrType::LegalTerminator:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000793 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
794 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquettec991cf32018-11-01 23:09:06 +0000795 // The instruction also acts as a terminator, so we have to record that
796 // in the string.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000797 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400798 InstrListForMBB);
Eli Friedman042dc9e2018-05-22 19:11:06 +0000799 break;
800
Jessica Paquetteaa087322018-06-04 21:14:16 +0000801 case InstrType::Invisible:
Jessica Paquettec991cf32018-11-01 23:09:06 +0000802 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
803 // skip this instruction. So, unset the flag here.
Jessica Paquettebd729882018-09-17 18:40:21 +0000804 AddedIllegalLastTime = false;
Jessica Paquette78681be2017-07-27 23:24:43 +0000805 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000806 }
807 }
808
Jessica Paquette267d2662018-11-08 00:02:11 +0000809 // Are there enough legal instructions in the block for outlining to be
810 // possible?
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000811 if (HaveLegalRange) {
Jessica Paquette267d2662018-11-08 00:02:11 +0000812 // After we're done every insertion, uniquely terminate this part of the
813 // "string". This makes sure we won't match across basic block or function
814 // boundaries since the "end" is encoded uniquely and thus appears in no
815 // repeated substring.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000816 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400817 InstrListForMBB);
Jessica Paquette267d2662018-11-08 00:02:11 +0000818 InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
819 InstrListForMBB.end());
820 UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
821 UnsignedVecForMBB.end());
822 }
Jessica Paquette596f4832017-03-06 21:31:18 +0000823 }
824
825 InstructionMapper() {
826 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
827 // changed.
828 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000829 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000830 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000831 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000832 }
833};
834
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000835/// An interprocedural pass which finds repeated sequences of
Jessica Paquette596f4832017-03-06 21:31:18 +0000836/// instructions and replaces them with calls to functions.
837///
838/// Each instruction is mapped to an unsigned integer and placed in a string.
839/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
840/// is then repeatedly queried for repeated sequences of instructions. Each
841/// non-overlapping repeated sequence is then placed in its own
842/// \p MachineFunction and each instance is then replaced with a call to that
843/// function.
844struct MachineOutliner : public ModulePass {
845
846 static char ID;
847
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000848 /// Set to true if the outliner should consider functions with
Jessica Paquette13593842017-10-07 00:16:34 +0000849 /// linkonceodr linkage.
850 bool OutlineFromLinkOnceODRs = false;
851
Jin Lin0d896272020-03-17 15:40:26 -0700852 /// The current repeat number of machine outlining.
853 unsigned OutlineRepeatedNum = 0;
854
Jessica Paquette8bda1882018-06-30 03:56:03 +0000855 /// Set to true if the outliner should run on all functions in the module
856 /// considered safe for outlining.
857 /// Set to true by default for compatibility with llc's -run-pass option.
858 /// Set when the pass is constructed in TargetPassConfig.
859 bool RunOnAllFunctions = true;
860
Jessica Paquette596f4832017-03-06 21:31:18 +0000861 StringRef getPassName() const override { return "Machine Outliner"; }
862
863 void getAnalysisUsage(AnalysisUsage &AU) const override {
Yuanfang Chencc382cf2019-09-30 17:54:50 +0000864 AU.addRequired<MachineModuleInfoWrapperPass>();
865 AU.addPreserved<MachineModuleInfoWrapperPass>();
Jessica Paquette596f4832017-03-06 21:31:18 +0000866 AU.setPreservesAll();
867 ModulePass::getAnalysisUsage(AU);
868 }
869
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000870 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000871 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
872 }
873
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000874 /// Remark output explaining that not outlining a set of candidates would be
875 /// better than outlining that set.
876 void emitNotOutliningCheaperRemark(
877 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
878 OutlinedFunction &OF);
879
Jessica Paquette58e706a2018-07-24 20:20:45 +0000880 /// Remark output explaining that a function was outlined.
881 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
882
Jessica Paquettece3a2dc2018-12-05 23:39:07 +0000883 /// Find all repeated substrings that satisfy the outlining cost model by
884 /// constructing a suffix tree.
Jessica Paquette78681be2017-07-27 23:24:43 +0000885 ///
886 /// If a substring appears at least twice, then it must be represented by
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000887 /// an internal node which appears in at least two suffixes. Each suffix
888 /// is represented by a leaf node. To do this, we visit each internal node
889 /// in the tree, using the leaf children of each internal node. If an
890 /// internal node represents a beneficial substring, then we use each of
891 /// its leaf children to find the locations of its substring.
Jessica Paquette78681be2017-07-27 23:24:43 +0000892 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000893 /// \param Mapper Contains outlining mapping information.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000894 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
895 /// each type of candidate.
Jessica Paquettece3a2dc2018-12-05 23:39:07 +0000896 void findCandidates(InstructionMapper &Mapper,
897 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000898
Jessica Paquette4ae3b712018-12-05 22:50:26 +0000899 /// Replace the sequences of instructions represented by \p OutlinedFunctions
900 /// with calls to functions.
Jessica Paquette596f4832017-03-06 21:31:18 +0000901 ///
902 /// \param M The module we are outlining from.
Jessica Paquette596f4832017-03-06 21:31:18 +0000903 /// \param FunctionList A list of functions to be inserted into the module.
904 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette4ae3b712018-12-05 22:50:26 +0000905 bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400906 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
Jessica Paquette596f4832017-03-06 21:31:18 +0000907
908 /// Creates a function for \p OF and inserts it into the module.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +0000909 MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +0000910 InstructionMapper &Mapper,
911 unsigned Name);
Jessica Paquette596f4832017-03-06 21:31:18 +0000912
Jin Lin0d896272020-03-17 15:40:26 -0700913 /// Calls runOnceOnModule NumRepeat times
Jin Lin7b166d52020-03-17 18:33:55 -0700914 bool runOnModule(Module &M) override;
Jin Linab2dcff2020-03-17 15:40:26 -0700915
Jin Lin0d896272020-03-17 15:40:26 -0700916 /// Calls 'doOutline()'.
917 bool runOnceOnModule(Module &M, unsigned Iter);
918
Jessica Paquette596f4832017-03-06 21:31:18 +0000919 /// Construct a suffix tree on the instructions in \p M and outline repeated
920 /// strings from that tree.
Puyan Lotfia51fc8d2019-10-28 15:10:21 -0400921 bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
Jessica Paquetteaa087322018-06-04 21:14:16 +0000922
923 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
924 /// function for remark emission.
925 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
Jessica Paquettee18d6ff2018-12-05 23:24:22 +0000926 for (const Candidate &C : OF.Candidates)
Simon Pilgrim7ad25832019-11-05 15:58:04 +0000927 if (MachineFunction *MF = C.getMF())
928 if (DISubprogram *SP = MF->getFunction().getSubprogram())
929 return SP;
Jessica Paquetteaa087322018-06-04 21:14:16 +0000930 return nullptr;
931 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +0000932
933 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
934 /// These are used to construct a suffix tree.
935 void populateMapper(InstructionMapper &Mapper, Module &M,
936 MachineModuleInfo &MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +0000937
Jessica Paquette2386eab2018-09-11 23:05:34 +0000938 /// Initialize information necessary to output a size remark.
939 /// FIXME: This should be handled by the pass manager, not the outliner.
940 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
941 /// pass manager.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400942 void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
943 StringMap<unsigned> &FunctionToInstrCount);
Jessica Paquette2386eab2018-09-11 23:05:34 +0000944
945 /// Emit the remark.
946 // FIXME: This should be handled by the pass manager, not the outliner.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400947 void
948 emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
949 const StringMap<unsigned> &FunctionToInstrCount);
Jessica Paquette2386eab2018-09-11 23:05:34 +0000950};
Jessica Paquette596f4832017-03-06 21:31:18 +0000951} // Anonymous namespace.
952
953char MachineOutliner::ID = 0;
954
955namespace llvm {
Jessica Paquette8bda1882018-06-30 03:56:03 +0000956ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
957 MachineOutliner *OL = new MachineOutliner();
958 OL->RunOnAllFunctions = RunOnAllFunctions;
959 return OL;
Jessica Paquette13593842017-10-07 00:16:34 +0000960}
961
Jessica Paquette78681be2017-07-27 23:24:43 +0000962} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000963
Jessica Paquette78681be2017-07-27 23:24:43 +0000964INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
965 false)
966
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000967void MachineOutliner::emitNotOutliningCheaperRemark(
968 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
969 OutlinedFunction &OF) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000970 // FIXME: Right now, we arbitrarily choose some Candidate from the
971 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
972 // We should probably sort these by function name or something to make sure
973 // the remarks are stable.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000974 Candidate &C = CandidatesForRepeatedSeq.front();
975 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
976 MORE.emit([&]() {
977 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
978 C.front()->getDebugLoc(), C.getMBB());
979 R << "Did not outline " << NV("Length", StringLen) << " instructions"
980 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
981 << " locations."
982 << " Bytes from outlining all occurrences ("
983 << NV("OutliningCost", OF.getOutliningCost()) << ")"
984 << " >= Unoutlined instruction bytes ("
985 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
986 << " (Also found at: ";
987
988 // Tell the user the other places the candidate was found.
989 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
990 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
991 CandidatesForRepeatedSeq[i].front()->getDebugLoc());
992 if (i != e - 1)
993 R << ", ";
994 }
995
996 R << ")";
997 return R;
998 });
999}
1000
Jessica Paquette58e706a2018-07-24 20:20:45 +00001001void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
1002 MachineBasicBlock *MBB = &*OF.MF->begin();
1003 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
1004 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
1005 MBB->findDebugLoc(MBB->begin()), MBB);
1006 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
Jessica Paquette34b618b2018-12-05 17:57:33 +00001007 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
Jessica Paquette58e706a2018-07-24 20:20:45 +00001008 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
1009 << " locations. "
1010 << "(Found at: ";
1011
1012 // Tell the user the other places the candidate was found.
1013 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
1014
Jessica Paquette58e706a2018-07-24 20:20:45 +00001015 R << NV((Twine("StartLoc") + Twine(i)).str(),
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001016 OF.Candidates[i].front()->getDebugLoc());
Jessica Paquette58e706a2018-07-24 20:20:45 +00001017 if (i != e - 1)
1018 R << ", ";
1019 }
1020
1021 R << ")";
1022
1023 MORE.emit(R);
1024}
1025
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001026void MachineOutliner::findCandidates(
1027 InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +00001028 FunctionList.clear();
Jessica Paquettece3a2dc2018-12-05 23:39:07 +00001029 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette78681be2017-07-27 23:24:43 +00001030
David Tellenbachfbe7f5e2019-10-30 16:28:11 +00001031 // First, find all of the repeated substrings in the tree of minimum length
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001032 // 2.
Jessica Paquetted4e7d072018-12-06 00:04:03 +00001033 std::vector<Candidate> CandidatesForRepeatedSeq;
Jessica Paquettea409cc92018-11-07 19:20:55 +00001034 for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
Jessica Paquetted4e7d072018-12-06 00:04:03 +00001035 CandidatesForRepeatedSeq.clear();
Jessica Paquettea409cc92018-11-07 19:20:55 +00001036 SuffixTree::RepeatedSubstring RS = *It;
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001037 unsigned StringLen = RS.Length;
1038 for (const unsigned &StartIdx : RS.StartIndices) {
1039 unsigned EndIdx = StartIdx + StringLen - 1;
1040 // Trick: Discard some candidates that would be incompatible with the
1041 // ones we've already found for this sequence. This will save us some
1042 // work in candidate selection.
1043 //
1044 // If two candidates overlap, then we can't outline them both. This
1045 // happens when we have candidates that look like, say
1046 //
1047 // AA (where each "A" is an instruction).
1048 //
1049 // We might have some portion of the module that looks like this:
1050 // AAAAAA (6 A's)
1051 //
1052 // In this case, there are 5 different copies of "AA" in this range, but
1053 // at most 3 can be outlined. If only outlining 3 of these is going to
1054 // be unbeneficial, then we ought to not bother.
1055 //
1056 // Note that two things DON'T overlap when they look like this:
1057 // start1...end1 .... start2...end2
1058 // That is, one must either
1059 // * End before the other starts
1060 // * Start after the other ends
1061 if (std::all_of(
1062 CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
1063 [&StartIdx, &EndIdx](const Candidate &C) {
1064 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
1065 })) {
1066 // It doesn't overlap with anything, so we can outline it.
1067 // Each sequence is over [StartIt, EndIt].
1068 // Save the candidate and its location.
Jessica Paquetted87f5442017-07-29 02:55:46 +00001069
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001070 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1071 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
Jessica Paquettecad864d2018-11-13 23:01:34 +00001072 MachineBasicBlock *MBB = StartIt->getParent();
Jessica Paquette78681be2017-07-27 23:24:43 +00001073
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001074 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
Jessica Paquettecad864d2018-11-13 23:01:34 +00001075 EndIt, MBB, FunctionList.size(),
1076 Mapper.MBBFlagsMap[MBB]);
Jessica Paquette809d7082017-07-28 03:21:58 +00001077 }
1078 }
1079
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001080 // We've found something we might want to outline.
1081 // Create an OutlinedFunction to store it and check if it'd be beneficial
1082 // to outline.
Jessica Paquetteddb039a2018-11-15 00:02:24 +00001083 if (CandidatesForRepeatedSeq.size() < 2)
Eli Friedmanda080782018-08-01 00:37:20 +00001084 continue;
1085
1086 // Arbitrarily choose a TII from the first candidate.
1087 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1088 const TargetInstrInfo *TII =
1089 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1090
Jessica Paquette9d93c602018-07-27 18:21:57 +00001091 OutlinedFunction OF =
Eli Friedmanda080782018-08-01 00:37:20 +00001092 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
Jessica Paquette9d93c602018-07-27 18:21:57 +00001093
Jessica Paquetteb2d53c52018-11-13 22:16:27 +00001094 // If we deleted too many candidates, then there's nothing worth outlining.
1095 // FIXME: This should take target-specified instruction sizes into account.
1096 if (OF.Candidates.size() < 2)
Jessica Paquette9d93c602018-07-27 18:21:57 +00001097 continue;
1098
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001099 // Is it better to outline this candidate than not?
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001100 if (OF.getBenefit() < 1) {
Jessica Paquette1cc52a02018-07-24 17:37:28 +00001101 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001102 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001103 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001104
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001105 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001106 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001107}
1108
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001109MachineFunction *MachineOutliner::createOutlinedFunction(
1110 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001111
Fangrui Songae6c9402019-04-10 14:52:37 +00001112 // Create the function name. This should be unique.
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001113 // FIXME: We should have a better naming scheme. This should be stable,
1114 // regardless of changes to the outliner's cost model/traversal order.
Jin Lin0d896272020-03-17 15:40:26 -07001115 std::string FunctionName;
1116 if (OutlineRepeatedNum > 0)
1117 FunctionName = ("OUTLINED_FUNCTION_" + Twine(OutlineRepeatedNum + 1) + "_" +
1118 Twine(Name))
1119 .str();
1120 else
1121 FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str();
Jessica Paquette596f4832017-03-06 21:31:18 +00001122
1123 // Create the function using an IR-level function.
1124 LLVMContext &C = M.getContext();
Fangrui Songae6c9402019-04-10 14:52:37 +00001125 Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1126 Function::ExternalLinkage, FunctionName, M);
Jessica Paquette596f4832017-03-06 21:31:18 +00001127
1128 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1129 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001130 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001131 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1132
Eli Friedman25bef202018-05-15 23:36:46 +00001133 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1134 // necessary.
1135
1136 // Set optsize/minsize, so we don't insert padding between outlined
1137 // functions.
1138 F->addFnAttr(Attribute::OptimizeForSize);
1139 F->addFnAttr(Attribute::MinSize);
1140
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001141 // Include target features from an arbitrary candidate for the outlined
1142 // function. This makes sure the outlined function knows what kinds of
1143 // instructions are going into it. This is fine, since all parent functions
1144 // must necessarily support the instructions that are in the outlined region.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001145 Candidate &FirstCand = OF.Candidates.front();
Jessica Paquette34b618b2018-12-05 17:57:33 +00001146 const Function &ParentFn = FirstCand.getMF()->getFunction();
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001147 if (ParentFn.hasFnAttribute("target-features"))
1148 F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1149
Jessica Paquette596f4832017-03-06 21:31:18 +00001150 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1151 IRBuilder<> Builder(EntryBB);
1152 Builder.CreateRetVoid();
1153
Yuanfang Chencc382cf2019-09-30 17:54:50 +00001154 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
Matthias Braun7bda1952017-06-06 00:44:35 +00001155 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001156 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1157 const TargetSubtargetInfo &STI = MF.getSubtarget();
1158 const TargetInstrInfo &TII = *STI.getInstrInfo();
1159
1160 // Insert the new function into the module.
1161 MF.insert(MF.begin(), &MBB);
1162
Jessica Paquette34b618b2018-12-05 17:57:33 +00001163 for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
1164 ++I) {
1165 MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
Chandler Carruthc73c0302018-08-16 21:30:05 +00001166 NewMI->dropMemRefs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001167
1168 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001169 NewMI->setDebugLoc(DebugLoc());
1170 MBB.insert(MBB.end(), NewMI);
1171 }
1172
Jessica Paquette69f517d2018-07-24 20:13:10 +00001173 TII.buildOutlinedFrame(MBB, MF, OF);
Jessica Paquette729e6862018-01-18 00:00:58 +00001174
Jessica Paquettecc06a782018-09-20 18:53:53 +00001175 // Outlined functions shouldn't preserve liveness.
1176 MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1177 MF.getRegInfo().freezeReservedRegs(MF);
1178
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001179 // If there's a DISubprogram associated with this outlined function, then
1180 // emit debug info for the outlined function.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001181 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001182 // We have a DISubprogram. Get its DICompileUnit.
1183 DICompileUnit *CU = SP->getUnit();
1184 DIBuilder DB(M, true, CU);
1185 DIFile *Unit = SP->getFile();
1186 Mangler Mg;
Jessica Paquettecc06a782018-09-20 18:53:53 +00001187 // Get the mangled name of the function for the linkage name.
1188 std::string Dummy;
1189 llvm::raw_string_ostream MangledNameStream(Dummy);
1190 Mg.getNameWithPrefix(MangledNameStream, F, false);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001191
Jessica Paquettecc06a782018-09-20 18:53:53 +00001192 DISubprogram *OutlinedSP = DB.createFunction(
1193 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1194 Unit /* File */,
1195 0 /* Line 0 is reserved for compiler-generated code. */,
1196 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
Paul Robinsoncda54212018-11-19 18:29:28 +00001197 0, /* Line 0 is reserved for compiler-generated code. */
Jessica Paquettecc06a782018-09-20 18:53:53 +00001198 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
Paul Robinsoncda54212018-11-19 18:29:28 +00001199 /* Outlined code is optimized code by definition. */
1200 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001201
Jessica Paquettecc06a782018-09-20 18:53:53 +00001202 // Don't add any new variables to the subprogram.
1203 DB.finalizeSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001204
Jessica Paquettecc06a782018-09-20 18:53:53 +00001205 // Attach subprogram to the function.
1206 F->setSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001207 // We're done with the DIBuilder.
1208 DB.finalize();
1209 }
1210
Jessica Paquette596f4832017-03-06 21:31:18 +00001211 return &MF;
1212}
1213
Jessica Paquette4ae3b712018-12-05 22:50:26 +00001214bool MachineOutliner::outline(Module &M,
1215 std::vector<OutlinedFunction> &FunctionList,
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001216 InstructionMapper &Mapper,
1217 unsigned &OutlinedFunctionNum) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001218
1219 bool OutlinedSomething = false;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001220
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001221 // Sort by benefit. The most beneficial functions should be outlined first.
Fangrui Songefd94c52019-04-23 14:51:27 +00001222 llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
1223 const OutlinedFunction &RHS) {
1224 return LHS.getBenefit() > RHS.getBenefit();
1225 });
Jessica Paquette596f4832017-03-06 21:31:18 +00001226
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001227 // Walk over each function, outlining them as we go along. Functions are
1228 // outlined greedily, based off the sort above.
1229 for (OutlinedFunction &OF : FunctionList) {
1230 // If we outlined something that overlapped with a candidate in a previous
1231 // step, then we can't outline from it.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001232 erase_if(OF.Candidates, [&Mapper](Candidate &C) {
Jessica Paquetted9d93092018-12-05 22:47:25 +00001233 return std::any_of(
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001234 Mapper.UnsignedVec.begin() + C.getStartIdx(),
1235 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
Jessica Paquetted9d93092018-12-05 22:47:25 +00001236 [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
Jessica Paquette235d8772018-12-05 22:27:38 +00001237 });
Jessica Paquette596f4832017-03-06 21:31:18 +00001238
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001239 // If we made it unbeneficial to outline this function, skip it.
Jessica Paquette85af63d2017-10-17 19:03:23 +00001240 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001241 continue;
1242
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001243 // It's beneficial. Create the function and outline its sequence's
1244 // occurrences.
1245 OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
1246 emitOutlinedFunctionRemark(OF);
1247 FunctionsCreated++;
1248 OutlinedFunctionNum++; // Created a function, move to the next name.
Jessica Paquette596f4832017-03-06 21:31:18 +00001249 MachineFunction *MF = OF.MF;
1250 const TargetSubtargetInfo &STI = MF->getSubtarget();
1251 const TargetInstrInfo &TII = *STI.getInstrInfo();
1252
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001253 // Replace occurrences of the sequence with calls to the new function.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001254 for (Candidate &C : OF.Candidates) {
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001255 MachineBasicBlock &MBB = *C.getMBB();
1256 MachineBasicBlock::iterator StartIt = C.front();
1257 MachineBasicBlock::iterator EndIt = C.back();
Jessica Paquette596f4832017-03-06 21:31:18 +00001258
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001259 // Insert the call.
1260 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
Jessica Paquette0b672492018-04-27 23:36:35 +00001261
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001262 // If the caller tracks liveness, then we need to make sure that
1263 // anything we outline doesn't break liveness assumptions. The outlined
1264 // functions themselves currently don't track liveness, but we should
1265 // make sure that the ranges we yank things out of aren't wrong.
1266 if (MBB.getParent()->getProperties().hasProperty(
1267 MachineFunctionProperties::Property::TracksLiveness)) {
Jin Linfc6fda92020-03-05 13:54:58 -08001268 // The following code is to add implicit def operands to the call
Djordje Todorovic71d38692019-06-27 13:10:29 +00001269 // instruction. It also updates call site information for moved
1270 // code.
Jin Linfc6fda92020-03-05 13:54:58 -08001271 SmallSet<Register, 2> UseRegs, DefRegs;
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001272 // Copy over the defs in the outlined range.
1273 // First inst in outlined range <-- Anything that's defined in this
1274 // ... .. range has to be added as an
1275 // implicit Last inst in outlined range <-- def to the call
Djordje Todorovic71d38692019-06-27 13:10:29 +00001276 // instruction. Also remove call site information for outlined block
Jin Linfc6fda92020-03-05 13:54:58 -08001277 // of code. The exposed uses need to be copied in the outlined range.
1278 for (MachineBasicBlock::reverse_iterator Iter = EndIt.getReverse(),
1279 Last = std::next(CallInst.getReverse());
1280 Iter != Last; Iter++) {
1281 MachineInstr *MI = &*Iter;
1282 for (MachineOperand &MOP : MI->operands()) {
1283 // Skip over anything that isn't a register.
1284 if (!MOP.isReg())
1285 continue;
1286
1287 if (MOP.isDef()) {
1288 // Introduce DefRegs set to skip the redundant register.
1289 DefRegs.insert(MOP.getReg());
1290 if (UseRegs.count(MOP.getReg()))
1291 // Since the regiester is modeled as defined,
1292 // it is not necessary to be put in use register set.
1293 UseRegs.erase(MOP.getReg());
1294 } else if (!MOP.isUndef()) {
1295 // Any register which is not undefined should
1296 // be put in the use register set.
1297 UseRegs.insert(MOP.getReg());
1298 }
1299 }
1300 if (MI->isCandidateForCallSiteEntry())
1301 MI->getMF()->eraseCallSiteInfo(MI);
1302 }
1303
1304 for (const Register &I : DefRegs)
1305 // If it's a def, add it to the call instruction.
1306 CallInst->addOperand(MachineOperand::CreateReg(
1307 I, true, /* isDef = true */
1308 true /* isImp = true */));
1309
1310 for (const Register &I : UseRegs)
1311 // If it's a exposed use, add it to the call instruction.
1312 CallInst->addOperand(
1313 MachineOperand::CreateReg(I, false, /* isDef = false */
1314 true /* isImp = true */));
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001315 }
1316
1317 // Erase from the point after where the call was inserted up to, and
1318 // including, the final instruction in the sequence.
1319 // Erase needs one past the end, so we need std::next there too.
1320 MBB.erase(std::next(StartIt), std::next(EndIt));
Jessica Paquette235d8772018-12-05 22:27:38 +00001321
Jessica Paquetted9d93092018-12-05 22:47:25 +00001322 // Keep track of what we removed by marking them all as -1.
Jessica Paquette235d8772018-12-05 22:27:38 +00001323 std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1324 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
Jessica Paquetted9d93092018-12-05 22:47:25 +00001325 [](unsigned &I) { I = static_cast<unsigned>(-1); });
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001326 OutlinedSomething = true;
1327
1328 // Statistics.
1329 NumOutlined++;
Jessica Paquette0b672492018-04-27 23:36:35 +00001330 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001331 }
1332
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001333 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001334
1335 return OutlinedSomething;
1336}
1337
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001338void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1339 MachineModuleInfo &MMI) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001340 // Build instruction mappings for each function in the module. Start by
1341 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001342 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001343
Jessica Paquettedf822742018-03-22 21:07:09 +00001344 // If there's nothing in F, then there's no reason to try and outline from
1345 // it.
1346 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001347 continue;
1348
Jessica Paquettedf822742018-03-22 21:07:09 +00001349 // There's something in F. Check if it has a MachineFunction associated with
1350 // it.
1351 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001352
Jessica Paquettedf822742018-03-22 21:07:09 +00001353 // If it doesn't, then there's nothing to outline from. Move to the next
1354 // Function.
1355 if (!MF)
1356 continue;
1357
Eli Friedmanda080782018-08-01 00:37:20 +00001358 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1359
Jessica Paquette8bda1882018-06-30 03:56:03 +00001360 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
1361 continue;
1362
Jessica Paquettedf822742018-03-22 21:07:09 +00001363 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1364 // If it isn't, then move on to the next Function in the module.
1365 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1366 continue;
1367
1368 // We have a function suitable for outlining. Iterate over every
1369 // MachineBasicBlock in MF and try to map its instructions to a list of
1370 // unsigned integers.
1371 for (MachineBasicBlock &MBB : *MF) {
1372 // If there isn't anything in MBB, then there's no point in outlining from
1373 // it.
Jessica Paquetteb320ca22018-09-20 21:53:25 +00001374 // If there are fewer than 2 instructions in the MBB, then it can't ever
1375 // contain something worth outlining.
1376 // FIXME: This should be based off of the maximum size in B of an outlined
1377 // call versus the size in B of the MBB.
1378 if (MBB.empty() || MBB.size() < 2)
Jessica Paquette596f4832017-03-06 21:31:18 +00001379 continue;
1380
Jessica Paquettedf822742018-03-22 21:07:09 +00001381 // Check if MBB could be the target of an indirect branch. If it is, then
1382 // we don't want to outline from it.
1383 if (MBB.hasAddressTaken())
1384 continue;
1385
1386 // MBB is suitable for outlining. Map it to a list of unsigneds.
Eli Friedmanda080782018-08-01 00:37:20 +00001387 Mapper.convertToUnsignedVec(MBB, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001388 }
1389 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001390}
1391
Jessica Paquette2386eab2018-09-11 23:05:34 +00001392void MachineOutliner::initSizeRemarkInfo(
1393 const Module &M, const MachineModuleInfo &MMI,
1394 StringMap<unsigned> &FunctionToInstrCount) {
1395 // Collect instruction counts for every function. We'll use this to emit
1396 // per-function size remarks later.
1397 for (const Function &F : M) {
1398 MachineFunction *MF = MMI.getMachineFunction(F);
1399
1400 // We only care about MI counts here. If there's no MachineFunction at this
1401 // point, then there won't be after the outliner runs, so let's move on.
1402 if (!MF)
1403 continue;
1404 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1405 }
1406}
1407
1408void MachineOutliner::emitInstrCountChangedRemark(
1409 const Module &M, const MachineModuleInfo &MMI,
1410 const StringMap<unsigned> &FunctionToInstrCount) {
1411 // Iterate over each function in the module and emit remarks.
1412 // Note that we won't miss anything by doing this, because the outliner never
1413 // deletes functions.
1414 for (const Function &F : M) {
1415 MachineFunction *MF = MMI.getMachineFunction(F);
1416
1417 // The outliner never deletes functions. If we don't have a MF here, then we
1418 // didn't have one prior to outlining either.
1419 if (!MF)
1420 continue;
1421
Benjamin Krameradcd0262020-01-28 20:23:46 +01001422 std::string Fname = std::string(F.getName());
Jessica Paquette2386eab2018-09-11 23:05:34 +00001423 unsigned FnCountAfter = MF->getInstructionCount();
1424 unsigned FnCountBefore = 0;
1425
1426 // Check if the function was recorded before.
1427 auto It = FunctionToInstrCount.find(Fname);
1428
1429 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1430 // to that.
1431 if (It != FunctionToInstrCount.end())
1432 FnCountBefore = It->second;
1433
1434 // Compute the delta and emit a remark if there was a change.
1435 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1436 static_cast<int64_t>(FnCountBefore);
1437 if (FnDelta == 0)
1438 continue;
1439
1440 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1441 MORE.emit([&]() {
1442 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001443 DiagnosticLocation(), &MF->front());
Jessica Paquette2386eab2018-09-11 23:05:34 +00001444 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1445 << ": Function: "
1446 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1447 << ": MI instruction count changed from "
1448 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1449 FnCountBefore)
1450 << " to "
1451 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1452 FnCountAfter)
1453 << "; Delta: "
1454 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1455 return R;
1456 });
1457 }
1458}
1459
Jin Lin0d896272020-03-17 15:40:26 -07001460bool MachineOutliner::runOnceOnModule(Module &M, unsigned Iter) {
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001461 // Check if there's anything in the module. If it's empty, then there's
1462 // nothing to outline.
1463 if (M.empty())
1464 return false;
1465
Jin Lin0d896272020-03-17 15:40:26 -07001466 OutlineRepeatedNum = Iter;
1467
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001468 // Number to append to the current outlined function.
1469 unsigned OutlinedFunctionNum = 0;
1470
1471 if (!doOutline(M, OutlinedFunctionNum))
1472 return false;
1473 return true;
1474}
1475
1476bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
Yuanfang Chencc382cf2019-09-30 17:54:50 +00001477 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001478
1479 // If the user passed -enable-machine-outliner=always or
1480 // -enable-machine-outliner, the pass will run on all functions in the module.
1481 // Otherwise, if the target supports default outlining, it will run on all
1482 // functions deemed by the target to be worth outlining from by default. Tell
1483 // the user how the outliner is running.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001484 LLVM_DEBUG({
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001485 dbgs() << "Machine Outliner: Running on ";
1486 if (RunOnAllFunctions)
1487 dbgs() << "all functions";
1488 else
1489 dbgs() << "target-default functions";
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001490 dbgs() << "\n";
1491 });
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001492
1493 // If the user specifies that they want to outline from linkonceodrs, set
1494 // it here.
1495 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1496 InstructionMapper Mapper;
1497
1498 // Prepare instruction mappings for the suffix tree.
1499 populateMapper(Mapper, M, MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +00001500 std::vector<OutlinedFunction> FunctionList;
1501
Jessica Paquetteacffa282017-03-23 21:27:38 +00001502 // Find all of the outlining candidates.
Jessica Paquettece3a2dc2018-12-05 23:39:07 +00001503 findCandidates(Mapper, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001504
Jessica Paquette2386eab2018-09-11 23:05:34 +00001505 // If we've requested size remarks, then collect the MI counts of every
1506 // function before outlining, and the MI counts after outlining.
1507 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1508 // the pass manager's responsibility.
1509 // This could pretty easily be placed in outline instead, but because we
1510 // really ultimately *don't* want this here, it's done like this for now
1511 // instead.
1512
1513 // Check if we want size remarks.
1514 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1515 StringMap<unsigned> FunctionToInstrCount;
1516 if (ShouldEmitSizeRemarks)
1517 initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
1518
Jessica Paquetteacffa282017-03-23 21:27:38 +00001519 // Outline each of the candidates and return true if something was outlined.
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001520 bool OutlinedSomething =
1521 outline(M, FunctionList, Mapper, OutlinedFunctionNum);
Jessica Paquette729e6862018-01-18 00:00:58 +00001522
Jessica Paquette2386eab2018-09-11 23:05:34 +00001523 // If we outlined something, we definitely changed the MI count of the
1524 // module. If we've asked for size remarks, then output them.
1525 // FIXME: This should be in the pass manager.
1526 if (ShouldEmitSizeRemarks && OutlinedSomething)
1527 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
1528
Jessica Paquette729e6862018-01-18 00:00:58 +00001529 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001530}
Jin Lin0d896272020-03-17 15:40:26 -07001531
1532// Apply machine outlining for NumRepeat times.
1533bool MachineOutliner::runOnModule(Module &M) {
1534 if (NumRepeat < 1)
1535 report_fatal_error("Expect NumRepeat for machine outlining "
1536 "to be greater than or equal to 1!\n");
1537
1538 bool Changed = false;
1539 for (unsigned I = 0; I < NumRepeat; I++) {
1540 if (!runOnceOnModule(M, I)) {
1541 LLVM_DEBUG(dbgs() << "Stopped outlining at iteration " << I
1542 << " because no changes were found.\n";);
1543 return Changed;
1544 }
1545 Changed = true;
1546 }
1547 LLVM_DEBUG(dbgs() << "Stopped outlining because iteration is "
1548 "equal to " << NumRepeat << "\n";);
1549 return Changed;
1550}