84 #include <system_error> 89 using namespace sampleprof;
91 #define DEBUG_TYPE "sample-profile" 100 "sample-profile-max-propagate-iterations",
cl::init(100),
101 cl::desc(
"Maximum number of iterations to go through when propagating " 102 "sample block/edge weights through the CFG."));
106 cl::desc(
"Emit a warning if less than N% of records in the input profile " 107 "are matched to the IR."));
111 cl::desc(
"Emit a warning if less than N% of samples in the input profile " 112 "are matched to the IR."));
116 cl::desc(
"Use this option to turn off/on warnings about function with " 117 "samples but without debug information to use those samples. "));
123 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
128 class SampleCoverageTracker {
130 SampleCoverageTracker() =
default;
133 uint32_t Discriminator, uint64_t Samples);
134 unsigned computeCoverage(
unsigned Used,
unsigned Total)
const;
139 uint64_t getTotalUsedSamples()
const {
return TotalUsedSamples; }
144 SampleCoverage.clear();
145 TotalUsedSamples = 0;
149 using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
150 using FunctionSamplesCoverageMap =
162 FunctionSamplesCoverageMap SampleCoverage;
175 uint64_t TotalUsedSamples = 0;
183 class SampleProfileLoader {
189 : GetAC(
std::move(GetAssumptionCache)),
190 GetTTI(
std::move(GetTargetTransformInfo)), Filename(Name),
191 IsThinLTOPreLink(IsThinLTOPreLink) {}
193 bool doInitialization(
Module &M);
197 void dump() { Reader->dump(); }
206 std::vector<const FunctionSamples *>
207 findIndirectCallFunctionSamples(
const Instruction &
I, uint64_t &Sum)
const;
216 void findEquivalenceClasses(
Function &
F);
217 template <
bool IsPostDom>
222 uint64_t visitEdge(Edge
E,
unsigned *NumUnknownEdges, Edge *UnknownEdge);
224 bool propagateThroughEdges(
Function &
F,
bool UpdateBlockCount);
225 void computeDominanceAndLoopInfo(
Function &
F);
226 void clearFunctionData();
232 BlockWeightMap BlockWeights;
238 EdgeWeightMap EdgeWeights;
252 EquivalenceClassMap EquivalenceClass;
261 std::unique_ptr<DominatorTree> DT;
262 std::unique_ptr<PostDominatorTree> PDT;
263 std::unique_ptr<LoopInfo> LI;
265 std::function<AssumptionCache &(Function &)> GetAC;
266 std::function<TargetTransformInfo &(Function &)> GetTTI;
269 BlockEdgeMap Predecessors;
272 BlockEdgeMap Successors;
274 SampleCoverageTracker CoverageTracker;
277 std::unique_ptr<SampleProfileReader> Reader;
283 std::string Filename;
286 bool ProfileIsValid =
false;
292 bool IsThinLTOPreLink;
301 uint64_t TotalCollectedSamples = 0;
307 class SampleProfileLoaderLegacyPass :
public ModulePass {
313 bool IsThinLTOPreLink =
false)
314 :
ModulePass(ID), SampleLoader(Name, IsThinLTOPreLink,
316 return ACT->getAssumptionCache(
F);
319 return TTIWP->getTTI(
F);
325 void dump() { SampleLoader.dump(); }
327 bool doInitialization(
Module &M)
override {
328 return SampleLoader.doInitialization(M);
331 StringRef getPassName()
const override {
return "Sample profile pass"; }
332 bool runOnModule(
Module &M)
override;
341 SampleProfileLoader SampleLoader;
364 assert(PSI &&
"PSI is expected to be non null");
378 unsigned &Count = SampleCoverage[FS][Loc];
379 bool FirstTime = (++Count == 1);
381 TotalUsedSamples += Samples;
391 auto I = SampleCoverage.find(FS);
395 unsigned Count = (
I != SampleCoverage.end()) ?
I->second.size() : 0;
401 for (
const auto &J :
I.second) {
404 Count += countUsedRecords(CalleeSamples, PSI);
420 for (
const auto &J :
I.second) {
423 Count += countBodyRecords(CalleeSamples, PSI);
437 Total +=
I.second.getSamples();
441 for (
const auto &J :
I.second) {
444 Total += countBodySamples(CalleeSamples, PSI);
455 unsigned SampleCoverageTracker::computeCoverage(
unsigned Used,
456 unsigned Total)
const {
458 "number of used records cannot exceed the total number of records");
459 return Total > 0 ? Used * 100 / Total : 100;
463 void SampleProfileLoader::clearFunctionData() {
464 BlockWeights.clear();
466 VisitedBlocks.clear();
467 VisitedEdges.clear();
468 EquivalenceClass.clear();
472 Predecessors.clear();
474 CoverageTracker.clear();
482 void SampleProfileLoader::printEdgeWeight(
raw_ostream &OS, Edge
E) {
483 OS <<
"weight[" << E.first->getName() <<
"->" << E.second->getName()
484 <<
"]: " << EdgeWeights[
E] <<
"\n";
491 void SampleProfileLoader::printBlockEquivalence(
raw_ostream &OS,
493 const BasicBlock *Equiv = EquivalenceClass[BB];
494 OS <<
"equivalence[" << BB->
getName()
495 <<
"]: " << ((Equiv) ? EquivalenceClass[BB]->
getName() :
"NONE") <<
"\n";
502 void SampleProfileLoader::printBlockWeight(
raw_ostream &OS,
504 const auto &
I = BlockWeights.find(BB);
505 uint64_t
W = (
I == BlockWeights.end() ? 0 :
I->second);
506 OS <<
"weight[" << BB->
getName() <<
"]: " << W <<
"\n";
524 return std::error_code();
528 return std::error_code();
533 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst))
534 return std::error_code();
540 if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
542 findCalleeFunctionSamples(Inst))
551 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.
get());
555 Remark <<
"Applied " <<
ore::NV(
"NumSamples", *R);
556 Remark <<
" samples from profile (offset: ";
557 Remark <<
ore::NV(
"LineOffset", LineOffset);
560 Remark <<
ore::NV(
"Discriminator", Discriminator);
568 <<
" (line offset: " << LineOffset <<
"." 585 bool HasWeight =
false;
602 bool SampleProfileLoader::computeBlockWeights(
Function &
F) {
603 bool Changed =
false;
605 for (
const auto &BB : F) {
608 BlockWeights[&BB] = Weight.
get();
609 VisitedBlocks.insert(&BB);
631 SampleProfileLoader::findCalleeFunctionSamples(
const Instruction &Inst)
const {
638 if (
const CallInst *CI = dyn_cast<CallInst>(&Inst))
646 std::string CalleeGUID;
647 CalleeName =
getRepInFormat(CalleeName, Reader->getFormat(), CalleeGUID);
656 std::vector<const FunctionSamples *>
657 SampleProfileLoader::findIndirectCallFunctionSamples(
660 std::vector<const FunctionSamples *> R;
676 for (
const auto &T_C :
T.get())
682 for (
const auto &NameFS : *M) {
683 Sum += NameFS.second.getEntrySamples();
684 R.push_back(&NameFS.second);
704 SampleProfileLoader::findFunctionSamples(
const Instruction &Inst)
const {
710 return Samples->findFunctionSamples(DIL);
713 bool SampleProfileLoader::inlineCallInstruction(
Instruction *
I) {
714 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
729 None,
nullptr,
nullptr);
732 <<
"incompatible inlining");
739 <<
"inlined hot callee '" <<
ore::NV(
"Callee", CalledFunction)
759 bool SampleProfileLoader::inlineHotFunctions(
762 bool Changed =
false;
765 bool LocalChanged =
false;
772 if ((isa<CallInst>(I) || isa<InvokeInst>(I)) &&
773 !isa<IntrinsicInst>(
I) && (FS = findCalleeFunctionSamples(I))) {
786 if (CalledFunction == &F)
789 if (PromotedInsns.
count(I))
792 for (
const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
793 if (IsThinLTOPreLink) {
799 auto CalleeFunctionName = FS->
getName();
806 auto Fname =
getRepInFormat(F.getName(), Reader->getFormat(), FGUID);
807 if (CalleeFunctionName == Fname)
810 const char *Reason =
"Callee function not available";
811 auto R =
SymbolMap.find(CalleeFunctionName);
812 if (R !=
SymbolMap.end() && R->getValue() &&
813 !R->getValue()->isDeclaration() &&
814 R->getValue()->getSubprogram() &&
822 if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
823 inlineCallInstruction(DI))
827 <<
"\nFailed to promote indirect call to " 828 << CalleeFunctionName <<
" because " << Reason <<
"\n");
831 }
else if (CalledFunction && CalledFunction->
getSubprogram() &&
833 if (inlineCallInstruction(I))
835 }
else if (IsThinLTOPreLink) {
836 findCalleeFunctionSamples(*I)->findInlinedFunctions(
873 template <
bool IsPostDom>
874 void SampleProfileLoader::findEquivalencesFor(
878 uint64_t Weight = BlockWeights[EC];
879 for (
const auto *BB2 : Descendants) {
880 bool IsDomParent = DomTree->
dominates(BB2, BB1);
881 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
882 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
883 EquivalenceClass[BB2] = EC;
885 if (VisitedBlocks.count(BB2)) {
886 VisitedBlocks.insert(EC);
897 Weight =
std::max(Weight, BlockWeights[BB2]);
901 BlockWeights[EC] = Samples->getHeadSamples() + 1;
903 BlockWeights[EC] = Weight;
916 void SampleProfileLoader::findEquivalenceClasses(
Function &F) {
924 if (EquivalenceClass.count(BB1)) {
930 EquivalenceClass[BB1] = BB1;
942 DominatedBBs.
clear();
943 DT->getDescendants(BB1, DominatedBBs);
944 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
956 dbgs() <<
"\nAssign the same weight to all blocks in the same class\n");
959 const BasicBlock *EquivBB = EquivalenceClass[BB];
961 BlockWeights[BB] = BlockWeights[EquivBB];
976 uint64_t SampleProfileLoader::visitEdge(Edge E,
unsigned *NumUnknownEdges,
978 if (!VisitedEdges.count(E)) {
979 (*NumUnknownEdges)++;
984 return EdgeWeights[
E];
1000 bool SampleProfileLoader::propagateThroughEdges(
Function &F,
1001 bool UpdateBlockCount) {
1002 bool Changed =
false;
1004 for (
const auto &BI : F) {
1013 for (
unsigned i = 0; i < 2; i++) {
1014 uint64_t TotalWeight = 0;
1015 unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1016 Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
1020 NumTotalEdges = Predecessors[BB].size();
1021 for (
auto *Pred : Predecessors[BB]) {
1022 Edge E = std::make_pair(Pred, BB);
1023 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1024 if (E.first == E.second)
1025 SelfReferentialEdge =
E;
1027 if (NumTotalEdges == 1) {
1028 SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1032 NumTotalEdges = Successors[BB].size();
1033 for (
auto *Succ : Successors[BB]) {
1034 Edge E = std::make_pair(BB, Succ);
1035 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1037 if (NumTotalEdges == 1) {
1038 SingleEdge = std::make_pair(BB, Successors[BB][0]);
1065 if (NumUnknownEdges <= 1) {
1066 uint64_t &BBWeight = BlockWeights[EC];
1067 if (NumUnknownEdges == 0) {
1068 if (!VisitedBlocks.count(EC)) {
1072 if (TotalWeight > BBWeight) {
1073 BBWeight = TotalWeight;
1076 <<
" known. Set weight for block: ";
1077 printBlockWeight(
dbgs(), BB););
1079 }
else if (NumTotalEdges == 1 &&
1080 EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1083 EdgeWeights[SingleEdge] = BlockWeights[EC];
1086 }
else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
1089 if (BBWeight >= TotalWeight)
1090 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1092 EdgeWeights[UnknownEdge] = 0;
1095 OtherEC = EquivalenceClass[UnknownEdge.first];
1097 OtherEC = EquivalenceClass[UnknownEdge.second];
1099 if (VisitedBlocks.count(OtherEC) &&
1100 EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1101 EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
1102 VisitedEdges.insert(UnknownEdge);
1105 printEdgeWeight(
dbgs(), UnknownEdge));
1107 }
else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1110 for (
auto *Pred : Predecessors[BB]) {
1111 Edge E = std::make_pair(Pred, BB);
1113 VisitedEdges.insert(E);
1116 for (
auto *Succ : Successors[BB]) {
1117 Edge E = std::make_pair(BB, Succ);
1119 VisitedEdges.insert(E);
1122 }
else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
1123 uint64_t &BBWeight = BlockWeights[BB];
1125 if (BBWeight >= TotalWeight)
1126 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1128 EdgeWeights[SelfReferentialEdge] = 0;
1129 VisitedEdges.insert(SelfReferentialEdge);
1132 printEdgeWeight(
dbgs(), SelfReferentialEdge));
1134 if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1135 BlockWeights[EC] = TotalWeight;
1136 VisitedBlocks.insert(EC);
1149 void SampleProfileLoader::buildEdges(
Function &F) {
1150 for (
auto &BI : F) {
1155 if (!Predecessors[B1].empty())
1159 if (Visited.
insert(B2).second)
1160 Predecessors[B1].push_back(B2);
1165 if (!Successors[B1].empty())
1169 if (Visited.
insert(B2).second)
1170 Successors[B1].push_back(B2);
1179 for (
auto I = M.
begin(); I != M.
end(); ++
I)
1180 R.
push_back({Function::getGUID(I->getKey()), I->getValue()});
1182 [](
const InstrProfValueData &L,
const InstrProfValueData &R) {
1183 if (L.Count == R.Count)
1184 return L.Value > R.Value;
1186 return L.Count > R.Count;
1208 void SampleProfileLoader::propagateWeights(
Function &F) {
1209 bool Changed =
true;
1214 for (
auto &BI : F) {
1216 Loop *L = LI->getLoopFor(BB);
1221 if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1222 BlockWeights[Header] = BlockWeights[BB];
1235 Changed = propagateThroughEdges(F,
false);
1241 VisitedEdges.clear();
1244 Changed = propagateThroughEdges(F,
false);
1251 Changed = propagateThroughEdges(F,
true);
1256 LLVM_DEBUG(
dbgs() <<
"\nPropagation complete. Setting branch weights\n");
1259 for (
auto &BI : F) {
1262 if (BlockWeights[BB]) {
1263 for (
auto &I : BB->getInstList()) {
1264 if (!isa<CallInst>(I) && !isa<InvokeInst>(
I))
1268 const DebugLoc &DLoc = I.getDebugLoc();
1279 if (!
T ||
T.get().empty())
1284 findIndirectCallFunctionSamples(I, Sum);
1286 SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1287 SortedCallTargets.
size());
1288 }
else if (!dyn_cast<IntrinsicInst>(&I)) {
1298 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1304 :
Twine(
"<UNKNOWN LOCATION>"))
1311 Edge E = std::make_pair(BB, Succ);
1312 uint64_t Weight = EdgeWeights[
E];
1323 Weights.
push_back(static_cast<uint32_t>(Weight + 1));
1325 if (Weight > MaxWeight) {
1332 uint64_t TempWeight;
1344 <<
"most popular destination for conditional branches at " 1345 <<
ore::NV(
"CondBranchesLoc", BranchLoc);
1364 unsigned SampleProfileLoader::getFunctionLoc(
Function &F) {
1366 return S->getLine();
1374 "No debug information found in function " + F.
getName() +
1375 ": Function profile not used",
1380 void SampleProfileLoader::computeDominanceAndLoopInfo(
Function &F) {
1439 bool SampleProfileLoader::emitAnnotations(
Function &F) {
1440 bool Changed =
false;
1442 if (getFunctionLoc(F) == 0)
1446 << F.
getName() <<
": " << getFunctionLoc(F) <<
"\n");
1449 Changed |= inlineHotFunctions(F, InlinedGUIDs);
1452 Changed |= computeBlockWeights(F);
1465 computeDominanceAndLoopInfo(F);
1468 findEquivalenceClasses(F);
1471 propagateWeights(F);
1476 unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1477 unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
1478 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1482 Twine(Used) +
" of " +
Twine(Total) +
" available profile records (" +
1483 Twine(Coverage) +
"%) were applied",
1489 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1490 uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
1491 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1495 Twine(Used) +
" of " +
Twine(Total) +
" available profile samples (" +
1496 Twine(Coverage) +
"%) were applied",
1506 "Sample Profile loader",
false,
false)
1513 bool SampleProfileLoader::doInitialization(
Module &M) {
1514 auto &Ctx = M.getContext();
1516 if (std::error_code EC = ReaderOrErr.getError()) {
1517 std::string Msg =
"Could not open profile: " + EC.message();
1521 Reader = std::move(ReaderOrErr.get());
1531 return new SampleProfileLoaderLegacyPass(Name);
1536 if (!ProfileIsValid)
1544 for (
const auto &
I : Reader->getProfiles())
1545 TotalCollectedSamples +=
I.second.getTotalSamples();
1554 auto pos = OrigName.
find(
'.');
1557 auto r =
SymbolMap.insert(std::make_pair(NewName, F));
1563 r.first->second =
nullptr;
1567 bool retval =
false;
1569 if (!
F.isDeclaration()) {
1570 clearFunctionData();
1576 bool SampleProfileLoaderLegacyPass::runOnModule(
Module &M) {
1577 ACT = &getAnalysis<AssumptionCacheTracker>();
1578 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1580 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1581 return SampleLoader.runOnModule(M,
nullptr, PSI);
1589 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1596 OwnedORE = make_unique<OptimizationRemarkEmitter>(&
F);
1597 ORE = OwnedORE.get();
1599 Samples = Reader->getSamplesFor(F);
1600 if (Samples && !Samples->empty())
1601 return emitAnnotations(F);
1617 SampleProfileLoader SampleLoader(
1619 IsThinLTOPreLink, GetAssumptionCache, GetTTI);
1621 SampleLoader.doInitialization(M);
1624 if (!SampleLoader.runOnModule(M, &AM, PSI))
void push_back(const T &Elt)
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const
Returns the FunctionSamplesMap at the given Loc.
Thresholds to tune inline cost analysis.
Represents either an error or a value T.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
static StringRef getRepInFormat(StringRef Name, SampleProfileFormat Format, std::string &GUIDBuf)
A Module instance is used to store all the information related to an LLVM module. ...
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
Implements a dense probed hash-table based set.
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
Analysis providing profile information.
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
bool isLegalToPromote(CallSite CS, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
static ErrorOr< std::unique_ptr< SampleProfileReader > > create(const Twine &Filename, LLVMContext &C)
Create a sample profile reader appropriate to the file format.
ErrorOr< uint64_t > findSamplesAt(uint32_t LineOffset, uint32_t Discriminator) const
Return the number of samples collected at the given location.
std::map< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
uint64_t getOrCompHotCountThreshold()
Returns HotCountThreshold if set.
const StringRef & getName() const
Return the function name.
static SmallVector< InstrProfValueData, 2 > SortCallTargets(const SampleRecord::CallTargetMap &M)
Returns the sorted CallTargetMap M by count in descending order.
InlineFunctionInfo - This class captures the data input to the InlineFunction call, and records the auxiliary results produced by it.
bool isHotCount(uint64_t C)
Returns true if F is a hot function.
Represents the cost of inlining a function.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Representation of the samples collected for a function.
bool InlineFunction(CallInst *C, InlineFunctionInfo &IFI, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true)
InlineFunction - This function inlines the called function into the basic block of the caller...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
LLVMContext & getContext() const
Get the global data context.
static StringRef getName(Value *V)
Metadata * getProfileSummary()
Returns profile summary metadata.
StringRef getFilename() const
BlockT * getHeader() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
static cl::opt< std::string > SampleProfileFile("sample-profile-file", cl::init(""), cl::value_desc("filename"), cl::desc("Profile file loaded by -sample-profile"), cl::Hidden)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
ModulePass * createSampleProfileLoaderPass()
Instruction * promoteIndirectCall(Instruction *Inst, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
amdgpu Simplify well known AMD library false Value * Callee
static cl::opt< unsigned > SampleProfileRecordCoverage("sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"), cl::desc("Emit a warning if less than N% of records in the input profile " "are matched to the IR."))
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Interval::succ_iterator succ_end(Interval *I)
Core dominator tree base class.
const BasicBlock & getEntryBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const Module *M, uint64_t Threshold, bool isCompact) const
Recursively traverses all children, if the total sample count of the corresponding function is no les...
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
static cl::opt< unsigned > SampleProfileMaxPropagateIterations("sample-profile-max-propagate-iterations", cl::init(100), cl::desc("Maximum number of iterations to go through when propagating " "sample block/edge weights through the CFG."))
DISubprogram * getSubprogram() const
Get the attached subprogram.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Function::ProfileCount ProfileCount
Represent the analysis usage information of a pass.
Interval::pred_iterator pred_end(Interval *I)
void initializeSampleProfileLoaderLegacyPassPass(PassRegistry &)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Used in the streaming interface as the general argument type.
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Class to represent profile counts.
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
InlineCost getInlineCost(CallSite CS, const InlineParams &Params, TargetTransformInfo &CalleeTTI, std::function< AssumptionCache &(Function &)> &GetAssumptionCache, Optional< function_ref< BlockFrequencyInfo &(Function &)>> GetBFI, ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
Optional< bool > ComputeFullInlineCost
Compute inline cost even when the cost has exceeded the threshold.
void sort(IteratorTy Start, IteratorTy End)
const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName) const
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName...
A function analysis which provides an AssumptionCache.
const InstListType & getInstList() const
Return the underlying instruction list container.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
static unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
ErrorOr< SampleRecord::CallTargetMap > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const
Returns the call target map collected at a given location.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
static void clear(coro::Shape &Shape)
iterator insert(iterator I, T &&Elt)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void setProfileSummary(Metadata *M)
Attach profile summary metadata to this module.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
unsigned getBaseDiscriminator() const
Returns the base discriminator stored in the discriminator.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represents the relative location of an instruction.
static cl::opt< unsigned > SampleProfileSampleCoverage("sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"), cl::desc("Emit a warning if less than N% of samples in the input profile " "are matched to the IR."))
static bool callsiteIsHot(const FunctionSamples *CallsiteFS, ProfileSummaryInfo *PSI)
Return true if the given callsite is hot wrt to hot cutoff threshold.
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
const Function * getParent() const
Return the enclosing method, or null if none.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
std::map< std::string, FunctionSamples > FunctionSamplesMap
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", "Sample Profile loader", false, false) INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Provides ErrorOr<T> smart pointer.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Module * getParent()
Get the module that this global value is contained inside of...
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
sample Sample Profile loader
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
This class implements an extremely fast bulk output stream that can only output to a stream...
print Print MemDeps of function
This file defines a set of templates that efficiently compute a dominator tree over a generic graph...
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
uint64_t getEntrySamples() const
Return the sample count of the first instruction of the function.
static cl::opt< bool > NoWarnSampleUnused("no-warn-sample-unused", cl::init(false), cl::Hidden, cl::desc("Use this option to turn off/on warnings about function with " "samples but without debug information to use those samples. "))
This header defines various interfaces for pass management in LLVM.
Diagnostic information for the sample profiler.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
This file provides the interface for the sampled PGO loader pass.
const BasicBlock * getParent() const
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...