LLVM 24.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.
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 AI = ListAI;
71 ListAI = *AllocaList->rbegin();
72 break;
73 }
74 if (AI)
75 AllocaList->pop_back();
76 else
77 AI = new AllocaInst(Ty, DL.getAllocaAddrSpace(), "",
78 Fn->getEntryBlock().begin());
79 UsedAllocas[AI] = AllocaList;
80 return AI;
81 }
82
83 /// Return the temporary allocas.
85 for (auto [AI, List] : UsedAllocas)
86 List->push_back(AI);
87 UsedAllocas.clear();
88 }
89
90 /// Save instruction \p I to be erased later. The instructions are erased when
91 /// the IR builder is destroyed.
93
94 /// Commonly used values for IR inspection and creation.
95 ///{
97
99
100 const DataLayout &DL = M.getDataLayout();
101
107 ///}
108
110
111 /// Map that holds a list of currently available allocas for a function and
112 /// alloca size.
114
115 /// Map that holds the currently used allocas and the list where they belong.
116 /// Once an alloca has to be returned, it is returned directly to its list.
118
119 /// Instructions that should be erased later.
121
122 /// The underlying IR builder with insertion callback.
124
125 /// The current epoch number. Each instrumentation, e.g., of an instruction,
126 /// is happening in a dedicated epoch. The epoch allows to determine if
127 /// instrumentation instructions were already around, due to prior
128 /// instrumentations, or have been introduced to support the current
129 /// instrumentation, e.g., compute information about the current instruction.
130 unsigned Epoch = 0;
131
132 /// A mapping from instrumentation instructions to the epoch they have been
133 /// created.
135};
136
137/// Helper that represent the caches for instrumentation call arguments. The
138/// value of an argument may not need to be recomputed between the pre and post
139/// instrumentation calls.
141 /// A cache for direct and indirect arguments. The cache is indexed by the
142 /// epoch, the instrumentation opportunity name and the argument name. The
143 /// result is a value.
147};
148
149/// Boolean option bitset with a compile-time number of bits to store as many
150/// options as the enumeration type \p EnumTy defines. The enumeration type is
151/// expected to have an ascending and consecutive values, starting at zero, and
152/// the last value being artificial and named as NumConfig (i.e., the number of
153/// values in the enumeration).
154template <typename EnumTy> struct BaseConfigTy {
155 /// The bistset with as many bits as the enumeration's values.
156 std::bitset<static_cast<int>(EnumTy::NumConfig)> Options;
157
158 /// Construct the option bitset with all bits set to \p Enable. If not
159 /// provided, all options are enabled.
160 BaseConfigTy(bool Enable = true) {
161 if (Enable)
162 Options.set();
163 }
164
165 /// Check if the option \p Opt is enabled.
166 bool has(EnumTy Opt) const { return Options.test(static_cast<int>(Opt)); }
167
168 /// Set the boolean value of option \p Opt to \p Value.
169 void set(EnumTy Opt, bool Value = true) {
170 Options.set(static_cast<int>(Opt), Value);
171 }
172};
173
174/// Evaluate the filter expression against the current instrumentation
175/// opportunity. Returns true if the filter passes (or is empty), false
176/// otherwise. Dynamic values (non-constants) are assumed to pass.
178bool evaluateFilter(Value &V, bool &Changed, InstrumentationOpportunity &IO,
179 InstrumentationConfig &IConf,
180 InstrumentorIRBuilderTy &IIRB);
181
182} // namespace instrumentor
183} // end namespace llvm
184
185#endif // LLVM_TRANSFORMS_IPO_INSTRUMENTOR_UTILS_H
#define LLVM_ABI
Definition Compiler.h:215
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
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
an instruction to allocate memory on the stack
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
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:794
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:360
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:2901
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Class to represent pointers.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
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:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
LLVM Value Representation.
Definition Value.h:75
Changed
LLVM_ABI bool evaluateFilter(Value &V, bool &Changed, 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.
AllocaInst * getAlloca(Function *Fn, Type *Ty)
Get a temporary alloca to communicate (large) values with the runtime.
MapVector< AllocaInst *, AllocaListTy * > UsedAllocas
Map that holds the currently used allocas and the list where they belong.
InstrumentorIRBuilderTy(Module &M)
Construct an IR builder for the module M.
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.