LLVM 23.0.0git
ProfDataUtils.h
Go to the documentation of this file.
1//===- llvm/IR/ProfDataUtils.h - Profiling Metadata Utilities ---*- 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/// This file contains the declarations for profiling metadata utility
11/// functions.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_PROFDATAUTILS_H
16#define LLVM_IR_PROFDATAUTILS_H
17
20#include "llvm/IR/Metadata.h"
22#include <cstddef>
23#include <type_traits>
24
25namespace llvm {
27 LLVM_ABI static const char *BranchWeights;
28 LLVM_ABI static const char *ValueProfile;
29 LLVM_ABI static const char *FunctionEntryCount;
31 LLVM_ABI static const char *ExpectedBranchWeights;
33};
34
35/// Profile-based loop metadata that should be accessed only by using
36/// \c llvm::getLoopEstimatedTripCount and \c llvm::setLoopEstimatedTripCount.
37LLVM_ABI extern const char *LLVMLoopEstimatedTripCount;
38
39/// Checks if an Instruction has MD_prof Metadata
40LLVM_ABI bool hasProfMD(const Instruction &I);
41
42/// Checks if an MDNode contains Branch Weight Metadata
43LLVM_ABI bool isBranchWeightMD(const MDNode *ProfileData);
44
45/// Checks if an MDNode contains value profiling Metadata
46LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData);
47
48/// Checks if an instructions has Branch Weight Metadata
49///
50/// \param I The instruction to check
51/// \returns True if I has an MD_prof node containing Branch Weights. False
52/// otherwise.
54
55/// Checks if an instructions has valid Branch Weight Metadata
56///
57/// \param I The instruction to check
58/// \returns True if I has an MD_prof node containing valid Branch Weights,
59/// i.e., one weight for each successor. False otherwise.
61
62/// Get the branch weights metadata node
63///
64/// \param I The Instruction to get the weights from.
65/// \returns A pointer to I's branch weights metadata node, if it exists.
66/// Nullptr otherwise.
68
69/// Get the valid branch weights metadata node
70///
71/// \param I The Instruction to get the weights from.
72/// \returns A pointer to I's valid branch weights metadata node, if it exists.
73/// Nullptr otherwise.
75
76/// Check if Branch Weight Metadata has an "expected" field from an llvm.expect*
77/// intrinsic
79
80/// Check if Branch Weight Metadata has an "expected" field from an llvm.expect*
81/// intrinsic
82LLVM_ABI bool hasBranchWeightOrigin(const MDNode *ProfileData);
83
84/// Return the offset to the first branch weight data
85LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData);
86
87LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData);
88
89/// Extract branch weights from MD_prof metadata
90///
91/// \param ProfileData A pointer to an MDNode.
92/// \param [out] Weights An output vector to fill with branch weights
93/// \returns True if weights were extracted, False otherwise. When false Weights
94/// will be cleared.
95LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData,
97
98/// Faster version of extractBranchWeights() that skips checks and must only
99/// be called with "branch_weights" metadata nodes. Supports uint32_t.
100LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData,
102
103/// Faster version of extractBranchWeights() that skips checks and must only
104/// be called with "branch_weights" metadata nodes. Supports uint64_t.
105LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData,
107
108/// Extract branch weights attatched to an Instruction
109///
110/// \param I The Instruction to extract weights from.
111/// \param [out] Weights An output vector to fill with branch weights
112/// \returns True if weights were extracted, False otherwise. When false Weights
113/// will be cleared.
116
117/// Extract branch weights from a conditional branch or select Instruction.
118///
119/// \param I The instruction to extract branch weights from.
120/// \param [out] TrueVal will contain the branch weight for the True branch
121/// \param [out] FalseVal will contain the branch weight for the False branch
122/// \returns True on success with profile weights filled in. False if no
123/// metadata or invalid metadata was found.
125 uint64_t &FalseVal);
126
127/// Retrieve the total of all weights from MD_prof data.
128///
129/// \param ProfileData The profile data to extract the total weight from
130/// \param [out] TotalWeights input variable to fill with total weights
131/// \returns True on success with profile total weights filled in. False if no
132/// metadata was found.
133LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData,
134 uint64_t &TotalWeights);
135
136/// Retrieve the total of all weights from an instruction.
137///
138/// \param I The instruction to extract the total weight from
139/// \param [out] TotalWeights input variable to fill with total weights
140/// \returns True on success with profile total weights filled in. False if no
141/// metadata was found.
143 uint64_t &TotalWeights);
144
145/// Create a new `branch_weights` metadata node and add or overwrite
146/// a `prof` metadata reference to instruction `I`.
147/// \param I the Instruction to set branch weights on.
148/// \param Weights an array of weights to set on instruction I.
149/// \param IsExpected were these weights added from an llvm.expect* intrinsic.
151 bool IsExpected, bool ElideAllZero = false);
152
153/// Push the weights right to fit in uint32_t.
155
156/// Variant of `setBranchWeights` where the `Weights` will be fit first to
157/// uint32_t by shifting right.
159 bool IsExpected,
160 bool ElideAllZero = false);
161
162/// downscale the given weights preserving the ratio. If the maximum value is
163/// not already known and not provided via \param KnownMaxCount , it will be
164/// obtained from \param Weights.
167 std::optional<uint64_t> KnownMaxCount = std::nullopt);
168
169/// Calculate what to divide by to scale counts.
170///
171/// Given the maximum count, calculate a divisor that will scale all the
172/// weights to strictly less than std::numeric_limits<uint32_t>::max().
174 return MaxCount < std::numeric_limits<uint32_t>::max()
175 ? 1
176 : MaxCount / std::numeric_limits<uint32_t>::max() + 1;
177}
178
179/// Scale an individual branch count.
180///
181/// Scale a 64-bit weight down to 32-bits using \c Scale.
182///
184 uint64_t Scaled = Count / Scale;
185 assert(Scaled <= std::numeric_limits<uint32_t>::max() && "overflow 32-bits");
186 return Scaled;
187}
188
189/// Specify that the branch weights for this terminator cannot be known at
190/// compile time. This should only be called by passes, and never as a default
191/// behavior in e.g. MDBuilder. The goal is to use this info to validate passes
192/// do not accidentally drop profile info, and this API is called in cases where
193/// the pass explicitly cannot provide that info. Defaulting it in would hide
194/// bugs where the pass forgets to transfer over or otherwise specify profile
195/// info. Use `PassName` to capture the pass name (i.e. DEBUG_TYPE) for
196/// debuggability.
198 StringRef PassName);
199
200/// Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch
201/// weights in the new instruction if the parent function of the original
202/// instruction has an entry count. This is to not confuse users by injecting
203/// profile data into non-profiled functions. If \p F is nullptr, we will fetch
204/// the function from \p I.
205LLVM_ABI void
207 const Function *F = nullptr);
208
209/// Analogous to setExplicitlyUnknownBranchWeights, but for functions and their
210/// entry counts.
212 StringRef PassName);
213
214LLVM_ABI bool isExplicitlyUnknownProfileMetadata(const MDNode &MD);
215LLVM_ABI bool hasExplicitlyUnknownBranchWeights(const Instruction &I);
216
217/// Scaling the profile data attached to 'I' using the ratio of S/T.
218LLVM_ABI void scaleProfData(Instruction &I, uint64_t S, uint64_t T);
219
220// Helper to apply a metadata setting function to an Instruction* if profiling
221// is enabled. If profiling is disabled (ProfcheckDisableMetadataFixes is true)
222// or V is not an Instruction, the callback will not be invoked.
224 Value *V, llvm::function_ref<void(Instruction *)> setMetadataCallback);
225
226/// Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2
227/// are 2 booleans that are the conditions of 2 branches for which we have the
228/// branch weights B1 and B2, respectively. In both B1 and B2, the first
229/// position (index 0) is for the 'true' branch, and the second position (index
230/// 1) is for the 'false' branch.
231template <typename T1, typename T2,
232 typename = typename std::enable_if<
233 std::is_arithmetic_v<T1> && std::is_arithmetic_v<T2> &&
234 sizeof(T1) <= sizeof(uint64_t) && sizeof(T2) <= sizeof(uint64_t)>>
237 const SmallVector<T2, 2> &B2) {
238 // For the first conditional branch, the probability the "true" case is taken
239 // is p(b1) = B1[0] / (B1[0] + B1[1]). The "false" case's probability is
240 // p(not b1) = B1[1] / (B1[0] + B1[1]).
241 // Similarly for the second conditional branch and B2.
242 //
243 // The probability of the new branch NOT being taken is:
244 // not P = p((not b1) and (not b2)) =
245 // = B1[1] / (B1[0]+B1[1]) * B2[1] / (B2[0]+B2[1]) =
246 // = B1[1] * B2[1] / (B1[0] + B1[1]) * (B2[0] + B2[1])
247 // Then the probability of it being taken is: P = 1 - (not P).
248 // The denominator will be the same as above, and the numerator of P will be:
249 // (B1[0] + B1[1]) * (B2[0] + B2[1]) - B1[1]*B2[1]
250 // Which then reduces to what's shown below (out of the 4 terms coming out of
251 // the product of sums, the subtracted one cancels out).
252 assert(B1.size() == 2);
253 assert(B2.size() == 2);
254 uint64_t FalseWeight = B1[1] * B2[1];
255 uint64_t TrueWeight = B1[0] * (B2[0] + B2[1]) + B1[1] * B2[0];
256 return {TrueWeight, FalseWeight};
257}
258} // namespace llvm
259#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
@ Scaled
#define LLVM_ABI
Definition Compiler.h:213
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
#define T1
This file defines the SmallVector class.
static const char PassName[]
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Metadata node.
Definition Metadata.h:1080
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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 void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
LLVM_ABI bool isBranchWeightMD(const MDNode *ProfileData)
Checks if an MDNode contains Branch Weight Metadata.
LLVM_ABI bool isExplicitlyUnknownProfileMetadata(const MDNode &MD)
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
LLVM_ABI void applyProfMetadataIfEnabled(Value *V, llvm::function_ref< void(Instruction *)> setMetadataCallback)
LLVM_ABI void setExplicitlyUnknownBranchWeights(Instruction &I, StringRef PassName)
Specify that the branch weights for this terminator cannot be known at compile time.
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, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
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.
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI void setExplicitlyUnknownFunctionEntryCount(Function &F, StringRef PassName)
Analogous to setExplicitlyUnknownBranchWeights, but for functions and their entry counts.
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.
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
SmallVector< uint64_t, 2 > getDisjunctionWeights(const SmallVector< T1, 2 > &B1, const SmallVector< T2, 2 > &B2)
Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2 are 2 booleans that are t...
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
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.
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.
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
static LLVM_ABI const char * SyntheticFunctionEntryCount
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights