LLVM 24.0.0git
ReOptimizeLayer.cpp
Go to the documentation of this file.
5
6using namespace llvm;
7using namespace orc;
8
9bool ReOptimizeLayer::ReOptMaterializationUnitState::tryStartReoptimize() {
10 std::unique_lock<std::mutex> Lock(Mutex);
11 if (Reoptimizing)
12 return false;
13
14 Reoptimizing = true;
15 return true;
16}
17
18void ReOptimizeLayer::ReOptMaterializationUnitState::reoptimizeSucceeded() {
19 std::unique_lock<std::mutex> Lock(Mutex);
20 assert(Reoptimizing && "Tried to mark unstarted reoptimization as done");
21 Reoptimizing = false;
22 CurVersion++;
23}
24
25void ReOptimizeLayer::ReOptMaterializationUnitState::reoptimizeFailed() {
26 std::unique_lock<std::mutex> Lock(Mutex);
27 assert(Reoptimizing && "Tried to mark unstarted reoptimization as done");
28 Reoptimizing = false;
29}
30
32 shared::CWrapperFunctionBuffer (*JITDispatch)(void *Ctx, void *Tag,
33 const char *Data,
34 size_t Size),
35 void *JITDispatchCtx, void *Tag, uint64_t MUID, uint32_t CurVersion) {
36 // Serialize the arguments into a WrapperFunctionBuffer and call dispatch.
38 auto ArgBytes =
39 shared::WrapperFunctionBuffer::allocate(SPSArgs::size(MUID, CurVersion));
40 shared::SPSOutputBuffer OB(ArgBytes.data(), ArgBytes.size());
41 if (!SPSArgs::serialize(OB, MUID, CurVersion)) {
42 errs()
43 << "Reoptimization error: could not serialize reoptimization arguments";
44 abort();
45 }
47 JITDispatch(JITDispatchCtx, Tag, ArgBytes.data(), ArgBytes.size())};
48
49 if (const char *ErrMsg = Buf.getOutOfBandError()) {
50 errs() << "Reoptimization error: " << ErrMsg << "\naborting.\n";
51 abort();
52 }
53}
54
56 const DataLayout &DL) {
57 auto Ctx = std::make_unique<LLVMContext>();
58 auto Mod = std::make_unique<Module>("orc-rt-lite-reoptimize.ll", *Ctx);
59 Mod->setDataLayout(DL);
60
61 IRBuilder<> Builder(*Ctx);
62
63 // Create basic types portably
64 Type *VoidTy = Type::getVoidTy(*Ctx);
65 Type *Int8Ty = Type::getInt8Ty(*Ctx);
66 Type *Int32Ty = Type::getInt32Ty(*Ctx);
67 Type *Int64Ty = Type::getInt64Ty(*Ctx);
68 Type *VoidPtrTy = PointerType::getUnqual(*Ctx);
69
70 // Helper function type: void (void*, void*, void*, uint64_t, uint32_t)
71 FunctionType *HelperFnTy = FunctionType::get(
72 VoidTy, {VoidPtrTy, VoidPtrTy, VoidPtrTy, Int64Ty, Int32Ty}, false);
73
74 // Define ReoptimizeTag with initializer = 0
75 GlobalVariable *ReoptimizeTag = new GlobalVariable(
76 *Mod, Int8Ty, false, GlobalValue::ExternalLinkage,
77 ConstantInt::get(Int8Ty, 0), "__orc_rt_reoptimize_tag");
78
79 // Define orc_rt_lite_reoptimize function: void (uint64_t, uint32_t)
80 FunctionType *ReOptimizeFnTy =
81 FunctionType::get(VoidTy, {Int64Ty, Int32Ty}, false);
82
83 Function *ReOptimizeFn =
85 "__orc_rt_reoptimize", Mod.get());
86
87 // Set parameter names
88 auto ArgIt = ReOptimizeFn->arg_begin();
89 Value *MUID = &*ArgIt++;
90 MUID->setName("MUID");
91 Value *CurVersion = &*ArgIt;
92 CurVersion->setName("CurVersion");
93
94 // Build function body
95 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ReOptimizeFn);
96 Builder.SetInsertPoint(Entry);
97
98 ExecutorAddr JITDispatchSym, JITDispatchCtxSym;
99 if (auto Err =
100 lookupAndApply(ES.getBootstrapJITDylib(),
101 {recordAddr(rt::DispatchName, &JITDispatchSym),
102 recordAddr(rt::DispatchCtxName, &JITDispatchCtxSym)}))
103 return Err;
104
105 Type *IntPtrTy = DL.getIntPtrType(*Ctx);
106 Constant *JITDispatchPtr = ConstantExpr::getIntToPtr(
107 ConstantInt::get(IntPtrTy, JITDispatchSym.getValue()), VoidPtrTy);
108 Constant *JITDispatchCtxPtr = ConstantExpr::getIntToPtr(
109 ConstantInt::get(IntPtrTy, JITDispatchCtxSym.getValue()), VoidPtrTy);
110 Constant *HelperFnAddr = ConstantExpr::getIntToPtr(
111 ConstantInt::get(IntPtrTy, reinterpret_cast<uintptr_t>(
114
115 // Cast ReoptimizeTag to void*
116 Value *ReoptimizeTagPtr = Builder.CreatePointerCast(ReoptimizeTag, VoidPtrTy);
117
118 // Call the helper function
119 Builder.CreateCall(
120 HelperFnTy, HelperFnAddr,
121 {JITDispatchPtr, JITDispatchCtxPtr, ReoptimizeTagPtr, MUID, CurVersion});
122
123 // Return void
124 Builder.CreateRetVoid();
125
126 return BaseLayer.add(PlatformJD,
127 ThreadSafeModule(std::move(Mod), std::move(Ctx)));
128}
129
132 using ReoptimizeSPSSig = shared::SPSError(uint64_t, uint32_t);
133 WFs[Mangle("__orc_rt_reoptimize_tag")] =
134 ES.wrapAsyncWithSPS<ReoptimizeSPSSig>(this,
135 &ReOptimizeLayer::rt_reoptimize);
136 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
137}
138
139void ReOptimizeLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
140 ThreadSafeModule TSM) {
141 auto &JD = R->getTargetJITDylib();
142
143 bool HasNonCallable = false;
144 for (auto &KV : R->getSymbols()) {
145 auto &Flags = KV.second;
146 if (!Flags.isCallable())
147 HasNonCallable = true;
148 }
149
150 if (HasNonCallable) {
151 BaseLayer.emit(std::move(R), std::move(TSM));
152 return;
153 }
154
155 auto &MUState = createMaterializationUnitState(TSM);
156
157 if (auto Err = R->withResourceKeyDo([&](ResourceKey Key) {
158 registerMaterializationUnitResource(Key, MUState);
159 })) {
160 ES.reportError(std::move(Err));
161 R->failMaterialization();
162 return;
163 }
164
165 if (auto Err =
166 ProfilerFunc(*this, MUState.getID(), MUState.getCurVersion(), TSM)) {
167 ES.reportError(std::move(Err));
168 R->failMaterialization();
169 return;
170 }
171
172 auto InitialDests =
173 emitMUImplSymbols(MUState, MUState.getCurVersion(), JD, std::move(TSM));
174 if (!InitialDests) {
175 ES.reportError(InitialDests.takeError());
176 R->failMaterialization();
177 return;
178 }
179
180 RSManager.emitRedirectableSymbols(std::move(R), std::move(*InitialDests));
181}
182
185 unsigned CurVersion,
186 ThreadSafeModule &TSM) {
187 return TSM.withModuleDo([&](Module &M) -> Error {
188 Type *I64Ty = Type::getInt64Ty(M.getContext());
189 GlobalVariable *Counter = new GlobalVariable(
190 M, I64Ty, false, GlobalValue::InternalLinkage,
191 Constant::getNullValue(I64Ty), "__orc_reopt_counter");
192 for (auto &F : M) {
193 if (F.isDeclaration())
194 continue;
195 auto &BB = F.getEntryBlock();
196 auto *IP = &*BB.getFirstInsertionPt();
197 IRBuilder<> IRB(IP);
198 Value *Threshold = ConstantInt::get(I64Ty, CallCountThreshold, true);
199 Value *Cnt = IRB.CreateLoad(I64Ty, Counter);
200 // Use EQ to prevent further reoptimize calls.
201 Value *Cmp = IRB.CreateICmpEQ(Cnt, Threshold);
202 Value *Added = IRB.CreateAdd(Cnt, ConstantInt::get(I64Ty, 1));
203 (void)IRB.CreateStore(Added, Counter);
204 Instruction *SplitTerminator = SplitBlockAndInsertIfThen(Cmp, IP, false);
205 createReoptimizeCall(M, *SplitTerminator, MUID, CurVersion);
206 }
207 return Error::success();
208 });
209}
210
212ReOptimizeLayer::emitMUImplSymbols(ReOptMaterializationUnitState &MUState,
214 ThreadSafeModule TSM) {
216 cantFail(TSM.withModuleDo([&](Module &M) -> Error {
217 MangleAndInterner Mangle(ES, M.getDataLayout());
218 for (auto &F : M)
219 if (!F.isDeclaration()) {
220 std::string NewName =
221 (F.getName() + ".__def__." + Twine(Version)).str();
222 RenamedMap[Mangle(F.getName())] = Mangle(NewName);
223 F.setName(NewName);
224 }
225 return Error::success();
226 }));
227
228 auto RT = JD.createResourceTracker();
229 if (auto Err =
230 JD.define(std::make_unique<BasicIRLayerMaterializationUnit>(
231 BaseLayer, *getManglingOptions(), std::move(TSM)),
232 RT))
233 return Err;
234 MUState.setResourceTracker(RT);
235
236 SymbolLookupSet LookupSymbols;
237 for (auto [K, V] : RenamedMap)
238 LookupSymbols.add(V);
239
240 auto ImplSymbols =
241 ES.lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}}, LookupSymbols,
243 if (auto Err = ImplSymbols.takeError())
244 return Err;
245
247 for (auto [K, V] : RenamedMap)
248 Result[K] = (*ImplSymbols)[V];
249
250 return Result;
251}
252
253void ReOptimizeLayer::rt_reoptimize(SendErrorFn SendResult,
255 uint32_t CurVersion) {
256 auto &MUState = getMaterializationUnitState(MUID);
257 if (CurVersion < MUState.getCurVersion() || !MUState.tryStartReoptimize()) {
258 SendResult(Error::success());
259 return;
260 }
261
262 ThreadSafeModule TSM = cloneToNewContext(MUState.getThreadSafeModule());
263 auto OldRT = MUState.getResourceTracker();
264 auto &JD = OldRT->getJITDylib();
265
266 if (auto Err = ReOptFunc(*this, MUID, CurVersion + 1, OldRT, TSM)) {
267 ES.reportError(std::move(Err));
268 MUState.reoptimizeFailed();
269 SendResult(Error::success());
270 return;
271 }
272
273 auto SymbolDests =
274 emitMUImplSymbols(MUState, CurVersion + 1, JD, std::move(TSM));
275 if (!SymbolDests) {
276 ES.reportError(SymbolDests.takeError());
277 MUState.reoptimizeFailed();
278 SendResult(Error::success());
279 return;
280 }
281
282 if (auto Err = RSManager.redirect(JD, std::move(*SymbolDests))) {
283 ES.reportError(std::move(Err));
284 MUState.reoptimizeFailed();
285 SendResult(Error::success());
286 return;
287 }
288
289 MUState.reoptimizeSucceeded();
290 SendResult(Error::success());
291}
292
295 uint32_t CurVersion) {
296 Type *MUIDTy = IntegerType::get(M.getContext(), 64);
297 Type *VersionTy = IntegerType::get(M.getContext(), 32);
298 Function *ReoptimizeFunc = M.getFunction("__orc_rt_reoptimize");
299 if (!ReoptimizeFunc) {
300 std::vector<Type *> ArgTys = {MUIDTy, VersionTy};
301 FunctionType *FuncTy =
302 FunctionType::get(Type::getVoidTy(M.getContext()), ArgTys, false);
303 ReoptimizeFunc = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
304 "__orc_rt_reoptimize", &M);
305 }
306 Constant *MUIDArg = ConstantInt::get(MUIDTy, MUID, false);
307 Constant *CurVersionArg = ConstantInt::get(VersionTy, CurVersion, false);
308 IRBuilder<> IRB(&IP);
309 (void)IRB.CreateCall(ReoptimizeFunc, {MUIDArg, CurVersionArg});
310}
311
312ReOptimizeLayer::ReOptMaterializationUnitState &
313ReOptimizeLayer::createMaterializationUnitState(const ThreadSafeModule &TSM) {
314 std::unique_lock<std::mutex> Lock(Mutex);
315 ReOptMaterializationUnitID MUID = NextID;
316 MUStates.emplace(MUID,
317 ReOptMaterializationUnitState(MUID, cloneToNewContext(TSM)));
318 ++NextID;
319 return MUStates.at(MUID);
320}
321
322ReOptimizeLayer::ReOptMaterializationUnitState &
323ReOptimizeLayer::getMaterializationUnitState(ReOptMaterializationUnitID MUID) {
324 std::unique_lock<std::mutex> Lock(Mutex);
325 return MUStates.at(MUID);
326}
327
328void ReOptimizeLayer::registerMaterializationUnitResource(
329 ResourceKey Key, ReOptMaterializationUnitState &State) {
330 std::unique_lock<std::mutex> Lock(Mutex);
331 MUResources[Key].insert(State.getID());
332}
333
335 std::unique_lock<std::mutex> Lock(Mutex);
336 for (auto MUID : MUResources[K])
337 MUStates.erase(MUID);
338
339 MUResources.erase(K);
340 return Error::success();
341}
342
344 ResourceKey SrcK) {
345 std::unique_lock<std::mutex> Lock(Mutex);
346 MUResources[DstK].insert_range(MUResources[SrcK]);
347 MUResources.erase(SrcK);
348}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define F(x, y, z)
Definition MD5.cpp:54
static void orc_rt_lite_reoptimize_helper(shared::CWrapperFunctionBuffer(*JITDispatch)(void *Ctx, void *Tag, const char *Data, size_t Size), void *JITDispatchCtx, void *Tag, uint64_t MUID, uint32_t CurVersion)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
const Function & getFunction() const
Definition Function.h:166
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2375
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1906
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1422
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2554
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
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:310
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition Core.cpp:1764
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1134
Represents an address in the executor process.
uint64_t getValue() const
const IRSymbolMapper::ManglingOptions *& getManglingOptions() const
Get the mangling options for this layer.
Definition Layer.h:79
Represents a JIT'd dynamic library.
Definition Core.h:675
Error registerRuntimeFunctions(JITDylib &PlatformJD)
Registers reoptimize runtime dispatch handlers to given PlatformJD.
ReOptimizeLayer(ExecutionSession &ES, DataLayout &DL, IRLayer &BaseLayer, RedirectableSymbolManager &RM)
void emit(std::unique_ptr< MaterializationResponsibility > R, ThreadSafeModule TSM) override
Emits the given module.
static void createReoptimizeCall(Module &M, Instruction &IP, ReOptMaterializationUnitID MUID, unsigned CurVersion)
void handleTransferResources(JITDylib &JD, ResourceKey DstK, ResourceKey SrcK) override
This function will be called inside the session lock.
Error addOrcRTLiteSupport(JITDylib &PlatformJD, const DataLayout &DL)
Add ORC Runtime-lite support for reoptimization to PlatformJD.
static Error reoptimizeIfCallFrequent(ReOptimizeLayer &Parent, ReOptMaterializationUnitID MUID, unsigned CurVersion, ThreadSafeModule &TSM)
Basic AddProfilerFunc that reoptimizes the function when the call count exceeds CallCountThreshold.
Error handleRemoveResources(JITDylib &JD, ResourceKey K) override
This function will be called outside the session lock.
static const uint64_t CallCountThreshold
A set of symbols to look up, each associated with a SymbolLookupFlags value.
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
An LLVM Module together with a shared ThreadSafeContext.
decltype(auto) withModuleDo(Func &&F)
Locks the associated ThreadSafeContext and calls the given function on the contained Module.
A utility class for serializing to a blob from a variadic list.
Output char buffer with overflow check.
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
const char * getOutOfBandError() const
If this value is an out-of-band error then this returns the error message, otherwise returns nullptr.
static WrapperFunctionBuffer allocate(size_t Size)
Create a WrapperFunctionBuffer with the given size and return a pointer to the underlying memory.
uintptr_t ResourceKey
Definition Core.h:60
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LLVM_ABI void lookupAndApply(unique_function< void(Error)> OnApplied, ExecutionSession &ES, LookupKind K, const JITDylibSearchOrder &SearchOrder, ArrayRef< LookupPrepareFn > PrepareFns)
Resolve the symbols contributed by every prepare function with a single lookup, then let each of thei...
LLVM_ABI ThreadSafeModule cloneToNewContext(const ThreadSafeModule &TSMW, GVPredicate ShouldCloneDef=GVPredicate(), GVModifier UpdateClonedDefSource=GVModifier())
Clones the given module on to a new context.
@ Resolved
Queried, materialization begun.
Definition Core.h:549
SmartMutex< false > Mutex
Mutex - A standard, always enforced mutex.
Definition Mutex.h:66
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...