LLVM 20.0.0git
Context.h
Go to the documentation of this file.
1//===- Context.h ------------------------------------------------*- 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#ifndef LLVM_SANDBOXIR_CONTEXT_H
10#define LLVM_SANDBOXIR_CONTEXT_H
11
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/MapVector.h"
15#include "llvm/IR/LLVMContext.h"
17#include "llvm/SandboxIR/Type.h"
18
19#include <cstdint>
20
21namespace llvm {
22namespace sandboxir {
23
24class Argument;
25class BBIterator;
26class Constant;
27class Module;
28class Value;
29
30class Context {
31public:
32 // A EraseInstrCallback receives the instruction about to be erased.
33 using EraseInstrCallback = std::function<void(Instruction *)>;
34 // A CreateInstrCallback receives the instruction about to be created.
35 using CreateInstrCallback = std::function<void(Instruction *)>;
36 // A MoveInstrCallback receives the instruction about to be moved, the
37 // destination BB and an iterator pointing to the insertion position.
39 std::function<void(Instruction *, const BBIterator &)>;
40
41 /// An ID for a registered callback. Used for deregistration. A dedicated type
42 /// is employed so as to keep IDs opaque to the end user; only Context should
43 /// deal with its underlying representation.
44 class CallbackID {
45 public:
46 // Uses a 64-bit integer so we don't have to worry about the unlikely case
47 // of overflowing a 32-bit counter.
48 using ValTy = uint64_t;
49 static constexpr const ValTy InvalidVal = 0;
50
51 private:
52 // Default initialization results in an invalid ID.
53 ValTy Val = InvalidVal;
54 explicit CallbackID(ValTy Val) : Val{Val} {
55 assert(Val != InvalidVal && "newly-created ID is invalid!");
56 }
57
58 public:
59 CallbackID() = default;
60 friend class Context;
61 friend struct DenseMapInfo<CallbackID>;
62 };
63
64protected:
66 friend class Type; // For LLVMCtx.
67 friend class PointerType; // For LLVMCtx.
68 friend class IntegerType; // For LLVMCtx.
69 friend class StructType; // For LLVMCtx.
70 friend class Region; // For LLVMCtx.
71 friend class IRSnapshotChecker; // To snapshot LLVMModuleToModuleMap.
72
74
75 /// Maps LLVM Value to the corresponding sandboxir::Value. Owns all
76 /// SandboxIR objects.
78
79 /// Maps an LLVM Module to the corresponding sandboxir::Module.
81
82 /// Type has a protected destructor to prohibit the user from managing the
83 /// lifetime of the Type objects. Context is friend of Type, and this custom
84 /// deleter can destroy Type.
85 struct TypeDeleter {
86 void operator()(Type *Ty) { delete Ty; }
87 };
88 /// Maps LLVM Type to the corresonding sandboxir::Type. Owns all Sandbox IR
89 /// Type objects.
91
92 /// Callbacks called when an IR instruction is about to get erased. Keys are
93 /// used as IDs for deregistration.
95 /// Callbacks called when an IR instruction is about to get created. Keys are
96 /// used as IDs for deregistration.
98 /// Callbacks called when an IR instruction is about to get moved. Keys are
99 /// used as IDs for deregistration.
101
102 /// A counter used for assigning callback IDs during registration. The same
103 /// counter is used for all kinds of callbacks so we can detect mismatched
104 /// registration/deregistration.
106
107 /// Remove \p V from the maps and returns the unique_ptr.
108 std::unique_ptr<Value> detachLLVMValue(llvm::Value *V);
109 /// Remove \p SBV from all SandboxIR maps and stop owning it. This effectively
110 /// detaches \p V from the underlying IR.
111 std::unique_ptr<Value> detach(Value *V);
112 friend class Instruction; // For detach().
113 /// Take ownership of VPtr and store it in `LLVMValueToValueMap`.
114 Value *registerValue(std::unique_ptr<Value> &&VPtr);
115 friend class EraseFromParent; // For registerValue().
116 /// This is the actual function that creates sandboxir values for \p V,
117 /// and among others handles all instruction types.
119 /// Get or create a sandboxir::Argument for an existing LLVM IR \p LLVMArg.
121 /// Get or create a sandboxir::Value for an existing LLVM IR \p LLVMV.
123 return getOrCreateValueInternal(LLVMV, 0);
124 }
125 /// Get or create a sandboxir::Constant from an existing LLVM IR \p LLVMC.
127 friend class Utils; // For getMemoryBase
128
131 void runMoveInstrCallbacks(Instruction *I, const BBIterator &Where);
132
133 // Friends for getOrCreateConstant().
134#define DEF_CONST(ID, CLASS) friend class CLASS;
135#include "llvm/SandboxIR/Values.def"
136
137 /// Create a sandboxir::BasicBlock for an existing LLVM IR \p BB. This will
138 /// also create all contents of the block.
140 friend class BasicBlock; // For getOrCreateValue().
141
143 auto &getLLVMIRBuilder() { return LLVMIRBuilder; }
144
146 friend VAArgInst; // For createVAArgInst()
148 friend FreezeInst; // For createFreezeInst()
150 friend FenceInst; // For createFenceInst()
152 friend SelectInst; // For createSelectInst()
154 friend InsertElementInst; // For createInsertElementInst()
156 friend ExtractElementInst; // For createExtractElementInst()
158 friend ShuffleVectorInst; // For createShuffleVectorInst()
160 friend ExtractValueInst; // For createExtractValueInst()
162 friend InsertValueInst; // For createInsertValueInst()
164 friend BranchInst; // For createBranchInst()
166 friend LoadInst; // For createLoadInst()
168 friend StoreInst; // For createStoreInst()
170 friend ReturnInst; // For createReturnInst()
172 friend CallInst; // For createCallInst()
174 friend InvokeInst; // For createInvokeInst()
176 friend CallBrInst; // For createCallBrInst()
178 friend LandingPadInst; // For createLandingPadInst()
180 friend CatchPadInst; // For createCatchPadInst()
182 friend CleanupPadInst; // For createCleanupPadInst()
184 friend CatchReturnInst; // For createCatchReturnInst()
186 friend CleanupReturnInst; // For createCleanupReturnInst()
188 friend GetElementPtrInst; // For createGetElementPtrInst()
190 friend CatchSwitchInst; // For createCatchSwitchInst()
192 friend ResumeInst; // For createResumeInst()
194 friend SwitchInst; // For createSwitchInst()
196 friend UnaryOperator; // For createUnaryOperator()
198 friend BinaryOperator; // For createBinaryOperator()
200 friend AtomicRMWInst; // For createAtomicRMWInst()
202 friend AtomicCmpXchgInst; // For createAtomicCmpXchgInst()
204 friend AllocaInst; // For createAllocaInst()
206 friend CastInst; // For createCastInst()
208 friend PHINode; // For createPHINode()
210 friend UnreachableInst; // For createUnreachableInst()
212 friend CmpInst; // For createCmpInst()
214 friend ICmpInst; // For createICmpInst()
216 friend FCmpInst; // For createFCmpInst()
217
218public:
220 ~Context();
221
223 /// Convenience function for `getTracker().save()`
224 void save() { IRTracker.save(); }
225 /// Convenience function for `getTracker().revert()`
226 void revert() { IRTracker.revert(); }
227 /// Convenience function for `getTracker().accept()`
228 void accept() { IRTracker.accept(); }
229
231 const sandboxir::Value *getValue(const llvm::Value *V) const {
232 return getValue(const_cast<llvm::Value *>(V));
233 }
234
235 Module *getModule(llvm::Module *LLVMM) const;
236
238
240 if (LLVMTy == nullptr)
241 return nullptr;
242 auto Pair = LLVMTypeToTypeMap.insert({LLVMTy, nullptr});
243 auto It = Pair.first;
244 if (Pair.second)
245 It->second = std::unique_ptr<Type, TypeDeleter>(new Type(LLVMTy, *this));
246 return It->second.get();
247 }
248
249 /// Create a sandboxir::Function for an existing LLVM IR \p F, including all
250 /// blocks and instructions.
251 /// This is the main API function for creating Sandbox IR.
252 /// Note: this will not fully populate its parent module. The only globals
253 /// that will be available are those used within the function.
255
256 /// Create a sandboxir::Module corresponding to \p LLVMM.
258
259 /// \Returns the number of values registered with Context.
260 size_t getNumValues() const { return LLVMValueToValueMap.size(); }
261
262 /// Register a callback that gets called when a SandboxIR instruction is about
263 /// to be removed from its parent. Note that this will also be called when
264 /// reverting the creation of an instruction.
265 /// \Returns a callback ID for later deregistration.
267 void unregisterEraseInstrCallback(CallbackID ID);
268
269 /// Register a callback that gets called right after a SandboxIR instruction
270 /// is created. Note that this will also be called when reverting the removal
271 /// of an instruction.
272 /// \Returns a callback ID for later deregistration.
274 void unregisterCreateInstrCallback(CallbackID ID);
275
276 /// Register a callback that gets called when a SandboxIR instruction is about
277 /// to be moved. Note that this will also be called when reverting a move.
278 /// \Returns a callback ID for later deregistration.
280 void unregisterMoveInstrCallback(CallbackID ID);
281
282 // TODO: Add callbacks for instructions inserted/removed if needed.
283};
284
285} // namespace sandboxir
286
287// DenseMap info for CallbackIDs
288template <> struct DenseMapInfo<sandboxir::Context::CallbackID> {
291
293 return CallbackID{ReprInfo::getEmptyKey()};
294 }
296 return CallbackID{ReprInfo::getTombstoneKey()};
297 }
298 static unsigned getHashValue(const CallbackID &ID) {
299 return ReprInfo::getHashValue(ID.Val);
300 }
301 static bool isEqual(const CallbackID &LHS, const CallbackID &RHS) {
302 return ReprInfo::isEqual(LHS.Val, RHS.Val);
303 }
304};
305
306} // namespace llvm
307
308#endif // LLVM_SANDBOXIR_CONTEXT_H
This file defines the DenseMap class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Value * RHS
Value * LHS
an instruction to allocate memory on the stack
Definition: Instructions.h:63
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:501
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:704
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
Conditional or Unconditional Branch instruction.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:444
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:661
This is an important base class in LLVM.
Definition: Constant.h:42
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
This instruction compares its operands according to the predicate given to the constructor.
An instruction for ordering other memory operations.
Definition: Instructions.h:424
This class represents a freeze function that returns random concrete value if an operand is either a ...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:933
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2704
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
The landingpad instruction holds all of the information necessary to generate correct exception handl...
An instruction for reading from memory.
Definition: Instructions.h:176
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Resume the propagation of an exception.
Return a value (possibly void), from a function.
This class represents the LLVM 'select' instruction.
This instruction constructs a fixed permutation of two input vectors.
An instruction for storing to memory.
Definition: Instructions.h:292
Multiway switch.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
This function has undefined behavior.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Definition: Value.h:74
Argument of a sandboxir::Function.
Definition: Argument.h:18
Iterator for Instructions in a `BasicBlock.
Definition: BasicBlock.h:23
Contains a list of sandboxir::Instruction's.
Definition: BasicBlock.h:67
An ID for a registered callback.
Definition: Context.h:44
static constexpr const ValTy InvalidVal
Definition: Context.h:49
BasicBlock * createBasicBlock(llvm::BasicBlock *BB)
Create a sandboxir::BasicBlock for an existing LLVM IR BB.
Definition: Context.cpp:421
std::function< void(Instruction *)> CreateInstrCallback
Definition: Context.h:35
GetElementPtrInst * createGetElementPtrInst(llvm::GetElementPtrInst *I)
Definition: Context.cpp:546
MapVector< CallbackID, CreateInstrCallback > CreateInstrCallbacks
Callbacks called when an IR instruction is about to get created.
Definition: Context.h:97
friend class Type
MessagePack types as defined in the standard, with the exception of Integer being divided into a sign...
Definition: Context.h:66
CmpInst * createCmpInst(llvm::CmpInst *I)
CallBrInst * createCallBrInst(llvm::CallBrInst *I)
Definition: Context.cpp:513
Module * createModule(llvm::Module *LLVMM)
Create a sandboxir::Module corresponding to LLVMM.
Definition: Context.cpp:648
IRBuilder< ConstantFolder > LLVMIRBuilder
Definition: Context.h:142
MapVector< CallbackID, EraseInstrCallback > EraseInstrCallbacks
Callbacks called when an IR instruction is about to get erased.
Definition: Context.h:94
sandboxir::Value * getValue(llvm::Value *V) const
Definition: Context.cpp:601
Argument * getOrCreateArgument(llvm::Argument *LLVMArg)
Get or create a sandboxir::Argument for an existing LLVM IR LLVMArg.
Definition: Context.cpp:407
ReturnInst * createReturnInst(llvm::ReturnInst *I)
Definition: Context.cpp:498
void runEraseInstrCallbacks(Instruction *I)
Definition: Context.cpp:666
Module * getModule(llvm::Module *LLVMM) const
Definition: Context.cpp:614
VAArgInst * createVAArgInst(llvm::VAArgInst *SI)
Definition: Context.cpp:430
auto & getLLVMIRBuilder()
Definition: Context.h:143
CleanupReturnInst * createCleanupReturnInst(llvm::CleanupReturnInst *I)
Definition: Context.cpp:540
AllocaInst * createAllocaInst(llvm::AllocaInst *I)
Definition: Context.cpp:581
Type * getType(llvm::Type *LLVMTy)
Definition: Context.h:239
void runCreateInstrCallbacks(Instruction *I)
Definition: Context.cpp:671
AtomicRMWInst * createAtomicRMWInst(llvm::AtomicRMWInst *I)
Definition: Context.cpp:571
InsertValueInst * createInsertValueInst(llvm::InsertValueInst *IVI)
Definition: Context.cpp:477
const sandboxir::Value * getValue(const llvm::Value *V) const
Definition: Context.h:231
DenseMap< llvm::Type *, std::unique_ptr< Type, TypeDeleter > > LLVMTypeToTypeMap
Maps LLVM Type to the corresonding sandboxir::Type.
Definition: Context.h:90
void accept()
Convenience function for getTracker().accept()
Definition: Context.h:228
FCmpInst * createFCmpInst(llvm::FCmpInst *I)
Definition: Context.cpp:597
std::function< void(Instruction *)> EraseInstrCallback
Definition: Context.h:33
CallbackID::ValTy NextCallbackID
A counter used for assigning callback IDs during registration.
Definition: Context.h:105
std::function< void(Instruction *, const BBIterator &)> MoveInstrCallback
Definition: Context.h:39
ExtractElementInst * createExtractElementInst(llvm::ExtractElementInst *EEI)
Definition: Context.cpp:451
Constant * getOrCreateConstant(llvm::Constant *LLVMC)
Get or create a sandboxir::Constant from an existing LLVM IR LLVMC.
Definition: Context.cpp:417
BranchInst * createBranchInst(llvm::BranchInst *I)
Definition: Context.cpp:483
ShuffleVectorInst * createShuffleVectorInst(llvm::ShuffleVectorInst *SVI)
Definition: Context.cpp:465
BinaryOperator * createBinaryOperator(llvm::BinaryOperator *I)
Definition: Context.cpp:567
Module * getOrCreateModule(llvm::Module *LLVMM)
Definition: Context.cpp:621
LoadInst * createLoadInst(llvm::LoadInst *LI)
Definition: Context.cpp:488
DenseMap< llvm::Value *, std::unique_ptr< Value > > LLVMValueToValueMap
Maps LLVM Value to the corresponding sandboxir::Value.
Definition: Context.h:77
FreezeInst * createFreezeInst(llvm::FreezeInst *SI)
Definition: Context.cpp:435
PHINode * createPHINode(llvm::PHINode *I)
Definition: Context.cpp:589
CallbackID registerCreateInstrCallback(CreateInstrCallback CB)
Register a callback that gets called right after a SandboxIR instruction is created.
Definition: Context.cpp:700
CatchPadInst * createCatchPadInst(llvm::CatchPadInst *I)
Definition: Context.cpp:527
ICmpInst * createICmpInst(llvm::ICmpInst *I)
Definition: Context.cpp:593
MapVector< CallbackID, MoveInstrCallback > MoveInstrCallbacks
Callbacks called when an IR instruction is about to get moved.
Definition: Context.h:100
std::unique_ptr< Value > detach(Value *V)
Remove SBV from all SandboxIR maps and stop owning it.
Definition: Context.cpp:27
void unregisterCreateInstrCallback(CallbackID ID)
Definition: Context.cpp:707
ExtractValueInst * createExtractValueInst(llvm::ExtractValueInst *IVI)
Definition: Context.cpp:471
void revert()
Convenience function for getTracker().revert()
Definition: Context.h:226
CastInst * createCastInst(llvm::CastInst *I)
Definition: Context.cpp:585
DenseMap< llvm::Module *, std::unique_ptr< Module > > LLVMModuleToModuleMap
Maps an LLVM Module to the corresponding sandboxir::Module.
Definition: Context.h:80
StoreInst * createStoreInst(llvm::StoreInst *SI)
Definition: Context.cpp:493
CatchReturnInst * createCatchReturnInst(llvm::CatchReturnInst *I)
Definition: Context.cpp:535
CatchSwitchInst * createCatchSwitchInst(llvm::CatchSwitchInst *I)
Definition: Context.cpp:551
void unregisterMoveInstrCallback(CallbackID ID)
Definition: Context.cpp:720
void save()
Convenience function for getTracker().save()
Definition: Context.h:224
CleanupPadInst * createCleanupPadInst(llvm::CleanupPadInst *I)
Definition: Context.cpp:531
Value * getOrCreateValue(llvm::Value *LLVMV)
Get or create a sandboxir::Value for an existing LLVM IR LLVMV.
Definition: Context.h:122
FenceInst * createFenceInst(llvm::FenceInst *SI)
Definition: Context.cpp:440
CallInst * createCallInst(llvm::CallInst *I)
Definition: Context.cpp:503
SwitchInst * createSwitchInst(llvm::SwitchInst *I)
Definition: Context.cpp:559
void runMoveInstrCallbacks(Instruction *I, const BBIterator &Where)
Definition: Context.cpp:676
UnaryOperator * createUnaryOperator(llvm::UnaryOperator *I)
Definition: Context.cpp:563
Value * getOrCreateValueInternal(llvm::Value *V, llvm::User *U=nullptr)
This is the actual function that creates sandboxir values for V, and among others handles all instruc...
Definition: Context.cpp:55
InvokeInst * createInvokeInst(llvm::InvokeInst *I)
Definition: Context.cpp:508
Value * registerValue(std::unique_ptr< Value > &&VPtr)
Take ownership of VPtr and store it in LLVMValueToValueMap.
Definition: Context.cpp:34
LandingPadInst * createLandingPadInst(llvm::LandingPadInst *I)
Definition: Context.cpp:523
InsertElementInst * createInsertElementInst(llvm::InsertElementInst *IEI)
Definition: Context.cpp:458
Function * createFunction(llvm::Function *F)
Create a sandboxir::Function for an existing LLVM IR F, including all blocks and instructions.
Definition: Context.cpp:630
SelectInst * createSelectInst(llvm::SelectInst *SI)
Definition: Context.cpp:445
ResumeInst * createResumeInst(llvm::ResumeInst *I)
Definition: Context.cpp:555
void unregisterEraseInstrCallback(CallbackID ID)
Definition: Context.cpp:693
LLVMContext & LLVMCtx
Definition: Context.h:65
Tracker & getTracker()
Definition: Context.h:222
friend class BasicBlock
Various leaf nodes.
Definition: Context.h:140
CallbackID registerMoveInstrCallback(MoveInstrCallback CB)
Register a callback that gets called when a SandboxIR instruction is about to be moved.
Definition: Context.cpp:713
UnreachableInst * createUnreachableInst(llvm::UnreachableInst *UI)
Definition: Context.cpp:518
AtomicCmpXchgInst * createAtomicCmpXchgInst(llvm::AtomicCmpXchgInst *I)
Definition: Context.cpp:576
CallbackID registerEraseInstrCallback(EraseInstrCallback CB)
Register a callback that gets called when a SandboxIR instruction is about to be removed from its par...
Definition: Context.cpp:686
size_t getNumValues() const
\Returns the number of values registered with Context.
Definition: Context.h:260
std::unique_ptr< Value > detachLLVMValue(llvm::Value *V)
Remove V from the maps and returns the unique_ptr.
Definition: Context.cpp:16
A class that saves hashes and textual IR snapshots of functions in a SandboxIR Context,...
Definition: Tracker.h:77
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition: Instruction.h:42
Class to represent integer types.
Definition: Type.h:462
In SandboxIR the Module is mainly used to access the list of global objects.
Definition: Module.h:31
The main job of the Region is to point to new instructions generated by vectorization passes.
Definition: Region.h:54
The tracker collects all the change objects and implements the main API for saving / reverting / acce...
Definition: Tracker.h:440
void revert()
Stops tracking and reverts to saved state.
Definition: Tracker.cpp:348
void save()
Turns on IR tracking.
Definition: Tracker.cpp:341
void accept()
Stops tracking and accept changes.
Definition: Tracker.cpp:359
Just like llvm::Type these are immutable, unique, never get freed and can only be created via static ...
Definition: Type.h:43
A SandboxIR Value has users. This is the base class.
Definition: Value.h:63
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
static unsigned getHashValue(const CallbackID &ID)
Definition: Context.h:298
static bool isEqual(const CallbackID &LHS, const CallbackID &RHS)
Definition: Context.h:301
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52
Type has a protected destructor to prohibit the user from managing the lifetime of the Type objects.
Definition: Context.h:85