LLVM 23.0.0git
InstrumentorUtils.h
Go to the documentation of this file.
1//===-- Transforms/IPO/InstrumentorUtils.h --------------------------------===//
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// General utilities for the Instrumentor pass.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TRANSFORMS_IPO_INSTRUMENTOR_UTILS_H
14#define LLVM_TRANSFORMS_IPO_INSTRUMENTOR_UTILS_H
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/Instruction.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/Module.h"
24
25#include <bitset>
26#include <tuple>
27
28namespace llvm {
29namespace instrumentor {
30
33
34/// An IR builder augmented with extra information for the instrumentor pass.
35/// The underlying IR builder features an insertion callback to keep track of
36/// the new instructions.
38 /// Construct an IR builder for the module \p M.
40 : M(M), Ctx(M.getContext()),
42 // Save the inserted instructions in a structure.
44 [&](Instruction *I) { NewInsts[I] = Epoch; })) {}
45
46 /// Destroy the IR builder and remove all erasable instructions cached during
47 /// the process of instrumenting.
49 for (auto *I : ErasableInstructions) {
50 if (!I->getType()->isVoidTy())
51 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
52 I->eraseFromParent();
53 }
54
55 // Delete the alloca lists that may have been allocated.
56 for (auto &KV : AllocaMap) {
57 if (KV.second)
58 delete KV.second;
59 }
60 }
61
62 /// Get a temporary alloca to communicate (large) values with the runtime.
63 AllocaInst *getAlloca(Function *Fn, Type *Ty, bool MatchType = false) {
64 const DataLayout &DL = Fn->getDataLayout();
65 auto *&AllocaList = AllocaMap[{Fn, DL.getTypeAllocSize(Ty)}];
66 if (!AllocaList)
67 AllocaList = new AllocaListTy;
68 AllocaInst *AI = nullptr;
69 for (auto *&ListAI : *AllocaList) {
70 if (MatchType && ListAI->getAllocatedType() != Ty)
71 continue;
72 AI = ListAI;
73 ListAI = *AllocaList->rbegin();
74 break;
75 }
76 if (AI)
77 AllocaList->pop_back();
78 else
79 AI = new AllocaInst(Ty, DL.getAllocaAddrSpace(), "",
80 Fn->getEntryBlock().begin());
81 UsedAllocas[AI] = AllocaList;
82 return AI;
83 }
84
85 /// Return the temporary allocas.
87 for (auto [AI, List] : UsedAllocas)
88 List->push_back(AI);
89 UsedAllocas.clear();
90 }
91
92 /// Save instruction \p I to be erased later. The instructions are erased when
93 /// the IR builder is destroyed.
95
96 /// Commonly used values for IR inspection and creation.
97 ///{
99
101
102 const DataLayout &DL = M.getDataLayout();
103
109 ///}
110
112
113 /// Map that holds a list of currently available allocas for a function and
114 /// alloca size.
116
117 /// Map that holds the currently used allocas and the list where they belong.
118 /// Once an alloca has to be returned, it is returned directly to its list.
120
121 /// Instructions that should be erased later.
123
124 /// The underlying IR builder with insertion callback.
126
127 /// The current epoch number. Each instrumentation, e.g., of an instruction,
128 /// is happening in a dedicated epoch. The epoch allows to determine if
129 /// instrumentation instructions were already around, due to prior
130 /// instrumentations, or have been introduced to support the current
131 /// instrumentation, e.g., compute information about the current instruction.
132 unsigned Epoch = 0;
133
134 /// A mapping from instrumentation instructions to the epoch they have been
135 /// created.
137};
138
139/// Helper that represent the caches for instrumentation call arguments. The
140/// value of an argument may not need to be recomputed between the pre and post
141/// instrumentation calls.
143 /// A cache for direct and indirect arguments. The cache is indexed by the
144 /// epoch, the instrumentation opportunity name and the argument name. The
145 /// result is a value.
149};
150
151/// Boolean option bitset with a compile-time number of bits to store as many
152/// options as the enumeration type \p EnumTy defines. The enumeration type is
153/// expected to have an ascending and consecutive values, starting at zero, and
154/// the last value being artificial and named as NumConfig (i.e., the number of
155/// values in the enumeration).
156template <typename EnumTy> struct BaseConfigTy {
157 /// The bistset with as many bits as the enumeration's values.
158 std::bitset<static_cast<int>(EnumTy::NumConfig)> Options;
159
160 /// Construct the option bitset with all bits set to \p Enable. If not
161 /// provided, all options are enabled.
162 BaseConfigTy(bool Enable = true) {
163 if (Enable)
164 Options.set();
165 }
166
167 /// Check if the option \p Opt is enabled.
168 bool has(EnumTy Opt) const { return Options.test(static_cast<int>(Opt)); }
169
170 /// Set the boolean value of option \p Opt to \p Value.
171 void set(EnumTy Opt, bool Value = true) {
172 Options.set(static_cast<int>(Opt), Value);
173 }
174};
175
176/// Evaluate the filter expression against the current instrumentation
177/// opportunity. Returns true if the filter passes (or is empty), false
178/// otherwise. Dynamic values (non-constants) are assumed to pass.
180bool evaluateFilter(Value &V, InstrumentationOpportunity &IO,
181 InstrumentationConfig &IConf,
182 InstrumentorIRBuilderTy &IIRB);
183
184} // namespace instrumentor
185} // end namespace llvm
186
187#endif // LLVM_TRANSFORMS_IPO_INSTRUMENTOR_UTILS_H
#define LLVM_ABI
Definition Compiler.h:213
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition MD5.cpp:57
an instruction to allocate memory on the stack
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
ConstantFolder - Create constants with minimum, target independent, folding.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
const BasicBlock & getEntryBlock() const
Definition Function.h:809
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:362
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:75
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2858
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Class to represent pointers.
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:314
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:313
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:286
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI bool evaluateFilter(Value &V, InstrumentationOpportunity &IO, InstrumentationConfig &IConf, InstrumentorIRBuilderTy &IIRB)
Evaluate the filter expression against the current instrumentation opportunity.
This is an optimization pass for GlobalISel generic memory operations.
@ Enable
Enable colors.
Definition WithColor.h:47
void set(EnumTy Opt, bool Value=true)
Set the boolean value of option Opt to Value.
std::bitset< static_cast< int >(ConfigKind::NumConfig)> Options
BaseConfigTy(bool Enable=true)
Construct the option bitset with all bits set to Enable.
bool has(EnumTy Opt) const
Check if the option Opt is enabled.
Helper that represent the caches for instrumentation call arguments.
DenseMap< std::tuple< unsigned, StringRef, StringRef >, Value * > DirectArgCache
A cache for direct and indirect arguments.
DenseMap< std::tuple< unsigned, StringRef, StringRef >, Value * > IndirectArgCache
The class that contains the configuration for the instrumentor.
Base class for instrumentation opportunities.
IRBuilder< ConstantFolder, IRBuilderCallbackInserter > IRB
The underlying IR builder with insertion callback.
~InstrumentorIRBuilderTy()
Destroy the IR builder and remove all erasable instructions cached during the process of instrumentin...
unsigned Epoch
The current epoch number.
InstrumentorIRBuilderTy(Module &M)
Construct an IR builder for the module M.
AllocaInst * getAlloca(Function *Fn, Type *Ty, bool MatchType=false)
Get a temporary alloca to communicate (large) values with the runtime.
DenseMap< AllocaInst *, AllocaListTy * > UsedAllocas
Map that holds the currently used allocas and the list where they belong.
void returnAllocas()
Return the temporary allocas.
SmallPtrSet< Instruction *, 32 > ErasableInstructions
Instructions that should be erased later.
DenseMap< Instruction *, unsigned > NewInsts
A mapping from instrumentation instructions to the epoch they have been created.
Module & M
Commonly used values for IR inspection and creation.
DenseMap< std::pair< Function *, unsigned >, AllocaListTy * > AllocaMap
Map that holds a list of currently available allocas for a function and alloca size.
void eraseLater(Instruction *I)
Save instruction I to be erased later.