LLVM 22.0.0git
MachineOutliner.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/SmallSet.h"
60#include "llvm/ADT/Statistic.h"
61#include "llvm/ADT/Twine.h"
68#include "llvm/CodeGen/Passes.h"
72#include "llvm/IR/DIBuilder.h"
73#include "llvm/IR/IRBuilder.h"
74#include "llvm/IR/Mangler.h"
75#include "llvm/IR/Module.h"
78#include "llvm/Support/Debug.h"
83#include <tuple>
84#include <vector>
85
86#define DEBUG_TYPE "machine-outliner"
87
88using namespace llvm;
89using namespace ore;
90using namespace outliner;
91
92// Statistics for outlined functions.
93STATISTIC(NumOutlined, "Number of candidates outlined");
94STATISTIC(FunctionsCreated, "Number of functions created");
95
96// Statistics for instruction mapping.
97STATISTIC(NumLegalInUnsignedVec, "Outlinable instructions mapped");
98STATISTIC(NumIllegalInUnsignedVec,
99 "Unoutlinable instructions mapped + number of sentinel values");
100STATISTIC(NumSentinels, "Sentinel values inserted during mapping");
101STATISTIC(NumInvisible,
102 "Invisible instructions skipped during mapping");
103STATISTIC(UnsignedVecSize,
104 "Total number of instructions mapped and saved to mapping vector");
105STATISTIC(StableHashAttempts,
106 "Count of hashing attempts made for outlined functions");
107STATISTIC(StableHashDropped,
108 "Count of unsuccessful hashing attempts for outlined functions");
109STATISTIC(NumRemovedLOHs, "Total number of Linker Optimization Hints removed");
110
111// Set to true if the user wants the outliner to run on linkonceodr linkage
112// functions. This is false by default because the linker can dedupe linkonceodr
113// functions. Since the outliner is confined to a single module (modulo LTO),
114// this is off by default. It should, however, be the default behaviour in
115// LTO.
117 "enable-linkonceodr-outlining", cl::Hidden,
118 cl::desc("Enable the machine outliner on linkonceodr functions"),
119 cl::init(false));
120
121/// Number of times to re-run the outliner. This is not the total number of runs
122/// as the outliner will run at least one time. The default value is set to 0,
123/// meaning the outliner will run one time and rerun zero times after that.
125 "machine-outliner-reruns", cl::init(0), cl::Hidden,
126 cl::desc(
127 "Number of times to rerun the outliner after the initial outline"));
128
130 "outliner-benefit-threshold", cl::init(1), cl::Hidden,
131 cl::desc(
132 "The minimum size in bytes before an outlining candidate is accepted"));
133
135 "outliner-leaf-descendants", cl::init(true), cl::Hidden,
136 cl::desc("Consider all leaf descendants of internal nodes of the suffix "
137 "tree as candidates for outlining (if false, only leaf children "
138 "are considered)"));
139
140static cl::opt<bool>
141 DisableGlobalOutlining("disable-global-outlining", cl::Hidden,
142 cl::desc("Disable global outlining only by ignoring "
143 "the codegen data generation or use"),
144 cl::init(false));
145
147 "append-content-hash-outlined-name", cl::Hidden,
148 cl::desc("This appends the content hash to the globally outlined function "
149 "name. It's beneficial for enhancing the precision of the stable "
150 "hash and for ordering the outlined functions."),
151 cl::init(true));
152
153namespace {
154
155/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
156struct InstructionMapper {
157 const MachineModuleInfo &MMI;
158
159 /// The next available integer to assign to a \p MachineInstr that
160 /// cannot be outlined.
161 ///
162 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
163 unsigned IllegalInstrNumber = -3;
164
165 /// The next available integer to assign to a \p MachineInstr that can
166 /// be outlined.
167 unsigned LegalInstrNumber = 0;
168
169 /// Correspondence from \p MachineInstrs to unsigned integers.
171 InstructionIntegerMap;
172
173 /// Correspondence between \p MachineBasicBlocks and target-defined flags.
175
176 /// The vector of unsigned integers that the module is mapped to.
177 SmallVector<unsigned> UnsignedVec;
178
179 /// Stores the location of the instruction associated with the integer
180 /// at index i in \p UnsignedVec for each index i.
182
183 // Set if we added an illegal number in the previous step.
184 // Since each illegal number is unique, we only need one of them between
185 // each range of legal numbers. This lets us make sure we don't add more
186 // than one illegal number per range.
187 bool AddedIllegalLastTime = false;
188
189 /// Maps \p *It to a legal integer.
190 ///
191 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
192 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
193 ///
194 /// \returns The integer that \p *It was mapped to.
195 unsigned mapToLegalUnsigned(
196 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
197 bool &HaveLegalRange, unsigned &NumLegalInBlock,
198 SmallVector<unsigned> &UnsignedVecForMBB,
200 // We added something legal, so we should unset the AddedLegalLastTime
201 // flag.
202 AddedIllegalLastTime = false;
203
204 // If we have at least two adjacent legal instructions (which may have
205 // invisible instructions in between), remember that.
206 if (CanOutlineWithPrevInstr)
207 HaveLegalRange = true;
208 CanOutlineWithPrevInstr = true;
209
210 // Keep track of the number of legal instructions we insert.
211 NumLegalInBlock++;
212
213 // Get the integer for this instruction or give it the current
214 // LegalInstrNumber.
215 InstrListForMBB.push_back(It);
216 MachineInstr &MI = *It;
217 bool WasInserted;
219 ResultIt;
220 std::tie(ResultIt, WasInserted) =
221 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
222 unsigned MINumber = ResultIt->second;
223
224 // There was an insertion.
225 if (WasInserted)
226 LegalInstrNumber++;
227
228 UnsignedVecForMBB.push_back(MINumber);
229
230 // Make sure we don't overflow or use any integers reserved by the DenseMap.
231 if (LegalInstrNumber >= IllegalInstrNumber)
232 report_fatal_error("Instruction mapping overflow!");
233
234 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
235 "Tried to assign DenseMap tombstone or empty key to instruction.");
236 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
237 "Tried to assign DenseMap tombstone or empty key to instruction.");
238
239 // Statistics.
240 ++NumLegalInUnsignedVec;
241 return MINumber;
242 }
243
244 /// Maps \p *It to an illegal integer.
245 ///
246 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
247 /// IllegalInstrNumber.
248 ///
249 /// \returns The integer that \p *It was mapped to.
250 unsigned mapToIllegalUnsigned(
251 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
252 SmallVector<unsigned> &UnsignedVecForMBB,
254 // Can't outline an illegal instruction. Set the flag.
255 CanOutlineWithPrevInstr = false;
256
257 // Only add one illegal number per range of legal numbers.
258 if (AddedIllegalLastTime)
259 return IllegalInstrNumber;
260
261 // Remember that we added an illegal number last time.
262 AddedIllegalLastTime = true;
263 unsigned MINumber = IllegalInstrNumber;
264
265 InstrListForMBB.push_back(It);
266 UnsignedVecForMBB.push_back(IllegalInstrNumber);
267 IllegalInstrNumber--;
268 // Statistics.
269 ++NumIllegalInUnsignedVec;
270
271 assert(LegalInstrNumber < IllegalInstrNumber &&
272 "Instruction mapping overflow!");
273
274 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
275 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
276
277 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
278 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
279
280 return MINumber;
281 }
282
283 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
284 /// and appends it to \p UnsignedVec and \p InstrList.
285 ///
286 /// Two instructions are assigned the same integer if they are identical.
287 /// If an instruction is deemed unsafe to outline, then it will be assigned an
288 /// unique integer. The resulting mapping is placed into a suffix tree and
289 /// queried for candidates.
290 ///
291 /// \param MBB The \p MachineBasicBlock to be translated into integers.
292 /// \param TII \p TargetInstrInfo for the function.
293 void convertToUnsignedVec(MachineBasicBlock &MBB,
294 const TargetInstrInfo &TII) {
295 LLVM_DEBUG(dbgs() << "*** Converting MBB '" << MBB.getName()
296 << "' to unsigned vector ***\n");
297 unsigned Flags = 0;
298
299 // Don't even map in this case.
300 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
301 return;
302
303 auto OutlinableRanges = TII.getOutlinableRanges(MBB, Flags);
304 LLVM_DEBUG(dbgs() << MBB.getName() << ": " << OutlinableRanges.size()
305 << " outlinable range(s)\n");
306 if (OutlinableRanges.empty())
307 return;
308
309 // Store info for the MBB for later outlining.
310 MBBFlagsMap[&MBB] = Flags;
311
313
314 // The number of instructions in this block that will be considered for
315 // outlining.
316 unsigned NumLegalInBlock = 0;
317
318 // True if we have at least two legal instructions which aren't separated
319 // by an illegal instruction.
320 bool HaveLegalRange = false;
321
322 // True if we can perform outlining given the last mapped (non-invisible)
323 // instruction. This lets us know if we have a legal range.
324 bool CanOutlineWithPrevInstr = false;
325
326 // FIXME: Should this all just be handled in the target, rather than using
327 // repeated calls to getOutliningType?
328 SmallVector<unsigned> UnsignedVecForMBB;
330
331 LLVM_DEBUG(dbgs() << "*** Mapping outlinable ranges ***\n");
332 for (auto &OutlinableRange : OutlinableRanges) {
333 auto OutlinableRangeBegin = OutlinableRange.first;
334 auto OutlinableRangeEnd = OutlinableRange.second;
335#ifndef NDEBUG
337 dbgs() << "Mapping "
338 << std::distance(OutlinableRangeBegin, OutlinableRangeEnd)
339 << " instruction range\n");
340 // Everything outside of an outlinable range is illegal.
341 unsigned NumSkippedInRange = 0;
342#endif
343 for (; It != OutlinableRangeBegin; ++It) {
344#ifndef NDEBUG
345 ++NumSkippedInRange;
346#endif
347 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
348 InstrListForMBB);
349 }
350#ifndef NDEBUG
351 LLVM_DEBUG(dbgs() << "Skipped " << NumSkippedInRange
352 << " instructions outside outlinable range\n");
353#endif
354 assert(It != MBB.end() && "Should still have instructions?");
355 // `It` is now positioned at the beginning of a range of instructions
356 // which may be outlinable. Check if each instruction is known to be safe.
357 for (; It != OutlinableRangeEnd; ++It) {
358 // Keep track of where this instruction is in the module.
359 switch (TII.getOutliningType(MMI, It, Flags)) {
360 case InstrType::Illegal:
361 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
362 InstrListForMBB);
363 break;
364
365 case InstrType::Legal:
366 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
367 NumLegalInBlock, UnsignedVecForMBB,
368 InstrListForMBB);
369 break;
370
371 case InstrType::LegalTerminator:
372 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
373 NumLegalInBlock, UnsignedVecForMBB,
374 InstrListForMBB);
375 // The instruction also acts as a terminator, so we have to record
376 // that in the string.
377 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
378 InstrListForMBB);
379 break;
380
381 case InstrType::Invisible:
382 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
383 // skip this instruction. So, unset the flag here.
384 ++NumInvisible;
385 AddedIllegalLastTime = false;
386 break;
387 }
388 }
389 }
390
391 LLVM_DEBUG(dbgs() << "HaveLegalRange = " << HaveLegalRange << "\n");
392
393 // Are there enough legal instructions in the block for outlining to be
394 // possible?
395 if (HaveLegalRange) {
396 // After we're done every insertion, uniquely terminate this part of the
397 // "string". This makes sure we won't match across basic block or function
398 // boundaries since the "end" is encoded uniquely and thus appears in no
399 // repeated substring.
400 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
401 InstrListForMBB);
402 ++NumSentinels;
403 append_range(InstrList, InstrListForMBB);
404 append_range(UnsignedVec, UnsignedVecForMBB);
405 }
406 }
407
408 InstructionMapper(const MachineModuleInfo &MMI_) : MMI(MMI_) {
409 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
410 // changed.
412 "DenseMapInfo<unsigned>'s empty key isn't -1!");
414 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
415 }
416};
417
418/// An interprocedural pass which finds repeated sequences of
419/// instructions and replaces them with calls to functions.
420///
421/// Each instruction is mapped to an unsigned integer and placed in a string.
422/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
423/// is then repeatedly queried for repeated sequences of instructions. Each
424/// non-overlapping repeated sequence is then placed in its own
425/// \p MachineFunction and each instance is then replaced with a call to that
426/// function.
427struct MachineOutliner : public ModulePass {
428
429 static char ID;
430
431 MachineModuleInfo *MMI = nullptr;
432 const TargetMachine *TM = nullptr;
433
434 /// Set to true if the outliner should consider functions with
435 /// linkonceodr linkage.
436 bool OutlineFromLinkOnceODRs = false;
437
438 /// The current repeat number of machine outlining.
439 unsigned OutlineRepeatedNum = 0;
440
441 /// Set to true if the outliner should run on all functions in the module
442 /// considered safe for outlining.
443 /// Set to true by default for compatibility with llc's -run-pass option.
444 /// Set when the pass is constructed in TargetPassConfig.
445 bool RunOnAllFunctions = true;
446
447 /// This is a compact representation of hash sequences of outlined functions.
448 /// It is used when OutlinerMode = CGDataMode::Write.
449 /// The resulting hash tree will be emitted into __llvm_outlined section
450 /// which will be dead-stripped not going to the final binary.
451 /// A post-process using llvm-cgdata, lld, or ThinLTO can merge them into
452 /// a global oulined hash tree for the subsequent codegen.
453 std::unique_ptr<OutlinedHashTree> LocalHashTree;
454
455 /// The mode of the outliner.
456 /// When is's CGDataMode::None, candidates are populated with the suffix tree
457 /// within a module and outlined.
458 /// When it's CGDataMode::Write, in addition to CGDataMode::None, the hash
459 /// sequences of outlined functions are published into LocalHashTree.
460 /// When it's CGDataMode::Read, candidates are populated with the global
461 /// outlined hash tree that has been built by the previous codegen.
462 CGDataMode OutlinerMode = CGDataMode::None;
463
464 StringRef getPassName() const override { return "Machine Outliner"; }
465
466 void getAnalysisUsage(AnalysisUsage &AU) const override {
471 AU.setPreservesAll();
473 }
474
475 MachineOutliner() : ModulePass(ID) {
477 }
478
479 /// Remark output explaining that not outlining a set of candidates would be
480 /// better than outlining that set.
481 void emitNotOutliningCheaperRemark(
482 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
483 OutlinedFunction &OF);
484
485 /// Remark output explaining that a function was outlined.
486 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
487
488 /// Find all repeated substrings that satisfy the outlining cost model by
489 /// constructing a suffix tree.
490 ///
491 /// If a substring appears at least twice, then it must be represented by
492 /// an internal node which appears in at least two suffixes. Each suffix
493 /// is represented by a leaf node. To do this, we visit each internal node
494 /// in the tree, using the leaf children of each internal node. If an
495 /// internal node represents a beneficial substring, then we use each of
496 /// its leaf children to find the locations of its substring.
497 ///
498 /// \param Mapper Contains outlining mapping information.
499 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
500 /// each type of candidate.
501 void
502 findCandidates(InstructionMapper &Mapper,
503 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
504
505 /// Find all repeated substrings that match in the global outlined hash
506 /// tree built from the previous codegen.
507 ///
508 /// \param Mapper Contains outlining mapping information.
509 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
510 /// each type of candidate.
511 void findGlobalCandidates(
512 InstructionMapper &Mapper,
513 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
514
515 /// Replace the sequences of instructions represented by \p OutlinedFunctions
516 /// with calls to functions.
517 ///
518 /// \param M The module we are outlining from.
519 /// \param FunctionList A list of functions to be inserted into the module.
520 /// \param Mapper Contains the instruction mappings for the module.
521 /// \param[out] OutlinedFunctionNum The outlined function number.
522 bool outline(Module &M,
523 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
524 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
525
526 /// Creates a function for \p OF and inserts it into the module.
528 InstructionMapper &Mapper,
529 unsigned Name);
530
531 /// Compute and publish the stable hash sequence of instructions in the
532 /// outlined function, \p MF. The parameter \p CandSize represents the number
533 /// of candidates that have identical instruction sequences to \p MF.
534 void computeAndPublishHashSequence(MachineFunction &MF, unsigned CandSize);
535
536 /// Initialize the outliner mode.
537 void initializeOutlinerMode(const Module &M);
538
539 /// Emit the outlined hash tree into __llvm_outline section.
540 void emitOutlinedHashTree(Module &M);
541
542 /// Calls 'doOutline()' 1 + OutlinerReruns times.
543 bool runOnModule(Module &M) override;
544
545 /// Construct a suffix tree on the instructions in \p M and outline repeated
546 /// strings from that tree.
547 bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
548
549 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
550 /// function for remark emission.
552 for (const Candidate &C : OF.Candidates)
553 if (MachineFunction *MF = C.getMF())
554 if (DISubprogram *SP = MF->getFunction().getSubprogram())
555 return SP;
556 return nullptr;
557 }
558
559 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
560 /// These are used to construct a suffix tree.
561 void populateMapper(InstructionMapper &Mapper, Module &M);
562
563 /// Initialize information necessary to output a size remark.
564 /// FIXME: This should be handled by the pass manager, not the outliner.
565 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
566 /// pass manager.
567 void initSizeRemarkInfo(const Module &M,
568 StringMap<unsigned> &FunctionToInstrCount);
569
570 /// Emit the remark.
571 // FIXME: This should be handled by the pass manager, not the outliner.
572 void
573 emitInstrCountChangedRemark(const Module &M,
574 const StringMap<unsigned> &FunctionToInstrCount);
575};
576} // Anonymous namespace.
577
578char MachineOutliner::ID = 0;
579
580namespace llvm {
581ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
582 MachineOutliner *OL = new MachineOutliner();
583 OL->RunOnAllFunctions = RunOnAllFunctions;
584 return OL;
585}
586
587} // namespace llvm
588
589INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
590 false)
591
592void MachineOutliner::emitNotOutliningCheaperRemark(
593 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
594 OutlinedFunction &OF) {
595 // FIXME: Right now, we arbitrarily choose some Candidate from the
596 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
597 // We should probably sort these by function name or something to make sure
598 // the remarks are stable.
599 Candidate &C = CandidatesForRepeatedSeq.front();
600 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
601 MORE.emit([&]() {
602 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
603 C.front().getDebugLoc(), C.getMBB());
604 R << "Did not outline " << NV("Length", StringLen) << " instructions"
605 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
606 << " locations."
607 << " Bytes from outlining all occurrences ("
608 << NV("OutliningCost", OF.getOutliningCost()) << ")"
609 << " >= Unoutlined instruction bytes ("
610 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
611 << " (Also found at: ";
612
613 // Tell the user the other places the candidate was found.
614 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
615 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
616 CandidatesForRepeatedSeq[i].front().getDebugLoc());
617 if (i != e - 1)
618 R << ", ";
619 }
620
621 R << ")";
622 return R;
623 });
624}
625
626void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
627 MachineBasicBlock *MBB = &*OF.MF->begin();
629 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
631 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
632 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
633 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
634 << " locations. "
635 << "(Found at: ";
636
637 // Tell the user the other places the candidate was found.
638 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
639
640 R << NV((Twine("StartLoc") + Twine(i)).str(),
641 OF.Candidates[i].front().getDebugLoc());
642 if (i != e - 1)
643 R << ", ";
644 }
645
646 R << ")";
647
648 MORE.emit(R);
649}
650
652 unsigned StartIdx;
653 unsigned EndIdx;
654 unsigned Count;
655 MatchedEntry(unsigned StartIdx, unsigned EndIdx, unsigned Count)
657 MatchedEntry() = delete;
658};
659
660// Find all matches in the global outlined hash tree.
661// It's quadratic complexity in theory, but it's nearly linear in practice
662// since the length of outlined sequences are small within a block.
663static SmallVector<MatchedEntry> getMatchedEntries(InstructionMapper &Mapper) {
664 auto &InstrList = Mapper.InstrList;
665 auto &UnsignedVec = Mapper.UnsignedVec;
666
667 SmallVector<MatchedEntry> MatchedEntries;
668 auto Size = UnsignedVec.size();
669
670 // Get the global outlined hash tree built from the previous run.
672 const auto *RootNode = cgdata::getOutlinedHashTree()->getRoot();
673
674 auto getValidInstr = [&](unsigned Index) -> const MachineInstr * {
675 if (UnsignedVec[Index] >= Mapper.LegalInstrNumber)
676 return nullptr;
677 return &(*InstrList[Index]);
678 };
679
680 auto getStableHashAndFollow =
681 [](const MachineInstr &MI, const HashNode *CurrNode) -> const HashNode * {
682 stable_hash StableHash = stableHashValue(MI);
683 if (!StableHash)
684 return nullptr;
685 auto It = CurrNode->Successors.find(StableHash);
686 return (It == CurrNode->Successors.end()) ? nullptr : It->second.get();
687 };
688
689 for (unsigned I = 0; I < Size; ++I) {
690 const MachineInstr *MI = getValidInstr(I);
691 if (!MI || MI->isDebugInstr())
692 continue;
693 const HashNode *CurrNode = getStableHashAndFollow(*MI, RootNode);
694 if (!CurrNode)
695 continue;
696
697 for (unsigned J = I + 1; J < Size; ++J) {
698 const MachineInstr *MJ = getValidInstr(J);
699 if (!MJ)
700 break;
701 // Skip debug instructions as we did for the outlined function.
702 if (MJ->isDebugInstr())
703 continue;
704 CurrNode = getStableHashAndFollow(*MJ, CurrNode);
705 if (!CurrNode)
706 break;
707 // Even with a match ending with a terminal, we continue finding
708 // matches to populate all candidates.
709 if (auto Count = CurrNode->Terminals)
710 MatchedEntries.emplace_back(I, J, *Count);
711 }
712 }
713
714 return MatchedEntries;
715}
716
717void MachineOutliner::findGlobalCandidates(
718 InstructionMapper &Mapper,
719 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
720 FunctionList.clear();
721 auto &InstrList = Mapper.InstrList;
722 auto &MBBFlagsMap = Mapper.MBBFlagsMap;
723
724 std::vector<Candidate> CandidatesForRepeatedSeq;
725 for (auto &ME : getMatchedEntries(Mapper)) {
726 CandidatesForRepeatedSeq.clear();
727 MachineBasicBlock::iterator StartIt = InstrList[ME.StartIdx];
728 MachineBasicBlock::iterator EndIt = InstrList[ME.EndIdx];
729 auto Length = ME.EndIdx - ME.StartIdx + 1;
730 MachineBasicBlock *MBB = StartIt->getParent();
731 CandidatesForRepeatedSeq.emplace_back(ME.StartIdx, Length, StartIt, EndIt,
732 MBB, FunctionList.size(),
733 MBBFlagsMap[MBB]);
734 const TargetInstrInfo *TII =
736 unsigned MinRepeats = 1;
737 std::optional<std::unique_ptr<OutlinedFunction>> OF =
738 TII->getOutliningCandidateInfo(*MMI, CandidatesForRepeatedSeq,
739 MinRepeats);
740 if (!OF.has_value() || OF.value()->Candidates.empty())
741 continue;
742 // We create a global candidate for each match.
743 assert(OF.value()->Candidates.size() == MinRepeats);
744 FunctionList.emplace_back(std::make_unique<GlobalOutlinedFunction>(
745 std::move(OF.value()), ME.Count));
746 }
747}
748
749void MachineOutliner::findCandidates(
750 InstructionMapper &Mapper,
751 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
752 FunctionList.clear();
753 SuffixTree ST(Mapper.UnsignedVec, OutlinerLeafDescendants);
754
755 // First, find all of the repeated substrings in the tree of minimum length
756 // 2.
757 std::vector<Candidate> CandidatesForRepeatedSeq;
758 LLVM_DEBUG(dbgs() << "*** Discarding overlapping candidates *** \n");
760 dbgs() << "Searching for overlaps in all repeated sequences...\n");
761 for (SuffixTree::RepeatedSubstring &RS : ST) {
762 CandidatesForRepeatedSeq.clear();
763 unsigned StringLen = RS.Length;
764 LLVM_DEBUG(dbgs() << " Sequence length: " << StringLen << "\n");
765 // Debug code to keep track of how many candidates we removed.
766#ifndef NDEBUG
767 unsigned NumDiscarded = 0;
768 unsigned NumKept = 0;
769#endif
770 // Sort the start indices so that we can efficiently check if candidates
771 // overlap with the ones we've already found for this sequence.
772 llvm::sort(RS.StartIndices);
773 for (const unsigned &StartIdx : RS.StartIndices) {
774 // Trick: Discard some candidates that would be incompatible with the
775 // ones we've already found for this sequence. This will save us some
776 // work in candidate selection.
777 //
778 // If two candidates overlap, then we can't outline them both. This
779 // happens when we have candidates that look like, say
780 //
781 // AA (where each "A" is an instruction).
782 //
783 // We might have some portion of the module that looks like this:
784 // AAAAAA (6 A's)
785 //
786 // In this case, there are 5 different copies of "AA" in this range, but
787 // at most 3 can be outlined. If only outlining 3 of these is going to
788 // be unbeneficial, then we ought to not bother.
789 //
790 // Note that two things DON'T overlap when they look like this:
791 // start1...end1 .... start2...end2
792 // That is, one must either
793 // * End before the other starts
794 // * Start after the other ends
795 unsigned EndIdx = StartIdx + StringLen - 1;
796 if (!CandidatesForRepeatedSeq.empty() &&
797 StartIdx <= CandidatesForRepeatedSeq.back().getEndIdx()) {
798#ifndef NDEBUG
799 ++NumDiscarded;
800 LLVM_DEBUG(dbgs() << " .. DISCARD candidate @ [" << StartIdx << ", "
801 << EndIdx << "]; overlaps with candidate @ ["
802 << CandidatesForRepeatedSeq.back().getStartIdx()
803 << ", " << CandidatesForRepeatedSeq.back().getEndIdx()
804 << "]\n");
805#endif
806 continue;
807 }
808 // It doesn't overlap with anything, so we can outline it.
809 // Each sequence is over [StartIt, EndIt].
810 // Save the candidate and its location.
811#ifndef NDEBUG
812 ++NumKept;
813#endif
814 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
815 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
816 MachineBasicBlock *MBB = StartIt->getParent();
817 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, EndIt,
818 MBB, FunctionList.size(),
819 Mapper.MBBFlagsMap[MBB]);
820 }
821#ifndef NDEBUG
822 LLVM_DEBUG(dbgs() << " Candidates discarded: " << NumDiscarded
823 << "\n");
824 LLVM_DEBUG(dbgs() << " Candidates kept: " << NumKept << "\n\n");
825#endif
826 unsigned MinRepeats = 2;
827
828 // We've found something we might want to outline.
829 // Create an OutlinedFunction to store it and check if it'd be beneficial
830 // to outline.
831 if (CandidatesForRepeatedSeq.size() < MinRepeats)
832 continue;
833
834 // Arbitrarily choose a TII from the first candidate.
835 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
836 const TargetInstrInfo *TII =
837 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
838
839 std::optional<std::unique_ptr<OutlinedFunction>> OF =
840 TII->getOutliningCandidateInfo(*MMI, CandidatesForRepeatedSeq,
841 MinRepeats);
842
843 // If we deleted too many candidates, then there's nothing worth outlining.
844 // FIXME: This should take target-specified instruction sizes into account.
845 if (!OF.has_value() || OF.value()->Candidates.size() < MinRepeats)
846 continue;
847
848 // Is it better to outline this candidate than not?
849 if (OF.value()->getBenefit() < OutlinerBenefitThreshold) {
850 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq,
851 *OF.value());
852 continue;
853 }
854
855 FunctionList.emplace_back(std::move(OF.value()));
856 }
857}
858
859void MachineOutliner::computeAndPublishHashSequence(MachineFunction &MF,
860 unsigned CandSize) {
861 // Compute the hash sequence for the outlined function.
862 SmallVector<stable_hash> OutlinedHashSequence;
863 for (auto &MBB : MF) {
864 for (auto &NewMI : MBB) {
865 stable_hash Hash = stableHashValue(NewMI);
866 if (!Hash) {
867 OutlinedHashSequence.clear();
868 break;
869 }
870 OutlinedHashSequence.push_back(Hash);
871 }
872 }
873
874 // Append a unique name based on the non-empty hash sequence.
875 if (AppendContentHashToOutlinedName && !OutlinedHashSequence.empty()) {
876 auto CombinedHash = stable_hash_combine(OutlinedHashSequence);
877 auto NewName =
878 MF.getName().str() + ".content." + std::to_string(CombinedHash);
879 MF.getFunction().setName(NewName);
880 }
881
882 // Publish the non-empty hash sequence to the local hash tree.
883 if (OutlinerMode == CGDataMode::Write) {
884 StableHashAttempts++;
885 if (!OutlinedHashSequence.empty())
886 LocalHashTree->insert({OutlinedHashSequence, CandSize});
887 else
888 StableHashDropped++;
889 }
890}
891
892MachineFunction *MachineOutliner::createOutlinedFunction(
893 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
894
895 // Create the function name. This should be unique.
896 // FIXME: We should have a better naming scheme. This should be stable,
897 // regardless of changes to the outliner's cost model/traversal order.
898 std::string FunctionName = "OUTLINED_FUNCTION_";
899 if (OutlineRepeatedNum > 0)
900 FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
901 FunctionName += std::to_string(Name);
902 LLVM_DEBUG(dbgs() << "NEW FUNCTION: " << FunctionName << "\n");
903
904 // Create the function using an IR-level function.
905 LLVMContext &C = M.getContext();
906 Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
907 Function::ExternalLinkage, FunctionName, M);
908
909 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
910 // which gives us better results when we outline from linkonceodr functions.
911 F->setLinkage(GlobalValue::InternalLinkage);
912 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
913
914 // Set optsize/minsize, so we don't insert padding between outlined
915 // functions.
916 F->addFnAttr(Attribute::OptimizeForSize);
917 F->addFnAttr(Attribute::MinSize);
918
919 Candidate &FirstCand = OF.Candidates.front();
920 const TargetInstrInfo &TII =
921 *FirstCand.getMF()->getSubtarget().getInstrInfo();
922
923 TII.mergeOutliningCandidateAttributes(*F, OF.Candidates);
924
925 // Set uwtable, so we generate eh_frame.
926 UWTableKind UW = std::accumulate(
927 OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None,
928 [](UWTableKind K, const outliner::Candidate &C) {
929 return std::max(K, C.getMF()->getFunction().getUWTableKind());
930 });
931 F->setUWTableKind(UW);
932
933 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
934 IRBuilder<> Builder(EntryBB);
935 Builder.CreateRetVoid();
936
937 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
939 MF.setIsOutlined(true);
941
942 // Insert the new function into the module.
943 MF.insert(MF.begin(), &MBB);
944
945 MachineFunction *OriginalMF = FirstCand.front().getMF();
946 const std::vector<MCCFIInstruction> &Instrs =
947 OriginalMF->getFrameInstructions();
948 for (auto &MI : FirstCand) {
949 if (MI.isDebugInstr())
950 continue;
951
952 // Don't keep debug information for outlined instructions.
953 auto DL = DebugLoc();
954 if (MI.isCFIInstruction()) {
955 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
956 MCCFIInstruction CFI = Instrs[CFIIndex];
957 BuildMI(MBB, MBB.end(), DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
958 .addCFIIndex(MF.addFrameInst(CFI));
959 } else {
960 MachineInstr &NewMI = TII.duplicate(MBB, MBB.end(), MI);
961 NewMI.dropMemRefs(MF);
962 NewMI.setDebugLoc(DL);
963 }
964 }
965
966 if (OutlinerMode != CGDataMode::None)
967 computeAndPublishHashSequence(MF, OF.Candidates.size());
968
969 // Set normal properties for a late MachineFunction.
970 MF.getProperties().resetIsSSA();
971 MF.getProperties().setNoPHIs();
972 MF.getProperties().setNoVRegs();
973 MF.getProperties().setTracksLiveness();
975
976 // Compute live-in set for outlined fn
977 const MachineRegisterInfo &MRI = MF.getRegInfo();
978 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
979 LivePhysRegs LiveIns(TRI);
980 for (auto &Cand : OF.Candidates) {
981 // Figure out live-ins at the first instruction.
982 MachineBasicBlock &OutlineBB = *Cand.front().getParent();
983 LivePhysRegs CandLiveIns(TRI);
984 CandLiveIns.addLiveOuts(OutlineBB);
985 for (const MachineInstr &MI :
986 reverse(make_range(Cand.begin(), OutlineBB.end())))
987 CandLiveIns.stepBackward(MI);
988
989 // The live-in set for the outlined function is the union of the live-ins
990 // from all the outlining points.
991 for (MCPhysReg Reg : CandLiveIns)
992 LiveIns.addReg(Reg);
993 }
994 addLiveIns(MBB, LiveIns);
995
996 TII.buildOutlinedFrame(MBB, MF, OF);
997
998 // If there's a DISubprogram associated with this outlined function, then
999 // emit debug info for the outlined function.
1000 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1001 // We have a DISubprogram. Get its DICompileUnit.
1002 DICompileUnit *CU = SP->getUnit();
1003 DIBuilder DB(M, true, CU);
1004 DIFile *Unit = SP->getFile();
1005 Mangler Mg;
1006 // Get the mangled name of the function for the linkage name.
1007 std::string Dummy;
1008 raw_string_ostream MangledNameStream(Dummy);
1009 Mg.getNameWithPrefix(MangledNameStream, F, false);
1010
1011 DISubprogram *OutlinedSP = DB.createFunction(
1012 Unit /* Context */, F->getName(), StringRef(Dummy), Unit /* File */,
1013 0 /* Line 0 is reserved for compiler-generated code. */,
1014 DB.createSubroutineType(DB.getOrCreateTypeArray({})), /* void type */
1015 0, /* Line 0 is reserved for compiler-generated code. */
1016 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1017 /* Outlined code is optimized code by definition. */
1018 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1019
1020 // Attach subprogram to the function.
1021 F->setSubprogram(OutlinedSP);
1022 // We're done with the DIBuilder.
1023 DB.finalize();
1024 }
1025
1026 return &MF;
1027}
1028
1029bool MachineOutliner::outline(
1030 Module &M, std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
1031 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum) {
1032 LLVM_DEBUG(dbgs() << "*** Outlining ***\n");
1033 LLVM_DEBUG(dbgs() << "NUMBER OF POTENTIAL FUNCTIONS: " << FunctionList.size()
1034 << "\n");
1035 bool OutlinedSomething = false;
1036
1037 // Sort by priority where priority := getNotOutlinedCost / getOutliningCost.
1038 // The function with highest priority should be outlined first.
1039 stable_sort(FunctionList, [](const std::unique_ptr<OutlinedFunction> &LHS,
1040 const std::unique_ptr<OutlinedFunction> &RHS) {
1041 return LHS->getNotOutlinedCost() * RHS->getOutliningCost() >
1042 RHS->getNotOutlinedCost() * LHS->getOutliningCost();
1043 });
1044
1045 // Walk over each function, outlining them as we go along. Functions are
1046 // outlined greedily, based off the sort above.
1047 auto *UnsignedVecBegin = Mapper.UnsignedVec.begin();
1048 LLVM_DEBUG(dbgs() << "WALKING FUNCTION LIST\n");
1049 for (auto &OF : FunctionList) {
1050#ifndef NDEBUG
1051 auto NumCandidatesBefore = OF->Candidates.size();
1052#endif
1053 // If we outlined something that overlapped with a candidate in a previous
1054 // step, then we can't outline from it.
1055 erase_if(OF->Candidates, [&UnsignedVecBegin](Candidate &C) {
1056 return std::any_of(UnsignedVecBegin + C.getStartIdx(),
1057 UnsignedVecBegin + C.getEndIdx() + 1, [](unsigned I) {
1058 return I == static_cast<unsigned>(-1);
1059 });
1060 });
1061
1062#ifndef NDEBUG
1063 auto NumCandidatesAfter = OF->Candidates.size();
1064 LLVM_DEBUG(dbgs() << "PRUNED: " << NumCandidatesBefore - NumCandidatesAfter
1065 << "/" << NumCandidatesBefore << " candidates\n");
1066#endif
1067
1068 // If we made it unbeneficial to outline this function, skip it.
1069 if (OF->getBenefit() < OutlinerBenefitThreshold) {
1070 LLVM_DEBUG(dbgs() << "SKIP: Expected benefit (" << OF->getBenefit()
1071 << " B) < threshold (" << OutlinerBenefitThreshold
1072 << " B)\n");
1073 continue;
1074 }
1075
1076 LLVM_DEBUG(dbgs() << "OUTLINE: Expected benefit (" << OF->getBenefit()
1077 << " B) > threshold (" << OutlinerBenefitThreshold
1078 << " B)\n");
1079
1080 // Remove all Linker Optimization Hints from the candidates.
1081 // TODO: The intersection of the LOHs from all candidates should be legal in
1082 // the outlined function.
1084 for (Candidate &C : OF->Candidates) {
1085 for (MachineInstr &MI : C)
1086 MIs.insert(&MI);
1087 NumRemovedLOHs += TM->clearLinkerOptimizationHints(MIs);
1088 MIs.clear();
1089 }
1090
1091 // It's beneficial. Create the function and outline its sequence's
1092 // occurrences.
1093 OF->MF = createOutlinedFunction(M, *OF, Mapper, OutlinedFunctionNum);
1094 emitOutlinedFunctionRemark(*OF);
1095 FunctionsCreated++;
1096 OutlinedFunctionNum++; // Created a function, move to the next name.
1097 MachineFunction *MF = OF->MF;
1098 const TargetSubtargetInfo &STI = MF->getSubtarget();
1099 const TargetInstrInfo &TII = *STI.getInstrInfo();
1100
1101 // Replace occurrences of the sequence with calls to the new function.
1102 LLVM_DEBUG(dbgs() << "CREATE OUTLINED CALLS\n");
1103 for (Candidate &C : OF->Candidates) {
1104 MachineBasicBlock &MBB = *C.getMBB();
1105 MachineBasicBlock::iterator StartIt = C.begin();
1106 MachineBasicBlock::iterator EndIt = std::prev(C.end());
1107
1108 // Insert the call.
1109 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
1110// Insert the call.
1111#ifndef NDEBUG
1112 auto MBBBeingOutlinedFromName =
1113 MBB.getName().empty() ? "<unknown>" : MBB.getName().str();
1114 auto MFBeingOutlinedFromName = MBB.getParent()->getName().empty()
1115 ? "<unknown>"
1116 : MBB.getParent()->getName().str();
1117 LLVM_DEBUG(dbgs() << " CALL: " << MF->getName() << " in "
1118 << MFBeingOutlinedFromName << ":"
1119 << MBBBeingOutlinedFromName << "\n");
1120 LLVM_DEBUG(dbgs() << " .. " << *CallInst);
1121#endif
1122
1123 // If the caller tracks liveness, then we need to make sure that
1124 // anything we outline doesn't break liveness assumptions. The outlined
1125 // functions themselves currently don't track liveness, but we should
1126 // make sure that the ranges we yank things out of aren't wrong.
1127 if (MBB.getParent()->getProperties().hasTracksLiveness()) {
1128 // The following code is to add implicit def operands to the call
1129 // instruction. It also updates call site information for moved
1130 // code.
1131 SmallSet<Register, 2> UseRegs, DefRegs;
1132 // Copy over the defs in the outlined range.
1133 // First inst in outlined range <-- Anything that's defined in this
1134 // ... .. range has to be added as an
1135 // implicit Last inst in outlined range <-- def to the call
1136 // instruction. Also remove call site information for outlined block
1137 // of code. The exposed uses need to be copied in the outlined range.
1139 Iter = EndIt.getReverse(),
1140 Last = std::next(CallInst.getReverse());
1141 Iter != Last; Iter++) {
1142 MachineInstr *MI = &*Iter;
1143 SmallSet<Register, 2> InstrUseRegs;
1144 for (MachineOperand &MOP : MI->operands()) {
1145 // Skip over anything that isn't a register.
1146 if (!MOP.isReg())
1147 continue;
1148
1149 if (MOP.isDef()) {
1150 // Introduce DefRegs set to skip the redundant register.
1151 DefRegs.insert(MOP.getReg());
1152 if (UseRegs.count(MOP.getReg()) &&
1153 !InstrUseRegs.count(MOP.getReg()))
1154 // Since the regiester is modeled as defined,
1155 // it is not necessary to be put in use register set.
1156 UseRegs.erase(MOP.getReg());
1157 } else if (!MOP.isUndef()) {
1158 // Any register which is not undefined should
1159 // be put in the use register set.
1160 UseRegs.insert(MOP.getReg());
1161 InstrUseRegs.insert(MOP.getReg());
1162 }
1163 }
1164 if (MI->isCandidateForAdditionalCallInfo())
1165 MI->getMF()->eraseAdditionalCallInfo(MI);
1166 }
1167
1168 for (const Register &I : DefRegs)
1169 // If it's a def, add it to the call instruction.
1170 CallInst->addOperand(
1171 MachineOperand::CreateReg(I, true, /* isDef = true */
1172 true /* isImp = true */));
1173
1174 for (const Register &I : UseRegs)
1175 // If it's a exposed use, add it to the call instruction.
1176 CallInst->addOperand(
1177 MachineOperand::CreateReg(I, false, /* isDef = false */
1178 true /* isImp = true */));
1179 }
1180
1181 // Erase from the point after where the call was inserted up to, and
1182 // including, the final instruction in the sequence.
1183 // Erase needs one past the end, so we need std::next there too.
1184 MBB.erase(std::next(StartIt), std::next(EndIt));
1185
1186 // Keep track of what we removed by marking them all as -1.
1187 for (unsigned &I : make_range(UnsignedVecBegin + C.getStartIdx(),
1188 UnsignedVecBegin + C.getEndIdx() + 1))
1189 I = static_cast<unsigned>(-1);
1190 OutlinedSomething = true;
1191
1192 // Statistics.
1193 NumOutlined++;
1194 }
1195 }
1196
1197 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n");
1198 return OutlinedSomething;
1199}
1200
1201void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M) {
1202 // Build instruction mappings for each function in the module. Start by
1203 // iterating over each Function in M.
1204 LLVM_DEBUG(dbgs() << "*** Populating mapper ***\n");
1205 for (Function &F : M) {
1206 LLVM_DEBUG(dbgs() << "MAPPING FUNCTION: " << F.getName() << "\n");
1207
1208 if (F.hasFnAttribute("nooutline")) {
1209 LLVM_DEBUG(dbgs() << "SKIP: Function has nooutline attribute\n");
1210 continue;
1211 }
1212
1213 // There's something in F. Check if it has a MachineFunction associated with
1214 // it.
1216
1217 // If it doesn't, then there's nothing to outline from. Move to the next
1218 // Function.
1219 if (!MF) {
1220 LLVM_DEBUG(dbgs() << "SKIP: Function does not have a MachineFunction\n");
1221 continue;
1222 }
1223
1225 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF)) {
1226 LLVM_DEBUG(dbgs() << "SKIP: Target does not want to outline from "
1227 "function by default\n");
1228 continue;
1229 }
1230
1231 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1232 // If it isn't, then move on to the next Function in the module.
1233 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) {
1234 LLVM_DEBUG(dbgs() << "SKIP: " << MF->getName()
1235 << ": unsafe to outline from\n");
1236 continue;
1237 }
1238
1239 // We have a function suitable for outlining. Iterate over every
1240 // MachineBasicBlock in MF and try to map its instructions to a list of
1241 // unsigned integers.
1242 const unsigned MinMBBSize = 2;
1243
1244 for (MachineBasicBlock &MBB : *MF) {
1245 LLVM_DEBUG(dbgs() << " MAPPING MBB: '" << MBB.getName() << "'\n");
1246 // If there isn't anything in MBB, then there's no point in outlining from
1247 // it.
1248 // If there are fewer than 2 instructions in the MBB, then it can't ever
1249 // contain something worth outlining.
1250 // FIXME: This should be based off of the maximum size in B of an outlined
1251 // call versus the size in B of the MBB.
1252 if (MBB.size() < MinMBBSize) {
1253 LLVM_DEBUG(dbgs() << " SKIP: MBB size less than minimum size of "
1254 << MinMBBSize << "\n");
1255 continue;
1256 }
1257
1258 // Check if MBB could be the target of an indirect branch. If it is, then
1259 // we don't want to outline from it.
1260 if (MBB.hasAddressTaken()) {
1261 LLVM_DEBUG(dbgs() << " SKIP: MBB's address is taken\n");
1262 continue;
1263 }
1264
1265 // MBB is suitable for outlining. Map it to a list of unsigneds.
1266 Mapper.convertToUnsignedVec(MBB, *TII);
1267 }
1268 }
1269 // Statistics.
1270 UnsignedVecSize = Mapper.UnsignedVec.size();
1271}
1272
1273void MachineOutliner::initSizeRemarkInfo(
1274 const Module &M, StringMap<unsigned> &FunctionToInstrCount) {
1275 // Collect instruction counts for every function. We'll use this to emit
1276 // per-function size remarks later.
1277 for (const Function &F : M) {
1279
1280 // We only care about MI counts here. If there's no MachineFunction at this
1281 // point, then there won't be after the outliner runs, so let's move on.
1282 if (!MF)
1283 continue;
1284 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1285 }
1286}
1287
1288void MachineOutliner::emitInstrCountChangedRemark(
1289 const Module &M, const StringMap<unsigned> &FunctionToInstrCount) {
1290 // Iterate over each function in the module and emit remarks.
1291 // Note that we won't miss anything by doing this, because the outliner never
1292 // deletes functions.
1293 for (const Function &F : M) {
1295
1296 // The outliner never deletes functions. If we don't have a MF here, then we
1297 // didn't have one prior to outlining either.
1298 if (!MF)
1299 continue;
1300
1301 std::string Fname = std::string(F.getName());
1302 unsigned FnCountAfter = MF->getInstructionCount();
1303 unsigned FnCountBefore = 0;
1304
1305 // Check if the function was recorded before.
1306 auto It = FunctionToInstrCount.find(Fname);
1307
1308 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1309 // to that.
1310 if (It != FunctionToInstrCount.end())
1311 FnCountBefore = It->second;
1312
1313 // Compute the delta and emit a remark if there was a change.
1314 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1315 static_cast<int64_t>(FnCountBefore);
1316 if (FnDelta == 0)
1317 continue;
1318
1320 MORE.emit([&]() {
1321 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1322 DiagnosticLocation(), &MF->front());
1323 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1324 << ": Function: "
1325 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1326 << ": MI instruction count changed from "
1327 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1328 FnCountBefore)
1329 << " to "
1331 FnCountAfter)
1332 << "; Delta: "
1333 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1334 return R;
1335 });
1336 }
1337}
1338
1339void MachineOutliner::initializeOutlinerMode(const Module &M) {
1341 return;
1342
1343 if (auto *IndexWrapperPass =
1344 getAnalysisIfAvailable<ImmutableModuleSummaryIndexWrapperPass>()) {
1345 auto *TheIndex = IndexWrapperPass->getIndex();
1346 // (Full)LTO module does not have functions added to the index.
1347 // In this case, we run the outliner without using codegen data as usual.
1348 if (TheIndex && !TheIndex->hasExportedFunctions(M))
1349 return;
1350 }
1351
1352 // When codegen data write is enabled, we want to write the local outlined
1353 // hash tree to the custom section, `__llvm_outline`.
1354 // When the outlined hash tree is available from the previous codegen data,
1355 // we want to read it to optimistically create global outlining candidates.
1356 if (cgdata::emitCGData()) {
1357 OutlinerMode = CGDataMode::Write;
1358 // Create a local outlined hash tree to be published.
1359 LocalHashTree = std::make_unique<OutlinedHashTree>();
1360 // We don't need to read the outlined hash tree from the previous codegen
1361 } else if (cgdata::hasOutlinedHashTree())
1362 OutlinerMode = CGDataMode::Read;
1363}
1364
1365void MachineOutliner::emitOutlinedHashTree(Module &M) {
1366 assert(LocalHashTree);
1367 if (!LocalHashTree->empty()) {
1368 LLVM_DEBUG({
1369 dbgs() << "Emit outlined hash tree. Size: " << LocalHashTree->size()
1370 << "\n";
1371 });
1374
1375 OutlinedHashTreeRecord HTR(std::move(LocalHashTree));
1376 HTR.serialize(OS);
1377
1378 llvm::StringRef Data(Buf.data(), Buf.size());
1379 std::unique_ptr<MemoryBuffer> Buffer =
1380 MemoryBuffer::getMemBuffer(Data, "in-memory outlined hash tree", false);
1381
1382 Triple TT(M.getTargetTriple());
1384 M, *Buffer,
1385 getCodeGenDataSectionName(CG_outline, TT.getObjectFormat()));
1386 }
1387}
1388
1389bool MachineOutliner::runOnModule(Module &M) {
1390 if (skipModule(M))
1391 return false;
1392
1393 // Check if there's anything in the module. If it's empty, then there's
1394 // nothing to outline.
1395 if (M.empty())
1396 return false;
1397
1398 // Initialize the outliner mode.
1399 initializeOutlinerMode(M);
1400
1401 MMI = &getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1402 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
1403
1404 // Number to append to the current outlined function.
1405 unsigned OutlinedFunctionNum = 0;
1406
1407 OutlineRepeatedNum = 0;
1408 if (!doOutline(M, OutlinedFunctionNum))
1409 return false;
1410
1411 for (unsigned I = 0; I < OutlinerReruns; ++I) {
1412 OutlinedFunctionNum = 0;
1413 OutlineRepeatedNum++;
1414 if (!doOutline(M, OutlinedFunctionNum)) {
1415 LLVM_DEBUG({
1416 dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1417 << OutlinerReruns + 1 << "\n";
1418 });
1419 break;
1420 }
1421 }
1422
1423 if (OutlinerMode == CGDataMode::Write)
1424 emitOutlinedHashTree(M);
1425
1426 return true;
1427}
1428
1429bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1430 // If the user passed -enable-machine-outliner=always or
1431 // -enable-machine-outliner, the pass will run on all functions in the module.
1432 // Otherwise, if the target supports default outlining, it will run on all
1433 // functions deemed by the target to be worth outlining from by default. Tell
1434 // the user how the outliner is running.
1435 LLVM_DEBUG({
1436 dbgs() << "Machine Outliner: Running on ";
1437 if (RunOnAllFunctions)
1438 dbgs() << "all functions";
1439 else
1440 dbgs() << "target-default functions";
1441 dbgs() << "\n";
1442 });
1443
1444 // If the user specifies that they want to outline from linkonceodrs, set
1445 // it here.
1446 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1447 InstructionMapper Mapper(*MMI);
1448
1449 // Prepare instruction mappings for the suffix tree.
1450 populateMapper(Mapper, M);
1451 std::vector<std::unique_ptr<OutlinedFunction>> FunctionList;
1452
1453 // Find all of the outlining candidates.
1454 if (OutlinerMode == CGDataMode::Read)
1455 findGlobalCandidates(Mapper, FunctionList);
1456 else
1457 findCandidates(Mapper, FunctionList);
1458
1459 // If we've requested size remarks, then collect the MI counts of every
1460 // function before outlining, and the MI counts after outlining.
1461 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1462 // the pass manager's responsibility.
1463 // This could pretty easily be placed in outline instead, but because we
1464 // really ultimately *don't* want this here, it's done like this for now
1465 // instead.
1466
1467 // Check if we want size remarks.
1468 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1469 StringMap<unsigned> FunctionToInstrCount;
1470 if (ShouldEmitSizeRemarks)
1471 initSizeRemarkInfo(M, FunctionToInstrCount);
1472
1473 // Outline each of the candidates and return true if something was outlined.
1474 bool OutlinedSomething =
1475 outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1476
1477 // If we outlined something, we definitely changed the MI count of the
1478 // module. If we've asked for size remarks, then output them.
1479 // FIXME: This should be in the pass manager.
1480 if (ShouldEmitSizeRemarks && OutlinedSomething)
1481 emitInstrCountChangedRemark(M, FunctionToInstrCount);
1482
1483 LLVM_DEBUG({
1484 if (!OutlinedSomething)
1485 dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1486 << " because no changes were found.\n";
1487 });
1488
1489 return OutlinedSomething;
1490}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the DenseMap class.
std::string Name
uint64_t Size
const HexagonInstrInfo * TII
static DISubprogram * getSubprogramOrNull(OutlinableGroup &Group)
Get the subprogram if it exists for one of the outlined regions.
Definition: IROutliner.cpp:620
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
static cl::opt< bool > DisableGlobalOutlining("disable-global-outlining", cl::Hidden, cl::desc("Disable global outlining only by ignoring " "the codegen data generation or use"), cl::init(false))
static cl::opt< unsigned > OutlinerBenefitThreshold("outliner-benefit-threshold", cl::init(1), cl::Hidden, cl::desc("The minimum size in bytes before an outlining candidate is accepted"))
static cl::opt< bool > OutlinerLeafDescendants("outliner-leaf-descendants", cl::init(true), cl::Hidden, cl::desc("Consider all leaf descendants of internal nodes of the suffix " "tree as candidates for outlining (if false, only leaf children " "are considered)"))
static cl::opt< bool > AppendContentHashToOutlinedName("append-content-hash-outlined-name", cl::Hidden, cl::desc("This appends the content hash to the globally outlined function " "name. It's beneficial for enhancing the precision of the stable " "hash and for ordering the outlined functions."), cl::init(true))
static cl::opt< unsigned > OutlinerReruns("machine-outliner-reruns", cl::init(0), cl::Hidden, cl::desc("Number of times to rerun the outliner after the initial outline"))
Number of times to re-run the outliner.
#define DEBUG_TYPE
static cl::opt< bool > EnableLinkOnceODROutlining("enable-linkonceodr-outlining", cl::Hidden, cl::desc("Enable the machine outliner on linkonceodr functions"), cl::init(false))
static SmallVector< MatchedEntry > getMatchedEntries(InstructionMapper &Mapper)
Contains all data structures shared between the outliner implemented in MachineOutliner....
Register const TargetRegisterInfo * TRI
This is the interface to build a ModuleSummaryIndex for a module.
static Expected< Function * > createOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, StringRef FuncName, SmallVectorImpl< Value * > &Inputs, OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc, OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
raw_pwrite_stream & OS
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:206
This class represents a function call, abstracting a target machine's calling convention.
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
Subprogram description. Uses SubclassData1.
A debug info location.
Definition: DebugLoc.h:124
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:166
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:60
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2780
Legacy wrapper pass to provide the ModuleSummaryIndex object.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:52
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
unsigned getInstructionCount() const
Return the number of MachineInstrs in this MachineFunction.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
Definition: MachineInstr.h:72
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:359
bool isDebugInstr() const
LLVM_ABI void dropMemRefs(MachineFunction &MF)
Clear this MachineInstr's memory reference descriptor list.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
This class contains meta information specific to a module.
LLVM_ABI MachineFunction & getOrCreateMachineFunction(Function &F)
Returns the MachineFunction constructed for the IR function F.
LLVM_ABI MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr.
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
Diagnostic information for optimization analysis remarks.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:121
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:255
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
const HashNode * getRoot() const
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:112
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:85
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:401
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:176
bool erase(const T &V)
Definition: SmallSet.h:198
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:182
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:133
iterator end()
Definition: StringMap.h:224
iterator find(StringRef Key)
Definition: StringMap.h:237
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:233
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:83
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:692
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
SmallVector< const MachineInstr * > InstrList
bool hasOutlinedHashTree()
Definition: CodeGenData.h:172
const OutlinedHashTree * getOutlinedHashTree()
Definition: CodeGenData.h:180
bool emitCGData()
Definition: CodeGenData.h:188
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Length
Definition: DWP.cpp:477
void stable_sort(R &&Range)
Definition: STLExtras.h:2077
CGDataMode
Definition: CodeGenData.h:106
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2155
LLVM_ABI void initializeMachineOutlinerPass(PassRegistry &)
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
UWTableKind
Definition: CodeGen.h:148
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
LLVM_ABI stable_hash stableHashValue(const MachineOperand &MO)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
LLVM_ABI ModulePass * createMachineOutlinerPass(bool RunOnAllFunctions=true)
This pass performs outlining on machine instructions directly before printing assembly.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2139
stable_hash stable_hash_combine(ArrayRef< stable_hash > Buffer)
Definition: StableHashing.h:30
LLVM_ABI void embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName, Align Alignment=Align(1))
Embed the memory buffer Buf into the module M as a global using the specified section name.
void addLiveIns(MachineBasicBlock &MBB, const LivePhysRegs &LiveRegs)
Adds registers contained in LiveRegs to the block live-in list of MBB.
LLVM_ABI std::string getCodeGenDataSectionName(CGDataSectKind CGSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
#define MORE()
Definition: regcomp.c:246
MatchedEntry()=delete
MatchedEntry(unsigned StartIdx, unsigned EndIdx, unsigned Count)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:54
Used in the streaming interface as the general argument type.
A HashNode is an entry in an OutlinedHashTree, holding a hash value and a collection of Successors (o...
std::optional< unsigned > Terminals
The number of terminals in the sequence ending at this node.
A repeated substring in the tree.
Definition: SuffixTree.h:50
An individual sequence of instructions to be replaced with a call to an outlined function.
MachineFunction * getMF() const
The information necessary to create an outlined function for some class of candidate.