LLVM 19.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
15#include "llvm/ADT/Twine.h"
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"
24
25using namespace llvm;
26
27namespace {
28
29// MD_prof nodes have the following layout
30//
31// In general:
32// { String name, Array of i32 }
33//
34// In terms of Types:
35// { MDString, [i32, i32, ...]}
36//
37// Concretely for Branch Weights
38// { "branch_weights", [i32 1, i32 10000]}
39//
40// We maintain some constants here to ensure that we access the branch weights
41// correctly, and can change the behavior in the future if the layout changes
42
43// The index at which the weights vector starts
44constexpr unsigned WeightsIdx = 1;
45
46// the minimum number of operands for MD_prof nodes with branch weights
47constexpr unsigned MinBWOps = 3;
48
49// We may want to add support for other MD_prof types, so provide an abstraction
50// for checking the metadata type.
51bool isTargetMD(const MDNode *ProfData, const char *Name, unsigned MinOps) {
52 // TODO: This routine may be simplified if MD_prof used an enum instead of a
53 // string to differentiate the types of MD_prof nodes.
54 if (!ProfData || !Name || MinOps < 2)
55 return false;
56
57 unsigned NOps = ProfData->getNumOperands();
58 if (NOps < MinOps)
59 return false;
60
61 auto *ProfDataName = dyn_cast<MDString>(ProfData->getOperand(0));
62 if (!ProfDataName)
63 return false;
64
65 return ProfDataName->getString() == Name;
66}
67
68template <typename T,
69 typename = typename std::enable_if<std::is_arithmetic_v<T>>>
70static void extractFromBranchWeightMD(const MDNode *ProfileData,
71 SmallVectorImpl<T> &Weights) {
72 assert(isBranchWeightMD(ProfileData) && "wrong metadata");
73
74 unsigned NOps = ProfileData->getNumOperands();
75 assert(WeightsIdx < NOps && "Weights Index must be less than NOps.");
76 Weights.resize(NOps - WeightsIdx);
77
78 for (unsigned Idx = WeightsIdx, E = NOps; Idx != E; ++Idx) {
79 ConstantInt *Weight =
80 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(Idx));
81 assert(Weight && "Malformed branch_weight in MD_prof node");
82 assert(Weight->getValue().getActiveBits() <= 32 &&
83 "Too many bits for uint32_t");
84 Weights[Idx - WeightsIdx] = Weight->getZExtValue();
85 }
86}
87
88} // namespace
89
90namespace llvm {
91
92bool hasProfMD(const Instruction &I) {
93 return I.hasMetadata(LLVMContext::MD_prof);
94}
95
96bool isBranchWeightMD(const MDNode *ProfileData) {
97 return isTargetMD(ProfileData, "branch_weights", MinBWOps);
98}
99
101 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
102 return isBranchWeightMD(ProfileData);
103}
104
107}
108
110 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
111 if (!isBranchWeightMD(ProfileData))
112 return nullptr;
113 return ProfileData;
114}
115
117 auto *ProfileData = getBranchWeightMDNode(I);
118 if (ProfileData && ProfileData->getNumOperands() == 1 + I.getNumSuccessors())
119 return ProfileData;
120 return nullptr;
121}
122
123void extractFromBranchWeightMD32(const MDNode *ProfileData,
124 SmallVectorImpl<uint32_t> &Weights) {
125 extractFromBranchWeightMD(ProfileData, Weights);
126}
127
128void extractFromBranchWeightMD64(const MDNode *ProfileData,
129 SmallVectorImpl<uint64_t> &Weights) {
130 extractFromBranchWeightMD(ProfileData, Weights);
131}
132
133bool extractBranchWeights(const MDNode *ProfileData,
134 SmallVectorImpl<uint32_t> &Weights) {
135 if (!isBranchWeightMD(ProfileData))
136 return false;
137 extractFromBranchWeightMD(ProfileData, Weights);
138 return true;
139}
140
142 SmallVectorImpl<uint32_t> &Weights) {
143 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
144 return extractBranchWeights(ProfileData, Weights);
145}
146
148 uint64_t &FalseVal) {
149 assert((I.getOpcode() == Instruction::Br ||
150 I.getOpcode() == Instruction::Select) &&
151 "Looking for branch weights on something besides branch, select, or "
152 "switch");
153
155 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
156 if (!extractBranchWeights(ProfileData, Weights))
157 return false;
158
159 if (Weights.size() > 2)
160 return false;
161
162 TrueVal = Weights[0];
163 FalseVal = Weights[1];
164 return true;
165}
166
167bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalVal) {
168 TotalVal = 0;
169 if (!ProfileData)
170 return false;
171
172 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
173 if (!ProfDataName)
174 return false;
175
176 if (ProfDataName->getString() == "branch_weights") {
177 for (unsigned Idx = 1; Idx < ProfileData->getNumOperands(); Idx++) {
178 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(Idx));
179 assert(V && "Malformed branch_weight in MD_prof node");
180 TotalVal += V->getValue().getZExtValue();
181 }
182 return true;
183 }
184
185 if (ProfDataName->getString() == "VP" && ProfileData->getNumOperands() > 3) {
186 TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
187 ->getValue()
188 .getZExtValue();
189 return true;
190 }
191 return false;
192}
193
195 return extractProfTotalWeight(I.getMetadata(LLVMContext::MD_prof), TotalVal);
196}
197
199 MDBuilder MDB(I.getContext());
200 MDNode *BranchWeights = MDB.createBranchWeights(Weights);
201 I.setMetadata(LLVMContext::MD_prof, BranchWeights);
202}
203
205 assert(T != 0 && "Caller should guarantee");
206 auto *ProfileData = I.getMetadata(LLVMContext::MD_prof);
207 if (ProfileData == nullptr)
208 return;
209
210 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
211 if (!ProfDataName || (ProfDataName->getString() != "branch_weights" &&
212 ProfDataName->getString() != "VP"))
213 return;
214
215 LLVMContext &C = I.getContext();
216
217 MDBuilder MDB(C);
219 Vals.push_back(ProfileData->getOperand(0));
220 APInt APS(128, S), APT(128, T);
221 if (ProfDataName->getString() == "branch_weights" &&
222 ProfileData->getNumOperands() > 0) {
223 // Using APInt::div may be expensive, but most cases should fit 64 bits.
224 APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
225 ->getValue()
226 .getZExtValue());
227 Val *= APS;
228 Vals.push_back(MDB.createConstant(ConstantInt::get(
229 Type::getInt32Ty(C), Val.udiv(APT).getLimitedValue(UINT32_MAX))));
230 } else if (ProfDataName->getString() == "VP")
231 for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
232 // The first value is the key of the value profile, which will not change.
233 Vals.push_back(ProfileData->getOperand(i));
234 uint64_t Count =
235 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
236 ->getValue()
237 .getZExtValue();
238 // Don't scale the magic number.
239 if (Count == NOMORE_ICP_MAGICNUM) {
240 Vals.push_back(ProfileData->getOperand(i + 1));
241 continue;
242 }
243 // Using APInt::div may be expensive, but most cases should fit 64 bits.
244 APInt Val(128, Count);
245 Val *= APS;
246 Vals.push_back(MDB.createConstant(ConstantInt::get(
247 Type::getInt64Ty(C), Val.udiv(APT).getLimitedValue())));
248 }
249 I.setMetadata(LLVMContext::MD_prof, MDNode::get(C, Vals));
250}
251
252} // namespace llvm
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.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1543
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1463
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:453
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:80
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:154
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:145
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:24
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1434
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void resize(size_type N)
Definition: SmallVector.h:651
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
static IntegerType * getInt32Ty(LLVMContext &C)
static 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
bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalWeights)
Retrieve the total of all weights from MD_prof data.
bool isBranchWeightMD(const MDNode *ProfileData)
Checks if an MDNode contains Branch Weight Metadata.
MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
bool hasValidBranchWeightMD(const Instruction &I)
Checks if an instructions has valid Branch Weight Metadata.
void extractFromBranchWeightMD32(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
bool hasProfMD(const Instruction &I)
Checks if an Instruction has MD_prof Metadata.
bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
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:57
void scaleProfData(Instruction &I, uint64_t S, uint64_t T)
Scaling the profile data attached to 'I' using the ratio of S/T.
void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...