LLVM 22.0.0git
ProfDataUtils.cpp
Go to the documentation of this file.
1//===- ProfDataUtils.cpp - Utility functions for MD_prof Metadata ---------===//
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// This file implements utilities for working with Profiling Metadata.
10//
11//===----------------------------------------------------------------------===//
12
14
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/Function.h"
19#include "llvm/IR/LLVMContext.h"
20#include "llvm/IR/MDBuilder.h"
21#include "llvm/IR/Metadata.h"
22
23using namespace llvm;
24
25namespace {
26
27// MD_prof nodes have the following layout
28//
29// In general:
30// { String name, Array of i32 }
31//
32// In terms of Types:
33// { MDString, [i32, i32, ...]}
34//
35// Concretely for Branch Weights
36// { "branch_weights", [i32 1, i32 10000]}
37//
38// We maintain some constants here to ensure that we access the branch weights
39// correctly, and can change the behavior in the future if the layout changes
40
41// the minimum number of operands for MD_prof nodes with branch weights
42constexpr unsigned MinBWOps = 3;
43
44// the minimum number of operands for MD_prof nodes with value profiles
45constexpr unsigned MinVPOps = 5;
46
47// We may want to add support for other MD_prof types, so provide an abstraction
48// for checking the metadata type.
49bool isTargetMD(const MDNode *ProfData, const char *Name, unsigned MinOps) {
50 // TODO: This routine may be simplified if MD_prof used an enum instead of a
51 // string to differentiate the types of MD_prof nodes.
52 if (!ProfData || !Name || MinOps < 2)
53 return false;
54
55 unsigned NOps = ProfData->getNumOperands();
56 if (NOps < MinOps)
57 return false;
58
59 auto *ProfDataName = dyn_cast<MDString>(ProfData->getOperand(0));
60 if (!ProfDataName)
61 return false;
62
63 return ProfDataName->getString() == Name;
64}
65
66template <typename T,
67 typename = typename std::enable_if<std::is_arithmetic_v<T>>>
68static void extractFromBranchWeightMD(const MDNode *ProfileData,
69 SmallVectorImpl<T> &Weights) {
70 assert(isBranchWeightMD(ProfileData) && "wrong metadata");
71
72 unsigned NOps = ProfileData->getNumOperands();
73 unsigned WeightsIdx = getBranchWeightOffset(ProfileData);
74 assert(WeightsIdx < NOps && "Weights Index must be less than NOps.");
75 Weights.resize(NOps - WeightsIdx);
76
77 for (unsigned Idx = WeightsIdx, E = NOps; Idx != E; ++Idx) {
78 ConstantInt *Weight =
79 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(Idx));
80 assert(Weight && "Malformed branch_weight in MD_prof node");
81 assert(Weight->getValue().getActiveBits() <= (sizeof(T) * 8) &&
82 "Too many bits for MD_prof branch_weight");
83 Weights[Idx - WeightsIdx] = Weight->getZExtValue();
84 }
85}
86
87} // namespace
88
89namespace llvm {
90
91const char *MDProfLabels::BranchWeights = "branch_weights";
92const char *MDProfLabels::ExpectedBranchWeights = "expected";
93const char *MDProfLabels::ValueProfile = "VP";
94const char *MDProfLabels::FunctionEntryCount = "function_entry_count";
96 "synthetic_function_entry_count";
97const char *MDProfLabels::UnknownBranchWeightsMarker = "unknown";
98
99bool hasProfMD(const Instruction &I) {
100 return I.hasMetadata(LLVMContext::MD_prof);
101}
102
103bool isBranchWeightMD(const MDNode *ProfileData) {
104 return isTargetMD(ProfileData, MDProfLabels::BranchWeights, MinBWOps);
105}
106
107bool isValueProfileMD(const MDNode *ProfileData) {
108 return isTargetMD(ProfileData, MDProfLabels::ValueProfile, MinVPOps);
109}
110
112 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
113 return isBranchWeightMD(ProfileData);
114}
115
116static bool hasCountTypeMD(const Instruction &I) {
117 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
118 // Value profiles record count-type information.
119 if (isValueProfileMD(ProfileData))
120 return true;
121 // Conservatively assume non CallBase instruction only get taken/not-taken
122 // branch probability, so not interpret them as count.
123 return isa<CallBase>(I) && !isBranchWeightMD(ProfileData);
124}
125
128}
129
131 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
132 return hasBranchWeightOrigin(ProfileData);
133}
134
135bool hasBranchWeightOrigin(const MDNode *ProfileData) {
136 if (!isBranchWeightMD(ProfileData))
137 return false;
138 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(1));
139 // NOTE: if we ever have more types of branch weight provenance,
140 // we need to check the string value is "expected". For now, we
141 // supply a more generic API, and avoid the spurious comparisons.
142 assert(ProfDataName == nullptr ||
143 ProfDataName->getString() == MDProfLabels::ExpectedBranchWeights);
144 return ProfDataName != nullptr;
145}
146
147unsigned getBranchWeightOffset(const MDNode *ProfileData) {
148 return hasBranchWeightOrigin(ProfileData) ? 2 : 1;
149}
150
151unsigned getNumBranchWeights(const MDNode &ProfileData) {
152 return ProfileData.getNumOperands() - getBranchWeightOffset(&ProfileData);
153}
154
156 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
157 if (!isBranchWeightMD(ProfileData))
158 return nullptr;
159 return ProfileData;
160}
161
163 auto *ProfileData = getBranchWeightMDNode(I);
164 if (ProfileData && getNumBranchWeights(*ProfileData) == I.getNumSuccessors())
165 return ProfileData;
166 return nullptr;
167}
168
169void extractFromBranchWeightMD32(const MDNode *ProfileData,
170 SmallVectorImpl<uint32_t> &Weights) {
171 extractFromBranchWeightMD(ProfileData, Weights);
172}
173
174void extractFromBranchWeightMD64(const MDNode *ProfileData,
175 SmallVectorImpl<uint64_t> &Weights) {
176 extractFromBranchWeightMD(ProfileData, Weights);
177}
178
179bool extractBranchWeights(const MDNode *ProfileData,
180 SmallVectorImpl<uint32_t> &Weights) {
181 if (!isBranchWeightMD(ProfileData))
182 return false;
183 extractFromBranchWeightMD(ProfileData, Weights);
184 return true;
185}
186
188 SmallVectorImpl<uint32_t> &Weights) {
189 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
190 return extractBranchWeights(ProfileData, Weights);
191}
192
194 uint64_t &FalseVal) {
195 assert((I.getOpcode() == Instruction::Br ||
196 I.getOpcode() == Instruction::Select) &&
197 "Looking for branch weights on something besides branch, select, or "
198 "switch");
199
201 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
202 if (!extractBranchWeights(ProfileData, Weights))
203 return false;
204
205 if (Weights.size() > 2)
206 return false;
207
208 TrueVal = Weights[0];
209 FalseVal = Weights[1];
210 return true;
211}
212
213bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalVal) {
214 TotalVal = 0;
215 if (!ProfileData)
216 return false;
217
218 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
219 if (!ProfDataName)
220 return false;
221
222 if (ProfDataName->getString() == MDProfLabels::BranchWeights) {
223 unsigned Offset = getBranchWeightOffset(ProfileData);
224 for (unsigned Idx = Offset; Idx < ProfileData->getNumOperands(); ++Idx) {
225 auto *V = mdconst::extract<ConstantInt>(ProfileData->getOperand(Idx));
226 TotalVal += V->getValue().getZExtValue();
227 }
228 return true;
229 }
230
231 if (ProfDataName->getString() == MDProfLabels::ValueProfile &&
232 ProfileData->getNumOperands() > 3) {
233 TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
234 ->getValue()
235 .getZExtValue();
236 return true;
237 }
238 return false;
239}
240
242 return extractProfTotalWeight(I.getMetadata(LLVMContext::MD_prof), TotalVal);
243}
244
246 MDBuilder MDB(I.getContext());
247 I.setMetadata(
248 LLVMContext::MD_prof,
249 MDNode::get(I.getContext(),
251}
252
254 if (MD.getNumOperands() != 1)
255 return false;
257}
258
260 auto *MD = I.getMetadata(LLVMContext::MD_prof);
261 if (!MD)
262 return false;
264}
265
267 bool IsExpected) {
268 MDBuilder MDB(I.getContext());
269 MDNode *BranchWeights = MDB.createBranchWeights(Weights, IsExpected);
270 I.setMetadata(LLVMContext::MD_prof, BranchWeights);
271}
272
274 std::optional<uint64_t> KnownMaxCount) {
275 uint64_t MaxCount = KnownMaxCount.has_value() ? KnownMaxCount.value()
276 : *llvm::max_element(Weights);
277 assert(MaxCount > 0 && "Bad max count");
278 uint64_t Scale = calculateCountScale(MaxCount);
279 SmallVector<uint32_t> DownscaledWeights;
280 for (const auto &ECI : Weights)
281 DownscaledWeights.push_back(scaleBranchCount(ECI, Scale));
282 return DownscaledWeights;
283}
284
286 assert(T != 0 && "Caller should guarantee");
287 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
288 if (ProfileData == nullptr)
289 return;
290
291 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
292 if (!ProfDataName ||
293 (ProfDataName->getString() != MDProfLabels::BranchWeights &&
294 ProfDataName->getString() != MDProfLabels::ValueProfile))
295 return;
296
297 if (!hasCountTypeMD(I))
298 return;
299
300 LLVMContext &C = I.getContext();
301
302 MDBuilder MDB(C);
304 Vals.push_back(ProfileData->getOperand(0));
305 APInt APS(128, S), APT(128, T);
306 if (ProfDataName->getString() == MDProfLabels::BranchWeights &&
307 ProfileData->getNumOperands() > 0) {
308 // Using APInt::div may be expensive, but most cases should fit 64 bits.
309 APInt Val(128,
310 mdconst::dyn_extract<ConstantInt>(
311 ProfileData->getOperand(getBranchWeightOffset(ProfileData)))
312 ->getValue()
313 .getZExtValue());
314 Val *= APS;
315 Vals.push_back(MDB.createConstant(ConstantInt::get(
316 Type::getInt32Ty(C), Val.udiv(APT).getLimitedValue(UINT32_MAX))));
317 } else if (ProfDataName->getString() == MDProfLabels::ValueProfile)
318 for (unsigned Idx = 1; Idx < ProfileData->getNumOperands(); Idx += 2) {
319 // The first value is the key of the value profile, which will not change.
320 Vals.push_back(ProfileData->getOperand(Idx));
321 uint64_t Count =
322 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(Idx + 1))
323 ->getValue()
324 .getZExtValue();
325 // Don't scale the magic number.
326 if (Count == NOMORE_ICP_MAGICNUM) {
327 Vals.push_back(ProfileData->getOperand(Idx + 1));
328 continue;
329 }
330 // Using APInt::div may be expensive, but most cases should fit 64 bits.
331 APInt Val(128, Count);
332 Val *= APS;
333 Vals.push_back(MDB.createConstant(ConstantInt::get(
334 Type::getInt64Ty(C), Val.udiv(APT).getLimitedValue())));
335 }
336 I.setMetadata(LLVMContext::MD_prof, MDNode::get(C, Vals));
337}
338
339} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
This file contains the declarations for profiling metadata utility functions.
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition: APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1573
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1512
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:475
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
This is the shared class of boolean and integer constants.
Definition: Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:163
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:154
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:25
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:38
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition: MDBuilder.cpp:21
Metadata node.
Definition: Metadata.h:1077
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1445
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1565
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1451
bool equalsStr(StringRef Str) const
Definition: Metadata.h:921
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void resize(size_type N)
Definition: SmallVector.h:639
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
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
LLVM_ABI void setExplicitlyUnknownBranchWeights(Instruction &I)
Specify that the branch weights for this terminator cannot be known at compile time.
LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalWeights)
Retrieve the total of all weights from MD_prof data.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI bool isBranchWeightMD(const MDNode *ProfileData)
Checks if an MDNode contains Branch Weight Metadata.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
LLVM_ABI bool hasValidBranchWeightMD(const Instruction &I)
Checks if an instructions has valid Branch Weight Metadata.
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
LLVM_ABI bool hasExplicitlyUnknownBranchWeights(const Instruction &I)
LLVM_ABI bool hasProfMD(const Instruction &I)
Checks if an Instruction has MD_prof Metadata.
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:2049
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
LLVM_ABI bool isExplicitlyUnknownBranchWeightsMetadata(const MDNode &MD)
uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
LLVM_ABI SmallVector< uint32_t > downscaleWeights(ArrayRef< uint64_t > Weights, std::optional< uint64_t > KnownMaxCount=std::nullopt)
downscale the given weights preserving the ratio.
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
Definition: Metadata.h:58
LLVM_ABI void scaleProfData(Instruction &I, uint64_t S, uint64_t T)
Scaling the profile data attached to 'I' using the ratio of S/T.
static bool hasCountTypeMD(const Instruction &I)
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
static LLVM_ABI const char * ExpectedBranchWeights
Definition: ProfDataUtils.h:29
static LLVM_ABI const char * SyntheticFunctionEntryCount
Definition: ProfDataUtils.h:28
static LLVM_ABI const char * BranchWeights
Definition: ProfDataUtils.h:25
static LLVM_ABI const char * FunctionEntryCount
Definition: ProfDataUtils.h:27
static LLVM_ABI const char * UnknownBranchWeightsMarker
Definition: ProfDataUtils.h:30
static LLVM_ABI const char * ValueProfile
Definition: ProfDataUtils.h:26