LLVM 20.0.0git
IndirectionUtils.cpp
Go to the documentation of this file.
1//===---- IndirectionUtils.cpp - Utilities for call indirection in Orc ----===//
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
10#include "llvm/ADT/STLExtras.h"
13#include "llvm/IR/IRBuilder.h"
14#include "llvm/IR/Module.h"
17#include "llvm/Support/Format.h"
20#include <sstream>
21
22#define DEBUG_TYPE "orc"
23
24using namespace llvm;
25using namespace llvm::orc;
26
27namespace {
28
29class CompileCallbackMaterializationUnit : public orc::MaterializationUnit {
30public:
31 using CompileFunction = JITCompileCallbackManager::CompileFunction;
32
33 CompileCallbackMaterializationUnit(SymbolStringPtr Name,
34 CompileFunction Compile)
35 : MaterializationUnit(Interface(
37 Name(std::move(Name)), Compile(std::move(Compile)) {}
38
39 StringRef getName() const override { return "<Compile Callbacks>"; }
40
41private:
42 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
44 Result[Name] = {Compile(), JITSymbolFlags::Exported};
45 // No dependencies, so these calls cannot fail.
46 cantFail(R->notifyResolved(Result));
47 cantFail(R->notifyEmitted({}));
48 }
49
50 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
51 llvm_unreachable("Discard should never occur on a LMU?");
52 }
53
55 CompileFunction Compile;
56};
57
58} // namespace
59
60namespace llvm {
61namespace orc {
62
64void IndirectStubsManager::anchor() {}
65
68 if (auto TrampolineAddr = TP->getTrampoline()) {
69 auto CallbackName =
70 ES.intern(std::string("cc") + std::to_string(++NextCallbackId));
71
72 std::lock_guard<std::mutex> Lock(CCMgrMutex);
73 AddrToSymbol[*TrampolineAddr] = CallbackName;
75 CallbacksJD.define(std::make_unique<CompileCallbackMaterializationUnit>(
76 std::move(CallbackName), std::move(Compile))));
77 return *TrampolineAddr;
78 } else
79 return TrampolineAddr.takeError();
80}
81
85
86 {
87 std::unique_lock<std::mutex> Lock(CCMgrMutex);
88 auto I = AddrToSymbol.find(TrampolineAddr);
89
90 // If this address is not associated with a compile callback then report an
91 // error to the execution session and return ErrorHandlerAddress to the
92 // callee.
93 if (I == AddrToSymbol.end()) {
94 Lock.unlock();
95 ES.reportError(
96 make_error<StringError>("No compile callback for trampoline at " +
97 formatv("{0:x}", TrampolineAddr),
99 return ErrorHandlerAddress;
100 } else
101 Name = I->second;
102 }
103
104 if (auto Sym =
107 Name))
108 return Sym->getAddress();
109 else {
110 llvm::dbgs() << "Didn't find callback.\n";
111 // If anything goes wrong materializing Sym then report it to the session
112 // and return the ErrorHandlerAddress;
113 ES.reportError(Sym.takeError());
114 return ErrorHandlerAddress;
115 }
116}
117
120 ExecutorAddr ErrorHandlerAddress) {
121 switch (T.getArch()) {
122 default:
123 return make_error<StringError>(
124 std::string("No callback manager available for ") + T.str(),
126 case Triple::aarch64:
127 case Triple::aarch64_32: {
129 return CCMgrT::Create(ES, ErrorHandlerAddress);
130 }
131
132 case Triple::x86: {
134 return CCMgrT::Create(ES, ErrorHandlerAddress);
135 }
136
137 case Triple::loongarch64: {
139 return CCMgrT::Create(ES, ErrorHandlerAddress);
140 }
141
142 case Triple::mips: {
144 return CCMgrT::Create(ES, ErrorHandlerAddress);
145 }
146 case Triple::mipsel: {
148 return CCMgrT::Create(ES, ErrorHandlerAddress);
149 }
150
151 case Triple::mips64:
152 case Triple::mips64el: {
154 return CCMgrT::Create(ES, ErrorHandlerAddress);
155 }
156
157 case Triple::riscv64: {
159 return CCMgrT::Create(ES, ErrorHandlerAddress);
160 }
161
162 case Triple::x86_64: {
163 if (T.getOS() == Triple::OSType::Win32) {
165 return CCMgrT::Create(ES, ErrorHandlerAddress);
166 } else {
168 return CCMgrT::Create(ES, ErrorHandlerAddress);
169 }
170 }
171
172 }
173}
174
175std::function<std::unique_ptr<IndirectStubsManager>()>
177 switch (T.getArch()) {
178 default:
179 return [](){
180 return std::make_unique<
182 };
183
184 case Triple::aarch64:
186 return [](){
187 return std::make_unique<
189 };
190
191 case Triple::x86:
192 return [](){
193 return std::make_unique<
195 };
196
198 return []() {
199 return std::make_unique<
201 };
202
203 case Triple::mips:
204 return [](){
205 return std::make_unique<
207 };
208
209 case Triple::mipsel:
210 return [](){
211 return std::make_unique<
213 };
214
215 case Triple::mips64:
216 case Triple::mips64el:
217 return [](){
218 return std::make_unique<
220 };
221
222 case Triple::riscv64:
223 return []() {
224 return std::make_unique<
226 };
227
228 case Triple::x86_64:
229 if (T.getOS() == Triple::OSType::Win32) {
230 return [](){
231 return std::make_unique<
233 };
234 } else {
235 return [](){
236 return std::make_unique<
238 };
239 }
240
241 }
242}
243
245 Constant *AddrIntVal =
246 ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr.getValue());
247 Constant *AddrPtrVal =
248 ConstantExpr::getIntToPtr(AddrIntVal, PointerType::get(&FT, 0));
249 return AddrPtrVal;
250}
251
253 const Twine &Name, Constant *Initializer) {
254 auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
255 Initializer, Name, nullptr,
257 IP->setVisibility(GlobalValue::HiddenVisibility);
258 return IP;
259}
260
261void makeStub(Function &F, Value &ImplPointer) {
262 assert(F.isDeclaration() && "Can't turn a definition into a stub.");
263 assert(F.getParent() && "Function isn't in a module.");
264 Module &M = *F.getParent();
265 BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
266 IRBuilder<> Builder(EntryBlock);
267 LoadInst *ImplAddr = Builder.CreateLoad(F.getType(), &ImplPointer);
268 std::vector<Value*> CallArgs;
269 for (auto &A : F.args())
270 CallArgs.push_back(&A);
271 CallInst *Call = Builder.CreateCall(F.getFunctionType(), ImplAddr, CallArgs);
272 Call->setTailCall();
273 Call->setAttributes(F.getAttributes());
274 if (F.getReturnType()->isVoidTy())
275 Builder.CreateRetVoid();
276 else
277 Builder.CreateRet(Call);
278}
279
280std::vector<GlobalValue *> SymbolLinkagePromoter::operator()(Module &M) {
281 std::vector<GlobalValue *> PromotedGlobals;
282
283 for (auto &GV : M.global_values()) {
284 bool Promoted = true;
285
286 // Rename if necessary.
287 if (!GV.hasName())
288 GV.setName("__orc_anon." + Twine(NextId++));
289 else if (GV.getName().starts_with("\01L"))
290 GV.setName("__" + GV.getName().substr(1) + "." + Twine(NextId++));
291 else if (GV.hasLocalLinkage())
292 GV.setName("__orc_lcl." + GV.getName() + "." + Twine(NextId++));
293 else
294 Promoted = false;
295
296 if (GV.hasLocalLinkage()) {
297 GV.setLinkage(GlobalValue::ExternalLinkage);
298 GV.setVisibility(GlobalValue::HiddenVisibility);
299 Promoted = true;
300 }
301 GV.setUnnamedAddr(GlobalValue::UnnamedAddr::None);
302
303 if (Promoted)
304 PromotedGlobals.push_back(&GV);
305 }
306
307 return PromotedGlobals;
308}
309
311 ValueToValueMapTy *VMap) {
312 Function *NewF =
313 Function::Create(cast<FunctionType>(F.getValueType()),
314 F.getLinkage(), F.getName(), &Dst);
315 NewF->copyAttributesFrom(&F);
316
317 if (VMap) {
318 (*VMap)[&F] = NewF;
319 auto NewArgI = NewF->arg_begin();
320 for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
321 ++ArgI, ++NewArgI)
322 (*VMap)[&*ArgI] = &*NewArgI;
323 }
324
325 return NewF;
326}
327
329 ValueToValueMapTy *VMap) {
330 GlobalVariable *NewGV = new GlobalVariable(
331 Dst, GV.getValueType(), GV.isConstant(),
332 GV.getLinkage(), nullptr, GV.getName(), nullptr,
334 NewGV->copyAttributesFrom(&GV);
335 if (VMap)
336 (*VMap)[&GV] = NewGV;
337 return NewGV;
338}
339
341 ValueToValueMapTy &VMap) {
342 assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
343 auto *NewA = GlobalAlias::create(OrigA.getValueType(),
345 OrigA.getLinkage(), OrigA.getName(), &Dst);
346 NewA->copyAttributesFrom(&OrigA);
347 VMap[&OrigA] = NewA;
348 return NewA;
349}
350
353 MCDisassembler &Disassembler,
354 MCInstrAnalysis &MIA) {
355 // AArch64 appears to already come with the necessary relocations. Among other
356 // architectures, only x86_64 is currently implemented here.
357 if (G.getTargetTriple().getArch() != Triple::x86_64)
358 return Error::success();
359
360 raw_null_ostream CommentStream;
361 auto &STI = Disassembler.getSubtargetInfo();
362
363 // Determine the function bounds
364 auto &B = Sym.getBlock();
365 assert(!B.isZeroFill() && "expected content block");
366 auto SymAddress = Sym.getAddress();
367 auto SymStartInBlock =
368 (const uint8_t *)B.getContent().data() + Sym.getOffset();
369 auto SymSize = Sym.getSize() ? Sym.getSize() : B.getSize() - Sym.getOffset();
370 auto Content = ArrayRef(SymStartInBlock, SymSize);
371
372 LLVM_DEBUG(dbgs() << "Adding self-relocations to " << Sym.getName() << "\n");
373
374 SmallDenseSet<uintptr_t, 8> ExistingRelocations;
375 for (auto &E : B.edges()) {
376 if (E.isRelocation())
377 ExistingRelocations.insert(E.getOffset());
378 }
379
380 size_t I = 0;
381 while (I < Content.size()) {
382 MCInst Instr;
383 uint64_t InstrSize = 0;
384 uint64_t InstrStart = SymAddress.getValue() + I;
385 auto DecodeStatus = Disassembler.getInstruction(
386 Instr, InstrSize, Content.drop_front(I), InstrStart, CommentStream);
388 LLVM_DEBUG(dbgs() << "Aborting due to disassembly failure at address "
389 << InstrStart);
390 return make_error<StringError>(
391 formatv("failed to disassemble at address {0:x16}", InstrStart),
393 }
394 // Advance to the next instruction.
395 I += InstrSize;
396
397 // Check for a PC-relative address equal to the symbol itself.
398 auto PCRelAddr =
399 MIA.evaluateMemoryOperandAddress(Instr, &STI, InstrStart, InstrSize);
400 if (!PCRelAddr || *PCRelAddr != SymAddress.getValue())
401 continue;
402
403 auto RelocOffInInstr =
404 MIA.getMemoryOperandRelocationOffset(Instr, InstrSize);
405 if (!RelocOffInInstr || InstrSize - *RelocOffInInstr != 4) {
406 LLVM_DEBUG(dbgs() << "Skipping unknown self-relocation at "
407 << InstrStart);
408 continue;
409 }
410
411 auto RelocOffInBlock = orc::ExecutorAddr(InstrStart) + *RelocOffInInstr -
412 SymAddress + Sym.getOffset();
413 if (ExistingRelocations.contains(RelocOffInBlock))
414 continue;
415
416 LLVM_DEBUG(dbgs() << "Adding delta32 self-relocation at " << InstrStart);
417 B.addEdge(jitlink::x86_64::Delta32, RelocOffInBlock, Sym, /*Addend=*/-4);
418 }
419 return Error::success();
420}
421
422} // End namespace orc.
423} // End namespace llvm.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
T Content
uint64_t Addr
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
This class represents a function call, abstracting a target machine's calling convention.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2281
This is an important base class in LLVM.
Definition: Constant.h:42
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Class to represent function types.
Definition: DerivedTypes.h:103
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:172
arg_iterator arg_begin()
Definition: Function.h:866
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:863
const Constant * getAliasee() const
Definition: GlobalAlias.h:84
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:550
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
Type * getValueType() const
Definition: GlobalValue.h:296
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:514
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition: IRBuilder.h:1112
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:1807
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition: IRBuilder.h:1107
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2432
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2686
An instruction for reading from memory.
Definition: Instructions.h:174
Superclass for all disassemblers.
const MCSubtargetInfo & getSubtargetInfo() const
DecodeStatus
Ternary decode status.
virtual DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size, ArrayRef< uint8_t > Bytes, uint64_t Address, raw_ostream &CStream) const =0
Returns the disassembly of a single instruction.
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
virtual std::optional< uint64_t > getMemoryOperandRelocationOffset(const MCInst &Inst, uint64_t Size) const
Given an instruction with a memory operand that could require relocation, returns the offset within t...
virtual std::optional< uint64_t > evaluateMemoryOperandAddress(const MCInst &Inst, const MCSubtargetInfo *STI, uint64_t Addr, uint64_t Size) const
Given an instruction tries to get the address of a memory operand.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Class to represent pointers.
Definition: DerivedTypes.h:646
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:679
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ loongarch64
Definition: Triple.h:62
@ mips64el
Definition: Triple.h:67
@ aarch64_32
Definition: Triple.h:53
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
static IntegerType * getInt64Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
An ExecutionSession represents a running JIT program.
Definition: Core.h:1431
void reportError(Error Err)
Report a error for this execution session.
Definition: Core.h:1566
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1485
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:1810
Represents an address in the executor process.
ExecutorAddr executeCompileCallback(ExecutorAddr TrampolineAddr)
Execute the callback for the given trampoline id.
Expected< ExecutorAddr > getCompileCallback(CompileFunction Compile)
Reserve a compile callback.
std::function< ExecutorAddr()> CompileFunction
Represents a JIT'd dynamic library.
Definition: Core.h:989
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1910
IndirectStubsManager implementation for the host architecture, e.g.
Manage compile callbacks for in-process JITs.
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
Definition: Core.h:693
virtual StringRef getName() const =0
Return the name of this materialization unit.
virtual void materialize(std::unique_ptr< MaterializationResponsibility > R)=0
Implementations of this method should materialize all symbols in the materialzation unit,...
std::vector< GlobalValue * > operator()(Module &M)
Promote symbols in the given module.
Pointer to a pooled string representing a symbol name.
A raw_ostream that discards all output.
Definition: raw_ostream.h:731
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition: Core.h:166
Constant * createIRTypedAddress(FunctionType &FT, ExecutorAddr Addr)
Build a function pointer of FunctionType with the given constant address.
Expected< std::unique_ptr< JITCompileCallbackManager > > createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES, ExecutorAddr ErrorHandlerAddress)
Create a local compile callback manager.
void makeStub(Function &F, Value &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
Error addFunctionPointerRelocationsToCurrentSymbol(jitlink::Symbol &Sym, jitlink::LinkGraph &G, MCDisassembler &Disassembler, MCInstrAnalysis &MIA)
Introduce relocations to Sym in its own definition if there are any pointers formed via PC-relative a...
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
Definition: Core.h:124
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
std::function< std::unique_ptr< IndirectStubsManager >()> createLocalIndirectStubsManagerBuilder(const Triple &T)
Create a local indirect stubs manager builder.
GlobalAlias * cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA, ValueToValueMapTy &VMap)
Clone a global alias declaration into a new module.
GlobalVariable * createImplPointer(PointerType &PT, Module &M, const Twine &Name, Constant *Initializer)
Create a function pointer with the given type, name, and initializer in the given Module.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756