LLVM 20.0.0git
Instrumentation.h
Go to the documentation of this file.
1//===- Transforms/Instrumentation.h - Instrumentation passes ----*- 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// This file defines constructor functions for instrumentation passes.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TRANSFORMS_INSTRUMENTATION_H
14#define LLVM_TRANSFORMS_INSTRUMENTATION_H
15
16#include "llvm/ADT/StringRef.h"
17#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/Instruction.h"
22#include <cassert>
23#include <cstdint>
24#include <limits>
25#include <string>
26
27namespace llvm {
28
29class Triple;
30class OptimizationRemarkEmitter;
31class Comdat;
32class CallBase;
33class Module;
34
35/// Check if module has flag attached, if not add the flag.
36bool checkIfAlreadyInstrumented(Module &M, StringRef Flag);
37
38/// Instrumentation passes often insert conditional checks into entry blocks.
39/// Call this function before splitting the entry block to move instructions
40/// that must remain in the entry block up before the split point. Static
41/// allocas and llvm.localescape calls, for example, must remain in the entry
42/// block.
45
46// Create a constant for Str so that we can pass it to the run-time lib.
47GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
48 bool AllowMerging,
49 Twine NamePrefix = "");
50
51// Returns F.getComdat() if it exists.
52// Otherwise creates a new comdat, sets F's comdat, and returns it.
53// Returns nullptr on failure.
54Comdat *getOrCreateFunctionComdat(Function &F, Triple &T);
55
56// Place global in a large section for x86-64 ELF binaries to mitigate
57// relocation overflow pressure. This can be be used for metadata globals that
58// aren't directly accessed by code, which has no performance impact.
59void setGlobalVariableLargeSection(const Triple &TargetTriple,
60 GlobalVariable &GV);
61
62// Insert GCOV profiling instrumentation
64 static GCOVOptions getDefault();
65
66 // Specify whether to emit .gcno files.
68
69 // Specify whether to modify the program to emit .gcda files when run.
71
72 // A four-byte version string. The meaning of a version string is described in
73 // gcc's gcov-io.h
74 char Version[4];
75
76 // Add the 'noredzone' attribute to added runtime library calls.
78
79 // Use atomic profile counter increments.
80 bool Atomic = false;
81
82 // Regexes separated by a semi-colon to filter the files to instrument.
83 std::string Filter;
84
85 // Regexes separated by a semi-colon to filter the files to not instrument.
86 std::string Exclude;
87};
88
89// The pgo-specific indirect call promotion function declared below is used by
90// the pgo-driven indirect call promotion and sample profile passes. It's a
91// wrapper around llvm::promoteCall, et al. that additionally computes !prof
92// metadata. We place it in a pgo namespace so it's not confused with the
93// generic utilities.
94namespace pgo {
95
96// Helper function that transforms CB (either an indirect-call instruction, or
97// an invoke instruction , to a conditional call to F. This is like:
98// if (Inst.CalledValue == F)
99// F(...);
100// else
101// Inst(...);
102// end
103// TotalCount is the profile count value that the instruction executes.
104// Count is the profile count value that F is the target function.
105// These two values are used to update the branch weight.
106// If \p AttachProfToDirectCall is true, a prof metadata is attached to the
107// new direct call to contain \p Count.
108// Returns the promoted direct call instruction.
110 uint64_t TotalCount, bool AttachProfToDirectCall,
112} // namespace pgo
113
114/// Options for the frontend instrumentation based profiling pass.
116 // Add the 'noredzone' attribute to added runtime library calls.
117 bool NoRedZone = false;
118
119 // Do counter register promotion
120 bool DoCounterPromotion = false;
121
122 // Use atomic profile counter increments.
123 bool Atomic = false;
124
125 // Use BFI to guide register promotion
126 bool UseBFIInPromotion = false;
127
128 // Use sampling to reduce the profile instrumentation runtime overhead.
129 bool Sampling = false;
130
131 // Name of the profile file to use as output
133
134 InstrProfOptions() = default;
135};
136
137// Create the variable for profile sampling.
139
140// Options for sanitizer coverage instrumentation.
142 enum Type {
148 bool IndirectCalls = false;
149 bool TraceBB = false;
150 bool TraceCmp = false;
151 bool TraceDiv = false;
152 bool TraceGep = false;
153 bool Use8bitCounters = false;
154 bool TracePC = false;
155 bool TracePCGuard = false;
156 bool Inline8bitCounters = false;
157 bool InlineBoolFlag = false;
158 bool PCTable = false;
159 bool NoPrune = false;
160 bool StackDepth = false;
161 bool TraceLoads = false;
162 bool TraceStores = false;
163 bool CollectControlFlow = false;
164
166};
167
168/// Calculate what to divide by to scale counts.
169///
170/// Given the maximum count, calculate a divisor that will scale all the
171/// weights to strictly less than std::numeric_limits<uint32_t>::max().
172static inline uint64_t calculateCountScale(uint64_t MaxCount) {
173 return MaxCount < std::numeric_limits<uint32_t>::max()
174 ? 1
175 : MaxCount / std::numeric_limits<uint32_t>::max() + 1;
176}
177
178/// Scale an individual branch count.
179///
180/// Scale a 64-bit weight down to 32-bits using \c Scale.
181///
182static inline uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale) {
183 uint64_t Scaled = Count / Scale;
184 assert(Scaled <= std::numeric_limits<uint32_t>::max() && "overflow 32-bits");
185 return Scaled;
186}
187
188// Use to ensure the inserted instrumentation has a DebugLocation; if none is
189// attached to the source instruction, try to use a DILocation with offset 0
190// scoped to surrounding function (if it has a DebugLocation).
191//
192// Some non-call instructions may be missing debug info, but when inserting
193// instrumentation calls, some builds (e.g. LTO) want calls to have debug info
194// if the enclosing function does.
196 static void ensureDebugInfo(IRBuilder<> &IRB, const Function &F) {
197 if (IRB.getCurrentDebugLocation())
198 return;
199 if (DISubprogram *SP = F.getSubprogram())
200 IRB.SetCurrentDebugLocation(DILocation::get(SP->getContext(), 0, 0, SP));
201 }
202
204 ensureDebugInfo(*this, *IP->getFunction());
205 }
206};
207} // end namespace llvm
208
209#endif // LLVM_TRANSFORMS_INSTRUMENTATION_H
@ Scaled
#define F(x, y, z)
Definition: MD5.cpp:55
Machine Check Debug Module
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1236
Subprogram description.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:217
DebugLoc getCurrentDebugLocation() const
Get location information used by debugging information.
Definition: IRBuilder.cpp:64
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2686
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:70
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1542
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
The optimization diagnostic interface.
CallBase & promoteIndirectCall(CallBase &CB, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
GlobalVariable * createPrivateGlobalForString(Module &M, StringRef Str, bool AllowMerging, Twine NamePrefix="")
void createProfileSamplingVar(Module &M)
Comdat * getOrCreateFunctionComdat(Function &F, Triple &T)
static uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
void setGlobalVariableLargeSection(const Triple &TargetTriple, GlobalVariable &GV)
static uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
bool checkIfAlreadyInstrumented(Module &M, StringRef Flag)
Check if module has flag attached, if not add the flag.
static GCOVOptions getDefault()
std::string Exclude
std::string Filter
Options for the frontend instrumentation based profiling pass.
std::string InstrProfileOutput
InstrumentationIRBuilder(Instruction *IP)
static void ensureDebugInfo(IRBuilder<> &IRB, const Function &F)
enum llvm::SanitizerCoverageOptions::Type CoverageType