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