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