LLVM 22.0.0git
CtxProfAnalysis.h
Go to the documentation of this file.
1//===- CtxProfAnalysis.h - maintain contextual profile info -*- 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#ifndef LLVM_ANALYSIS_CTXPROFANALYSIS_H
10#define LLVM_ANALYSIS_CTXPROFANALYSIS_H
11
12#include "llvm/ADT/SetVector.h"
13#include "llvm/IR/GlobalValue.h"
14#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/PassManager.h"
19#include <optional>
20
21namespace llvm {
22
23class CtxProfAnalysis;
24
28
29/// The instrumented contextual profile, produced by the CtxProfAnalysis.
31 friend class CtxProfAnalysis;
33 struct FunctionInfo {
34 uint32_t NextCounterIndex = 0;
35 uint32_t NextCallsiteIndex = 0;
36 const std::string Name;
38 FunctionInfo(StringRef Name) : Name(Name) {}
39 };
40 PGOCtxProfile Profiles;
41
42 // True if this module is a post-thinlto module containing just functions
43 // participating in one or more contextual profiles.
44 bool IsInSpecializedModule = false;
45
46 // For the GUIDs in this module, associate metadata about each function which
47 // we'll need when we maintain the profiles during IPO transformations.
48 std::map<GlobalValue::GUID, FunctionInfo> FuncInfo;
49
50 /// Get the GUID of this Function if it's defined in this module.
51 LLVM_ABI GlobalValue::GUID getDefinedFunctionGUID(const Function &F) const;
52
53 // This is meant to be constructed from CtxProfAnalysis, which will also set
54 // its state piecemeal.
55 PGOContextualProfile() = default;
56
57 void initIndex();
58
59public:
62
64 return Profiles.Contexts;
65 }
66
67 const PGOCtxProfile &profiles() const { return Profiles; }
68
70
71 bool isFunctionKnown(const Function &F) const {
72 return getDefinedFunctionGUID(F) != 0;
73 }
74
76 auto It = FuncInfo.find(GUID);
77 if (It == FuncInfo.end())
78 return "";
79 return It->second.Name;
80 }
81
84 return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCounterIndex;
85 }
86
89 return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCallsiteIndex;
90 }
91
94 return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCounterIndex++;
95 }
96
99 return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCallsiteIndex++;
100 }
101
104
105 LLVM_ABI void update(Visitor, const Function &F);
106 LLVM_ABI void visit(ConstVisitor, const Function *F = nullptr) const;
107
108 LLVM_ABI const CtxProfFlatProfile flatten() const;
110
113 // Check whether the analysis has been explicitly invalidated. Otherwise,
114 // it's stateless and remains preserved.
115 auto PAC = PA.getChecker<CtxProfAnalysis>();
116 return !PAC.preservedWhenStateless();
117 }
118};
119
120class CtxProfAnalysis : public AnalysisInfoMixin<CtxProfAnalysis> {
121 const std::optional<StringRef> Profile;
122
123public:
125 LLVM_ABI explicit CtxProfAnalysis(
126 std::optional<StringRef> Profile = std::nullopt);
127
129
131
132 /// Get the instruction instrumenting a callsite, or nullptr if that cannot be
133 /// found.
135
136 /// Get the instruction instrumenting a BB, or nullptr if not present.
138
139 /// Get the step instrumentation associated with a `select`
142
143 // FIXME: refactor to an advisor model, and separate
145 CallBase &IC, Result &Profile,
146 SetVector<std::pair<CallBase *, Function *>> &Candidates);
147};
148
150 : public PassInfoMixin<CtxProfAnalysisPrinterPass> {
151public:
152 enum class PrintMode { Everything, YAML };
154
156 static bool isRequired() { return true; }
157
158private:
159 raw_ostream &OS;
160 const PrintMode Mode;
161};
162
163/// Utility that propagates counter values to each basic block and to each edge
164/// when a basic block has more than one outgoing edge, using an adaptation of
165/// PGOUseFunc::populateCounters.
166// FIXME(mtrofin): look into factoring the code to share one implementation.
167class ProfileAnnotatorImpl;
169 std::unique_ptr<ProfileAnnotatorImpl> PImpl;
170
171public:
173 LLVM_ABI uint64_t getBBCount(const BasicBlock &BB) const;
174
175 // Finds the true and false counts for the given select instruction. Returns
176 // false if the select doesn't have instrumentation or if the count of the
177 // parent BB is 0.
179 uint64_t &FalseCount) const;
180 // Clears Profile and populates it with the edge weights, in the same order as
181 // they need to appear in the MD_prof metadata. Also computes the max of those
182 // weights an returns it in MaxCount. Returs false if:
183 // - the BB has less than 2 successors
184 // - the counts are 0
187 uint64_t &MaxCount) const;
189};
190
191/// Assign a GUID to functions as metadata. GUID calculation takes linkage into
192/// account, which may change especially through and after thinlto. By
193/// pre-computing and assigning as metadata, this mechanism is resilient to such
194/// changes (as well as name changes e.g. suffix ".llvm." additions).
195
196// FIXME(mtrofin): we can generalize this mechanism to calculate a GUID early in
197// the pass pipeline, associate it with any Global Value, and then use it for
198// PGO and ThinLTO.
199// At that point, this should be moved elsewhere.
200class AssignGUIDPass : public PassInfoMixin<AssignGUIDPass> {
201public:
202 explicit AssignGUIDPass() = default;
203
204 /// Assign a GUID *if* one is not already assign, as a function metadata named
205 /// `GUIDMetadataName`.
207 LLVM_ABI static const char *GUIDMetadataName;
208 // This should become GlobalValue::getGUID
209 LLVM_ABI static uint64_t getGUID(const Function &F);
210};
211
212} // namespace llvm
213#endif // LLVM_ANALYSIS_CTXPROFANALYSIS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition: Compiler.h:213
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition: MD5.cpp:55
Load MIR Sample Profile
Reader for contextual iFDO profile, which comes in bitstream format.
ModuleAnalysisManager MAM
This file implements a set that has insertion order iteration characteristics.
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:294
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Assign a GUID to functions as metadata.
static LLVM_ABI uint64_t getGUID(const Function &F)
static LLVM_ABI const char * GUIDMetadataName
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Assign a GUID if one is not already assign, as a function metadata named GUIDMetadataName.
AssignGUIDPass()=default
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI PGOContextualProfile run(Module &M, ModuleAnalysisManager &MAM)
static LLVM_ABI InstrProfIncrementInst * getBBInstrumentation(BasicBlock &BB)
Get the instruction instrumenting a BB, or nullptr if not present.
static LLVM_ABI InstrProfIncrementInstStep * getSelectInstrumentation(SelectInst &SI)
Get the step instrumentation associated with a select
static LLVM_ABI void collectIndirectCallPromotionList(CallBase &IC, Result &Profile, SetVector< std::pair< CallBase *, Function * > > &Candidates)
static LLVM_ABI InstrProfCallsite * getCallsiteInstrumentation(CallBase &CB)
Get the instruction instrumenting a callsite, or nullptr if that cannot be found.
static LLVM_ABI AnalysisKey Key
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:577
This represents the llvm.instrprof.callsite intrinsic.
This represents the llvm.instrprof.increment.step intrinsic.
This represents the llvm.instrprof.increment intrinsic.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
The instrumented contextual profile, produced by the CtxProfAnalysis.
LLVM_ABI void visit(ConstVisitor, const Function *F=nullptr) const
PGOContextualProfile(PGOContextualProfile &&)=default
LLVM_ABI const CtxProfFlatProfile flatten() const
LLVM_ABI bool isInSpecializedModule() const
LLVM_ABI void update(Visitor, const Function &F)
StringRef getFunctionName(GlobalValue::GUID GUID) const
bool invalidate(Module &, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &)
uint32_t getNumCounters(const Function &F) const
uint32_t allocateNextCounterIndex(const Function &F)
const PGOCtxProfile & profiles() const
const CtxProfContextualProfiles & contexts() const
PGOContextualProfile(const PGOContextualProfile &)=delete
uint32_t getNumCallsites(const Function &F) const
uint32_t allocateNextCallsiteIndex(const Function &F)
LLVM_ABI const CtxProfFlatIndirectCallProfile flattenVirtCalls() const
bool isFunctionKnown(const Function &F) const
A node (context) in the loaded contextual profile, suitable for mutation during IPO passes.
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: Analysis.h:275
LLVM_ABI ~ProfileAnnotator()
LLVM_ABI bool getSelectInstrProfile(SelectInst &SI, uint64_t &TrueCount, uint64_t &FalseCount) const
LLVM_ABI bool getOutgoingBranchWeights(BasicBlock &BB, SmallVectorImpl< uint64_t > &Profile, uint64_t &MaxCount) const
LLVM_ABI uint64_t getBBCount(const BasicBlock &BB) const
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition: SetVector.h:59
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:301
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::map< GlobalValue::GUID, PGOCtxProfContext > CtxProfContextualProfiles
std::map< GlobalValue::GUID, SmallVector< uint64_t, 1 > > CtxProfFlatProfile
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:93
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:29
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:70