Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1 | //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | /// |
| 10 | /// \file |
| 11 | /// Replaces repeated sequences of instructions with function calls. |
| 12 | /// |
| 13 | /// This works by placing every instruction from every basic block in a |
| 14 | /// suffix tree, and repeatedly querying that tree for repeated sequences of |
| 15 | /// instructions. If a sequence of instructions appears often, then it ought |
| 16 | /// to be beneficial to pull out into a function. |
| 17 | /// |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 18 | /// The MachineOutliner communicates with a given target using hooks defined in |
| 19 | /// TargetInstrInfo.h. The target supplies the outliner with information on how |
| 20 | /// a specific sequence of instructions should be outlined. This information |
| 21 | /// is used to deduce the number of instructions necessary to |
| 22 | /// |
| 23 | /// * Create an outlined function |
| 24 | /// * Call that outlined function |
| 25 | /// |
| 26 | /// Targets must implement |
| 27 | /// * getOutliningCandidateInfo |
| 28 | /// * insertOutlinerEpilogue |
| 29 | /// * insertOutlinedCall |
| 30 | /// * insertOutlinerPrologue |
| 31 | /// * isFunctionSafeToOutlineFrom |
| 32 | /// |
| 33 | /// in order to make use of the MachineOutliner. |
| 34 | /// |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 35 | /// This was originally presented at the 2016 LLVM Developers' Meeting in the |
| 36 | /// talk "Reducing Code Size Using Outlining". For a high-level overview of |
| 37 | /// how this pass works, the talk is available on YouTube at |
| 38 | /// |
| 39 | /// https://www.youtube.com/watch?v=yorld-WSOeU |
| 40 | /// |
| 41 | /// The slides for the talk are available at |
| 42 | /// |
| 43 | /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf |
| 44 | /// |
| 45 | /// The talk provides an overview of how the outliner finds candidates and |
| 46 | /// ultimately outlines them. It describes how the main data structure for this |
| 47 | /// pass, the suffix tree, is queried and purged for candidates. It also gives |
| 48 | /// a simplified suffix tree construction algorithm for suffix trees based off |
| 49 | /// of the algorithm actually used here, Ukkonen's algorithm. |
| 50 | /// |
| 51 | /// For the original RFC for this pass, please see |
| 52 | /// |
| 53 | /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html |
| 54 | /// |
| 55 | /// For more information on the suffix tree data structure, please see |
| 56 | /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf |
| 57 | /// |
| 58 | //===----------------------------------------------------------------------===// |
| 59 | #include "llvm/ADT/DenseMap.h" |
| 60 | #include "llvm/ADT/Statistic.h" |
| 61 | #include "llvm/ADT/Twine.h" |
| 62 | #include "llvm/CodeGen/MachineFrameInfo.h" |
| 63 | #include "llvm/CodeGen/MachineFunction.h" |
| 64 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 65 | #include "llvm/CodeGen/MachineModuleInfo.h" |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 66 | #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 67 | #include "llvm/CodeGen/Passes.h" |
| 68 | #include "llvm/IR/IRBuilder.h" |
| 69 | #include "llvm/Support/Allocator.h" |
| 70 | #include "llvm/Support/Debug.h" |
| 71 | #include "llvm/Support/raw_ostream.h" |
| 72 | #include "llvm/Target/TargetInstrInfo.h" |
| 73 | #include "llvm/Target/TargetMachine.h" |
| 74 | #include "llvm/Target/TargetRegisterInfo.h" |
| 75 | #include "llvm/Target/TargetSubtargetInfo.h" |
| 76 | #include <functional> |
| 77 | #include <map> |
| 78 | #include <sstream> |
| 79 | #include <tuple> |
| 80 | #include <vector> |
| 81 | |
| 82 | #define DEBUG_TYPE "machine-outliner" |
| 83 | |
| 84 | using namespace llvm; |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 85 | using namespace ore; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 86 | |
| 87 | STATISTIC(NumOutlined, "Number of candidates outlined"); |
| 88 | STATISTIC(FunctionsCreated, "Number of functions created"); |
| 89 | |
| 90 | namespace { |
| 91 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 92 | /// \brief An individual sequence of instructions to be replaced with a call to |
| 93 | /// an outlined function. |
| 94 | struct Candidate { |
| 95 | |
| 96 | /// Set to false if the candidate overlapped with another candidate. |
| 97 | bool InCandidateList = true; |
| 98 | |
| 99 | /// The start index of this \p Candidate. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 100 | unsigned StartIdx; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 101 | |
| 102 | /// The number of instructions in this \p Candidate. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 103 | unsigned Len; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 104 | |
| 105 | /// The index of this \p Candidate's \p OutlinedFunction in the list of |
| 106 | /// \p OutlinedFunctions. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 107 | unsigned FunctionIdx; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 108 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 109 | /// Contains all target-specific information for this \p Candidate. |
| 110 | TargetInstrInfo::MachineOutlinerInfo MInfo; |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 111 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 112 | /// \brief The number of instructions that would be saved by outlining every |
| 113 | /// candidate of this type. |
| 114 | /// |
| 115 | /// This is a fixed value which is not updated during the candidate pruning |
| 116 | /// process. It is only used for deciding which candidate to keep if two |
| 117 | /// candidates overlap. The true benefit is stored in the OutlinedFunction |
| 118 | /// for some given candidate. |
| 119 | unsigned Benefit = 0; |
| 120 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 121 | Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx) |
| 122 | : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {} |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 123 | |
| 124 | Candidate() {} |
| 125 | |
| 126 | /// \brief Used to ensure that \p Candidates are outlined in an order that |
| 127 | /// preserves the start and end indices of other \p Candidates. |
| 128 | bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; } |
| 129 | }; |
| 130 | |
| 131 | /// \brief The information necessary to create an outlined function for some |
| 132 | /// class of candidate. |
| 133 | struct OutlinedFunction { |
| 134 | |
| 135 | /// The actual outlined function created. |
| 136 | /// This is initialized after we go through and create the actual function. |
| 137 | MachineFunction *MF = nullptr; |
| 138 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 139 | /// A number assigned to this function which appears at the end of its name. |
| 140 | unsigned Name; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 141 | |
| 142 | /// The number of candidates for this OutlinedFunction. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 143 | unsigned OccurrenceCount = 0; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 144 | |
| 145 | /// \brief The sequence of integers corresponding to the instructions in this |
| 146 | /// function. |
| 147 | std::vector<unsigned> Sequence; |
| 148 | |
| 149 | /// The number of instructions this function would save. |
| 150 | unsigned Benefit = 0; |
| 151 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 152 | /// Contains all target-specific information for this \p OutlinedFunction. |
| 153 | TargetInstrInfo::MachineOutlinerInfo MInfo; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 154 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 155 | OutlinedFunction(unsigned Name, unsigned OccurrenceCount, |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 156 | const std::vector<unsigned> &Sequence, unsigned Benefit, |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 157 | TargetInstrInfo::MachineOutlinerInfo &MInfo) |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 158 | : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence), |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 159 | Benefit(Benefit), MInfo(MInfo) {} |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 160 | }; |
| 161 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 162 | /// Represents an undefined index in the suffix tree. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 163 | const unsigned EmptyIdx = -1; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 164 | |
| 165 | /// A node in a suffix tree which represents a substring or suffix. |
| 166 | /// |
| 167 | /// Each node has either no children or at least two children, with the root |
| 168 | /// being a exception in the empty tree. |
| 169 | /// |
| 170 | /// Children are represented as a map between unsigned integers and nodes. If |
| 171 | /// a node N has a child M on unsigned integer k, then the mapping represented |
| 172 | /// by N is a proper prefix of the mapping represented by M. Note that this, |
| 173 | /// although similar to a trie is somewhat different: each node stores a full |
| 174 | /// substring of the full mapping rather than a single character state. |
| 175 | /// |
| 176 | /// Each internal node contains a pointer to the internal node representing |
| 177 | /// the same string, but with the first character chopped off. This is stored |
| 178 | /// in \p Link. Each leaf node stores the start index of its respective |
| 179 | /// suffix in \p SuffixIdx. |
| 180 | struct SuffixTreeNode { |
| 181 | |
| 182 | /// The children of this node. |
| 183 | /// |
| 184 | /// A child existing on an unsigned integer implies that from the mapping |
| 185 | /// represented by the current node, there is a way to reach another |
| 186 | /// mapping by tacking that character on the end of the current string. |
| 187 | DenseMap<unsigned, SuffixTreeNode *> Children; |
| 188 | |
| 189 | /// A flag set to false if the node has been pruned from the tree. |
| 190 | bool IsInTree = true; |
| 191 | |
| 192 | /// The start index of this node's substring in the main string. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 193 | unsigned StartIdx = EmptyIdx; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 194 | |
| 195 | /// The end index of this node's substring in the main string. |
| 196 | /// |
| 197 | /// Every leaf node must have its \p EndIdx incremented at the end of every |
| 198 | /// step in the construction algorithm. To avoid having to update O(N) |
| 199 | /// nodes individually at the end of every step, the end index is stored |
| 200 | /// as a pointer. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 201 | unsigned *EndIdx = nullptr; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 202 | |
| 203 | /// For leaves, the start index of the suffix represented by this node. |
| 204 | /// |
| 205 | /// For all other nodes, this is ignored. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 206 | unsigned SuffixIdx = EmptyIdx; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 207 | |
| 208 | /// \brief For internal nodes, a pointer to the internal node representing |
| 209 | /// the same sequence with the first character chopped off. |
| 210 | /// |
Jessica Paquette | 4602c34 | 2017-07-28 05:59:30 +0000 | [diff] [blame] | 211 | /// 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] | 212 | /// Ukkonen's algorithm does to achieve linear-time construction is |
| 213 | /// keep track of which node the next insert should be at. This makes each |
| 214 | /// insert O(1), and there are a total of O(N) inserts. The suffix link |
| 215 | /// helps with inserting children of internal nodes. |
| 216 | /// |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 217 | /// 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] | 218 | /// next insertion must be at the node representing S - its first character. |
| 219 | /// This is given by the way that we iteratively build the tree in Ukkonen's |
| 220 | /// algorithm. The main idea is to look at the suffixes of each prefix in the |
| 221 | /// string, starting with the longest suffix of the prefix, and ending with |
| 222 | /// the shortest. Therefore, if we keep pointers between such nodes, we can |
| 223 | /// move to the next insertion point in O(1) time. If we don't, then we'd |
| 224 | /// have to query from the root, which takes O(N) time. This would make the |
| 225 | /// construction algorithm O(N^2) rather than O(N). |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 226 | SuffixTreeNode *Link = nullptr; |
| 227 | |
| 228 | /// The parent of this node. Every node except for the root has a parent. |
| 229 | SuffixTreeNode *Parent = nullptr; |
| 230 | |
| 231 | /// The number of times this node's string appears in the tree. |
| 232 | /// |
| 233 | /// This is equal to the number of leaf children of the string. It represents |
| 234 | /// the number of suffixes that the node's string is a prefix of. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 235 | unsigned OccurrenceCount = 0; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 236 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 237 | /// The length of the string formed by concatenating the edge labels from the |
| 238 | /// root to this node. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 239 | unsigned ConcatLen = 0; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 240 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 241 | /// Returns true if this node is a leaf. |
| 242 | bool isLeaf() const { return SuffixIdx != EmptyIdx; } |
| 243 | |
| 244 | /// Returns true if this node is the root of its owning \p SuffixTree. |
| 245 | bool isRoot() const { return StartIdx == EmptyIdx; } |
| 246 | |
| 247 | /// Return the number of elements in the substring associated with this node. |
| 248 | size_t size() const { |
| 249 | |
| 250 | // Is it the root? If so, it's the empty string so return 0. |
| 251 | if (isRoot()) |
| 252 | return 0; |
| 253 | |
| 254 | assert(*EndIdx != EmptyIdx && "EndIdx is undefined!"); |
| 255 | |
| 256 | // Size = the number of elements in the string. |
| 257 | // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1. |
| 258 | return *EndIdx - StartIdx + 1; |
| 259 | } |
| 260 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 261 | SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link, |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 262 | SuffixTreeNode *Parent) |
| 263 | : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {} |
| 264 | |
| 265 | SuffixTreeNode() {} |
| 266 | }; |
| 267 | |
| 268 | /// A data structure for fast substring queries. |
| 269 | /// |
| 270 | /// Suffix trees represent the suffixes of their input strings in their leaves. |
| 271 | /// A suffix tree is a type of compressed trie structure where each node |
| 272 | /// represents an entire substring rather than a single character. Each leaf |
| 273 | /// of the tree is a suffix. |
| 274 | /// |
| 275 | /// A suffix tree can be seen as a type of state machine where each state is a |
| 276 | /// substring of the full string. The tree is structured so that, for a string |
| 277 | /// of length N, there are exactly N leaves in the tree. This structure allows |
| 278 | /// us to quickly find repeated substrings of the input string. |
| 279 | /// |
| 280 | /// In this implementation, a "string" is a vector of unsigned integers. |
| 281 | /// These integers may result from hashing some data type. A suffix tree can |
| 282 | /// contain 1 or many strings, which can then be queried as one large string. |
| 283 | /// |
| 284 | /// The suffix tree is implemented using Ukkonen's algorithm for linear-time |
| 285 | /// suffix tree construction. Ukkonen's algorithm is explained in more detail |
| 286 | /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The |
| 287 | /// paper is available at |
| 288 | /// |
| 289 | /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf |
| 290 | class SuffixTree { |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 291 | public: |
| 292 | /// Stores each leaf node in the tree. |
| 293 | /// |
| 294 | /// This is used for finding outlining candidates. |
| 295 | std::vector<SuffixTreeNode *> LeafVector; |
| 296 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 297 | /// Each element is an integer representing an instruction in the module. |
| 298 | ArrayRef<unsigned> Str; |
| 299 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 300 | private: |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 301 | /// Maintains each node in the tree. |
Jessica Paquette | d4cb9c6 | 2017-03-08 23:55:33 +0000 | [diff] [blame] | 302 | SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 303 | |
| 304 | /// The root of the suffix tree. |
| 305 | /// |
| 306 | /// The root represents the empty string. It is maintained by the |
| 307 | /// \p NodeAllocator like every other node in the tree. |
| 308 | SuffixTreeNode *Root = nullptr; |
| 309 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 310 | /// Maintains the end indices of the internal nodes in the tree. |
| 311 | /// |
| 312 | /// Each internal node is guaranteed to never have its end index change |
| 313 | /// during the construction algorithm; however, leaves must be updated at |
| 314 | /// every step. Therefore, we need to store leaf end indices by reference |
| 315 | /// to avoid updating O(N) leaves at every step of construction. Thus, |
| 316 | /// every internal node must be allocated its own end index. |
| 317 | BumpPtrAllocator InternalEndIdxAllocator; |
| 318 | |
| 319 | /// The end index of each leaf in the tree. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 320 | unsigned LeafEndIdx = -1; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 321 | |
| 322 | /// \brief Helper struct which keeps track of the next insertion point in |
| 323 | /// Ukkonen's algorithm. |
| 324 | struct ActiveState { |
| 325 | /// The next node to insert at. |
| 326 | SuffixTreeNode *Node; |
| 327 | |
| 328 | /// The index of the first character in the substring currently being added. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 329 | unsigned Idx = EmptyIdx; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 330 | |
| 331 | /// 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^] | 332 | unsigned Len = 0; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 333 | }; |
| 334 | |
| 335 | /// \brief The point the next insertion will take place at in the |
| 336 | /// construction algorithm. |
| 337 | ActiveState Active; |
| 338 | |
| 339 | /// Allocate a leaf node and add it to the tree. |
| 340 | /// |
| 341 | /// \param Parent The parent of this node. |
| 342 | /// \param StartIdx The start index of this node's associated string. |
| 343 | /// \param Edge The label on the edge leaving \p Parent to this node. |
| 344 | /// |
| 345 | /// \returns A pointer to the allocated leaf node. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 346 | SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx, |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 347 | unsigned Edge) { |
| 348 | |
| 349 | assert(StartIdx <= LeafEndIdx && "String can't start after it ends!"); |
| 350 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 351 | SuffixTreeNode *N = new (NodeAllocator.Allocate()) |
| 352 | SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 353 | Parent.Children[Edge] = N; |
| 354 | |
| 355 | return N; |
| 356 | } |
| 357 | |
| 358 | /// Allocate an internal node and add it to the tree. |
| 359 | /// |
| 360 | /// \param Parent The parent of this node. Only null when allocating the root. |
| 361 | /// \param StartIdx The start index of this node's associated string. |
| 362 | /// \param EndIdx The end index of this node's associated string. |
| 363 | /// \param Edge The label on the edge leaving \p Parent to this node. |
| 364 | /// |
| 365 | /// \returns A pointer to the allocated internal node. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 366 | SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx, |
| 367 | unsigned EndIdx, unsigned Edge) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 368 | |
| 369 | assert(StartIdx <= EndIdx && "String can't start after it ends!"); |
| 370 | assert(!(!Parent && StartIdx != EmptyIdx) && |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 371 | "Non-root internal nodes must have parents!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 372 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 373 | unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 374 | SuffixTreeNode *N = new (NodeAllocator.Allocate()) |
| 375 | SuffixTreeNode(StartIdx, E, Root, Parent); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 376 | if (Parent) |
| 377 | Parent->Children[Edge] = N; |
| 378 | |
| 379 | return N; |
| 380 | } |
| 381 | |
| 382 | /// \brief Set the suffix indices of the leaves to the start indices of their |
| 383 | /// respective suffixes. Also stores each leaf in \p LeafVector at its |
| 384 | /// respective suffix index. |
| 385 | /// |
| 386 | /// \param[in] CurrNode The node currently being visited. |
| 387 | /// \param CurrIdx The current index of the string being visited. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 388 | void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 389 | |
| 390 | bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot(); |
| 391 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 392 | // Store the length of the concatenation of all strings from the root to |
| 393 | // this node. |
| 394 | if (!CurrNode.isRoot()) { |
| 395 | if (CurrNode.ConcatLen == 0) |
| 396 | CurrNode.ConcatLen = CurrNode.size(); |
| 397 | |
| 398 | if (CurrNode.Parent) |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 399 | CurrNode.ConcatLen += CurrNode.Parent->ConcatLen; |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 400 | } |
| 401 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 402 | // Traverse the tree depth-first. |
| 403 | for (auto &ChildPair : CurrNode.Children) { |
| 404 | assert(ChildPair.second && "Node had a null child!"); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 405 | setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size()); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 406 | } |
| 407 | |
| 408 | // Is this node a leaf? |
| 409 | if (IsLeaf) { |
| 410 | // If yes, give it a suffix index and bump its parent's occurrence count. |
| 411 | CurrNode.SuffixIdx = Str.size() - CurrIdx; |
| 412 | assert(CurrNode.Parent && "CurrNode had no parent!"); |
| 413 | CurrNode.Parent->OccurrenceCount++; |
| 414 | |
| 415 | // Store the leaf in the leaf vector for pruning later. |
| 416 | LeafVector[CurrNode.SuffixIdx] = &CurrNode; |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | /// \brief Construct the suffix tree for the prefix of the input ending at |
| 421 | /// \p EndIdx. |
| 422 | /// |
| 423 | /// Used to construct the full suffix tree iteratively. At the end of each |
| 424 | /// step, the constructed suffix tree is either a valid suffix tree, or a |
| 425 | /// suffix tree with implicit suffixes. At the end of the final step, the |
| 426 | /// suffix tree is a valid tree. |
| 427 | /// |
| 428 | /// \param EndIdx The end index of the current prefix in the main string. |
| 429 | /// \param SuffixesToAdd The number of suffixes that must be added |
| 430 | /// to complete the suffix tree at the current phase. |
| 431 | /// |
| 432 | /// \returns The number of suffixes that have not been added at the end of |
| 433 | /// this step. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 434 | unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 435 | SuffixTreeNode *NeedsLink = nullptr; |
| 436 | |
| 437 | while (SuffixesToAdd > 0) { |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 438 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 439 | // Are we waiting to add anything other than just the last character? |
| 440 | if (Active.Len == 0) { |
| 441 | // If not, then say the active index is the end index. |
| 442 | Active.Idx = EndIdx; |
| 443 | } |
| 444 | |
| 445 | assert(Active.Idx <= EndIdx && "Start index can't be after end index!"); |
| 446 | |
| 447 | // The first character in the current substring we're looking at. |
| 448 | unsigned FirstChar = Str[Active.Idx]; |
| 449 | |
| 450 | // Have we inserted anything starting with FirstChar at the current node? |
| 451 | if (Active.Node->Children.count(FirstChar) == 0) { |
| 452 | // If not, then we can just insert a leaf and move too the next step. |
| 453 | insertLeaf(*Active.Node, EndIdx, FirstChar); |
| 454 | |
| 455 | // The active node is an internal node, and we visited it, so it must |
| 456 | // need a link if it doesn't have one. |
| 457 | if (NeedsLink) { |
| 458 | NeedsLink->Link = Active.Node; |
| 459 | NeedsLink = nullptr; |
| 460 | } |
| 461 | } else { |
| 462 | // There's a match with FirstChar, so look for the point in the tree to |
| 463 | // insert a new node. |
| 464 | SuffixTreeNode *NextNode = Active.Node->Children[FirstChar]; |
| 465 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 466 | unsigned SubstringLen = NextNode->size(); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 467 | |
| 468 | // Is the current suffix we're trying to insert longer than the size of |
| 469 | // the child we want to move to? |
| 470 | if (Active.Len >= SubstringLen) { |
| 471 | // If yes, then consume the characters we've seen and move to the next |
| 472 | // node. |
| 473 | Active.Idx += SubstringLen; |
| 474 | Active.Len -= SubstringLen; |
| 475 | Active.Node = NextNode; |
| 476 | continue; |
| 477 | } |
| 478 | |
| 479 | // Otherwise, the suffix we're trying to insert must be contained in the |
| 480 | // next node we want to move to. |
| 481 | unsigned LastChar = Str[EndIdx]; |
| 482 | |
| 483 | // Is the string we're trying to insert a substring of the next node? |
| 484 | if (Str[NextNode->StartIdx + Active.Len] == LastChar) { |
| 485 | // If yes, then we're done for this step. Remember our insertion point |
| 486 | // and move to the next end index. At this point, we have an implicit |
| 487 | // suffix tree. |
| 488 | if (NeedsLink && !Active.Node->isRoot()) { |
| 489 | NeedsLink->Link = Active.Node; |
| 490 | NeedsLink = nullptr; |
| 491 | } |
| 492 | |
| 493 | Active.Len++; |
| 494 | break; |
| 495 | } |
| 496 | |
| 497 | // The string we're trying to insert isn't a substring of the next node, |
| 498 | // but matches up to a point. Split the node. |
| 499 | // |
| 500 | // For example, say we ended our search at a node n and we're trying to |
| 501 | // insert ABD. Then we'll create a new node s for AB, reduce n to just |
| 502 | // representing C, and insert a new leaf node l to represent d. This |
| 503 | // allows us to ensure that if n was a leaf, it remains a leaf. |
| 504 | // |
| 505 | // | ABC ---split---> | AB |
| 506 | // n s |
| 507 | // C / \ D |
| 508 | // n l |
| 509 | |
| 510 | // The node s from the diagram |
| 511 | SuffixTreeNode *SplitNode = |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 512 | insertInternalNode(Active.Node, NextNode->StartIdx, |
| 513 | NextNode->StartIdx + Active.Len - 1, FirstChar); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 514 | |
| 515 | // Insert the new node representing the new substring into the tree as |
| 516 | // a child of the split node. This is the node l from the diagram. |
| 517 | insertLeaf(*SplitNode, EndIdx, LastChar); |
| 518 | |
| 519 | // Make the old node a child of the split node and update its start |
| 520 | // index. This is the node n from the diagram. |
| 521 | NextNode->StartIdx += Active.Len; |
| 522 | NextNode->Parent = SplitNode; |
| 523 | SplitNode->Children[Str[NextNode->StartIdx]] = NextNode; |
| 524 | |
| 525 | // SplitNode is an internal node, update the suffix link. |
| 526 | if (NeedsLink) |
| 527 | NeedsLink->Link = SplitNode; |
| 528 | |
| 529 | NeedsLink = SplitNode; |
| 530 | } |
| 531 | |
| 532 | // We've added something new to the tree, so there's one less suffix to |
| 533 | // add. |
| 534 | SuffixesToAdd--; |
| 535 | |
| 536 | if (Active.Node->isRoot()) { |
| 537 | if (Active.Len > 0) { |
| 538 | Active.Len--; |
| 539 | Active.Idx = EndIdx - SuffixesToAdd + 1; |
| 540 | } |
| 541 | } else { |
| 542 | // Start the next phase at the next smallest suffix. |
| 543 | Active.Node = Active.Node->Link; |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | return SuffixesToAdd; |
| 548 | } |
| 549 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 550 | public: |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 551 | /// Construct a suffix tree from a sequence of unsigned integers. |
| 552 | /// |
| 553 | /// \param Str The string to construct the suffix tree for. |
| 554 | SuffixTree(const std::vector<unsigned> &Str) : Str(Str) { |
| 555 | Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0); |
| 556 | Root->IsInTree = true; |
| 557 | Active.Node = Root; |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 558 | LeafVector = std::vector<SuffixTreeNode *>(Str.size()); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 559 | |
| 560 | // Keep track of the number of suffixes we have to add of the current |
| 561 | // prefix. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 562 | unsigned SuffixesToAdd = 0; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 563 | Active.Node = Root; |
| 564 | |
| 565 | // Construct the suffix tree iteratively on each prefix of the string. |
| 566 | // PfxEndIdx is the end index of the current prefix. |
| 567 | // End is one past the last element in the string. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 568 | for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; |
| 569 | PfxEndIdx++) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 570 | SuffixesToAdd++; |
| 571 | LeafEndIdx = PfxEndIdx; // Extend each of the leaves. |
| 572 | SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd); |
| 573 | } |
| 574 | |
| 575 | // Set the suffix indices of each leaf. |
| 576 | assert(Root && "Root node can't be nullptr!"); |
| 577 | setSuffixIndices(*Root, 0); |
| 578 | } |
| 579 | }; |
| 580 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 581 | /// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings. |
| 582 | struct InstructionMapper { |
| 583 | |
| 584 | /// \brief The next available integer to assign to a \p MachineInstr that |
| 585 | /// cannot be outlined. |
| 586 | /// |
| 587 | /// Set to -3 for compatability with \p DenseMapInfo<unsigned>. |
| 588 | unsigned IllegalInstrNumber = -3; |
| 589 | |
| 590 | /// \brief The next available integer to assign to a \p MachineInstr that can |
| 591 | /// be outlined. |
| 592 | unsigned LegalInstrNumber = 0; |
| 593 | |
| 594 | /// Correspondence from \p MachineInstrs to unsigned integers. |
| 595 | DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait> |
| 596 | InstructionIntegerMap; |
| 597 | |
| 598 | /// Corresponcence from unsigned integers to \p MachineInstrs. |
| 599 | /// Inverse of \p InstructionIntegerMap. |
| 600 | DenseMap<unsigned, MachineInstr *> IntegerInstructionMap; |
| 601 | |
| 602 | /// The vector of unsigned integers that the module is mapped to. |
| 603 | std::vector<unsigned> UnsignedVec; |
| 604 | |
| 605 | /// \brief Stores the location of the instruction associated with the integer |
| 606 | /// at index i in \p UnsignedVec for each index i. |
| 607 | std::vector<MachineBasicBlock::iterator> InstrList; |
| 608 | |
| 609 | /// \brief Maps \p *It to a legal integer. |
| 610 | /// |
| 611 | /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap, |
| 612 | /// \p IntegerInstructionMap, and \p LegalInstrNumber. |
| 613 | /// |
| 614 | /// \returns The integer that \p *It was mapped to. |
| 615 | unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) { |
| 616 | |
| 617 | // Get the integer for this instruction or give it the current |
| 618 | // LegalInstrNumber. |
| 619 | InstrList.push_back(It); |
| 620 | MachineInstr &MI = *It; |
| 621 | bool WasInserted; |
| 622 | DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 623 | ResultIt; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 624 | std::tie(ResultIt, WasInserted) = |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 625 | InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber)); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 626 | unsigned MINumber = ResultIt->second; |
| 627 | |
| 628 | // There was an insertion. |
| 629 | if (WasInserted) { |
| 630 | LegalInstrNumber++; |
| 631 | IntegerInstructionMap.insert(std::make_pair(MINumber, &MI)); |
| 632 | } |
| 633 | |
| 634 | UnsignedVec.push_back(MINumber); |
| 635 | |
| 636 | // Make sure we don't overflow or use any integers reserved by the DenseMap. |
| 637 | if (LegalInstrNumber >= IllegalInstrNumber) |
| 638 | report_fatal_error("Instruction mapping overflow!"); |
| 639 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 640 | assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && |
| 641 | "Tried to assign DenseMap tombstone or empty key to instruction."); |
| 642 | assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && |
| 643 | "Tried to assign DenseMap tombstone or empty key to instruction."); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 644 | |
| 645 | return MINumber; |
| 646 | } |
| 647 | |
| 648 | /// Maps \p *It to an illegal integer. |
| 649 | /// |
| 650 | /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber. |
| 651 | /// |
| 652 | /// \returns The integer that \p *It was mapped to. |
| 653 | unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) { |
| 654 | unsigned MINumber = IllegalInstrNumber; |
| 655 | |
| 656 | InstrList.push_back(It); |
| 657 | UnsignedVec.push_back(IllegalInstrNumber); |
| 658 | IllegalInstrNumber--; |
| 659 | |
| 660 | assert(LegalInstrNumber < IllegalInstrNumber && |
| 661 | "Instruction mapping overflow!"); |
| 662 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 663 | assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && |
| 664 | "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 665 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 666 | assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && |
| 667 | "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 668 | |
| 669 | return MINumber; |
| 670 | } |
| 671 | |
| 672 | /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds |
| 673 | /// and appends it to \p UnsignedVec and \p InstrList. |
| 674 | /// |
| 675 | /// Two instructions are assigned the same integer if they are identical. |
| 676 | /// If an instruction is deemed unsafe to outline, then it will be assigned an |
| 677 | /// unique integer. The resulting mapping is placed into a suffix tree and |
| 678 | /// queried for candidates. |
| 679 | /// |
| 680 | /// \param MBB The \p MachineBasicBlock to be translated into integers. |
| 681 | /// \param TRI \p TargetRegisterInfo for the module. |
| 682 | /// \param TII \p TargetInstrInfo for the module. |
| 683 | void convertToUnsignedVec(MachineBasicBlock &MBB, |
| 684 | const TargetRegisterInfo &TRI, |
| 685 | const TargetInstrInfo &TII) { |
| 686 | for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et; |
| 687 | It++) { |
| 688 | |
| 689 | // Keep track of where this instruction is in the module. |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 690 | switch (TII.getOutliningType(*It)) { |
| 691 | case TargetInstrInfo::MachineOutlinerInstrType::Illegal: |
| 692 | mapToIllegalUnsigned(It); |
| 693 | break; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 694 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 695 | case TargetInstrInfo::MachineOutlinerInstrType::Legal: |
| 696 | mapToLegalUnsigned(It); |
| 697 | break; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 698 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 699 | case TargetInstrInfo::MachineOutlinerInstrType::Invisible: |
| 700 | break; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 701 | } |
| 702 | } |
| 703 | |
| 704 | // After we're done every insertion, uniquely terminate this part of the |
| 705 | // "string". This makes sure we won't match across basic block or function |
| 706 | // boundaries since the "end" is encoded uniquely and thus appears in no |
| 707 | // repeated substring. |
| 708 | InstrList.push_back(MBB.end()); |
| 709 | UnsignedVec.push_back(IllegalInstrNumber); |
| 710 | IllegalInstrNumber--; |
| 711 | } |
| 712 | |
| 713 | InstructionMapper() { |
| 714 | // Make sure that the implementation of DenseMapInfo<unsigned> hasn't |
| 715 | // changed. |
| 716 | assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 && |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 717 | "DenseMapInfo<unsigned>'s empty key isn't -1!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 718 | assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 && |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 719 | "DenseMapInfo<unsigned>'s tombstone key isn't -2!"); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 720 | } |
| 721 | }; |
| 722 | |
| 723 | /// \brief An interprocedural pass which finds repeated sequences of |
| 724 | /// instructions and replaces them with calls to functions. |
| 725 | /// |
| 726 | /// Each instruction is mapped to an unsigned integer and placed in a string. |
| 727 | /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree |
| 728 | /// is then repeatedly queried for repeated sequences of instructions. Each |
| 729 | /// non-overlapping repeated sequence is then placed in its own |
| 730 | /// \p MachineFunction and each instance is then replaced with a call to that |
| 731 | /// function. |
| 732 | struct MachineOutliner : public ModulePass { |
| 733 | |
| 734 | static char ID; |
| 735 | |
| 736 | StringRef getPassName() const override { return "Machine Outliner"; } |
| 737 | |
| 738 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 739 | AU.addRequired<MachineModuleInfo>(); |
| 740 | AU.addPreserved<MachineModuleInfo>(); |
| 741 | AU.setPreservesAll(); |
| 742 | ModulePass::getAnalysisUsage(AU); |
| 743 | } |
| 744 | |
| 745 | MachineOutliner() : ModulePass(ID) { |
| 746 | initializeMachineOutlinerPass(*PassRegistry::getPassRegistry()); |
| 747 | } |
| 748 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 749 | /// Find all repeated substrings that satisfy the outlining cost model. |
| 750 | /// |
| 751 | /// If a substring appears at least twice, then it must be represented by |
| 752 | /// an internal node which appears in at least two suffixes. Each suffix is |
| 753 | /// represented by a leaf node. To do this, we visit each internal node in |
| 754 | /// the tree, using the leaf children of each internal node. If an internal |
| 755 | /// node represents a beneficial substring, then we use each of its leaf |
| 756 | /// children to find the locations of its substring. |
| 757 | /// |
| 758 | /// \param ST A suffix tree to query. |
| 759 | /// \param TII TargetInstrInfo for the target. |
| 760 | /// \param Mapper Contains outlining mapping information. |
| 761 | /// \param[out] CandidateList Filled with candidates representing each |
| 762 | /// beneficial substring. |
| 763 | /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each |
| 764 | /// type of candidate. |
| 765 | /// |
| 766 | /// \returns The length of the longest candidate found. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 767 | unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII, |
| 768 | InstructionMapper &Mapper, |
| 769 | std::vector<Candidate> &CandidateList, |
| 770 | std::vector<OutlinedFunction> &FunctionList); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 771 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 772 | /// \brief Replace the sequences of instructions represented by the |
| 773 | /// \p Candidates in \p CandidateList with calls to \p MachineFunctions |
| 774 | /// described in \p FunctionList. |
| 775 | /// |
| 776 | /// \param M The module we are outlining from. |
| 777 | /// \param CandidateList A list of candidates to be outlined. |
| 778 | /// \param FunctionList A list of functions to be inserted into the module. |
| 779 | /// \param Mapper Contains the instruction mappings for the module. |
| 780 | bool outline(Module &M, const ArrayRef<Candidate> &CandidateList, |
| 781 | std::vector<OutlinedFunction> &FunctionList, |
| 782 | InstructionMapper &Mapper); |
| 783 | |
| 784 | /// Creates a function for \p OF and inserts it into the module. |
| 785 | MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF, |
| 786 | InstructionMapper &Mapper); |
| 787 | |
| 788 | /// Find potential outlining candidates and store them in \p CandidateList. |
| 789 | /// |
| 790 | /// For each type of potential candidate, also build an \p OutlinedFunction |
| 791 | /// struct containing the information to build the function for that |
| 792 | /// candidate. |
| 793 | /// |
| 794 | /// \param[out] CandidateList Filled with outlining candidates for the module. |
| 795 | /// \param[out] FunctionList Filled with functions corresponding to each type |
| 796 | /// of \p Candidate. |
| 797 | /// \param ST The suffix tree for the module. |
| 798 | /// \param TII TargetInstrInfo for the module. |
| 799 | /// |
| 800 | /// \returns The length of the longest candidate found. 0 if there are none. |
| 801 | unsigned buildCandidateList(std::vector<Candidate> &CandidateList, |
| 802 | std::vector<OutlinedFunction> &FunctionList, |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 803 | SuffixTree &ST, InstructionMapper &Mapper, |
Jessica Paquette | c984e21 | 2017-03-13 18:39:33 +0000 | [diff] [blame] | 804 | const TargetInstrInfo &TII); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 805 | |
| 806 | /// \brief Remove any overlapping candidates that weren't handled by the |
| 807 | /// suffix tree's pruning method. |
| 808 | /// |
| 809 | /// Pruning from the suffix tree doesn't necessarily remove all overlaps. |
| 810 | /// If a short candidate is chosen for outlining, then a longer candidate |
| 811 | /// which has that short candidate as a suffix is chosen, the tree's pruning |
| 812 | /// method will not find it. Thus, we need to prune before outlining as well. |
| 813 | /// |
| 814 | /// \param[in,out] CandidateList A list of outlining candidates. |
| 815 | /// \param[in,out] FunctionList A list of functions to be outlined. |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 816 | /// \param Mapper Contains instruction mapping info for outlining. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 817 | /// \param MaxCandidateLen The length of the longest candidate. |
| 818 | /// \param TII TargetInstrInfo for the module. |
| 819 | void pruneOverlaps(std::vector<Candidate> &CandidateList, |
| 820 | std::vector<OutlinedFunction> &FunctionList, |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 821 | InstructionMapper &Mapper, unsigned MaxCandidateLen, |
| 822 | const TargetInstrInfo &TII); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 823 | |
| 824 | /// Construct a suffix tree on the instructions in \p M and outline repeated |
| 825 | /// strings from that tree. |
| 826 | bool runOnModule(Module &M) override; |
| 827 | }; |
| 828 | |
| 829 | } // Anonymous namespace. |
| 830 | |
| 831 | char MachineOutliner::ID = 0; |
| 832 | |
| 833 | namespace llvm { |
| 834 | ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); } |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 835 | } // namespace llvm |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 836 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 837 | INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false, |
| 838 | false) |
| 839 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 840 | unsigned |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 841 | MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII, |
| 842 | InstructionMapper &Mapper, |
| 843 | std::vector<Candidate> &CandidateList, |
| 844 | std::vector<OutlinedFunction> &FunctionList) { |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 845 | CandidateList.clear(); |
| 846 | FunctionList.clear(); |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 847 | unsigned FnIdx = 0; |
| 848 | unsigned MaxLen = 0; |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 849 | |
| 850 | // FIXME: Visit internal nodes instead of leaves. |
| 851 | for (SuffixTreeNode *Leaf : ST.LeafVector) { |
| 852 | assert(Leaf && "Leaves in LeafVector cannot be null!"); |
| 853 | if (!Leaf->IsInTree) |
| 854 | continue; |
| 855 | |
| 856 | assert(Leaf->Parent && "All leaves must have parents!"); |
| 857 | SuffixTreeNode &Parent = *(Leaf->Parent); |
| 858 | |
| 859 | // If it doesn't appear enough, or we already outlined from it, skip it. |
| 860 | if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree) |
| 861 | continue; |
| 862 | |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 863 | // Figure out if this candidate is beneficial. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 864 | unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size(); |
Jessica Paquette | 95c1107 | 2017-08-14 22:57:41 +0000 | [diff] [blame] | 865 | |
| 866 | // Too short to be beneficial; skip it. |
| 867 | // FIXME: This isn't necessarily true for, say, X86. If we factor in |
| 868 | // instruction lengths we need more information than this. |
| 869 | if (StringLen < 2) |
| 870 | continue; |
| 871 | |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 872 | // If this is a beneficial class of candidate, then every one is stored in |
| 873 | // this vector. |
| 874 | std::vector<Candidate> CandidatesForRepeatedSeq; |
| 875 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 876 | // Describes the start and end point of each candidate. This allows the |
| 877 | // target to infer some information about each occurrence of each repeated |
| 878 | // sequence. |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 879 | // FIXME: CandidatesForRepeatedSeq and this should be combined. |
| 880 | std::vector< |
| 881 | std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>> |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 882 | RepeatedSequenceLocs; |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 883 | |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 884 | // Figure out the call overhead for each instance of the sequence. |
| 885 | for (auto &ChildPair : Parent.Children) { |
| 886 | SuffixTreeNode *M = ChildPair.second; |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 887 | |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 888 | if (M && M->IsInTree && M->isLeaf()) { |
| 889 | // Each sequence is over [StartIt, EndIt]. |
| 890 | MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx]; |
| 891 | MachineBasicBlock::iterator EndIt = |
| 892 | Mapper.InstrList[M->SuffixIdx + StringLen - 1]; |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 893 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 894 | CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen, FnIdx); |
| 895 | RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt)); |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 896 | |
| 897 | // Never visit this leaf again. |
| 898 | M->IsInTree = false; |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 899 | } |
| 900 | } |
| 901 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 902 | unsigned SequenceOverhead = StringLen; |
| 903 | TargetInstrInfo::MachineOutlinerInfo MInfo = |
| 904 | TII.getOutlininingCandidateInfo(RepeatedSequenceLocs); |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 905 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 906 | unsigned OutliningCost = |
| 907 | (MInfo.CallOverhead * Parent.OccurrenceCount) + MInfo.FrameOverhead; |
| 908 | unsigned NotOutliningCost = SequenceOverhead * Parent.OccurrenceCount; |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 909 | |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 910 | // Is it better to outline this candidate than not? |
| 911 | if (NotOutliningCost <= OutliningCost) { |
| 912 | // Outlining this candidate would take more instructions than not |
| 913 | // outlining. |
| 914 | // Emit a remark explaining why we didn't outline this candidate. |
| 915 | std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C = |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 916 | RepeatedSequenceLocs[0]; |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 917 | MachineOptimizationRemarkEmitter MORE( |
| 918 | *(C.first->getParent()->getParent()), nullptr); |
| 919 | MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper", |
| 920 | C.first->getDebugLoc(), |
| 921 | C.first->getParent()); |
| 922 | R << "Did not outline " << NV("Length", StringLen) << " instructions" |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 923 | << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size()) |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 924 | << " locations." |
| 925 | << " Instructions from outlining all occurrences (" |
| 926 | << NV("OutliningCost", OutliningCost) << ")" |
| 927 | << " >= Unoutlined instruction count (" |
| 928 | << NV("NotOutliningCost", NotOutliningCost) << ")" |
| 929 | << " (Also found at: "; |
| 930 | |
| 931 | // Tell the user the other places the candidate was found. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 932 | for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) { |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 933 | R << NV((Twine("OtherStartLoc") + Twine(i)).str(), |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 934 | RepeatedSequenceLocs[i].first->getDebugLoc()); |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 935 | if (i != e - 1) |
| 936 | R << ", "; |
| 937 | } |
| 938 | |
| 939 | R << ")"; |
| 940 | MORE.emit(R); |
| 941 | |
| 942 | // Move to the next candidate. |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 943 | continue; |
Jessica Paquette | ffe4abc | 2017-08-31 21:02:45 +0000 | [diff] [blame] | 944 | } |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 945 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 946 | unsigned Benefit = NotOutliningCost - OutliningCost; |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 947 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 948 | if (StringLen > MaxLen) |
| 949 | MaxLen = StringLen; |
| 950 | |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 951 | // At this point, the candidate class is seen as beneficial. Set their |
| 952 | // benefit values and save them in the candidate list. |
| 953 | for (Candidate &C : CandidatesForRepeatedSeq) { |
| 954 | C.Benefit = Benefit; |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 955 | C.MInfo = MInfo; |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 956 | CandidateList.push_back(C); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 957 | } |
| 958 | |
| 959 | // Save the function for the new candidate sequence. |
| 960 | std::vector<unsigned> CandidateSequence; |
| 961 | for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++) |
| 962 | CandidateSequence.push_back(ST.Str[i]); |
| 963 | |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 964 | FunctionList.emplace_back(FnIdx, CandidatesForRepeatedSeq.size(), |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 965 | CandidateSequence, Benefit, MInfo); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 966 | |
| 967 | // Move to the next function. |
| 968 | FnIdx++; |
| 969 | Parent.IsInTree = false; |
| 970 | } |
| 971 | |
| 972 | return MaxLen; |
| 973 | } |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 974 | |
| 975 | void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList, |
| 976 | std::vector<OutlinedFunction> &FunctionList, |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 977 | InstructionMapper &Mapper, |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 978 | unsigned MaxCandidateLen, |
| 979 | const TargetInstrInfo &TII) { |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 980 | // TODO: Experiment with interval trees or other interval-checking structures |
| 981 | // to lower the time complexity of this function. |
| 982 | // TODO: Can we do better than the simple greedy choice? |
| 983 | // Check for overlaps in the range. |
| 984 | // This is O(MaxCandidateLen * CandidateList.size()). |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 985 | for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et; |
| 986 | It++) { |
| 987 | Candidate &C1 = *It; |
| 988 | OutlinedFunction &F1 = FunctionList[C1.FunctionIdx]; |
| 989 | |
| 990 | // If we removed this candidate, skip it. |
| 991 | if (!C1.InCandidateList) |
| 992 | continue; |
| 993 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 994 | // Is it still worth it to outline C1? |
| 995 | if (F1.Benefit < 1 || F1.OccurrenceCount < 2) { |
| 996 | assert(F1.OccurrenceCount > 0 && |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 997 | "Can't remove OutlinedFunction with no occurrences!"); |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 998 | F1.OccurrenceCount--; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 999 | C1.InCandidateList = false; |
| 1000 | continue; |
| 1001 | } |
| 1002 | |
| 1003 | // The minimum start index of any candidate that could overlap with this |
| 1004 | // one. |
| 1005 | unsigned FarthestPossibleIdx = 0; |
| 1006 | |
| 1007 | // Either the index is 0, or it's at most MaxCandidateLen indices away. |
| 1008 | if (C1.StartIdx > MaxCandidateLen) |
| 1009 | FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen; |
| 1010 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1011 | // Compare against the candidates in the list that start at at most |
| 1012 | // FarthestPossibleIdx indices away from C1. There are at most |
| 1013 | // MaxCandidateLen of these. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1014 | for (auto Sit = It + 1; Sit != Et; Sit++) { |
| 1015 | Candidate &C2 = *Sit; |
| 1016 | OutlinedFunction &F2 = FunctionList[C2.FunctionIdx]; |
| 1017 | |
| 1018 | // Is this candidate too far away to overlap? |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1019 | if (C2.StartIdx < FarthestPossibleIdx) |
| 1020 | break; |
| 1021 | |
| 1022 | // Did we already remove this candidate in a previous step? |
| 1023 | if (!C2.InCandidateList) |
| 1024 | continue; |
| 1025 | |
| 1026 | // Is the function beneficial to outline? |
| 1027 | if (F2.OccurrenceCount < 2 || F2.Benefit < 1) { |
| 1028 | // If not, remove this candidate and move to the next one. |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1029 | assert(F2.OccurrenceCount > 0 && |
| 1030 | "Can't remove OutlinedFunction with no occurrences!"); |
| 1031 | F2.OccurrenceCount--; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1032 | C2.InCandidateList = false; |
| 1033 | continue; |
| 1034 | } |
| 1035 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 1036 | unsigned C2End = C2.StartIdx + C2.Len - 1; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1037 | |
| 1038 | // Do C1 and C2 overlap? |
| 1039 | // |
| 1040 | // Not overlapping: |
| 1041 | // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices |
| 1042 | // |
| 1043 | // We sorted our candidate list so C2Start <= C1Start. We know that |
| 1044 | // C2End > C2Start since each candidate has length >= 2. Therefore, all we |
| 1045 | // have to check is C2End < C2Start to see if we overlap. |
| 1046 | if (C2End < C1.StartIdx) |
| 1047 | continue; |
| 1048 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1049 | // C1 and C2 overlap. |
| 1050 | // We need to choose the better of the two. |
| 1051 | // |
| 1052 | // Approximate this by picking the one which would have saved us the |
| 1053 | // most instructions before any pruning. |
| 1054 | if (C1.Benefit >= C2.Benefit) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1055 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1056 | // C1 is better, so remove C2 and update C2's OutlinedFunction to |
| 1057 | // reflect the removal. |
| 1058 | assert(F2.OccurrenceCount > 0 && |
| 1059 | "Can't remove OutlinedFunction with no occurrences!"); |
| 1060 | F2.OccurrenceCount--; |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 1061 | |
| 1062 | // Remove the call overhead from the removed sequence. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 1063 | F2.Benefit += C2.MInfo.CallOverhead; |
Jessica Paquette | d87f544 | 2017-07-29 02:55:46 +0000 | [diff] [blame] | 1064 | |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 1065 | // Add back one instance of the sequence. |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 1066 | if (F2.Sequence.size() > F2.Benefit) |
| 1067 | F2.Benefit = 0; |
| 1068 | else |
| 1069 | F2.Benefit -= F2.Sequence.size(); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1070 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1071 | C2.InCandidateList = false; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1072 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1073 | DEBUG(dbgs() << "- Removed C2. \n"; |
| 1074 | dbgs() << "--- Num fns left for C2: " << F2.OccurrenceCount |
| 1075 | << "\n"; |
| 1076 | dbgs() << "--- C2's benefit: " << F2.Benefit << "\n";); |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1077 | |
| 1078 | } else { |
| 1079 | // C2 is better, so remove C1 and update C1's OutlinedFunction to |
| 1080 | // reflect the removal. |
| 1081 | assert(F1.OccurrenceCount > 0 && |
| 1082 | "Can't remove OutlinedFunction with no occurrences!"); |
| 1083 | F1.OccurrenceCount--; |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 1084 | |
| 1085 | // Remove the call overhead from the removed sequence. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 1086 | F1.Benefit += C1.MInfo.CallOverhead; |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 1087 | |
| 1088 | // Add back one instance of the sequence. |
| 1089 | if (F1.Sequence.size() > F1.Benefit) |
| 1090 | F1.Benefit = 0; |
| 1091 | else |
| 1092 | F1.Benefit -= F1.Sequence.size(); |
| 1093 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1094 | C1.InCandidateList = false; |
| 1095 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1096 | DEBUG(dbgs() << "- Removed C1. \n"; |
| 1097 | dbgs() << "--- Num fns left for C1: " << F1.OccurrenceCount |
| 1098 | << "\n"; |
| 1099 | dbgs() << "--- C1's benefit: " << F1.Benefit << "\n";); |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1100 | |
| 1101 | // C1 is out, so we don't have to compare it against anyone else. |
| 1102 | break; |
| 1103 | } |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1104 | } |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | unsigned |
| 1109 | MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList, |
| 1110 | std::vector<OutlinedFunction> &FunctionList, |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1111 | SuffixTree &ST, InstructionMapper &Mapper, |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1112 | const TargetInstrInfo &TII) { |
| 1113 | |
| 1114 | std::vector<unsigned> CandidateSequence; // Current outlining candidate. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 1115 | unsigned MaxCandidateLen = 0; // Length of the longest candidate. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1116 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1117 | MaxCandidateLen = |
| 1118 | findCandidates(ST, TII, Mapper, CandidateList, FunctionList); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1119 | |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1120 | // Sort the candidates in decending order. This will simplify the outlining |
| 1121 | // process when we have to remove the candidates from the mapping by |
| 1122 | // allowing us to cut them out without keeping track of an offset. |
| 1123 | std::stable_sort(CandidateList.begin(), CandidateList.end()); |
| 1124 | |
| 1125 | return MaxCandidateLen; |
| 1126 | } |
| 1127 | |
| 1128 | MachineFunction * |
| 1129 | MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF, |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1130 | InstructionMapper &Mapper) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1131 | |
| 1132 | // Create the function name. This should be unique. For now, just hash the |
| 1133 | // module name and include it in the function name plus the number of this |
| 1134 | // function. |
| 1135 | std::ostringstream NameStream; |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1136 | NameStream << "OUTLINED_FUNCTION_" << OF.Name; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1137 | |
| 1138 | // Create the function using an IR-level function. |
| 1139 | LLVMContext &C = M.getContext(); |
| 1140 | Function *F = dyn_cast<Function>( |
Serge Guelton | 59a2d7b | 2017-04-11 15:01:18 +0000 | [diff] [blame] | 1141 | M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C))); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1142 | assert(F && "Function was null!"); |
| 1143 | |
| 1144 | // NOTE: If this is linkonceodr, then we can take advantage of linker deduping |
| 1145 | // which gives us better results when we outline from linkonceodr functions. |
| 1146 | F->setLinkage(GlobalValue::PrivateLinkage); |
| 1147 | F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); |
| 1148 | |
| 1149 | BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F); |
| 1150 | IRBuilder<> Builder(EntryBB); |
| 1151 | Builder.CreateRetVoid(); |
| 1152 | |
| 1153 | MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); |
Matthias Braun | 7bda195 | 2017-06-06 00:44:35 +0000 | [diff] [blame] | 1154 | MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1155 | MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock(); |
| 1156 | const TargetSubtargetInfo &STI = MF.getSubtarget(); |
| 1157 | const TargetInstrInfo &TII = *STI.getInstrInfo(); |
| 1158 | |
| 1159 | // Insert the new function into the module. |
| 1160 | MF.insert(MF.begin(), &MBB); |
| 1161 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 1162 | TII.insertOutlinerPrologue(MBB, MF, OF.MInfo); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1163 | |
| 1164 | // Copy over the instructions for the function using the integer mappings in |
| 1165 | // its sequence. |
| 1166 | for (unsigned Str : OF.Sequence) { |
| 1167 | MachineInstr *NewMI = |
| 1168 | MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second); |
| 1169 | NewMI->dropMemRefs(); |
| 1170 | |
| 1171 | // Don't keep debug information for outlined instructions. |
| 1172 | // FIXME: This means outlined functions are currently undebuggable. |
| 1173 | NewMI->setDebugLoc(DebugLoc()); |
| 1174 | MBB.insert(MBB.end(), NewMI); |
| 1175 | } |
| 1176 | |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 1177 | TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1178 | |
| 1179 | return &MF; |
| 1180 | } |
| 1181 | |
| 1182 | bool MachineOutliner::outline(Module &M, |
| 1183 | const ArrayRef<Candidate> &CandidateList, |
| 1184 | std::vector<OutlinedFunction> &FunctionList, |
| 1185 | InstructionMapper &Mapper) { |
| 1186 | |
| 1187 | bool OutlinedSomething = false; |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1188 | // Replace the candidates with calls to their respective outlined functions. |
| 1189 | for (const Candidate &C : CandidateList) { |
| 1190 | |
| 1191 | // Was the candidate removed during pruneOverlaps? |
| 1192 | if (!C.InCandidateList) |
| 1193 | continue; |
| 1194 | |
| 1195 | // If not, then look at its OutlinedFunction. |
| 1196 | OutlinedFunction &OF = FunctionList[C.FunctionIdx]; |
| 1197 | |
| 1198 | // Was its OutlinedFunction made unbeneficial during pruneOverlaps? |
| 1199 | if (OF.OccurrenceCount < 2 || OF.Benefit < 1) |
| 1200 | continue; |
| 1201 | |
| 1202 | // If not, then outline it. |
| 1203 | assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!"); |
| 1204 | MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent(); |
| 1205 | MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx]; |
| 1206 | unsigned EndIdx = C.StartIdx + C.Len - 1; |
| 1207 | |
| 1208 | assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!"); |
| 1209 | MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; |
| 1210 | assert(EndIt != MBB->end() && "EndIt out of bounds!"); |
| 1211 | |
| 1212 | EndIt++; // Erase needs one past the end index. |
| 1213 | |
| 1214 | // Does this candidate have a function yet? |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1215 | if (!OF.MF) { |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1216 | OF.MF = createOutlinedFunction(M, OF, Mapper); |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1217 | FunctionsCreated++; |
| 1218 | } |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1219 | |
| 1220 | MachineFunction *MF = OF.MF; |
| 1221 | const TargetSubtargetInfo &STI = MF->getSubtarget(); |
| 1222 | const TargetInstrInfo &TII = *STI.getInstrInfo(); |
| 1223 | |
| 1224 | // Insert a call to the new function and erase the old sequence. |
Jessica Paquette | 4cf187b | 2017-09-27 20:47:39 +0000 | [diff] [blame^] | 1225 | TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1226 | StartIt = Mapper.InstrList[C.StartIdx]; |
| 1227 | MBB->erase(StartIt, EndIt); |
| 1228 | |
| 1229 | OutlinedSomething = true; |
| 1230 | |
| 1231 | // Statistics. |
| 1232 | NumOutlined++; |
| 1233 | } |
| 1234 | |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1235 | DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1236 | |
| 1237 | return OutlinedSomething; |
| 1238 | } |
| 1239 | |
| 1240 | bool MachineOutliner::runOnModule(Module &M) { |
| 1241 | |
| 1242 | // Is there anything in the module at all? |
| 1243 | if (M.empty()) |
| 1244 | return false; |
| 1245 | |
| 1246 | MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); |
Jessica Paquette | 78681be | 2017-07-27 23:24:43 +0000 | [diff] [blame] | 1247 | const TargetSubtargetInfo &STI = |
| 1248 | MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget(); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1249 | const TargetRegisterInfo *TRI = STI.getRegisterInfo(); |
| 1250 | const TargetInstrInfo *TII = STI.getInstrInfo(); |
| 1251 | |
| 1252 | InstructionMapper Mapper; |
| 1253 | |
| 1254 | // Build instruction mappings for each function in the module. |
| 1255 | for (Function &F : M) { |
Matthias Braun | 7bda195 | 2017-06-06 00:44:35 +0000 | [diff] [blame] | 1256 | MachineFunction &MF = MMI.getOrCreateMachineFunction(F); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1257 | |
| 1258 | // Is the function empty? Safe to outline from? |
| 1259 | if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF)) |
| 1260 | continue; |
| 1261 | |
| 1262 | // If it is, look at each MachineBasicBlock in the function. |
| 1263 | for (MachineBasicBlock &MBB : MF) { |
| 1264 | |
| 1265 | // Is there anything in MBB? |
| 1266 | if (MBB.empty()) |
| 1267 | continue; |
| 1268 | |
| 1269 | // If yes, map it. |
| 1270 | Mapper.convertToUnsignedVec(MBB, *TRI, *TII); |
| 1271 | } |
| 1272 | } |
| 1273 | |
| 1274 | // Construct a suffix tree, use it to find candidates, and then outline them. |
| 1275 | SuffixTree ST(Mapper.UnsignedVec); |
| 1276 | std::vector<Candidate> CandidateList; |
| 1277 | std::vector<OutlinedFunction> FunctionList; |
| 1278 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1279 | // Find all of the outlining candidates. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1280 | unsigned MaxCandidateLen = |
Jessica Paquette | c984e21 | 2017-03-13 18:39:33 +0000 | [diff] [blame] | 1281 | buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII); |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1282 | |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1283 | // Remove candidates that overlap with other candidates. |
Jessica Paquette | 809d708 | 2017-07-28 03:21:58 +0000 | [diff] [blame] | 1284 | pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII); |
Jessica Paquette | acffa28 | 2017-03-23 21:27:38 +0000 | [diff] [blame] | 1285 | |
| 1286 | // Outline each of the candidates and return true if something was outlined. |
Jessica Paquette | 596f483 | 2017-03-06 21:31:18 +0000 | [diff] [blame] | 1287 | return outline(M, CandidateList, FunctionList, Mapper); |
| 1288 | } |