Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1 | //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // 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 Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 6 | // |
| 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 Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 17 | /// 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 Paquette | 32de26d | 2018-06-19 21:14:48 +0000 | [diff] [blame] | 27 | /// * buildOutlinedFrame |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 28 | /// * insertOutlinedCall |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 29 | /// * isFunctionSafeToOutlineFrom |
| 30 | /// |
| 31 | /// in order to make use of the MachineOutliner. |
| 32 | /// |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 33 | /// 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 Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 57 | #include "llvm/CodeGen/MachineOutliner.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 58 | #include "llvm/ADT/DenseMap.h" |
| 59 | #include "llvm/ADT/Statistic.h" |
| 60 | #include "llvm/ADT/Twine.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 61 | #include "llvm/CodeGen/MachineFunction.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 62 | #include "llvm/CodeGen/MachineModuleInfo.h" |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 63 | #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" |
Geoff Berry | 82203c4 | 2018-01-31 20:15:16 +0000 | [diff] [blame] | 64 | #include "llvm/CodeGen/MachineRegisterInfo.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 65 | #include "llvm/CodeGen/Passes.h" |
David Blaikie | 3f833ed | 2017-11-08 01:01:31 +0000 | [diff] [blame] | 66 | #include "llvm/CodeGen/TargetInstrInfo.h" |
David Blaikie | b3bde2e | 2017-11-17 01:07:10 +0000 | [diff] [blame] | 67 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
Jessica Paquette | 729e686 | 2018-01-18 00:00:58 +0000 | [diff] [blame] | 68 | #include "llvm/IR/DIBuilder.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 69 | #include "llvm/IR/IRBuilder.h" |
Jessica Paquette | a499c3c | 2018-01-19 21:21:49 +0000 | [diff] [blame] | 70 | #include "llvm/IR/Mangler.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 71 | #include "llvm/Support/Allocator.h" |
Jessica Paquette | 1eca23b | 2018-04-19 22:17:07 +0000 | [diff] [blame] | 72 | #include "llvm/Support/CommandLine.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 73 | #include "llvm/Support/Debug.h" |
| 74 | #include "llvm/Support/raw_ostream.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 75 | #include <functional> |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 76 | #include <tuple> |
| 77 | #include <vector> |
| 78 | |
| 79 | #define DEBUG_TYPE "machine-outliner" |
| 80 | |
| 81 | using namespace llvm; |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 82 | using namespace ore; |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 83 | using namespace outliner; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 84 | |
| 85 | STATISTIC(NumOutlined, "Number of candidates outlined"); |
| 86 | STATISTIC(FunctionsCreated, "Number of functions created"); |
| 87 | |
Jessica Paquette | 1eca23b | 2018-04-19 22:17:07 +0000 | [diff] [blame] | 88 | // Set to true if the user wants the outliner to run on linkonceodr linkage |
| 89 | // functions. This is false by default because the linker can dedupe linkonceodr |
| 90 | // functions. Since the outliner is confined to a single module (modulo LTO), |
| 91 | // this is off by default. It should, however, be the default behaviour in |
| 92 | // LTO. |
| 93 | static cl::opt<bool> EnableLinkOnceODROutlining( |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 94 | "enable-linkonceodr-outlining", cl::Hidden, |
Jessica Paquette | 1eca23b | 2018-04-19 22:17:07 +0000 | [diff] [blame] | 95 | cl::desc("Enable the machine outliner on linkonceodr functions"), |
| 96 | cl::init(false)); |
| 97 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 98 | namespace { |
| 99 | |
| 100 | /// Represents an undefined index in the suffix tree. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 101 | const unsigned EmptyIdx = -1; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 102 | |
| 103 | /// A node in a suffix tree which represents a substring or suffix. |
| 104 | /// |
| 105 | /// Each node has either no children or at least two children, with the root |
| 106 | /// being a exception in the empty tree. |
| 107 | /// |
| 108 | /// Children are represented as a map between unsigned integers and nodes. If |
| 109 | /// a node N has a child M on unsigned integer k, then the mapping represented |
| 110 | /// by N is a proper prefix of the mapping represented by M. Note that this, |
| 111 | /// although similar to a trie is somewhat different: each node stores a full |
| 112 | /// substring of the full mapping rather than a single character state. |
| 113 | /// |
| 114 | /// Each internal node contains a pointer to the internal node representing |
| 115 | /// the same string, but with the first character chopped off. This is stored |
| 116 | /// in \p Link. Each leaf node stores the start index of its respective |
| 117 | /// suffix in \p SuffixIdx. |
| 118 | struct SuffixTreeNode { |
| 119 | |
| 120 | /// The children of this node. |
| 121 | /// |
| 122 | /// A child existing on an unsigned integer implies that from the mapping |
| 123 | /// represented by the current node, there is a way to reach another |
| 124 | /// mapping by tacking that character on the end of the current string. |
| 125 | DenseMap<unsigned, SuffixTreeNode *> Children; |
| 126 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 127 | /// The start index of this node's substring in the main string. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 128 | unsigned StartIdx = EmptyIdx; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 129 | |
| 130 | /// The end index of this node's substring in the main string. |
| 131 | /// |
| 132 | /// Every leaf node must have its \p EndIdx incremented at the end of every |
| 133 | /// step in the construction algorithm. To avoid having to update O(N) |
| 134 | /// nodes individually at the end of every step, the end index is stored |
| 135 | /// as a pointer. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 136 | unsigned *EndIdx = nullptr; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 137 | |
| 138 | /// For leaves, the start index of the suffix represented by this node. |
| 139 | /// |
| 140 | /// For all other nodes, this is ignored. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 141 | unsigned SuffixIdx = EmptyIdx; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 142 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 143 | /// For internal nodes, a pointer to the internal node representing |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 144 | /// the same sequence with the first character chopped off. |
| 145 | /// |
Jessica Paquette | 4602c34 | 2017-07-28 05:59:30 +0000 | [diff] [blame] | 146 | /// This acts as a shortcut in Ukkonen's algorithm. One of the things that |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 147 | /// Ukkonen's algorithm does to achieve linear-time construction is |
| 148 | /// keep track of which node the next insert should be at. This makes each |
| 149 | /// insert O(1), and there are a total of O(N) inserts. The suffix link |
| 150 | /// helps with inserting children of internal nodes. |
| 151 | /// |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 152 | /// Say we add a child to an internal node with associated mapping S. The |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 153 | /// next insertion must be at the node representing S - its first character. |
| 154 | /// This is given by the way that we iteratively build the tree in Ukkonen's |
| 155 | /// algorithm. The main idea is to look at the suffixes of each prefix in the |
| 156 | /// string, starting with the longest suffix of the prefix, and ending with |
| 157 | /// the shortest. Therefore, if we keep pointers between such nodes, we can |
| 158 | /// move to the next insertion point in O(1) time. If we don't, then we'd |
| 159 | /// have to query from the root, which takes O(N) time. This would make the |
| 160 | /// construction algorithm O(N^2) rather than O(N). |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 161 | SuffixTreeNode *Link = nullptr; |
| 162 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 163 | /// The length of the string formed by concatenating the edge labels from the |
| 164 | /// root to this node. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 165 | unsigned ConcatLen = 0; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 166 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 167 | /// Returns true if this node is a leaf. |
| 168 | bool isLeaf() const { return SuffixIdx != EmptyIdx; } |
| 169 | |
| 170 | /// Returns true if this node is the root of its owning \p SuffixTree. |
| 171 | bool isRoot() const { return StartIdx == EmptyIdx; } |
| 172 | |
| 173 | /// Return the number of elements in the substring associated with this node. |
| 174 | size_t size() const { |
| 175 | |
| 176 | // Is it the root? If so, it's the empty string so return 0. |
| 177 | if (isRoot()) |
| 178 | return 0; |
| 179 | |
| 180 | assert(*EndIdx != EmptyIdx && "EndIdx is undefined!"); |
| 181 | |
| 182 | // Size = the number of elements in the string. |
| 183 | // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1. |
| 184 | return *EndIdx - StartIdx + 1; |
| 185 | } |
| 186 | |
Jessica Paquette | df5b09b | 2018-11-07 19:56:13 +0000 | [diff] [blame] | 187 | SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link) |
| 188 | : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {} |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 189 | |
| 190 | SuffixTreeNode() {} |
| 191 | }; |
| 192 | |
| 193 | /// A data structure for fast substring queries. |
| 194 | /// |
| 195 | /// Suffix trees represent the suffixes of their input strings in their leaves. |
| 196 | /// A suffix tree is a type of compressed trie structure where each node |
| 197 | /// represents an entire substring rather than a single character. Each leaf |
| 198 | /// of the tree is a suffix. |
| 199 | /// |
| 200 | /// A suffix tree can be seen as a type of state machine where each state is a |
| 201 | /// substring of the full string. The tree is structured so that, for a string |
| 202 | /// of length N, there are exactly N leaves in the tree. This structure allows |
| 203 | /// us to quickly find repeated substrings of the input string. |
| 204 | /// |
| 205 | /// In this implementation, a "string" is a vector of unsigned integers. |
| 206 | /// These integers may result from hashing some data type. A suffix tree can |
| 207 | /// contain 1 or many strings, which can then be queried as one large string. |
| 208 | /// |
| 209 | /// The suffix tree is implemented using Ukkonen's algorithm for linear-time |
| 210 | /// suffix tree construction. Ukkonen's algorithm is explained in more detail |
| 211 | /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The |
| 212 | /// paper is available at |
| 213 | /// |
| 214 | /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf |
| 215 | class SuffixTree { |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 216 | public: |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 217 | /// Each element is an integer representing an instruction in the module. |
| 218 | ArrayRef<unsigned> Str; |
| 219 | |
Jessica Paquette | 4e54ef8 | 2018-11-06 21:46:41 +0000 | [diff] [blame] | 220 | /// A repeated substring in the tree. |
| 221 | struct RepeatedSubstring { |
| 222 | /// The length of the string. |
| 223 | unsigned Length; |
| 224 | |
| 225 | /// The start indices of each occurrence. |
| 226 | std::vector<unsigned> StartIndices; |
| 227 | }; |
| 228 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 229 | private: |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 230 | /// Maintains each node in the tree. |
Jessica Paquette | d4cb9c6 | 2017-03-08 23:55:33 +0000 | [diff] [blame] | 231 | SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 232 | |
| 233 | /// The root of the suffix tree. |
| 234 | /// |
| 235 | /// The root represents the empty string. It is maintained by the |
| 236 | /// \p NodeAllocator like every other node in the tree. |
| 237 | SuffixTreeNode *Root = nullptr; |
| 238 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 239 | /// Maintains the end indices of the internal nodes in the tree. |
| 240 | /// |
| 241 | /// Each internal node is guaranteed to never have its end index change |
| 242 | /// during the construction algorithm; however, leaves must be updated at |
| 243 | /// every step. Therefore, we need to store leaf end indices by reference |
| 244 | /// to avoid updating O(N) leaves at every step of construction. Thus, |
| 245 | /// every internal node must be allocated its own end index. |
| 246 | BumpPtrAllocator InternalEndIdxAllocator; |
| 247 | |
| 248 | /// The end index of each leaf in the tree. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 249 | unsigned LeafEndIdx = -1; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 250 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 251 | /// Helper struct which keeps track of the next insertion point in |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 252 | /// Ukkonen's algorithm. |
| 253 | struct ActiveState { |
| 254 | /// The next node to insert at. |
| 255 | SuffixTreeNode *Node; |
| 256 | |
| 257 | /// The index of the first character in the substring currently being added. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 258 | unsigned Idx = EmptyIdx; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 259 | |
| 260 | /// The length of the substring we have to add at the current step. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 261 | unsigned Len = 0; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 262 | }; |
| 263 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 264 | /// The point the next insertion will take place at in the |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 265 | /// construction algorithm. |
| 266 | ActiveState Active; |
| 267 | |
| 268 | /// Allocate a leaf node and add it to the tree. |
| 269 | /// |
| 270 | /// \param Parent The parent of this node. |
| 271 | /// \param StartIdx The start index of this node's associated string. |
| 272 | /// \param Edge The label on the edge leaving \p Parent to this node. |
| 273 | /// |
| 274 | /// \returns A pointer to the allocated leaf node. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 275 | SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx, |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 276 | unsigned Edge) { |
| 277 | |
| 278 | assert(StartIdx <= LeafEndIdx && "String can't start after it ends!"); |
| 279 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 280 | SuffixTreeNode *N = new (NodeAllocator.Allocate()) |
Jessica Paquette | df5b09b | 2018-11-07 19:56:13 +0000 | [diff] [blame] | 281 | SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 282 | Parent.Children[Edge] = N; |
| 283 | |
| 284 | return N; |
| 285 | } |
| 286 | |
| 287 | /// Allocate an internal node and add it to the tree. |
| 288 | /// |
| 289 | /// \param Parent The parent of this node. Only null when allocating the root. |
| 290 | /// \param StartIdx The start index of this node's associated string. |
| 291 | /// \param EndIdx The end index of this node's associated string. |
| 292 | /// \param Edge The label on the edge leaving \p Parent to this node. |
| 293 | /// |
| 294 | /// \returns A pointer to the allocated internal node. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 295 | SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx, |
| 296 | unsigned EndIdx, unsigned Edge) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 297 | |
| 298 | assert(StartIdx <= EndIdx && "String can't start after it ends!"); |
| 299 | assert(!(!Parent && StartIdx != EmptyIdx) && |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 300 | "Non-root internal nodes must have parents!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 301 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 302 | unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx); |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 303 | SuffixTreeNode *N = |
| 304 | new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 305 | if (Parent) |
| 306 | Parent->Children[Edge] = N; |
| 307 | |
| 308 | return N; |
| 309 | } |
| 310 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 311 | /// Set the suffix indices of the leaves to the start indices of their |
Jessica Paquette | 4e54ef8 | 2018-11-06 21:46:41 +0000 | [diff] [blame] | 312 | /// respective suffixes. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 313 | /// |
| 314 | /// \param[in] CurrNode The node currently being visited. |
Jessica Paquette | df5b09b | 2018-11-07 19:56:13 +0000 | [diff] [blame] | 315 | /// \param CurrNodeLen The concatenation of all node sizes from the root to |
| 316 | /// this node. Used to produce suffix indices. |
| 317 | void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrNodeLen) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 318 | |
| 319 | bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot(); |
| 320 | |
Jessica Paquette | df5b09b | 2018-11-07 19:56:13 +0000 | [diff] [blame] | 321 | // Store the concatenation of lengths down from the root. |
| 322 | CurrNode.ConcatLen = CurrNodeLen; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 323 | // Traverse the tree depth-first. |
| 324 | for (auto &ChildPair : CurrNode.Children) { |
| 325 | assert(ChildPair.second && "Node had a null child!"); |
Jessica Paquette | df5b09b | 2018-11-07 19:56:13 +0000 | [diff] [blame] | 326 | setSuffixIndices(*ChildPair.second, |
| 327 | CurrNodeLen + ChildPair.second->size()); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 328 | } |
| 329 | |
Jessica Paquette | df5b09b | 2018-11-07 19:56:13 +0000 | [diff] [blame] | 330 | // Is this node a leaf? If it is, give it a suffix index. |
| 331 | if (IsLeaf) |
| 332 | CurrNode.SuffixIdx = Str.size() - CurrNodeLen; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 333 | } |
| 334 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 335 | /// Construct the suffix tree for the prefix of the input ending at |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 336 | /// \p EndIdx. |
| 337 | /// |
| 338 | /// Used to construct the full suffix tree iteratively. At the end of each |
| 339 | /// step, the constructed suffix tree is either a valid suffix tree, or a |
| 340 | /// suffix tree with implicit suffixes. At the end of the final step, the |
| 341 | /// suffix tree is a valid tree. |
| 342 | /// |
| 343 | /// \param EndIdx The end index of the current prefix in the main string. |
| 344 | /// \param SuffixesToAdd The number of suffixes that must be added |
| 345 | /// to complete the suffix tree at the current phase. |
| 346 | /// |
| 347 | /// \returns The number of suffixes that have not been added at the end of |
| 348 | /// this step. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 349 | unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 350 | SuffixTreeNode *NeedsLink = nullptr; |
| 351 | |
| 352 | while (SuffixesToAdd > 0) { |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 353 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 354 | // Are we waiting to add anything other than just the last character? |
| 355 | if (Active.Len == 0) { |
| 356 | // If not, then say the active index is the end index. |
| 357 | Active.Idx = EndIdx; |
| 358 | } |
| 359 | |
| 360 | assert(Active.Idx <= EndIdx && "Start index can't be after end index!"); |
| 361 | |
| 362 | // The first character in the current substring we're looking at. |
| 363 | unsigned FirstChar = Str[Active.Idx]; |
| 364 | |
| 365 | // Have we inserted anything starting with FirstChar at the current node? |
| 366 | if (Active.Node->Children.count(FirstChar) == 0) { |
| 367 | // If not, then we can just insert a leaf and move too the next step. |
| 368 | insertLeaf(*Active.Node, EndIdx, FirstChar); |
| 369 | |
| 370 | // The active node is an internal node, and we visited it, so it must |
| 371 | // need a link if it doesn't have one. |
| 372 | if (NeedsLink) { |
| 373 | NeedsLink->Link = Active.Node; |
| 374 | NeedsLink = nullptr; |
| 375 | } |
| 376 | } else { |
| 377 | // There's a match with FirstChar, so look for the point in the tree to |
| 378 | // insert a new node. |
| 379 | SuffixTreeNode *NextNode = Active.Node->Children[FirstChar]; |
| 380 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 381 | unsigned SubstringLen = NextNode->size(); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 382 | |
| 383 | // Is the current suffix we're trying to insert longer than the size of |
| 384 | // the child we want to move to? |
| 385 | if (Active.Len >= SubstringLen) { |
| 386 | // If yes, then consume the characters we've seen and move to the next |
| 387 | // node. |
| 388 | Active.Idx += SubstringLen; |
| 389 | Active.Len -= SubstringLen; |
| 390 | Active.Node = NextNode; |
| 391 | continue; |
| 392 | } |
| 393 | |
| 394 | // Otherwise, the suffix we're trying to insert must be contained in the |
| 395 | // next node we want to move to. |
| 396 | unsigned LastChar = Str[EndIdx]; |
| 397 | |
| 398 | // Is the string we're trying to insert a substring of the next node? |
| 399 | if (Str[NextNode->StartIdx + Active.Len] == LastChar) { |
| 400 | // If yes, then we're done for this step. Remember our insertion point |
| 401 | // and move to the next end index. At this point, we have an implicit |
| 402 | // suffix tree. |
| 403 | if (NeedsLink && !Active.Node->isRoot()) { |
| 404 | NeedsLink->Link = Active.Node; |
| 405 | NeedsLink = nullptr; |
| 406 | } |
| 407 | |
| 408 | Active.Len++; |
| 409 | break; |
| 410 | } |
| 411 | |
| 412 | // The string we're trying to insert isn't a substring of the next node, |
| 413 | // but matches up to a point. Split the node. |
| 414 | // |
| 415 | // For example, say we ended our search at a node n and we're trying to |
| 416 | // insert ABD. Then we'll create a new node s for AB, reduce n to just |
| 417 | // representing C, and insert a new leaf node l to represent d. This |
| 418 | // allows us to ensure that if n was a leaf, it remains a leaf. |
| 419 | // |
| 420 | // | ABC ---split---> | AB |
| 421 | // n s |
| 422 | // C / \ D |
| 423 | // n l |
| 424 | |
| 425 | // The node s from the diagram |
| 426 | SuffixTreeNode *SplitNode = |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 427 | insertInternalNode(Active.Node, NextNode->StartIdx, |
| 428 | NextNode->StartIdx + Active.Len - 1, FirstChar); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 429 | |
| 430 | // Insert the new node representing the new substring into the tree as |
| 431 | // a child of the split node. This is the node l from the diagram. |
| 432 | insertLeaf(*SplitNode, EndIdx, LastChar); |
| 433 | |
| 434 | // Make the old node a child of the split node and update its start |
| 435 | // index. This is the node n from the diagram. |
| 436 | NextNode->StartIdx += Active.Len; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 437 | SplitNode->Children[Str[NextNode->StartIdx]] = NextNode; |
| 438 | |
| 439 | // SplitNode is an internal node, update the suffix link. |
| 440 | if (NeedsLink) |
| 441 | NeedsLink->Link = SplitNode; |
| 442 | |
| 443 | NeedsLink = SplitNode; |
| 444 | } |
| 445 | |
| 446 | // We've added something new to the tree, so there's one less suffix to |
| 447 | // add. |
| 448 | SuffixesToAdd--; |
| 449 | |
| 450 | if (Active.Node->isRoot()) { |
| 451 | if (Active.Len > 0) { |
| 452 | Active.Len--; |
| 453 | Active.Idx = EndIdx - SuffixesToAdd + 1; |
| 454 | } |
| 455 | } else { |
| 456 | // Start the next phase at the next smallest suffix. |
| 457 | Active.Node = Active.Node->Link; |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | return SuffixesToAdd; |
| 462 | } |
| 463 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 464 | public: |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 465 | /// Construct a suffix tree from a sequence of unsigned integers. |
| 466 | /// |
| 467 | /// \param Str The string to construct the suffix tree for. |
| 468 | SuffixTree(const std::vector<unsigned> &Str) : Str(Str) { |
| 469 | Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 470 | Active.Node = Root; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 471 | |
| 472 | // Keep track of the number of suffixes we have to add of the current |
| 473 | // prefix. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 474 | unsigned SuffixesToAdd = 0; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 475 | Active.Node = Root; |
| 476 | |
| 477 | // Construct the suffix tree iteratively on each prefix of the string. |
| 478 | // PfxEndIdx is the end index of the current prefix. |
| 479 | // End is one past the last element in the string. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame] | 480 | for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; |
| 481 | PfxEndIdx++) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 482 | SuffixesToAdd++; |
| 483 | LeafEndIdx = PfxEndIdx; // Extend each of the leaves. |
| 484 | SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd); |
| 485 | } |
| 486 | |
| 487 | // Set the suffix indices of each leaf. |
| 488 | assert(Root && "Root node can't be nullptr!"); |
| 489 | setSuffixIndices(*Root, 0); |
| 490 | } |
Jessica Paquette | 4e54ef8 | 2018-11-06 21:46:41 +0000 | [diff] [blame] | 491 | |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 492 | /// Iterator for finding all repeated substrings in the suffix tree. |
| 493 | struct RepeatedSubstringIterator { |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 494 | private: |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 495 | /// The current node we're visiting. |
| 496 | SuffixTreeNode *N = nullptr; |
| 497 | |
| 498 | /// The repeated substring associated with this node. |
| 499 | RepeatedSubstring RS; |
| 500 | |
| 501 | /// The nodes left to visit. |
| 502 | std::vector<SuffixTreeNode *> ToVisit; |
| 503 | |
| 504 | /// The minimum length of a repeated substring to find. |
| 505 | /// Since we're outlining, we want at least two instructions in the range. |
| 506 | /// FIXME: This may not be true for targets like X86 which support many |
| 507 | /// instruction lengths. |
| 508 | const unsigned MinLength = 2; |
| 509 | |
| 510 | /// Move the iterator to the next repeated substring. |
| 511 | void advance() { |
| 512 | // Clear the current state. If we're at the end of the range, then this |
| 513 | // is the state we want to be in. |
| 514 | RS = RepeatedSubstring(); |
| 515 | N = nullptr; |
| 516 | |
Jessica Paquette | 3cd70b3 | 2018-12-06 00:26:21 +0000 | [diff] [blame] | 517 | // Each leaf node represents a repeat of a string. |
| 518 | std::vector<SuffixTreeNode *> LeafChildren; |
| 519 | |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 520 | // Continue visiting nodes until we find one which repeats more than once. |
| 521 | while (!ToVisit.empty()) { |
| 522 | SuffixTreeNode *Curr = ToVisit.back(); |
| 523 | ToVisit.pop_back(); |
Jessica Paquette | 3cd70b3 | 2018-12-06 00:26:21 +0000 | [diff] [blame] | 524 | LeafChildren.clear(); |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 525 | |
| 526 | // Keep track of the length of the string associated with the node. If |
| 527 | // it's too short, we'll quit. |
| 528 | unsigned Length = Curr->ConcatLen; |
| 529 | |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 530 | // Iterate over each child, saving internal nodes for visiting, and |
| 531 | // leaf nodes in LeafChildren. Internal nodes represent individual |
| 532 | // strings, which may repeat. |
| 533 | for (auto &ChildPair : Curr->Children) { |
| 534 | // Save all of this node's children for processing. |
| 535 | if (!ChildPair.second->isLeaf()) |
| 536 | ToVisit.push_back(ChildPair.second); |
| 537 | |
| 538 | // It's not an internal node, so it must be a leaf. If we have a |
| 539 | // long enough string, then save the leaf children. |
| 540 | else if (Length >= MinLength) |
| 541 | LeafChildren.push_back(ChildPair.second); |
| 542 | } |
| 543 | |
| 544 | // The root never represents a repeated substring. If we're looking at |
| 545 | // that, then skip it. |
| 546 | if (Curr->isRoot()) |
| 547 | continue; |
| 548 | |
| 549 | // Do we have any repeated substrings? |
| 550 | if (LeafChildren.size() >= 2) { |
| 551 | // Yes. Update the state to reflect this, and then bail out. |
| 552 | N = Curr; |
| 553 | RS.Length = Length; |
| 554 | for (SuffixTreeNode *Leaf : LeafChildren) |
| 555 | RS.StartIndices.push_back(Leaf->SuffixIdx); |
| 556 | break; |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | // At this point, either NewRS is an empty RepeatedSubstring, or it was |
| 561 | // set in the above loop. Similarly, N is either nullptr, or the node |
| 562 | // associated with NewRS. |
| 563 | } |
| 564 | |
| 565 | public: |
| 566 | /// Return the current repeated substring. |
| 567 | RepeatedSubstring &operator*() { return RS; } |
| 568 | |
| 569 | RepeatedSubstringIterator &operator++() { |
| 570 | advance(); |
| 571 | return *this; |
| 572 | } |
| 573 | |
| 574 | RepeatedSubstringIterator operator++(int I) { |
| 575 | RepeatedSubstringIterator It(*this); |
| 576 | advance(); |
| 577 | return It; |
| 578 | } |
| 579 | |
| 580 | bool operator==(const RepeatedSubstringIterator &Other) { |
| 581 | return N == Other.N; |
| 582 | } |
| 583 | bool operator!=(const RepeatedSubstringIterator &Other) { |
| 584 | return !(*this == Other); |
| 585 | } |
| 586 | |
| 587 | RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) { |
| 588 | // Do we have a non-null node? |
| 589 | if (N) { |
| 590 | // Yes. At the first step, we need to visit all of N's children. |
| 591 | // Note: This means that we visit N last. |
| 592 | ToVisit.push_back(N); |
| 593 | advance(); |
| 594 | } |
| 595 | } |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 596 | }; |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 597 | |
| 598 | typedef RepeatedSubstringIterator iterator; |
| 599 | iterator begin() { return iterator(Root); } |
| 600 | iterator end() { return iterator(nullptr); } |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 601 | }; |
| 602 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 603 | /// Maps \p MachineInstrs to unsigned integers and stores the mappings. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 604 | struct InstructionMapper { |
| 605 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 606 | /// The next available integer to assign to a \p MachineInstr that |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 607 | /// cannot be outlined. |
| 608 | /// |
| 609 | /// Set to -3 for compatability with \p DenseMapInfo<unsigned>. |
| 610 | unsigned IllegalInstrNumber = -3; |
| 611 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 612 | /// The next available integer to assign to a \p MachineInstr that can |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 613 | /// be outlined. |
| 614 | unsigned LegalInstrNumber = 0; |
| 615 | |
| 616 | /// Correspondence from \p MachineInstrs to unsigned integers. |
| 617 | DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait> |
| 618 | InstructionIntegerMap; |
| 619 | |
Jessica Paquette | cad864d | 2018-11-13 23:01:34 +0000 | [diff] [blame] | 620 | /// Correspondence between \p MachineBasicBlocks and target-defined flags. |
| 621 | DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap; |
| 622 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 623 | /// The vector of unsigned integers that the module is mapped to. |
| 624 | std::vector<unsigned> UnsignedVec; |
| 625 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 626 | /// Stores the location of the instruction associated with the integer |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 627 | /// at index i in \p UnsignedVec for each index i. |
| 628 | std::vector<MachineBasicBlock::iterator> InstrList; |
| 629 | |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 630 | // Set if we added an illegal number in the previous step. |
| 631 | // Since each illegal number is unique, we only need one of them between |
| 632 | // each range of legal numbers. This lets us make sure we don't add more |
| 633 | // than one illegal number per range. |
| 634 | bool AddedIllegalLastTime = false; |
| 635 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 636 | /// Maps \p *It to a legal integer. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 637 | /// |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 638 | /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB, |
Jessica Paquette | ca3ed96 | 2018-12-06 00:01:51 +0000 | [diff] [blame] | 639 | /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 640 | /// |
| 641 | /// \returns The integer that \p *It was mapped to. |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 642 | unsigned mapToLegalUnsigned( |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 643 | MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr, |
| 644 | bool &HaveLegalRange, unsigned &NumLegalInBlock, |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 645 | std::vector<unsigned> &UnsignedVecForMBB, |
| 646 | std::vector<MachineBasicBlock::iterator> &InstrListForMBB) { |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 647 | // We added something legal, so we should unset the AddedLegalLastTime |
| 648 | // flag. |
| 649 | AddedIllegalLastTime = false; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 650 | |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 651 | // If we have at least two adjacent legal instructions (which may have |
| 652 | // invisible instructions in between), remember that. |
| 653 | if (CanOutlineWithPrevInstr) |
| 654 | HaveLegalRange = true; |
| 655 | CanOutlineWithPrevInstr = true; |
| 656 | |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 657 | // Keep track of the number of legal instructions we insert. |
| 658 | NumLegalInBlock++; |
| 659 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 660 | // Get the integer for this instruction or give it the current |
| 661 | // LegalInstrNumber. |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 662 | InstrListForMBB.push_back(It); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 663 | MachineInstr &MI = *It; |
| 664 | bool WasInserted; |
| 665 | DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 666 | ResultIt; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 667 | std::tie(ResultIt, WasInserted) = |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 668 | InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber)); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 669 | unsigned MINumber = ResultIt->second; |
| 670 | |
| 671 | // There was an insertion. |
Jessica Paquette | ca3ed96 | 2018-12-06 00:01:51 +0000 | [diff] [blame] | 672 | if (WasInserted) |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 673 | LegalInstrNumber++; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 674 | |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 675 | UnsignedVecForMBB.push_back(MINumber); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 676 | |
| 677 | // Make sure we don't overflow or use any integers reserved by the DenseMap. |
| 678 | if (LegalInstrNumber >= IllegalInstrNumber) |
| 679 | report_fatal_error("Instruction mapping overflow!"); |
| 680 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 681 | assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && |
| 682 | "Tried to assign DenseMap tombstone or empty key to instruction."); |
| 683 | assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && |
| 684 | "Tried to assign DenseMap tombstone or empty key to instruction."); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 685 | |
| 686 | return MINumber; |
| 687 | } |
| 688 | |
| 689 | /// Maps \p *It to an illegal integer. |
| 690 | /// |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 691 | /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p |
| 692 | /// IllegalInstrNumber. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 693 | /// |
| 694 | /// \returns The integer that \p *It was mapped to. |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 695 | unsigned mapToIllegalUnsigned( |
| 696 | MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr, |
| 697 | std::vector<unsigned> &UnsignedVecForMBB, |
| 698 | std::vector<MachineBasicBlock::iterator> &InstrListForMBB) { |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 699 | // Can't outline an illegal instruction. Set the flag. |
| 700 | CanOutlineWithPrevInstr = false; |
| 701 | |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 702 | // Only add one illegal number per range of legal numbers. |
| 703 | if (AddedIllegalLastTime) |
| 704 | return IllegalInstrNumber; |
| 705 | |
| 706 | // Remember that we added an illegal number last time. |
| 707 | AddedIllegalLastTime = true; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 708 | unsigned MINumber = IllegalInstrNumber; |
| 709 | |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 710 | InstrListForMBB.push_back(It); |
| 711 | UnsignedVecForMBB.push_back(IllegalInstrNumber); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 712 | IllegalInstrNumber--; |
| 713 | |
| 714 | assert(LegalInstrNumber < IllegalInstrNumber && |
| 715 | "Instruction mapping overflow!"); |
| 716 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 717 | assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && |
| 718 | "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 719 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 720 | assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && |
| 721 | "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 722 | |
| 723 | return MINumber; |
| 724 | } |
| 725 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 726 | /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 727 | /// and appends it to \p UnsignedVec and \p InstrList. |
| 728 | /// |
| 729 | /// Two instructions are assigned the same integer if they are identical. |
| 730 | /// If an instruction is deemed unsafe to outline, then it will be assigned an |
| 731 | /// unique integer. The resulting mapping is placed into a suffix tree and |
| 732 | /// queried for candidates. |
| 733 | /// |
| 734 | /// \param MBB The \p MachineBasicBlock to be translated into integers. |
Eli Friedman | da08078 | 2018-08-01 00:37:20 +0000 | [diff] [blame] | 735 | /// \param TII \p TargetInstrInfo for the function. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 736 | void convertToUnsignedVec(MachineBasicBlock &MBB, |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 737 | const TargetInstrInfo &TII) { |
Alexander Kornienko | 3635c89 | 2018-11-13 16:41:05 +0000 | [diff] [blame] | 738 | unsigned Flags = 0; |
Jessica Paquette | 82d9c0a | 2018-11-12 23:51:32 +0000 | [diff] [blame] | 739 | |
| 740 | // Don't even map in this case. |
| 741 | if (!TII.isMBBSafeToOutlineFrom(MBB, Flags)) |
| 742 | return; |
| 743 | |
Jessica Paquette | cad864d | 2018-11-13 23:01:34 +0000 | [diff] [blame] | 744 | // Store info for the MBB for later outlining. |
| 745 | MBBFlagsMap[&MBB] = Flags; |
| 746 | |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 747 | MachineBasicBlock::iterator It = MBB.begin(); |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 748 | |
| 749 | // The number of instructions in this block that will be considered for |
| 750 | // outlining. |
| 751 | unsigned NumLegalInBlock = 0; |
| 752 | |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 753 | // True if we have at least two legal instructions which aren't separated |
| 754 | // by an illegal instruction. |
| 755 | bool HaveLegalRange = false; |
| 756 | |
| 757 | // True if we can perform outlining given the last mapped (non-invisible) |
| 758 | // instruction. This lets us know if we have a legal range. |
| 759 | bool CanOutlineWithPrevInstr = false; |
| 760 | |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 761 | // FIXME: Should this all just be handled in the target, rather than using |
| 762 | // repeated calls to getOutliningType? |
| 763 | std::vector<unsigned> UnsignedVecForMBB; |
| 764 | std::vector<MachineBasicBlock::iterator> InstrListForMBB; |
| 765 | |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 766 | for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; It++) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 767 | // Keep track of where this instruction is in the module. |
Jessica Paquette | 3291e73 | 2018-01-09 00:26:18 +0000 | [diff] [blame] | 768 | switch (TII.getOutliningType(It, Flags)) { |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 769 | case InstrType::Illegal: |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 770 | mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, |
| 771 | InstrListForMBB); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 772 | break; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 773 | |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 774 | case InstrType::Legal: |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 775 | mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange, |
| 776 | NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 777 | break; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 778 | |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 779 | case InstrType::LegalTerminator: |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 780 | mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange, |
| 781 | NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB); |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 782 | // The instruction also acts as a terminator, so we have to record that |
| 783 | // in the string. |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 784 | mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 785 | InstrListForMBB); |
Eli Friedman | 042dc9e | 2018-05-22 19:11:06 +0000 | [diff] [blame] | 786 | break; |
| 787 | |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 788 | case InstrType::Invisible: |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 789 | // Normally this is set by mapTo(Blah)Unsigned, but we just want to |
| 790 | // skip this instruction. So, unset the flag here. |
Jessica Paquette | bd72988 | 2018-09-17 18:40:21 +0000 | [diff] [blame] | 791 | AddedIllegalLastTime = false; |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 792 | break; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 793 | } |
| 794 | } |
| 795 | |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 796 | // Are there enough legal instructions in the block for outlining to be |
| 797 | // possible? |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 798 | if (HaveLegalRange) { |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 799 | // After we're done every insertion, uniquely terminate this part of the |
| 800 | // "string". This makes sure we won't match across basic block or function |
| 801 | // boundaries since the "end" is encoded uniquely and thus appears in no |
| 802 | // repeated substring. |
Jessica Paquette | c4cf775 | 2018-11-08 00:33:38 +0000 | [diff] [blame] | 803 | mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 804 | InstrListForMBB); |
Jessica Paquette | 267d266 | 2018-11-08 00:02:11 +0000 | [diff] [blame] | 805 | InstrList.insert(InstrList.end(), InstrListForMBB.begin(), |
| 806 | InstrListForMBB.end()); |
| 807 | UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(), |
| 808 | UnsignedVecForMBB.end()); |
| 809 | } |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 810 | } |
| 811 | |
| 812 | InstructionMapper() { |
| 813 | // Make sure that the implementation of DenseMapInfo<unsigned> hasn't |
| 814 | // changed. |
| 815 | assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 && |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 816 | "DenseMapInfo<unsigned>'s empty key isn't -1!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 817 | assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 && |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 818 | "DenseMapInfo<unsigned>'s tombstone key isn't -2!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 819 | } |
| 820 | }; |
| 821 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 822 | /// An interprocedural pass which finds repeated sequences of |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 823 | /// instructions and replaces them with calls to functions. |
| 824 | /// |
| 825 | /// Each instruction is mapped to an unsigned integer and placed in a string. |
| 826 | /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree |
| 827 | /// is then repeatedly queried for repeated sequences of instructions. Each |
| 828 | /// non-overlapping repeated sequence is then placed in its own |
| 829 | /// \p MachineFunction and each instance is then replaced with a call to that |
| 830 | /// function. |
| 831 | struct MachineOutliner : public ModulePass { |
| 832 | |
| 833 | static char ID; |
| 834 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 835 | /// Set to true if the outliner should consider functions with |
Jessica Paquette | 1359384 | 2017-10-07 00:16:34 +0000 | [diff] [blame] | 836 | /// linkonceodr linkage. |
| 837 | bool OutlineFromLinkOnceODRs = false; |
| 838 | |
Jessica Paquette | 8bda188 | 2018-06-30 03:56:03 +0000 | [diff] [blame] | 839 | /// Set to true if the outliner should run on all functions in the module |
| 840 | /// considered safe for outlining. |
| 841 | /// Set to true by default for compatibility with llc's -run-pass option. |
| 842 | /// Set when the pass is constructed in TargetPassConfig. |
| 843 | bool RunOnAllFunctions = true; |
| 844 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 845 | StringRef getPassName() const override { return "Machine Outliner"; } |
| 846 | |
| 847 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Yuanfang Chen | cc382cf | 2019-09-30 17:54:50 +0000 | [diff] [blame] | 848 | AU.addRequired<MachineModuleInfoWrapperPass>(); |
| 849 | AU.addPreserved<MachineModuleInfoWrapperPass>(); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 850 | AU.setPreservesAll(); |
| 851 | ModulePass::getAnalysisUsage(AU); |
| 852 | } |
| 853 | |
Jessica Paquette | 1eca23b | 2018-04-19 22:17:07 +0000 | [diff] [blame] | 854 | MachineOutliner() : ModulePass(ID) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 855 | initializeMachineOutlinerPass(*PassRegistry::getPassRegistry()); |
| 856 | } |
| 857 | |
Jessica Paquette | 1cc52a0 | 2018-07-24 17:37:28 +0000 | [diff] [blame] | 858 | /// Remark output explaining that not outlining a set of candidates would be |
| 859 | /// better than outlining that set. |
| 860 | void emitNotOutliningCheaperRemark( |
| 861 | unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq, |
| 862 | OutlinedFunction &OF); |
| 863 | |
Jessica Paquette | 58e706a | 2018-07-24 20:20:45 +0000 | [diff] [blame] | 864 | /// Remark output explaining that a function was outlined. |
| 865 | void emitOutlinedFunctionRemark(OutlinedFunction &OF); |
| 866 | |
Jessica Paquette | ce3a2dc | 2018-12-05 23:39:07 +0000 | [diff] [blame] | 867 | /// Find all repeated substrings that satisfy the outlining cost model by |
| 868 | /// constructing a suffix tree. |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 869 | /// |
| 870 | /// If a substring appears at least twice, then it must be represented by |
Jessica Paquette | 1cc52a0 | 2018-07-24 17:37:28 +0000 | [diff] [blame] | 871 | /// an internal node which appears in at least two suffixes. Each suffix |
| 872 | /// is represented by a leaf node. To do this, we visit each internal node |
| 873 | /// in the tree, using the leaf children of each internal node. If an |
| 874 | /// internal node represents a beneficial substring, then we use each of |
| 875 | /// its leaf children to find the locations of its substring. |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 876 | /// |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 877 | /// \param Mapper Contains outlining mapping information. |
Jessica Paquette | 1cc52a0 | 2018-07-24 17:37:28 +0000 | [diff] [blame] | 878 | /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions |
| 879 | /// each type of candidate. |
Jessica Paquette | ce3a2dc | 2018-12-05 23:39:07 +0000 | [diff] [blame] | 880 | void findCandidates(InstructionMapper &Mapper, |
| 881 | std::vector<OutlinedFunction> &FunctionList); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 882 | |
Jessica Paquette | 4ae3b71 | 2018-12-05 22:50:26 +0000 | [diff] [blame] | 883 | /// Replace the sequences of instructions represented by \p OutlinedFunctions |
| 884 | /// with calls to functions. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 885 | /// |
| 886 | /// \param M The module we are outlining from. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 887 | /// \param FunctionList A list of functions to be inserted into the module. |
| 888 | /// \param Mapper Contains the instruction mappings for the module. |
Jessica Paquette | 4ae3b71 | 2018-12-05 22:50:26 +0000 | [diff] [blame] | 889 | bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList, |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 890 | InstructionMapper &Mapper, unsigned &OutlinedFunctionNum); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 891 | |
| 892 | /// Creates a function for \p OF and inserts it into the module. |
Jessica Paquette | e18d6ff | 2018-12-05 23:24:22 +0000 | [diff] [blame] | 893 | MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF, |
Jessica Paquette | a3eb0fa | 2018-11-07 18:36:43 +0000 | [diff] [blame] | 894 | InstructionMapper &Mapper, |
| 895 | unsigned Name); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 896 | |
Puyan Lotfi | a51fc8d | 2019-10-28 15:10:21 -0400 | [diff] [blame] | 897 | /// Calls 'doOutline()'. |
| 898 | bool runOnModule(Module &M) override; |
| 899 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 900 | /// Construct a suffix tree on the instructions in \p M and outline repeated |
| 901 | /// strings from that tree. |
Puyan Lotfi | a51fc8d | 2019-10-28 15:10:21 -0400 | [diff] [blame] | 902 | bool doOutline(Module &M, unsigned &OutlinedFunctionNum); |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 903 | |
| 904 | /// Return a DISubprogram for OF if one exists, and null otherwise. Helper |
| 905 | /// function for remark emission. |
| 906 | DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) { |
| 907 | DISubprogram *SP; |
Jessica Paquette | e18d6ff | 2018-12-05 23:24:22 +0000 | [diff] [blame] | 908 | for (const Candidate &C : OF.Candidates) |
| 909 | if (C.getMF() && (SP = C.getMF()->getFunction().getSubprogram())) |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 910 | return SP; |
| 911 | return nullptr; |
| 912 | } |
Jessica Paquette | 050d1ac | 2018-09-11 16:33:46 +0000 | [diff] [blame] | 913 | |
| 914 | /// Populate and \p InstructionMapper with instruction-to-integer mappings. |
| 915 | /// These are used to construct a suffix tree. |
| 916 | void populateMapper(InstructionMapper &Mapper, Module &M, |
| 917 | MachineModuleInfo &MMI); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 918 | |
Jessica Paquette | 2386eab | 2018-09-11 23:05:34 +0000 | [diff] [blame] | 919 | /// Initialize information necessary to output a size remark. |
| 920 | /// FIXME: This should be handled by the pass manager, not the outliner. |
| 921 | /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy |
| 922 | /// pass manager. |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 923 | void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI, |
| 924 | StringMap<unsigned> &FunctionToInstrCount); |
Jessica Paquette | 2386eab | 2018-09-11 23:05:34 +0000 | [diff] [blame] | 925 | |
| 926 | /// Emit the remark. |
| 927 | // FIXME: This should be handled by the pass manager, not the outliner. |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 928 | void |
| 929 | emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI, |
| 930 | const StringMap<unsigned> &FunctionToInstrCount); |
Jessica Paquette | 2386eab | 2018-09-11 23:05:34 +0000 | [diff] [blame] | 931 | }; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 932 | } // Anonymous namespace. |
| 933 | |
| 934 | char MachineOutliner::ID = 0; |
| 935 | |
| 936 | namespace llvm { |
Jessica Paquette | 8bda188 | 2018-06-30 03:56:03 +0000 | [diff] [blame] | 937 | ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) { |
| 938 | MachineOutliner *OL = new MachineOutliner(); |
| 939 | OL->RunOnAllFunctions = RunOnAllFunctions; |
| 940 | return OL; |
Jessica Paquette | 1359384 | 2017-10-07 00:16:34 +0000 | [diff] [blame] | 941 | } |
| 942 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 943 | } // namespace llvm |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 944 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 945 | INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false, |
| 946 | false) |
| 947 | |
Jessica Paquette | 1cc52a0 | 2018-07-24 17:37:28 +0000 | [diff] [blame] | 948 | void MachineOutliner::emitNotOutliningCheaperRemark( |
| 949 | unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq, |
| 950 | OutlinedFunction &OF) { |
Jessica Paquette | c991cf3 | 2018-11-01 23:09:06 +0000 | [diff] [blame] | 951 | // FIXME: Right now, we arbitrarily choose some Candidate from the |
| 952 | // OutlinedFunction. This isn't necessarily fixed, nor does it have to be. |
| 953 | // We should probably sort these by function name or something to make sure |
| 954 | // the remarks are stable. |
Jessica Paquette | 1cc52a0 | 2018-07-24 17:37:28 +0000 | [diff] [blame] | 955 | Candidate &C = CandidatesForRepeatedSeq.front(); |
| 956 | MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr); |
| 957 | MORE.emit([&]() { |
| 958 | MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper", |
| 959 | C.front()->getDebugLoc(), C.getMBB()); |
| 960 | R << "Did not outline " << NV("Length", StringLen) << " instructions" |
| 961 | << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size()) |
| 962 | << " locations." |
| 963 | << " Bytes from outlining all occurrences (" |
| 964 | << NV("OutliningCost", OF.getOutliningCost()) << ")" |
| 965 | << " >= Unoutlined instruction bytes (" |
| 966 | << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")" |
| 967 | << " (Also found at: "; |
| 968 | |
| 969 | // Tell the user the other places the candidate was found. |
| 970 | for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) { |
| 971 | R << NV((Twine("OtherStartLoc") + Twine(i)).str(), |
| 972 | CandidatesForRepeatedSeq[i].front()->getDebugLoc()); |
| 973 | if (i != e - 1) |
| 974 | R << ", "; |
| 975 | } |
| 976 | |
| 977 | R << ")"; |
| 978 | return R; |
| 979 | }); |
| 980 | } |
| 981 | |
Jessica Paquette | 58e706a | 2018-07-24 20:20:45 +0000 | [diff] [blame] | 982 | void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) { |
| 983 | MachineBasicBlock *MBB = &*OF.MF->begin(); |
| 984 | MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr); |
| 985 | MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction", |
| 986 | MBB->findDebugLoc(MBB->begin()), MBB); |
| 987 | R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by " |
Jessica Paquette | 34b618b | 2018-12-05 17:57:33 +0000 | [diff] [blame] | 988 | << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions " |
Jessica Paquette | 58e706a | 2018-07-24 20:20:45 +0000 | [diff] [blame] | 989 | << "from " << NV("NumOccurrences", OF.getOccurrenceCount()) |
| 990 | << " locations. " |
| 991 | << "(Found at: "; |
| 992 | |
| 993 | // Tell the user the other places the candidate was found. |
| 994 | for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) { |
| 995 | |
Jessica Paquette | 58e706a | 2018-07-24 20:20:45 +0000 | [diff] [blame] | 996 | R << NV((Twine("StartLoc") + Twine(i)).str(), |
Jessica Paquette | e18d6ff | 2018-12-05 23:24:22 +0000 | [diff] [blame] | 997 | OF.Candidates[i].front()->getDebugLoc()); |
Jessica Paquette | 58e706a | 2018-07-24 20:20:45 +0000 | [diff] [blame] | 998 | if (i != e - 1) |
| 999 | R << ", "; |
| 1000 | } |
| 1001 | |
| 1002 | R << ")"; |
| 1003 | |
| 1004 | MORE.emit(R); |
| 1005 | } |
| 1006 | |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 1007 | void MachineOutliner::findCandidates( |
| 1008 | InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) { |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1009 | FunctionList.clear(); |
Jessica Paquette | ce3a2dc | 2018-12-05 23:39:07 +0000 | [diff] [blame] | 1010 | SuffixTree ST(Mapper.UnsignedVec); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1011 | |
David Tellenbach | fbe7f5e | 2019-10-30 16:28:11 +0000 | [diff] [blame^] | 1012 | // First, find all of the repeated substrings in the tree of minimum length |
Jessica Paquette | 4e54ef8 | 2018-11-06 21:46:41 +0000 | [diff] [blame] | 1013 | // 2. |
Jessica Paquette | d4e7d07 | 2018-12-06 00:04:03 +0000 | [diff] [blame] | 1014 | std::vector<Candidate> CandidatesForRepeatedSeq; |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 1015 | for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) { |
Jessica Paquette | d4e7d07 | 2018-12-06 00:04:03 +0000 | [diff] [blame] | 1016 | CandidatesForRepeatedSeq.clear(); |
Jessica Paquette | a409cc9 | 2018-11-07 19:20:55 +0000 | [diff] [blame] | 1017 | SuffixTree::RepeatedSubstring RS = *It; |
Jessica Paquette | 4e54ef8 | 2018-11-06 21:46:41 +0000 | [diff] [blame] | 1018 | unsigned StringLen = RS.Length; |
| 1019 | for (const unsigned &StartIdx : RS.StartIndices) { |
| 1020 | unsigned EndIdx = StartIdx + StringLen - 1; |
| 1021 | // Trick: Discard some candidates that would be incompatible with the |
| 1022 | // ones we've already found for this sequence. This will save us some |
| 1023 | // work in candidate selection. |
| 1024 | // |
| 1025 | // If two candidates overlap, then we can't outline them both. This |
| 1026 | // happens when we have candidates that look like, say |
| 1027 | // |
| 1028 | // AA (where each "A" is an instruction). |
| 1029 | // |
| 1030 | // We might have some portion of the module that looks like this: |
| 1031 | // AAAAAA (6 A's) |
| 1032 | // |
| 1033 | // In this case, there are 5 different copies of "AA" in this range, but |
| 1034 | // at most 3 can be outlined. If only outlining 3 of these is going to |
| 1035 | // be unbeneficial, then we ought to not bother. |
| 1036 | // |
| 1037 | // Note that two things DON'T overlap when they look like this: |
| 1038 | // start1...end1 .... start2...end2 |
| 1039 | // That is, one must either |
| 1040 | // * End before the other starts |
| 1041 | // * Start after the other ends |
| 1042 | if (std::all_of( |
| 1043 | CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(), |
| 1044 | [&StartIdx, &EndIdx](const Candidate &C) { |
| 1045 | return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx()); |
| 1046 | })) { |
| 1047 | // It doesn't overlap with anything, so we can outline it. |
| 1048 | // Each sequence is over [StartIt, EndIt]. |
| 1049 | // Save the candidate and its location. |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 1050 | |
Jessica Paquette | 4e54ef8 | 2018-11-06 21:46:41 +0000 | [diff] [blame] | 1051 | MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx]; |
| 1052 | MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; |
Jessica Paquette | cad864d | 2018-11-13 23:01:34 +0000 | [diff] [blame] | 1053 | MachineBasicBlock *MBB = StartIt->getParent(); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1054 | |
Jessica Paquette | 4e54ef8 | 2018-11-06 21:46:41 +0000 | [diff] [blame] | 1055 | CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, |
Jessica Paquette | cad864d | 2018-11-13 23:01:34 +0000 | [diff] [blame] | 1056 | EndIt, MBB, FunctionList.size(), |
| 1057 | Mapper.MBBFlagsMap[MBB]); |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 1058 | } |
| 1059 | } |
| 1060 | |
Jessica Paquette | acc15e1 | 2017-10-03 20:32:55 +0000 | [diff] [blame] | 1061 | // We've found something we might want to outline. |
| 1062 | // Create an OutlinedFunction to store it and check if it'd be beneficial |
| 1063 | // to outline. |
Jessica Paquette | ddb039a | 2018-11-15 00:02:24 +0000 | [diff] [blame] | 1064 | if (CandidatesForRepeatedSeq.size() < 2) |
Eli Friedman | da08078 | 2018-08-01 00:37:20 +0000 | [diff] [blame] | 1065 | continue; |
| 1066 | |
| 1067 | // Arbitrarily choose a TII from the first candidate. |
| 1068 | // FIXME: Should getOutliningCandidateInfo move to TargetMachine? |
| 1069 | const TargetInstrInfo *TII = |
| 1070 | CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo(); |
| 1071 | |
Jessica Paquette | 9d93c60 | 2018-07-27 18:21:57 +0000 | [diff] [blame] | 1072 | OutlinedFunction OF = |
Eli Friedman | da08078 | 2018-08-01 00:37:20 +0000 | [diff] [blame] | 1073 | TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq); |
Jessica Paquette | 9d93c60 | 2018-07-27 18:21:57 +0000 | [diff] [blame] | 1074 | |
Jessica Paquette | b2d53c5 | 2018-11-13 22:16:27 +0000 | [diff] [blame] | 1075 | // If we deleted too many candidates, then there's nothing worth outlining. |
| 1076 | // FIXME: This should take target-specified instruction sizes into account. |
| 1077 | if (OF.Candidates.size() < 2) |
Jessica Paquette | 9d93c60 | 2018-07-27 18:21:57 +0000 | [diff] [blame] | 1078 | continue; |
| 1079 | |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 1080 | // Is it better to outline this candidate than not? |
Jessica Paquette | f94d1d2 | 2018-07-24 17:36:13 +0000 | [diff] [blame] | 1081 | if (OF.getBenefit() < 1) { |
Jessica Paquette | 1cc52a0 | 2018-07-24 17:37:28 +0000 | [diff] [blame] | 1082 | emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1083 | continue; |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 1084 | } |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1085 | |
Jessica Paquette | acc15e1 | 2017-10-03 20:32:55 +0000 | [diff] [blame] | 1086 | FunctionList.push_back(OF); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1087 | } |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1088 | } |
| 1089 | |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 1090 | MachineFunction *MachineOutliner::createOutlinedFunction( |
| 1091 | Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1092 | |
Fangrui Song | ae6c940 | 2019-04-10 14:52:37 +0000 | [diff] [blame] | 1093 | // Create the function name. This should be unique. |
Jessica Paquette | a3eb0fa | 2018-11-07 18:36:43 +0000 | [diff] [blame] | 1094 | // FIXME: We should have a better naming scheme. This should be stable, |
| 1095 | // regardless of changes to the outliner's cost model/traversal order. |
Fangrui Song | ae6c940 | 2019-04-10 14:52:37 +0000 | [diff] [blame] | 1096 | std::string FunctionName = ("OUTLINED_FUNCTION_" + Twine(Name)).str(); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1097 | |
| 1098 | // Create the function using an IR-level function. |
| 1099 | LLVMContext &C = M.getContext(); |
Fangrui Song | ae6c940 | 2019-04-10 14:52:37 +0000 | [diff] [blame] | 1100 | Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false), |
| 1101 | Function::ExternalLinkage, FunctionName, M); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1102 | |
| 1103 | // NOTE: If this is linkonceodr, then we can take advantage of linker deduping |
| 1104 | // which gives us better results when we outline from linkonceodr functions. |
Jessica Paquette | d506bf8 | 2018-04-03 21:36:00 +0000 | [diff] [blame] | 1105 | F->setLinkage(GlobalValue::InternalLinkage); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1106 | F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); |
| 1107 | |
Eli Friedman | 25bef20 | 2018-05-15 23:36:46 +0000 | [diff] [blame] | 1108 | // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's |
| 1109 | // necessary. |
| 1110 | |
| 1111 | // Set optsize/minsize, so we don't insert padding between outlined |
| 1112 | // functions. |
| 1113 | F->addFnAttr(Attribute::OptimizeForSize); |
| 1114 | F->addFnAttr(Attribute::MinSize); |
| 1115 | |
Jessica Paquette | e3932ee | 2018-10-29 20:27:07 +0000 | [diff] [blame] | 1116 | // Include target features from an arbitrary candidate for the outlined |
| 1117 | // function. This makes sure the outlined function knows what kinds of |
| 1118 | // instructions are going into it. This is fine, since all parent functions |
| 1119 | // must necessarily support the instructions that are in the outlined region. |
Jessica Paquette | e18d6ff | 2018-12-05 23:24:22 +0000 | [diff] [blame] | 1120 | Candidate &FirstCand = OF.Candidates.front(); |
Jessica Paquette | 34b618b | 2018-12-05 17:57:33 +0000 | [diff] [blame] | 1121 | const Function &ParentFn = FirstCand.getMF()->getFunction(); |
Jessica Paquette | e3932ee | 2018-10-29 20:27:07 +0000 | [diff] [blame] | 1122 | if (ParentFn.hasFnAttribute("target-features")) |
| 1123 | F->addFnAttr(ParentFn.getFnAttribute("target-features")); |
| 1124 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1125 | BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F); |
| 1126 | IRBuilder<> Builder(EntryBB); |
| 1127 | Builder.CreateRetVoid(); |
| 1128 | |
Yuanfang Chen | cc382cf | 2019-09-30 17:54:50 +0000 | [diff] [blame] | 1129 | MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI(); |
Matthias Braun | 7bda195 | 2017-06-06 00:44:35 +0000 | [diff] [blame] | 1130 | MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1131 | MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock(); |
| 1132 | const TargetSubtargetInfo &STI = MF.getSubtarget(); |
| 1133 | const TargetInstrInfo &TII = *STI.getInstrInfo(); |
| 1134 | |
| 1135 | // Insert the new function into the module. |
| 1136 | MF.insert(MF.begin(), &MBB); |
| 1137 | |
Jessica Paquette | 34b618b | 2018-12-05 17:57:33 +0000 | [diff] [blame] | 1138 | for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E; |
| 1139 | ++I) { |
| 1140 | MachineInstr *NewMI = MF.CloneMachineInstr(&*I); |
Chandler Carruth | c73c030 | 2018-08-16 21:30:05 +0000 | [diff] [blame] | 1141 | NewMI->dropMemRefs(MF); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1142 | |
| 1143 | // Don't keep debug information for outlined instructions. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1144 | NewMI->setDebugLoc(DebugLoc()); |
| 1145 | MBB.insert(MBB.end(), NewMI); |
| 1146 | } |
| 1147 | |
Jessica Paquette | 69f517d | 2018-07-24 20:13:10 +0000 | [diff] [blame] | 1148 | TII.buildOutlinedFrame(MBB, MF, OF); |
Jessica Paquette | 729e686 | 2018-01-18 00:00:58 +0000 | [diff] [blame] | 1149 | |
Jessica Paquette | cc06a78 | 2018-09-20 18:53:53 +0000 | [diff] [blame] | 1150 | // Outlined functions shouldn't preserve liveness. |
| 1151 | MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness); |
| 1152 | MF.getRegInfo().freezeReservedRegs(MF); |
| 1153 | |
Jessica Paquette | a499c3c | 2018-01-19 21:21:49 +0000 | [diff] [blame] | 1154 | // If there's a DISubprogram associated with this outlined function, then |
| 1155 | // emit debug info for the outlined function. |
Jessica Paquette | aa08732 | 2018-06-04 21:14:16 +0000 | [diff] [blame] | 1156 | if (DISubprogram *SP = getSubprogramOrNull(OF)) { |
Jessica Paquette | a499c3c | 2018-01-19 21:21:49 +0000 | [diff] [blame] | 1157 | // We have a DISubprogram. Get its DICompileUnit. |
| 1158 | DICompileUnit *CU = SP->getUnit(); |
| 1159 | DIBuilder DB(M, true, CU); |
| 1160 | DIFile *Unit = SP->getFile(); |
| 1161 | Mangler Mg; |
Jessica Paquette | cc06a78 | 2018-09-20 18:53:53 +0000 | [diff] [blame] | 1162 | // Get the mangled name of the function for the linkage name. |
| 1163 | std::string Dummy; |
| 1164 | llvm::raw_string_ostream MangledNameStream(Dummy); |
| 1165 | Mg.getNameWithPrefix(MangledNameStream, F, false); |
Jessica Paquette | a499c3c | 2018-01-19 21:21:49 +0000 | [diff] [blame] | 1166 | |
Jessica Paquette | cc06a78 | 2018-09-20 18:53:53 +0000 | [diff] [blame] | 1167 | DISubprogram *OutlinedSP = DB.createFunction( |
| 1168 | Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()), |
| 1169 | Unit /* File */, |
| 1170 | 0 /* Line 0 is reserved for compiler-generated code. */, |
| 1171 | DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */ |
Paul Robinson | cda5421 | 2018-11-19 18:29:28 +0000 | [diff] [blame] | 1172 | 0, /* Line 0 is reserved for compiler-generated code. */ |
Jessica Paquette | cc06a78 | 2018-09-20 18:53:53 +0000 | [diff] [blame] | 1173 | DINode::DIFlags::FlagArtificial /* Compiler-generated code. */, |
Paul Robinson | cda5421 | 2018-11-19 18:29:28 +0000 | [diff] [blame] | 1174 | /* Outlined code is optimized code by definition. */ |
| 1175 | DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized); |
Jessica Paquette | a499c3c | 2018-01-19 21:21:49 +0000 | [diff] [blame] | 1176 | |
Jessica Paquette | cc06a78 | 2018-09-20 18:53:53 +0000 | [diff] [blame] | 1177 | // Don't add any new variables to the subprogram. |
| 1178 | DB.finalizeSubprogram(OutlinedSP); |
Jessica Paquette | a499c3c | 2018-01-19 21:21:49 +0000 | [diff] [blame] | 1179 | |
Jessica Paquette | cc06a78 | 2018-09-20 18:53:53 +0000 | [diff] [blame] | 1180 | // Attach subprogram to the function. |
| 1181 | F->setSubprogram(OutlinedSP); |
Jessica Paquette | a499c3c | 2018-01-19 21:21:49 +0000 | [diff] [blame] | 1182 | // We're done with the DIBuilder. |
| 1183 | DB.finalize(); |
| 1184 | } |
| 1185 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1186 | return &MF; |
| 1187 | } |
| 1188 | |
Jessica Paquette | 4ae3b71 | 2018-12-05 22:50:26 +0000 | [diff] [blame] | 1189 | bool MachineOutliner::outline(Module &M, |
| 1190 | std::vector<OutlinedFunction> &FunctionList, |
Puyan Lotfi | a51fc8d | 2019-10-28 15:10:21 -0400 | [diff] [blame] | 1191 | InstructionMapper &Mapper, |
| 1192 | unsigned &OutlinedFunctionNum) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1193 | |
| 1194 | bool OutlinedSomething = false; |
Jessica Paquette | a3eb0fa | 2018-11-07 18:36:43 +0000 | [diff] [blame] | 1195 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1196 | // Sort by benefit. The most beneficial functions should be outlined first. |
Fangrui Song | efd94c5 | 2019-04-23 14:51:27 +0000 | [diff] [blame] | 1197 | llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS, |
| 1198 | const OutlinedFunction &RHS) { |
| 1199 | return LHS.getBenefit() > RHS.getBenefit(); |
| 1200 | }); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1201 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1202 | // Walk over each function, outlining them as we go along. Functions are |
| 1203 | // outlined greedily, based off the sort above. |
| 1204 | for (OutlinedFunction &OF : FunctionList) { |
| 1205 | // If we outlined something that overlapped with a candidate in a previous |
| 1206 | // step, then we can't outline from it. |
Jessica Paquette | e18d6ff | 2018-12-05 23:24:22 +0000 | [diff] [blame] | 1207 | erase_if(OF.Candidates, [&Mapper](Candidate &C) { |
Jessica Paquette | d9d9309 | 2018-12-05 22:47:25 +0000 | [diff] [blame] | 1208 | return std::any_of( |
Jessica Paquette | e18d6ff | 2018-12-05 23:24:22 +0000 | [diff] [blame] | 1209 | Mapper.UnsignedVec.begin() + C.getStartIdx(), |
| 1210 | Mapper.UnsignedVec.begin() + C.getEndIdx() + 1, |
Jessica Paquette | d9d9309 | 2018-12-05 22:47:25 +0000 | [diff] [blame] | 1211 | [](unsigned I) { return (I == static_cast<unsigned>(-1)); }); |
Jessica Paquette | 235d877 | 2018-12-05 22:27:38 +0000 | [diff] [blame] | 1212 | }); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1213 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1214 | // If we made it unbeneficial to outline this function, skip it. |
Jessica Paquette | 85af63d | 2017-10-17 19:03:23 +0000 | [diff] [blame] | 1215 | if (OF.getBenefit() < 1) |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1216 | continue; |
| 1217 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1218 | // It's beneficial. Create the function and outline its sequence's |
| 1219 | // occurrences. |
| 1220 | OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum); |
| 1221 | emitOutlinedFunctionRemark(OF); |
| 1222 | FunctionsCreated++; |
| 1223 | OutlinedFunctionNum++; // Created a function, move to the next name. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1224 | MachineFunction *MF = OF.MF; |
| 1225 | const TargetSubtargetInfo &STI = MF->getSubtarget(); |
| 1226 | const TargetInstrInfo &TII = *STI.getInstrInfo(); |
| 1227 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1228 | // Replace occurrences of the sequence with calls to the new function. |
Jessica Paquette | e18d6ff | 2018-12-05 23:24:22 +0000 | [diff] [blame] | 1229 | for (Candidate &C : OF.Candidates) { |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1230 | MachineBasicBlock &MBB = *C.getMBB(); |
| 1231 | MachineBasicBlock::iterator StartIt = C.front(); |
| 1232 | MachineBasicBlock::iterator EndIt = C.back(); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1233 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1234 | // Insert the call. |
| 1235 | auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C); |
Jessica Paquette | 0b67249 | 2018-04-27 23:36:35 +0000 | [diff] [blame] | 1236 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1237 | // If the caller tracks liveness, then we need to make sure that |
| 1238 | // anything we outline doesn't break liveness assumptions. The outlined |
| 1239 | // functions themselves currently don't track liveness, but we should |
| 1240 | // make sure that the ranges we yank things out of aren't wrong. |
| 1241 | if (MBB.getParent()->getProperties().hasProperty( |
| 1242 | MachineFunctionProperties::Property::TracksLiveness)) { |
| 1243 | // Helper lambda for adding implicit def operands to the call |
Djordje Todorovic | 71d3869 | 2019-06-27 13:10:29 +0000 | [diff] [blame] | 1244 | // instruction. It also updates call site information for moved |
| 1245 | // code. |
| 1246 | auto CopyDefsAndUpdateCalls = [&CallInst](MachineInstr &MI) { |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1247 | for (MachineOperand &MOP : MI.operands()) { |
| 1248 | // Skip over anything that isn't a register. |
| 1249 | if (!MOP.isReg()) |
| 1250 | continue; |
Jessica Paquette | 0b67249 | 2018-04-27 23:36:35 +0000 | [diff] [blame] | 1251 | |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1252 | // If it's a def, add it to the call instruction. |
| 1253 | if (MOP.isDef()) |
| 1254 | CallInst->addOperand(MachineOperand::CreateReg( |
| 1255 | MOP.getReg(), true, /* isDef = true */ |
| 1256 | true /* isImp = true */)); |
| 1257 | } |
Djordje Todorovic | 71d3869 | 2019-06-27 13:10:29 +0000 | [diff] [blame] | 1258 | if (MI.isCall()) |
Nikola Prica | 98603a8 | 2019-10-08 15:43:12 +0000 | [diff] [blame] | 1259 | MI.getMF()->eraseCallSiteInfo(&MI); |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1260 | }; |
| 1261 | // Copy over the defs in the outlined range. |
| 1262 | // First inst in outlined range <-- Anything that's defined in this |
| 1263 | // ... .. range has to be added as an |
| 1264 | // implicit Last inst in outlined range <-- def to the call |
Djordje Todorovic | 71d3869 | 2019-06-27 13:10:29 +0000 | [diff] [blame] | 1265 | // instruction. Also remove call site information for outlined block |
| 1266 | // of code. |
| 1267 | std::for_each(CallInst, std::next(EndIt), CopyDefsAndUpdateCalls); |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1268 | } |
| 1269 | |
| 1270 | // Erase from the point after where the call was inserted up to, and |
| 1271 | // including, the final instruction in the sequence. |
| 1272 | // Erase needs one past the end, so we need std::next there too. |
| 1273 | MBB.erase(std::next(StartIt), std::next(EndIt)); |
Jessica Paquette | 235d877 | 2018-12-05 22:27:38 +0000 | [diff] [blame] | 1274 | |
Jessica Paquette | d9d9309 | 2018-12-05 22:47:25 +0000 | [diff] [blame] | 1275 | // Keep track of what we removed by marking them all as -1. |
Jessica Paquette | 235d877 | 2018-12-05 22:27:38 +0000 | [diff] [blame] | 1276 | std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(), |
| 1277 | Mapper.UnsignedVec.begin() + C.getEndIdx() + 1, |
Jessica Paquette | d9d9309 | 2018-12-05 22:47:25 +0000 | [diff] [blame] | 1278 | [](unsigned &I) { I = static_cast<unsigned>(-1); }); |
Jessica Paquette | 962b3ae | 2018-12-05 21:36:04 +0000 | [diff] [blame] | 1279 | OutlinedSomething = true; |
| 1280 | |
| 1281 | // Statistics. |
| 1282 | NumOutlined++; |
Jessica Paquette | 0b67249 | 2018-04-27 23:36:35 +0000 | [diff] [blame] | 1283 | } |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1284 | } |
| 1285 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1286 | LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1287 | |
| 1288 | return OutlinedSomething; |
| 1289 | } |
| 1290 | |
Jessica Paquette | 050d1ac | 2018-09-11 16:33:46 +0000 | [diff] [blame] | 1291 | void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M, |
| 1292 | MachineModuleInfo &MMI) { |
Jessica Paquette | df82274 | 2018-03-22 21:07:09 +0000 | [diff] [blame] | 1293 | // Build instruction mappings for each function in the module. Start by |
| 1294 | // iterating over each Function in M. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1295 | for (Function &F : M) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1296 | |
Jessica Paquette | df82274 | 2018-03-22 21:07:09 +0000 | [diff] [blame] | 1297 | // If there's nothing in F, then there's no reason to try and outline from |
| 1298 | // it. |
| 1299 | if (F.empty()) |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1300 | continue; |
| 1301 | |
Jessica Paquette | 784892c | 2019-10-04 21:24:12 +0000 | [diff] [blame] | 1302 | // Disable outlining from noreturn functions right now. Noreturn requires |
| 1303 | // special handling for the case where what we are outlining could be a |
| 1304 | // tail call. |
| 1305 | if (F.hasFnAttribute(Attribute::NoReturn)) |
| 1306 | continue; |
| 1307 | |
Jessica Paquette | df82274 | 2018-03-22 21:07:09 +0000 | [diff] [blame] | 1308 | // There's something in F. Check if it has a MachineFunction associated with |
| 1309 | // it. |
| 1310 | MachineFunction *MF = MMI.getMachineFunction(F); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1311 | |
Jessica Paquette | df82274 | 2018-03-22 21:07:09 +0000 | [diff] [blame] | 1312 | // If it doesn't, then there's nothing to outline from. Move to the next |
| 1313 | // Function. |
| 1314 | if (!MF) |
| 1315 | continue; |
| 1316 | |
Eli Friedman | da08078 | 2018-08-01 00:37:20 +0000 | [diff] [blame] | 1317 | const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); |
| 1318 | |
Jessica Paquette | 8bda188 | 2018-06-30 03:56:03 +0000 | [diff] [blame] | 1319 | if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF)) |
| 1320 | continue; |
| 1321 | |
Jessica Paquette | df82274 | 2018-03-22 21:07:09 +0000 | [diff] [blame] | 1322 | // We have a MachineFunction. Ask the target if it's suitable for outlining. |
| 1323 | // If it isn't, then move on to the next Function in the module. |
| 1324 | if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) |
| 1325 | continue; |
| 1326 | |
| 1327 | // We have a function suitable for outlining. Iterate over every |
| 1328 | // MachineBasicBlock in MF and try to map its instructions to a list of |
| 1329 | // unsigned integers. |
| 1330 | for (MachineBasicBlock &MBB : *MF) { |
| 1331 | // If there isn't anything in MBB, then there's no point in outlining from |
| 1332 | // it. |
Jessica Paquette | b320ca2 | 2018-09-20 21:53:25 +0000 | [diff] [blame] | 1333 | // If there are fewer than 2 instructions in the MBB, then it can't ever |
| 1334 | // contain something worth outlining. |
| 1335 | // FIXME: This should be based off of the maximum size in B of an outlined |
| 1336 | // call versus the size in B of the MBB. |
| 1337 | if (MBB.empty() || MBB.size() < 2) |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1338 | continue; |
| 1339 | |
Jessica Paquette | df82274 | 2018-03-22 21:07:09 +0000 | [diff] [blame] | 1340 | // Check if MBB could be the target of an indirect branch. If it is, then |
| 1341 | // we don't want to outline from it. |
| 1342 | if (MBB.hasAddressTaken()) |
| 1343 | continue; |
| 1344 | |
| 1345 | // MBB is suitable for outlining. Map it to a list of unsigneds. |
Eli Friedman | da08078 | 2018-08-01 00:37:20 +0000 | [diff] [blame] | 1346 | Mapper.convertToUnsignedVec(MBB, *TII); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1347 | } |
| 1348 | } |
Jessica Paquette | 050d1ac | 2018-09-11 16:33:46 +0000 | [diff] [blame] | 1349 | } |
| 1350 | |
Jessica Paquette | 2386eab | 2018-09-11 23:05:34 +0000 | [diff] [blame] | 1351 | void MachineOutliner::initSizeRemarkInfo( |
| 1352 | const Module &M, const MachineModuleInfo &MMI, |
| 1353 | StringMap<unsigned> &FunctionToInstrCount) { |
| 1354 | // Collect instruction counts for every function. We'll use this to emit |
| 1355 | // per-function size remarks later. |
| 1356 | for (const Function &F : M) { |
| 1357 | MachineFunction *MF = MMI.getMachineFunction(F); |
| 1358 | |
| 1359 | // We only care about MI counts here. If there's no MachineFunction at this |
| 1360 | // point, then there won't be after the outliner runs, so let's move on. |
| 1361 | if (!MF) |
| 1362 | continue; |
| 1363 | FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount(); |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | void MachineOutliner::emitInstrCountChangedRemark( |
| 1368 | const Module &M, const MachineModuleInfo &MMI, |
| 1369 | const StringMap<unsigned> &FunctionToInstrCount) { |
| 1370 | // Iterate over each function in the module and emit remarks. |
| 1371 | // Note that we won't miss anything by doing this, because the outliner never |
| 1372 | // deletes functions. |
| 1373 | for (const Function &F : M) { |
| 1374 | MachineFunction *MF = MMI.getMachineFunction(F); |
| 1375 | |
| 1376 | // The outliner never deletes functions. If we don't have a MF here, then we |
| 1377 | // didn't have one prior to outlining either. |
| 1378 | if (!MF) |
| 1379 | continue; |
| 1380 | |
| 1381 | std::string Fname = F.getName(); |
| 1382 | unsigned FnCountAfter = MF->getInstructionCount(); |
| 1383 | unsigned FnCountBefore = 0; |
| 1384 | |
| 1385 | // Check if the function was recorded before. |
| 1386 | auto It = FunctionToInstrCount.find(Fname); |
| 1387 | |
| 1388 | // Did we have a previously-recorded size? If yes, then set FnCountBefore |
| 1389 | // to that. |
| 1390 | if (It != FunctionToInstrCount.end()) |
| 1391 | FnCountBefore = It->second; |
| 1392 | |
| 1393 | // Compute the delta and emit a remark if there was a change. |
| 1394 | int64_t FnDelta = static_cast<int64_t>(FnCountAfter) - |
| 1395 | static_cast<int64_t>(FnCountBefore); |
| 1396 | if (FnDelta == 0) |
| 1397 | continue; |
| 1398 | |
| 1399 | MachineOptimizationRemarkEmitter MORE(*MF, nullptr); |
| 1400 | MORE.emit([&]() { |
| 1401 | MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange", |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 1402 | DiagnosticLocation(), &MF->front()); |
Jessica Paquette | 2386eab | 2018-09-11 23:05:34 +0000 | [diff] [blame] | 1403 | R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner") |
| 1404 | << ": Function: " |
| 1405 | << DiagnosticInfoOptimizationBase::Argument("Function", F.getName()) |
| 1406 | << ": MI instruction count changed from " |
| 1407 | << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore", |
| 1408 | FnCountBefore) |
| 1409 | << " to " |
| 1410 | << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter", |
| 1411 | FnCountAfter) |
| 1412 | << "; Delta: " |
| 1413 | << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta); |
| 1414 | return R; |
| 1415 | }); |
| 1416 | } |
| 1417 | } |
| 1418 | |
Jessica Paquette | 050d1ac | 2018-09-11 16:33:46 +0000 | [diff] [blame] | 1419 | bool MachineOutliner::runOnModule(Module &M) { |
| 1420 | // Check if there's anything in the module. If it's empty, then there's |
| 1421 | // nothing to outline. |
| 1422 | if (M.empty()) |
| 1423 | return false; |
| 1424 | |
Puyan Lotfi | a51fc8d | 2019-10-28 15:10:21 -0400 | [diff] [blame] | 1425 | // Number to append to the current outlined function. |
| 1426 | unsigned OutlinedFunctionNum = 0; |
| 1427 | |
| 1428 | if (!doOutline(M, OutlinedFunctionNum)) |
| 1429 | return false; |
| 1430 | return true; |
| 1431 | } |
| 1432 | |
| 1433 | bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) { |
Yuanfang Chen | cc382cf | 2019-09-30 17:54:50 +0000 | [diff] [blame] | 1434 | MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI(); |
Jessica Paquette | 050d1ac | 2018-09-11 16:33:46 +0000 | [diff] [blame] | 1435 | |
| 1436 | // If the user passed -enable-machine-outliner=always or |
| 1437 | // -enable-machine-outliner, the pass will run on all functions in the module. |
| 1438 | // Otherwise, if the target supports default outlining, it will run on all |
| 1439 | // functions deemed by the target to be worth outlining from by default. Tell |
| 1440 | // the user how the outliner is running. |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 1441 | LLVM_DEBUG({ |
Jessica Paquette | 050d1ac | 2018-09-11 16:33:46 +0000 | [diff] [blame] | 1442 | dbgs() << "Machine Outliner: Running on "; |
| 1443 | if (RunOnAllFunctions) |
| 1444 | dbgs() << "all functions"; |
| 1445 | else |
| 1446 | dbgs() << "target-default functions"; |
Puyan Lotfi | 6b7615a | 2019-10-28 17:57:51 -0400 | [diff] [blame] | 1447 | dbgs() << "\n"; |
| 1448 | }); |
Jessica Paquette | 050d1ac | 2018-09-11 16:33:46 +0000 | [diff] [blame] | 1449 | |
| 1450 | // If the user specifies that they want to outline from linkonceodrs, set |
| 1451 | // it here. |
| 1452 | OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining; |
| 1453 | InstructionMapper Mapper; |
| 1454 | |
| 1455 | // Prepare instruction mappings for the suffix tree. |
| 1456 | populateMapper(Mapper, M, MMI); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1457 | std::vector<OutlinedFunction> FunctionList; |
| 1458 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1459 | // Find all of the outlining candidates. |
Jessica Paquette | ce3a2dc | 2018-12-05 23:39:07 +0000 | [diff] [blame] | 1460 | findCandidates(Mapper, FunctionList); |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1461 | |
Jessica Paquette | 2386eab | 2018-09-11 23:05:34 +0000 | [diff] [blame] | 1462 | // If we've requested size remarks, then collect the MI counts of every |
| 1463 | // function before outlining, and the MI counts after outlining. |
| 1464 | // FIXME: This shouldn't be in the outliner at all; it should ultimately be |
| 1465 | // the pass manager's responsibility. |
| 1466 | // This could pretty easily be placed in outline instead, but because we |
| 1467 | // really ultimately *don't* want this here, it's done like this for now |
| 1468 | // instead. |
| 1469 | |
| 1470 | // Check if we want size remarks. |
| 1471 | bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark(); |
| 1472 | StringMap<unsigned> FunctionToInstrCount; |
| 1473 | if (ShouldEmitSizeRemarks) |
| 1474 | initSizeRemarkInfo(M, MMI, FunctionToInstrCount); |
| 1475 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1476 | // Outline each of the candidates and return true if something was outlined. |
Puyan Lotfi | a51fc8d | 2019-10-28 15:10:21 -0400 | [diff] [blame] | 1477 | bool OutlinedSomething = |
| 1478 | outline(M, FunctionList, Mapper, OutlinedFunctionNum); |
Jessica Paquette | 729e686 | 2018-01-18 00:00:58 +0000 | [diff] [blame] | 1479 | |
Jessica Paquette | 2386eab | 2018-09-11 23:05:34 +0000 | [diff] [blame] | 1480 | // If we outlined something, we definitely changed the MI count of the |
| 1481 | // module. If we've asked for size remarks, then output them. |
| 1482 | // FIXME: This should be in the pass manager. |
| 1483 | if (ShouldEmitSizeRemarks && OutlinedSomething) |
| 1484 | emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount); |
| 1485 | |
Jessica Paquette | 729e686 | 2018-01-18 00:00:58 +0000 | [diff] [blame] | 1486 | return OutlinedSomething; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1487 | } |