1 //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// Replaces repeated sequences of instructions with function calls. 11 /// 12 /// This works by placing every instruction from every basic block in a 13 /// suffix tree, and repeatedly querying that tree for repeated sequences of 14 /// instructions. If a sequence of instructions appears often, then it ought 15 /// to be beneficial to pull out into a function. 16 /// 17 /// The MachineOutliner communicates with a given target using hooks defined in 18 /// TargetInstrInfo.h. The target supplies the outliner with information on how 19 /// a specific sequence of instructions should be outlined. This information 20 /// is used to deduce the number of instructions necessary to 21 /// 22 /// * Create an outlined function 23 /// * Call that outlined function 24 /// 25 /// Targets must implement 26 /// * getOutliningCandidateInfo 27 /// * buildOutlinedFrame 28 /// * insertOutlinedCall 29 /// * isFunctionSafeToOutlineFrom 30 /// 31 /// in order to make use of the MachineOutliner. 32 /// 33 /// This was originally presented at the 2016 LLVM Developers' Meeting in the 34 /// talk "Reducing Code Size Using Outlining". For a high-level overview of 35 /// how this pass works, the talk is available on YouTube at 36 /// 37 /// https://www.youtube.com/watch?v=yorld-WSOeU 38 /// 39 /// The slides for the talk are available at 40 /// 41 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf 42 /// 43 /// The talk provides an overview of how the outliner finds candidates and 44 /// ultimately outlines them. It describes how the main data structure for this 45 /// pass, the suffix tree, is queried and purged for candidates. It also gives 46 /// a simplified suffix tree construction algorithm for suffix trees based off 47 /// of the algorithm actually used here, Ukkonen's algorithm. 48 /// 49 /// For the original RFC for this pass, please see 50 /// 51 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html 52 /// 53 /// For more information on the suffix tree data structure, please see 54 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf 55 /// 56 //===----------------------------------------------------------------------===// 57 #include "llvm/CodeGen/MachineOutliner.h" 58 #include "llvm/ADT/DenseMap.h" 59 #include "llvm/ADT/SmallSet.h" 60 #include "llvm/ADT/Statistic.h" 61 #include "llvm/ADT/Twine.h" 62 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 63 #include "llvm/CodeGen/LivePhysRegs.h" 64 #include "llvm/CodeGen/MachineModuleInfo.h" 65 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.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/InitializePasses.h" 73 #include "llvm/Support/CommandLine.h" 74 #include "llvm/Support/Debug.h" 75 #include "llvm/Support/SuffixTree.h" 76 #include "llvm/Support/raw_ostream.h" 77 #include <functional> 78 #include <tuple> 79 #include <vector> 80 81 #define DEBUG_TYPE "machine-outliner" 82 83 using namespace llvm; 84 using namespace ore; 85 using namespace outliner; 86 87 // Statistics for outlined functions. 88 STATISTIC(NumOutlined, "Number of candidates outlined"); 89 STATISTIC(FunctionsCreated, "Number of functions created"); 90 91 // Statistics for instruction mapping. 92 STATISTIC(NumLegalInUnsignedVec, "Outlinable instructions mapped"); 93 STATISTIC(NumIllegalInUnsignedVec, 94 "Unoutlinable instructions mapped + number of sentinel values"); 95 STATISTIC(NumSentinels, "Sentinel values inserted during mapping"); 96 STATISTIC(NumInvisible, 97 "Invisible instructions skipped during mapping"); 98 STATISTIC(UnsignedVecSize, 99 "Total number of instructions mapped and saved to mapping vector"); 100 101 // Set to true if the user wants the outliner to run on linkonceodr linkage 102 // functions. This is false by default because the linker can dedupe linkonceodr 103 // functions. Since the outliner is confined to a single module (modulo LTO), 104 // this is off by default. It should, however, be the default behaviour in 105 // LTO. 106 static cl::opt<bool> EnableLinkOnceODROutlining( 107 "enable-linkonceodr-outlining", cl::Hidden, 108 cl::desc("Enable the machine outliner on linkonceodr functions"), 109 cl::init(false)); 110 111 /// Number of times to re-run the outliner. This is not the total number of runs 112 /// as the outliner will run at least one time. The default value is set to 0, 113 /// meaning the outliner will run one time and rerun zero times after that. 114 static cl::opt<unsigned> OutlinerReruns( 115 "machine-outliner-reruns", cl::init(0), cl::Hidden, 116 cl::desc( 117 "Number of times to rerun the outliner after the initial outline")); 118 119 namespace { 120 121 /// Maps \p MachineInstrs to unsigned integers and stores the mappings. 122 struct InstructionMapper { 123 124 /// The next available integer to assign to a \p MachineInstr that 125 /// cannot be outlined. 126 /// 127 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>. 128 unsigned IllegalInstrNumber = -3; 129 130 /// The next available integer to assign to a \p MachineInstr that can 131 /// be outlined. 132 unsigned LegalInstrNumber = 0; 133 134 /// Correspondence from \p MachineInstrs to unsigned integers. 135 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait> 136 InstructionIntegerMap; 137 138 /// Correspondence between \p MachineBasicBlocks and target-defined flags. 139 DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap; 140 141 /// The vector of unsigned integers that the module is mapped to. 142 SmallVector<unsigned> UnsignedVec; 143 144 /// Stores the location of the instruction associated with the integer 145 /// at index i in \p UnsignedVec for each index i. 146 SmallVector<MachineBasicBlock::iterator> InstrList; 147 148 // Set if we added an illegal number in the previous step. 149 // Since each illegal number is unique, we only need one of them between 150 // each range of legal numbers. This lets us make sure we don't add more 151 // than one illegal number per range. 152 bool AddedIllegalLastTime = false; 153 154 /// Maps \p *It to a legal integer. 155 /// 156 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB, 157 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber. 158 /// 159 /// \returns The integer that \p *It was mapped to. 160 unsigned mapToLegalUnsigned( 161 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr, 162 bool &HaveLegalRange, unsigned &NumLegalInBlock, 163 SmallVector<unsigned> &UnsignedVecForMBB, 164 SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) { 165 // We added something legal, so we should unset the AddedLegalLastTime 166 // flag. 167 AddedIllegalLastTime = false; 168 169 // If we have at least two adjacent legal instructions (which may have 170 // invisible instructions in between), remember that. 171 if (CanOutlineWithPrevInstr) 172 HaveLegalRange = true; 173 CanOutlineWithPrevInstr = true; 174 175 // Keep track of the number of legal instructions we insert. 176 NumLegalInBlock++; 177 178 // Get the integer for this instruction or give it the current 179 // LegalInstrNumber. 180 InstrListForMBB.push_back(It); 181 MachineInstr &MI = *It; 182 bool WasInserted; 183 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator 184 ResultIt; 185 std::tie(ResultIt, WasInserted) = 186 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber)); 187 unsigned MINumber = ResultIt->second; 188 189 // There was an insertion. 190 if (WasInserted) 191 LegalInstrNumber++; 192 193 UnsignedVecForMBB.push_back(MINumber); 194 195 // Make sure we don't overflow or use any integers reserved by the DenseMap. 196 if (LegalInstrNumber >= IllegalInstrNumber) 197 report_fatal_error("Instruction mapping overflow!"); 198 199 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && 200 "Tried to assign DenseMap tombstone or empty key to instruction."); 201 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && 202 "Tried to assign DenseMap tombstone or empty key to instruction."); 203 204 // Statistics. 205 ++NumLegalInUnsignedVec; 206 return MINumber; 207 } 208 209 /// Maps \p *It to an illegal integer. 210 /// 211 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p 212 /// IllegalInstrNumber. 213 /// 214 /// \returns The integer that \p *It was mapped to. 215 unsigned mapToIllegalUnsigned( 216 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr, 217 SmallVector<unsigned> &UnsignedVecForMBB, 218 SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) { 219 // Can't outline an illegal instruction. Set the flag. 220 CanOutlineWithPrevInstr = false; 221 222 // Only add one illegal number per range of legal numbers. 223 if (AddedIllegalLastTime) 224 return IllegalInstrNumber; 225 226 // Remember that we added an illegal number last time. 227 AddedIllegalLastTime = true; 228 unsigned MINumber = IllegalInstrNumber; 229 230 InstrListForMBB.push_back(It); 231 UnsignedVecForMBB.push_back(IllegalInstrNumber); 232 IllegalInstrNumber--; 233 // Statistics. 234 ++NumIllegalInUnsignedVec; 235 236 assert(LegalInstrNumber < IllegalInstrNumber && 237 "Instruction mapping overflow!"); 238 239 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && 240 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 241 242 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && 243 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 244 245 return MINumber; 246 } 247 248 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds 249 /// and appends it to \p UnsignedVec and \p InstrList. 250 /// 251 /// Two instructions are assigned the same integer if they are identical. 252 /// If an instruction is deemed unsafe to outline, then it will be assigned an 253 /// unique integer. The resulting mapping is placed into a suffix tree and 254 /// queried for candidates. 255 /// 256 /// \param MBB The \p MachineBasicBlock to be translated into integers. 257 /// \param TII \p TargetInstrInfo for the function. 258 void convertToUnsignedVec(MachineBasicBlock &MBB, 259 const TargetInstrInfo &TII) { 260 LLVM_DEBUG(dbgs() << "*** Converting MBB '" << MBB.getName() 261 << "' to unsigned vector ***\n"); 262 unsigned Flags = 0; 263 264 // Don't even map in this case. 265 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags)) 266 return; 267 268 auto OutlinableRanges = TII.getOutlinableRanges(MBB, Flags); 269 LLVM_DEBUG(dbgs() << MBB.getName() << ": " << OutlinableRanges.size() 270 << " outlinable range(s)\n"); 271 if (OutlinableRanges.empty()) 272 return; 273 274 // Store info for the MBB for later outlining. 275 MBBFlagsMap[&MBB] = Flags; 276 277 MachineBasicBlock::iterator It = MBB.begin(); 278 279 // The number of instructions in this block that will be considered for 280 // outlining. 281 unsigned NumLegalInBlock = 0; 282 283 // True if we have at least two legal instructions which aren't separated 284 // by an illegal instruction. 285 bool HaveLegalRange = false; 286 287 // True if we can perform outlining given the last mapped (non-invisible) 288 // instruction. This lets us know if we have a legal range. 289 bool CanOutlineWithPrevInstr = false; 290 291 // FIXME: Should this all just be handled in the target, rather than using 292 // repeated calls to getOutliningType? 293 SmallVector<unsigned> UnsignedVecForMBB; 294 SmallVector<MachineBasicBlock::iterator> InstrListForMBB; 295 296 LLVM_DEBUG(dbgs() << "*** Mapping outlinable ranges ***\n"); 297 for (auto &OutlinableRange : OutlinableRanges) { 298 auto OutlinableRangeBegin = OutlinableRange.first; 299 auto OutlinableRangeEnd = OutlinableRange.second; 300 #ifndef NDEBUG 301 LLVM_DEBUG( 302 dbgs() << "Mapping " 303 << std::distance(OutlinableRangeBegin, OutlinableRangeEnd) 304 << " instruction range\n"); 305 // Everything outside of an outlinable range is illegal. 306 unsigned NumSkippedInRange = 0; 307 #endif 308 for (; It != OutlinableRangeBegin; ++It) { 309 #ifndef NDEBUG 310 ++NumSkippedInRange; 311 #endif 312 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, 313 InstrListForMBB); 314 } 315 #ifndef NDEBUG 316 LLVM_DEBUG(dbgs() << "Skipped " << NumSkippedInRange 317 << " instructions outside outlinable range\n"); 318 #endif 319 assert(It != MBB.end() && "Should still have instructions?"); 320 // `It` is now positioned at the beginning of a range of instructions 321 // which may be outlinable. Check if each instruction is known to be safe. 322 for (; It != OutlinableRangeEnd; ++It) { 323 // Keep track of where this instruction is in the module. 324 switch (TII.getOutliningType(It, Flags)) { 325 case InstrType::Illegal: 326 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, 327 InstrListForMBB); 328 break; 329 330 case InstrType::Legal: 331 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange, 332 NumLegalInBlock, UnsignedVecForMBB, 333 InstrListForMBB); 334 break; 335 336 case InstrType::LegalTerminator: 337 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange, 338 NumLegalInBlock, UnsignedVecForMBB, 339 InstrListForMBB); 340 // The instruction also acts as a terminator, so we have to record 341 // that in the string. 342 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, 343 InstrListForMBB); 344 break; 345 346 case InstrType::Invisible: 347 // Normally this is set by mapTo(Blah)Unsigned, but we just want to 348 // skip this instruction. So, unset the flag here. 349 ++NumInvisible; 350 AddedIllegalLastTime = false; 351 break; 352 } 353 } 354 } 355 356 LLVM_DEBUG(dbgs() << "HaveLegalRange = " << HaveLegalRange << "\n"); 357 358 // Are there enough legal instructions in the block for outlining to be 359 // possible? 360 if (HaveLegalRange) { 361 // After we're done every insertion, uniquely terminate this part of the 362 // "string". This makes sure we won't match across basic block or function 363 // boundaries since the "end" is encoded uniquely and thus appears in no 364 // repeated substring. 365 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB, 366 InstrListForMBB); 367 ++NumSentinels; 368 append_range(InstrList, InstrListForMBB); 369 append_range(UnsignedVec, UnsignedVecForMBB); 370 } 371 } 372 373 InstructionMapper() { 374 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't 375 // changed. 376 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 && 377 "DenseMapInfo<unsigned>'s empty key isn't -1!"); 378 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 && 379 "DenseMapInfo<unsigned>'s tombstone key isn't -2!"); 380 } 381 }; 382 383 /// An interprocedural pass which finds repeated sequences of 384 /// instructions and replaces them with calls to functions. 385 /// 386 /// Each instruction is mapped to an unsigned integer and placed in a string. 387 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree 388 /// is then repeatedly queried for repeated sequences of instructions. Each 389 /// non-overlapping repeated sequence is then placed in its own 390 /// \p MachineFunction and each instance is then replaced with a call to that 391 /// function. 392 struct MachineOutliner : public ModulePass { 393 394 static char ID; 395 396 /// Set to true if the outliner should consider functions with 397 /// linkonceodr linkage. 398 bool OutlineFromLinkOnceODRs = false; 399 400 /// The current repeat number of machine outlining. 401 unsigned OutlineRepeatedNum = 0; 402 403 /// Set to true if the outliner should run on all functions in the module 404 /// considered safe for outlining. 405 /// Set to true by default for compatibility with llc's -run-pass option. 406 /// Set when the pass is constructed in TargetPassConfig. 407 bool RunOnAllFunctions = true; 408 409 StringRef getPassName() const override { return "Machine Outliner"; } 410 411 void getAnalysisUsage(AnalysisUsage &AU) const override { 412 AU.addRequired<MachineModuleInfoWrapperPass>(); 413 AU.addPreserved<MachineModuleInfoWrapperPass>(); 414 AU.setPreservesAll(); 415 ModulePass::getAnalysisUsage(AU); 416 } 417 418 MachineOutliner() : ModulePass(ID) { 419 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry()); 420 } 421 422 /// Remark output explaining that not outlining a set of candidates would be 423 /// better than outlining that set. 424 void emitNotOutliningCheaperRemark( 425 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq, 426 OutlinedFunction &OF); 427 428 /// Remark output explaining that a function was outlined. 429 void emitOutlinedFunctionRemark(OutlinedFunction &OF); 430 431 /// Find all repeated substrings that satisfy the outlining cost model by 432 /// constructing a suffix tree. 433 /// 434 /// If a substring appears at least twice, then it must be represented by 435 /// an internal node which appears in at least two suffixes. Each suffix 436 /// is represented by a leaf node. To do this, we visit each internal node 437 /// in the tree, using the leaf children of each internal node. If an 438 /// internal node represents a beneficial substring, then we use each of 439 /// its leaf children to find the locations of its substring. 440 /// 441 /// \param Mapper Contains outlining mapping information. 442 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions 443 /// each type of candidate. 444 void findCandidates(InstructionMapper &Mapper, 445 std::vector<OutlinedFunction> &FunctionList); 446 447 /// Replace the sequences of instructions represented by \p OutlinedFunctions 448 /// with calls to functions. 449 /// 450 /// \param M The module we are outlining from. 451 /// \param FunctionList A list of functions to be inserted into the module. 452 /// \param Mapper Contains the instruction mappings for the module. 453 bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList, 454 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum); 455 456 /// Creates a function for \p OF and inserts it into the module. 457 MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF, 458 InstructionMapper &Mapper, 459 unsigned Name); 460 461 /// Calls 'doOutline()' 1 + OutlinerReruns times. 462 bool runOnModule(Module &M) override; 463 464 /// Construct a suffix tree on the instructions in \p M and outline repeated 465 /// strings from that tree. 466 bool doOutline(Module &M, unsigned &OutlinedFunctionNum); 467 468 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper 469 /// function for remark emission. 470 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) { 471 for (const Candidate &C : OF.Candidates) 472 if (MachineFunction *MF = C.getMF()) 473 if (DISubprogram *SP = MF->getFunction().getSubprogram()) 474 return SP; 475 return nullptr; 476 } 477 478 /// Populate and \p InstructionMapper with instruction-to-integer mappings. 479 /// These are used to construct a suffix tree. 480 void populateMapper(InstructionMapper &Mapper, Module &M, 481 MachineModuleInfo &MMI); 482 483 /// Initialize information necessary to output a size remark. 484 /// FIXME: This should be handled by the pass manager, not the outliner. 485 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy 486 /// pass manager. 487 void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI, 488 StringMap<unsigned> &FunctionToInstrCount); 489 490 /// Emit the remark. 491 // FIXME: This should be handled by the pass manager, not the outliner. 492 void 493 emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI, 494 const StringMap<unsigned> &FunctionToInstrCount); 495 }; 496 } // Anonymous namespace. 497 498 char MachineOutliner::ID = 0; 499 500 namespace llvm { 501 ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) { 502 MachineOutliner *OL = new MachineOutliner(); 503 OL->RunOnAllFunctions = RunOnAllFunctions; 504 return OL; 505 } 506 507 } // namespace llvm 508 509 INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false, 510 false) 511 512 void MachineOutliner::emitNotOutliningCheaperRemark( 513 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq, 514 OutlinedFunction &OF) { 515 // FIXME: Right now, we arbitrarily choose some Candidate from the 516 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be. 517 // We should probably sort these by function name or something to make sure 518 // the remarks are stable. 519 Candidate &C = CandidatesForRepeatedSeq.front(); 520 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr); 521 MORE.emit([&]() { 522 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper", 523 C.front()->getDebugLoc(), C.getMBB()); 524 R << "Did not outline " << NV("Length", StringLen) << " instructions" 525 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size()) 526 << " locations." 527 << " Bytes from outlining all occurrences (" 528 << NV("OutliningCost", OF.getOutliningCost()) << ")" 529 << " >= Unoutlined instruction bytes (" 530 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")" 531 << " (Also found at: "; 532 533 // Tell the user the other places the candidate was found. 534 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) { 535 R << NV((Twine("OtherStartLoc") + Twine(i)).str(), 536 CandidatesForRepeatedSeq[i].front()->getDebugLoc()); 537 if (i != e - 1) 538 R << ", "; 539 } 540 541 R << ")"; 542 return R; 543 }); 544 } 545 546 void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) { 547 MachineBasicBlock *MBB = &*OF.MF->begin(); 548 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr); 549 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction", 550 MBB->findDebugLoc(MBB->begin()), MBB); 551 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by " 552 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions " 553 << "from " << NV("NumOccurrences", OF.getOccurrenceCount()) 554 << " locations. " 555 << "(Found at: "; 556 557 // Tell the user the other places the candidate was found. 558 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) { 559 560 R << NV((Twine("StartLoc") + Twine(i)).str(), 561 OF.Candidates[i].front()->getDebugLoc()); 562 if (i != e - 1) 563 R << ", "; 564 } 565 566 R << ")"; 567 568 MORE.emit(R); 569 } 570 571 void MachineOutliner::findCandidates( 572 InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) { 573 FunctionList.clear(); 574 SuffixTree ST(Mapper.UnsignedVec); 575 576 // First, find all of the repeated substrings in the tree of minimum length 577 // 2. 578 std::vector<Candidate> CandidatesForRepeatedSeq; 579 LLVM_DEBUG(dbgs() << "*** Discarding overlapping candidates *** \n"); 580 LLVM_DEBUG( 581 dbgs() << "Searching for overlaps in all repeated sequences...\n"); 582 for (const SuffixTree::RepeatedSubstring &RS : ST) { 583 CandidatesForRepeatedSeq.clear(); 584 unsigned StringLen = RS.Length; 585 LLVM_DEBUG(dbgs() << " Sequence length: " << StringLen << "\n"); 586 // Debug code to keep track of how many candidates we removed. 587 #ifndef NDEBUG 588 unsigned NumDiscarded = 0; 589 unsigned NumKept = 0; 590 #endif 591 for (const unsigned &StartIdx : RS.StartIndices) { 592 // Trick: Discard some candidates that would be incompatible with the 593 // ones we've already found for this sequence. This will save us some 594 // work in candidate selection. 595 // 596 // If two candidates overlap, then we can't outline them both. This 597 // happens when we have candidates that look like, say 598 // 599 // AA (where each "A" is an instruction). 600 // 601 // We might have some portion of the module that looks like this: 602 // AAAAAA (6 A's) 603 // 604 // In this case, there are 5 different copies of "AA" in this range, but 605 // at most 3 can be outlined. If only outlining 3 of these is going to 606 // be unbeneficial, then we ought to not bother. 607 // 608 // Note that two things DON'T overlap when they look like this: 609 // start1...end1 .... start2...end2 610 // That is, one must either 611 // * End before the other starts 612 // * Start after the other ends 613 unsigned EndIdx = StartIdx + StringLen - 1; 614 auto FirstOverlap = find_if( 615 CandidatesForRepeatedSeq, [StartIdx, EndIdx](const Candidate &C) { 616 return EndIdx >= C.getStartIdx() && StartIdx <= C.getEndIdx(); 617 }); 618 if (FirstOverlap != CandidatesForRepeatedSeq.end()) { 619 #ifndef NDEBUG 620 ++NumDiscarded; 621 LLVM_DEBUG(dbgs() << " .. DISCARD candidate @ [" << StartIdx 622 << ", " << EndIdx << "]; overlaps with candidate @ [" 623 << FirstOverlap->getStartIdx() << ", " 624 << FirstOverlap->getEndIdx() << "]\n"); 625 #endif 626 continue; 627 } 628 // It doesn't overlap with anything, so we can outline it. 629 // Each sequence is over [StartIt, EndIt]. 630 // Save the candidate and its location. 631 #ifndef NDEBUG 632 ++NumKept; 633 #endif 634 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx]; 635 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; 636 MachineBasicBlock *MBB = StartIt->getParent(); 637 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, EndIt, 638 MBB, FunctionList.size(), 639 Mapper.MBBFlagsMap[MBB]); 640 } 641 #ifndef NDEBUG 642 LLVM_DEBUG(dbgs() << " Candidates discarded: " << NumDiscarded 643 << "\n"); 644 LLVM_DEBUG(dbgs() << " Candidates kept: " << NumKept << "\n\n"); 645 #endif 646 647 // We've found something we might want to outline. 648 // Create an OutlinedFunction to store it and check if it'd be beneficial 649 // to outline. 650 if (CandidatesForRepeatedSeq.size() < 2) 651 continue; 652 653 // Arbitrarily choose a TII from the first candidate. 654 // FIXME: Should getOutliningCandidateInfo move to TargetMachine? 655 const TargetInstrInfo *TII = 656 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo(); 657 658 OutlinedFunction OF = 659 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq); 660 661 // If we deleted too many candidates, then there's nothing worth outlining. 662 // FIXME: This should take target-specified instruction sizes into account. 663 if (OF.Candidates.size() < 2) 664 continue; 665 666 // Is it better to outline this candidate than not? 667 if (OF.getBenefit() < 1) { 668 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF); 669 continue; 670 } 671 672 FunctionList.push_back(OF); 673 } 674 } 675 676 MachineFunction *MachineOutliner::createOutlinedFunction( 677 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) { 678 679 // Create the function name. This should be unique. 680 // FIXME: We should have a better naming scheme. This should be stable, 681 // regardless of changes to the outliner's cost model/traversal order. 682 std::string FunctionName = "OUTLINED_FUNCTION_"; 683 if (OutlineRepeatedNum > 0) 684 FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_"; 685 FunctionName += std::to_string(Name); 686 687 // Create the function using an IR-level function. 688 LLVMContext &C = M.getContext(); 689 Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false), 690 Function::ExternalLinkage, FunctionName, M); 691 692 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping 693 // which gives us better results when we outline from linkonceodr functions. 694 F->setLinkage(GlobalValue::InternalLinkage); 695 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 696 697 // Set optsize/minsize, so we don't insert padding between outlined 698 // functions. 699 F->addFnAttr(Attribute::OptimizeForSize); 700 F->addFnAttr(Attribute::MinSize); 701 702 Candidate &FirstCand = OF.Candidates.front(); 703 const TargetInstrInfo &TII = 704 *FirstCand.getMF()->getSubtarget().getInstrInfo(); 705 706 TII.mergeOutliningCandidateAttributes(*F, OF.Candidates); 707 708 // Set uwtable, so we generate eh_frame. 709 UWTableKind UW = std::accumulate( 710 OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None, 711 [](UWTableKind K, const outliner::Candidate &C) { 712 return std::max(K, C.getMF()->getFunction().getUWTableKind()); 713 }); 714 if (UW != UWTableKind::None) 715 F->setUWTableKind(UW); 716 717 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F); 718 IRBuilder<> Builder(EntryBB); 719 Builder.CreateRetVoid(); 720 721 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI(); 722 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); 723 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock(); 724 725 // Insert the new function into the module. 726 MF.insert(MF.begin(), &MBB); 727 728 MachineFunction *OriginalMF = FirstCand.front()->getMF(); 729 const std::vector<MCCFIInstruction> &Instrs = 730 OriginalMF->getFrameInstructions(); 731 for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E; 732 ++I) { 733 if (I->isDebugInstr()) 734 continue; 735 736 // Don't keep debug information for outlined instructions. 737 auto DL = DebugLoc(); 738 if (I->isCFIInstruction()) { 739 unsigned CFIIndex = I->getOperand(0).getCFIIndex(); 740 MCCFIInstruction CFI = Instrs[CFIIndex]; 741 BuildMI(MBB, MBB.end(), DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 742 .addCFIIndex(MF.addFrameInst(CFI)); 743 } else { 744 MachineInstr *NewMI = MF.CloneMachineInstr(&*I); 745 NewMI->dropMemRefs(MF); 746 NewMI->setDebugLoc(DL); 747 MBB.insert(MBB.end(), NewMI); 748 } 749 } 750 751 // Set normal properties for a late MachineFunction. 752 MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA); 753 MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs); 754 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs); 755 MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness); 756 MF.getRegInfo().freezeReservedRegs(MF); 757 758 // Compute live-in set for outlined fn 759 const MachineRegisterInfo &MRI = MF.getRegInfo(); 760 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 761 LivePhysRegs LiveIns(TRI); 762 for (auto &Cand : OF.Candidates) { 763 // Figure out live-ins at the first instruction. 764 MachineBasicBlock &OutlineBB = *Cand.front()->getParent(); 765 LivePhysRegs CandLiveIns(TRI); 766 CandLiveIns.addLiveOuts(OutlineBB); 767 for (const MachineInstr &MI : 768 reverse(make_range(Cand.front(), OutlineBB.end()))) 769 CandLiveIns.stepBackward(MI); 770 771 // The live-in set for the outlined function is the union of the live-ins 772 // from all the outlining points. 773 for (MCPhysReg Reg : CandLiveIns) 774 LiveIns.addReg(Reg); 775 } 776 addLiveIns(MBB, LiveIns); 777 778 TII.buildOutlinedFrame(MBB, MF, OF); 779 780 // If there's a DISubprogram associated with this outlined function, then 781 // emit debug info for the outlined function. 782 if (DISubprogram *SP = getSubprogramOrNull(OF)) { 783 // We have a DISubprogram. Get its DICompileUnit. 784 DICompileUnit *CU = SP->getUnit(); 785 DIBuilder DB(M, true, CU); 786 DIFile *Unit = SP->getFile(); 787 Mangler Mg; 788 // Get the mangled name of the function for the linkage name. 789 std::string Dummy; 790 raw_string_ostream MangledNameStream(Dummy); 791 Mg.getNameWithPrefix(MangledNameStream, F, false); 792 793 DISubprogram *OutlinedSP = DB.createFunction( 794 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()), 795 Unit /* File */, 796 0 /* Line 0 is reserved for compiler-generated code. */, 797 DB.createSubroutineType( 798 DB.getOrCreateTypeArray(std::nullopt)), /* void type */ 799 0, /* Line 0 is reserved for compiler-generated code. */ 800 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */, 801 /* Outlined code is optimized code by definition. */ 802 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized); 803 804 // Don't add any new variables to the subprogram. 805 DB.finalizeSubprogram(OutlinedSP); 806 807 // Attach subprogram to the function. 808 F->setSubprogram(OutlinedSP); 809 // We're done with the DIBuilder. 810 DB.finalize(); 811 } 812 813 return &MF; 814 } 815 816 bool MachineOutliner::outline(Module &M, 817 std::vector<OutlinedFunction> &FunctionList, 818 InstructionMapper &Mapper, 819 unsigned &OutlinedFunctionNum) { 820 821 bool OutlinedSomething = false; 822 823 // Sort by benefit. The most beneficial functions should be outlined first. 824 stable_sort(FunctionList, 825 [](const OutlinedFunction &LHS, const OutlinedFunction &RHS) { 826 return LHS.getBenefit() > RHS.getBenefit(); 827 }); 828 829 // Walk over each function, outlining them as we go along. Functions are 830 // outlined greedily, based off the sort above. 831 auto *UnsignedVecBegin = Mapper.UnsignedVec.begin(); 832 for (OutlinedFunction &OF : FunctionList) { 833 // If we outlined something that overlapped with a candidate in a previous 834 // step, then we can't outline from it. 835 erase_if(OF.Candidates, [&UnsignedVecBegin](Candidate &C) { 836 return std::any_of(UnsignedVecBegin + C.getStartIdx(), 837 UnsignedVecBegin + C.getEndIdx() + 1, [](unsigned I) { 838 return I == static_cast<unsigned>(-1); 839 }); 840 }); 841 842 // If we made it unbeneficial to outline this function, skip it. 843 if (OF.getBenefit() < 1) 844 continue; 845 846 // It's beneficial. Create the function and outline its sequence's 847 // occurrences. 848 OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum); 849 emitOutlinedFunctionRemark(OF); 850 FunctionsCreated++; 851 OutlinedFunctionNum++; // Created a function, move to the next name. 852 MachineFunction *MF = OF.MF; 853 const TargetSubtargetInfo &STI = MF->getSubtarget(); 854 const TargetInstrInfo &TII = *STI.getInstrInfo(); 855 856 // Replace occurrences of the sequence with calls to the new function. 857 for (Candidate &C : OF.Candidates) { 858 MachineBasicBlock &MBB = *C.getMBB(); 859 MachineBasicBlock::iterator StartIt = C.front(); 860 MachineBasicBlock::iterator EndIt = C.back(); 861 862 // Insert the call. 863 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C); 864 865 // If the caller tracks liveness, then we need to make sure that 866 // anything we outline doesn't break liveness assumptions. The outlined 867 // functions themselves currently don't track liveness, but we should 868 // make sure that the ranges we yank things out of aren't wrong. 869 if (MBB.getParent()->getProperties().hasProperty( 870 MachineFunctionProperties::Property::TracksLiveness)) { 871 // The following code is to add implicit def operands to the call 872 // instruction. It also updates call site information for moved 873 // code. 874 SmallSet<Register, 2> UseRegs, DefRegs; 875 // Copy over the defs in the outlined range. 876 // First inst in outlined range <-- Anything that's defined in this 877 // ... .. range has to be added as an 878 // implicit Last inst in outlined range <-- def to the call 879 // instruction. Also remove call site information for outlined block 880 // of code. The exposed uses need to be copied in the outlined range. 881 for (MachineBasicBlock::reverse_iterator 882 Iter = EndIt.getReverse(), 883 Last = std::next(CallInst.getReverse()); 884 Iter != Last; Iter++) { 885 MachineInstr *MI = &*Iter; 886 SmallSet<Register, 2> InstrUseRegs; 887 for (MachineOperand &MOP : MI->operands()) { 888 // Skip over anything that isn't a register. 889 if (!MOP.isReg()) 890 continue; 891 892 if (MOP.isDef()) { 893 // Introduce DefRegs set to skip the redundant register. 894 DefRegs.insert(MOP.getReg()); 895 if (UseRegs.count(MOP.getReg()) && 896 !InstrUseRegs.count(MOP.getReg())) 897 // Since the regiester is modeled as defined, 898 // it is not necessary to be put in use register set. 899 UseRegs.erase(MOP.getReg()); 900 } else if (!MOP.isUndef()) { 901 // Any register which is not undefined should 902 // be put in the use register set. 903 UseRegs.insert(MOP.getReg()); 904 InstrUseRegs.insert(MOP.getReg()); 905 } 906 } 907 if (MI->isCandidateForCallSiteEntry()) 908 MI->getMF()->eraseCallSiteInfo(MI); 909 } 910 911 for (const Register &I : DefRegs) 912 // If it's a def, add it to the call instruction. 913 CallInst->addOperand( 914 MachineOperand::CreateReg(I, true, /* isDef = true */ 915 true /* isImp = true */)); 916 917 for (const Register &I : UseRegs) 918 // If it's a exposed use, add it to the call instruction. 919 CallInst->addOperand( 920 MachineOperand::CreateReg(I, false, /* isDef = false */ 921 true /* isImp = true */)); 922 } 923 924 // Erase from the point after where the call was inserted up to, and 925 // including, the final instruction in the sequence. 926 // Erase needs one past the end, so we need std::next there too. 927 MBB.erase(std::next(StartIt), std::next(EndIt)); 928 929 // Keep track of what we removed by marking them all as -1. 930 for (unsigned &I : make_range(UnsignedVecBegin + C.getStartIdx(), 931 UnsignedVecBegin + C.getEndIdx() + 1)) 932 I = static_cast<unsigned>(-1); 933 OutlinedSomething = true; 934 935 // Statistics. 936 NumOutlined++; 937 } 938 } 939 940 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";); 941 return OutlinedSomething; 942 } 943 944 void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M, 945 MachineModuleInfo &MMI) { 946 // Build instruction mappings for each function in the module. Start by 947 // iterating over each Function in M. 948 LLVM_DEBUG(dbgs() << "*** Populating mapper ***\n"); 949 for (Function &F : M) { 950 LLVM_DEBUG(dbgs() << "MAPPING FUNCTION: " << F.getName() << "\n"); 951 952 if (F.hasFnAttribute("nooutline")) { 953 LLVM_DEBUG(dbgs() << "SKIP: Function has nooutline attribute\n"); 954 continue; 955 } 956 957 // There's something in F. Check if it has a MachineFunction associated with 958 // it. 959 MachineFunction *MF = MMI.getMachineFunction(F); 960 961 // If it doesn't, then there's nothing to outline from. Move to the next 962 // Function. 963 if (!MF) { 964 LLVM_DEBUG(dbgs() << "SKIP: Function does not have a MachineFunction\n"); 965 continue; 966 } 967 968 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 969 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF)) { 970 LLVM_DEBUG(dbgs() << "SKIP: Target does not want to outline from " 971 "function by default\n"); 972 continue; 973 } 974 975 // We have a MachineFunction. Ask the target if it's suitable for outlining. 976 // If it isn't, then move on to the next Function in the module. 977 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) { 978 LLVM_DEBUG(dbgs() << "SKIP: " << MF->getName() 979 << ": unsafe to outline from\n"); 980 continue; 981 } 982 983 // We have a function suitable for outlining. Iterate over every 984 // MachineBasicBlock in MF and try to map its instructions to a list of 985 // unsigned integers. 986 const unsigned MinMBBSize = 2; 987 988 for (MachineBasicBlock &MBB : *MF) { 989 LLVM_DEBUG(dbgs() << " MAPPING MBB: '" << MBB.getName() << "'\n"); 990 // If there isn't anything in MBB, then there's no point in outlining from 991 // it. 992 // If there are fewer than 2 instructions in the MBB, then it can't ever 993 // contain something worth outlining. 994 // FIXME: This should be based off of the maximum size in B of an outlined 995 // call versus the size in B of the MBB. 996 if (MBB.size() < MinMBBSize) { 997 LLVM_DEBUG(dbgs() << " SKIP: MBB size less than minimum size of " 998 << MinMBBSize << "\n"); 999 continue; 1000 } 1001 1002 // Check if MBB could be the target of an indirect branch. If it is, then 1003 // we don't want to outline from it. 1004 if (MBB.hasAddressTaken()) { 1005 LLVM_DEBUG(dbgs() << " SKIP: MBB's address is taken\n"); 1006 continue; 1007 } 1008 1009 // MBB is suitable for outlining. Map it to a list of unsigneds. 1010 Mapper.convertToUnsignedVec(MBB, *TII); 1011 } 1012 } 1013 // Statistics. 1014 UnsignedVecSize = Mapper.UnsignedVec.size(); 1015 } 1016 1017 void MachineOutliner::initSizeRemarkInfo( 1018 const Module &M, const MachineModuleInfo &MMI, 1019 StringMap<unsigned> &FunctionToInstrCount) { 1020 // Collect instruction counts for every function. We'll use this to emit 1021 // per-function size remarks later. 1022 for (const Function &F : M) { 1023 MachineFunction *MF = MMI.getMachineFunction(F); 1024 1025 // We only care about MI counts here. If there's no MachineFunction at this 1026 // point, then there won't be after the outliner runs, so let's move on. 1027 if (!MF) 1028 continue; 1029 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount(); 1030 } 1031 } 1032 1033 void MachineOutliner::emitInstrCountChangedRemark( 1034 const Module &M, const MachineModuleInfo &MMI, 1035 const StringMap<unsigned> &FunctionToInstrCount) { 1036 // Iterate over each function in the module and emit remarks. 1037 // Note that we won't miss anything by doing this, because the outliner never 1038 // deletes functions. 1039 for (const Function &F : M) { 1040 MachineFunction *MF = MMI.getMachineFunction(F); 1041 1042 // The outliner never deletes functions. If we don't have a MF here, then we 1043 // didn't have one prior to outlining either. 1044 if (!MF) 1045 continue; 1046 1047 std::string Fname = std::string(F.getName()); 1048 unsigned FnCountAfter = MF->getInstructionCount(); 1049 unsigned FnCountBefore = 0; 1050 1051 // Check if the function was recorded before. 1052 auto It = FunctionToInstrCount.find(Fname); 1053 1054 // Did we have a previously-recorded size? If yes, then set FnCountBefore 1055 // to that. 1056 if (It != FunctionToInstrCount.end()) 1057 FnCountBefore = It->second; 1058 1059 // Compute the delta and emit a remark if there was a change. 1060 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) - 1061 static_cast<int64_t>(FnCountBefore); 1062 if (FnDelta == 0) 1063 continue; 1064 1065 MachineOptimizationRemarkEmitter MORE(*MF, nullptr); 1066 MORE.emit([&]() { 1067 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange", 1068 DiagnosticLocation(), &MF->front()); 1069 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner") 1070 << ": Function: " 1071 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName()) 1072 << ": MI instruction count changed from " 1073 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore", 1074 FnCountBefore) 1075 << " to " 1076 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter", 1077 FnCountAfter) 1078 << "; Delta: " 1079 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta); 1080 return R; 1081 }); 1082 } 1083 } 1084 1085 bool MachineOutliner::runOnModule(Module &M) { 1086 // Check if there's anything in the module. If it's empty, then there's 1087 // nothing to outline. 1088 if (M.empty()) 1089 return false; 1090 1091 // Number to append to the current outlined function. 1092 unsigned OutlinedFunctionNum = 0; 1093 1094 OutlineRepeatedNum = 0; 1095 if (!doOutline(M, OutlinedFunctionNum)) 1096 return false; 1097 1098 for (unsigned I = 0; I < OutlinerReruns; ++I) { 1099 OutlinedFunctionNum = 0; 1100 OutlineRepeatedNum++; 1101 if (!doOutline(M, OutlinedFunctionNum)) { 1102 LLVM_DEBUG({ 1103 dbgs() << "Did not outline on iteration " << I + 2 << " out of " 1104 << OutlinerReruns + 1 << "\n"; 1105 }); 1106 break; 1107 } 1108 } 1109 1110 return true; 1111 } 1112 1113 bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) { 1114 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI(); 1115 1116 // If the user passed -enable-machine-outliner=always or 1117 // -enable-machine-outliner, the pass will run on all functions in the module. 1118 // Otherwise, if the target supports default outlining, it will run on all 1119 // functions deemed by the target to be worth outlining from by default. Tell 1120 // the user how the outliner is running. 1121 LLVM_DEBUG({ 1122 dbgs() << "Machine Outliner: Running on "; 1123 if (RunOnAllFunctions) 1124 dbgs() << "all functions"; 1125 else 1126 dbgs() << "target-default functions"; 1127 dbgs() << "\n"; 1128 }); 1129 1130 // If the user specifies that they want to outline from linkonceodrs, set 1131 // it here. 1132 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining; 1133 InstructionMapper Mapper; 1134 1135 // Prepare instruction mappings for the suffix tree. 1136 populateMapper(Mapper, M, MMI); 1137 std::vector<OutlinedFunction> FunctionList; 1138 1139 // Find all of the outlining candidates. 1140 findCandidates(Mapper, FunctionList); 1141 1142 // If we've requested size remarks, then collect the MI counts of every 1143 // function before outlining, and the MI counts after outlining. 1144 // FIXME: This shouldn't be in the outliner at all; it should ultimately be 1145 // the pass manager's responsibility. 1146 // This could pretty easily be placed in outline instead, but because we 1147 // really ultimately *don't* want this here, it's done like this for now 1148 // instead. 1149 1150 // Check if we want size remarks. 1151 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark(); 1152 StringMap<unsigned> FunctionToInstrCount; 1153 if (ShouldEmitSizeRemarks) 1154 initSizeRemarkInfo(M, MMI, FunctionToInstrCount); 1155 1156 // Outline each of the candidates and return true if something was outlined. 1157 bool OutlinedSomething = 1158 outline(M, FunctionList, Mapper, OutlinedFunctionNum); 1159 1160 // If we outlined something, we definitely changed the MI count of the 1161 // module. If we've asked for size remarks, then output them. 1162 // FIXME: This should be in the pass manager. 1163 if (ShouldEmitSizeRemarks && OutlinedSomething) 1164 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount); 1165 1166 LLVM_DEBUG({ 1167 if (!OutlinedSomething) 1168 dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum 1169 << " because no changes were found.\n"; 1170 }); 1171 1172 return OutlinedSomething; 1173 } 1174