xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/IndirectionUtils.cpp (revision 3078531de10dcae44b253a35125c949ff4235284)
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 
9 #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/Triple.h"
12 #include "llvm/ExecutionEngine/JITLink/x86_64.h"
13 #include "llvm/ExecutionEngine/Orc/OrcABISupport.h"
14 #include "llvm/IR/IRBuilder.h"
15 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
16 #include "llvm/MC/MCInstrAnalysis.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Transforms/Utils/Cloning.h"
19 #include <sstream>
20 
21 #define DEBUG_TYPE "orc"
22 
23 using namespace llvm;
24 using namespace llvm::orc;
25 
26 namespace {
27 
28 class CompileCallbackMaterializationUnit : public orc::MaterializationUnit {
29 public:
30   using CompileFunction = JITCompileCallbackManager::CompileFunction;
31 
32   CompileCallbackMaterializationUnit(SymbolStringPtr Name,
33                                      CompileFunction Compile)
34       : MaterializationUnit(Interface(
35             SymbolFlagsMap({{Name, JITSymbolFlags::Exported}}), nullptr)),
36         Name(std::move(Name)), Compile(std::move(Compile)) {}
37 
38   StringRef getName() const override { return "<Compile Callbacks>"; }
39 
40 private:
41   void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
42     SymbolMap Result;
43     Result[Name] = JITEvaluatedSymbol(Compile(), JITSymbolFlags::Exported);
44     // No dependencies, so these calls cannot fail.
45     cantFail(R->notifyResolved(Result));
46     cantFail(R->notifyEmitted());
47   }
48 
49   void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
50     llvm_unreachable("Discard should never occur on a LMU?");
51   }
52 
53   SymbolStringPtr Name;
54   CompileFunction Compile;
55 };
56 
57 } // namespace
58 
59 namespace llvm {
60 namespace orc {
61 
62 TrampolinePool::~TrampolinePool() {}
63 void IndirectStubsManager::anchor() {}
64 
65 Expected<JITTargetAddress>
66 JITCompileCallbackManager::getCompileCallback(CompileFunction Compile) {
67   if (auto TrampolineAddr = TP->getTrampoline()) {
68     auto CallbackName =
69         ES.intern(std::string("cc") + std::to_string(++NextCallbackId));
70 
71     std::lock_guard<std::mutex> Lock(CCMgrMutex);
72     AddrToSymbol[*TrampolineAddr] = CallbackName;
73     cantFail(
74         CallbacksJD.define(std::make_unique<CompileCallbackMaterializationUnit>(
75             std::move(CallbackName), std::move(Compile))));
76     return *TrampolineAddr;
77   } else
78     return TrampolineAddr.takeError();
79 }
80 
81 JITTargetAddress JITCompileCallbackManager::executeCompileCallback(
82     JITTargetAddress TrampolineAddr) {
83   SymbolStringPtr Name;
84 
85   {
86     std::unique_lock<std::mutex> Lock(CCMgrMutex);
87     auto I = AddrToSymbol.find(TrampolineAddr);
88 
89     // If this address is not associated with a compile callback then report an
90     // error to the execution session and return ErrorHandlerAddress to the
91     // callee.
92     if (I == AddrToSymbol.end()) {
93       Lock.unlock();
94       std::string ErrMsg;
95       {
96         raw_string_ostream ErrMsgStream(ErrMsg);
97         ErrMsgStream << "No compile callback for trampoline at "
98                      << format("0x%016" PRIx64, TrampolineAddr);
99       }
100       ES.reportError(
101           make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode()));
102       return ErrorHandlerAddress;
103     } else
104       Name = I->second;
105   }
106 
107   if (auto Sym =
108           ES.lookup(makeJITDylibSearchOrder(
109                         &CallbacksJD, JITDylibLookupFlags::MatchAllSymbols),
110                     Name))
111     return Sym->getAddress();
112   else {
113     llvm::dbgs() << "Didn't find callback.\n";
114     // If anything goes wrong materializing Sym then report it to the session
115     // and return the ErrorHandlerAddress;
116     ES.reportError(Sym.takeError());
117     return ErrorHandlerAddress;
118   }
119 }
120 
121 Expected<std::unique_ptr<JITCompileCallbackManager>>
122 createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES,
123                                   JITTargetAddress ErrorHandlerAddress) {
124   switch (T.getArch()) {
125   default:
126     return make_error<StringError>(
127         std::string("No callback manager available for ") + T.str(),
128         inconvertibleErrorCode());
129   case Triple::aarch64:
130   case Triple::aarch64_32: {
131     typedef orc::LocalJITCompileCallbackManager<orc::OrcAArch64> CCMgrT;
132     return CCMgrT::Create(ES, ErrorHandlerAddress);
133     }
134 
135     case Triple::x86: {
136       typedef orc::LocalJITCompileCallbackManager<orc::OrcI386> CCMgrT;
137       return CCMgrT::Create(ES, ErrorHandlerAddress);
138     }
139 
140     case Triple::mips: {
141       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Be> CCMgrT;
142       return CCMgrT::Create(ES, ErrorHandlerAddress);
143     }
144     case Triple::mipsel: {
145       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Le> CCMgrT;
146       return CCMgrT::Create(ES, ErrorHandlerAddress);
147     }
148 
149     case Triple::mips64:
150     case Triple::mips64el: {
151       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips64> CCMgrT;
152       return CCMgrT::Create(ES, ErrorHandlerAddress);
153     }
154 
155     case Triple::x86_64: {
156       if (T.getOS() == Triple::OSType::Win32) {
157         typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_Win32> CCMgrT;
158         return CCMgrT::Create(ES, ErrorHandlerAddress);
159       } else {
160         typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_SysV> CCMgrT;
161         return CCMgrT::Create(ES, ErrorHandlerAddress);
162       }
163     }
164 
165   }
166 }
167 
168 std::function<std::unique_ptr<IndirectStubsManager>()>
169 createLocalIndirectStubsManagerBuilder(const Triple &T) {
170   switch (T.getArch()) {
171     default:
172       return [](){
173         return std::make_unique<
174                        orc::LocalIndirectStubsManager<orc::OrcGenericABI>>();
175       };
176 
177     case Triple::aarch64:
178     case Triple::aarch64_32:
179       return [](){
180         return std::make_unique<
181                        orc::LocalIndirectStubsManager<orc::OrcAArch64>>();
182       };
183 
184     case Triple::x86:
185       return [](){
186         return std::make_unique<
187                        orc::LocalIndirectStubsManager<orc::OrcI386>>();
188       };
189 
190     case Triple::mips:
191       return [](){
192           return std::make_unique<
193                       orc::LocalIndirectStubsManager<orc::OrcMips32Be>>();
194       };
195 
196     case Triple::mipsel:
197       return [](){
198           return std::make_unique<
199                       orc::LocalIndirectStubsManager<orc::OrcMips32Le>>();
200       };
201 
202     case Triple::mips64:
203     case Triple::mips64el:
204       return [](){
205           return std::make_unique<
206                       orc::LocalIndirectStubsManager<orc::OrcMips64>>();
207       };
208 
209     case Triple::x86_64:
210       if (T.getOS() == Triple::OSType::Win32) {
211         return [](){
212           return std::make_unique<
213                      orc::LocalIndirectStubsManager<orc::OrcX86_64_Win32>>();
214         };
215       } else {
216         return [](){
217           return std::make_unique<
218                      orc::LocalIndirectStubsManager<orc::OrcX86_64_SysV>>();
219         };
220       }
221 
222   }
223 }
224 
225 Constant* createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr) {
226   Constant *AddrIntVal =
227     ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr);
228   Constant *AddrPtrVal =
229     ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
230                           PointerType::get(&FT, 0));
231   return AddrPtrVal;
232 }
233 
234 GlobalVariable* createImplPointer(PointerType &PT, Module &M,
235                                   const Twine &Name, Constant *Initializer) {
236   auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
237                                Initializer, Name, nullptr,
238                                GlobalValue::NotThreadLocal, 0, true);
239   IP->setVisibility(GlobalValue::HiddenVisibility);
240   return IP;
241 }
242 
243 void makeStub(Function &F, Value &ImplPointer) {
244   assert(F.isDeclaration() && "Can't turn a definition into a stub.");
245   assert(F.getParent() && "Function isn't in a module.");
246   Module &M = *F.getParent();
247   BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
248   IRBuilder<> Builder(EntryBlock);
249   LoadInst *ImplAddr = Builder.CreateLoad(F.getType(), &ImplPointer);
250   std::vector<Value*> CallArgs;
251   for (auto &A : F.args())
252     CallArgs.push_back(&A);
253   CallInst *Call = Builder.CreateCall(F.getFunctionType(), ImplAddr, CallArgs);
254   Call->setTailCall();
255   Call->setAttributes(F.getAttributes());
256   if (F.getReturnType()->isVoidTy())
257     Builder.CreateRetVoid();
258   else
259     Builder.CreateRet(Call);
260 }
261 
262 std::vector<GlobalValue *> SymbolLinkagePromoter::operator()(Module &M) {
263   std::vector<GlobalValue *> PromotedGlobals;
264 
265   for (auto &GV : M.global_values()) {
266     bool Promoted = true;
267 
268     // Rename if necessary.
269     if (!GV.hasName())
270       GV.setName("__orc_anon." + Twine(NextId++));
271     else if (GV.getName().startswith("\01L"))
272       GV.setName("__" + GV.getName().substr(1) + "." + Twine(NextId++));
273     else if (GV.hasLocalLinkage())
274       GV.setName("__orc_lcl." + GV.getName() + "." + Twine(NextId++));
275     else
276       Promoted = false;
277 
278     if (GV.hasLocalLinkage()) {
279       GV.setLinkage(GlobalValue::ExternalLinkage);
280       GV.setVisibility(GlobalValue::HiddenVisibility);
281       Promoted = true;
282     }
283     GV.setUnnamedAddr(GlobalValue::UnnamedAddr::None);
284 
285     if (Promoted)
286       PromotedGlobals.push_back(&GV);
287   }
288 
289   return PromotedGlobals;
290 }
291 
292 Function* cloneFunctionDecl(Module &Dst, const Function &F,
293                             ValueToValueMapTy *VMap) {
294   Function *NewF =
295     Function::Create(cast<FunctionType>(F.getValueType()),
296                      F.getLinkage(), F.getName(), &Dst);
297   NewF->copyAttributesFrom(&F);
298 
299   if (VMap) {
300     (*VMap)[&F] = NewF;
301     auto NewArgI = NewF->arg_begin();
302     for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
303          ++ArgI, ++NewArgI)
304       (*VMap)[&*ArgI] = &*NewArgI;
305   }
306 
307   return NewF;
308 }
309 
310 void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
311                       ValueMaterializer *Materializer,
312                       Function *NewF) {
313   assert(!OrigF.isDeclaration() && "Nothing to move");
314   if (!NewF)
315     NewF = cast<Function>(VMap[&OrigF]);
316   else
317     assert(VMap[&OrigF] == NewF && "Incorrect function mapping in VMap.");
318   assert(NewF && "Function mapping missing from VMap.");
319   assert(NewF->getParent() != OrigF.getParent() &&
320          "moveFunctionBody should only be used to move bodies between "
321          "modules.");
322 
323   SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
324   CloneFunctionInto(NewF, &OrigF, VMap,
325                     CloneFunctionChangeType::DifferentModule, Returns, "",
326                     nullptr, nullptr, Materializer);
327   OrigF.deleteBody();
328 }
329 
330 GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
331                                         ValueToValueMapTy *VMap) {
332   GlobalVariable *NewGV = new GlobalVariable(
333       Dst, GV.getValueType(), GV.isConstant(),
334       GV.getLinkage(), nullptr, GV.getName(), nullptr,
335       GV.getThreadLocalMode(), GV.getType()->getAddressSpace());
336   NewGV->copyAttributesFrom(&GV);
337   if (VMap)
338     (*VMap)[&GV] = NewGV;
339   return NewGV;
340 }
341 
342 void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
343                                    ValueToValueMapTy &VMap,
344                                    ValueMaterializer *Materializer,
345                                    GlobalVariable *NewGV) {
346   assert(OrigGV.hasInitializer() && "Nothing to move");
347   if (!NewGV)
348     NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
349   else
350     assert(VMap[&OrigGV] == NewGV &&
351            "Incorrect global variable mapping in VMap.");
352   assert(NewGV->getParent() != OrigGV.getParent() &&
353          "moveGlobalVariableInitializer should only be used to move "
354          "initializers between modules");
355 
356   NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
357                                  nullptr, Materializer));
358 }
359 
360 GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
361                                   ValueToValueMapTy &VMap) {
362   assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
363   auto *NewA = GlobalAlias::create(OrigA.getValueType(),
364                                    OrigA.getType()->getPointerAddressSpace(),
365                                    OrigA.getLinkage(), OrigA.getName(), &Dst);
366   NewA->copyAttributesFrom(&OrigA);
367   VMap[&OrigA] = NewA;
368   return NewA;
369 }
370 
371 void cloneModuleFlagsMetadata(Module &Dst, const Module &Src,
372                               ValueToValueMapTy &VMap) {
373   auto *MFs = Src.getModuleFlagsMetadata();
374   if (!MFs)
375     return;
376   for (auto *MF : MFs->operands())
377     Dst.addModuleFlag(MapMetadata(MF, VMap));
378 }
379 
380 Error addFunctionPointerRelocationsToCurrentSymbol(jitlink::Symbol &Sym,
381                                                    jitlink::LinkGraph &G,
382                                                    MCDisassembler &Disassembler,
383                                                    MCInstrAnalysis &MIA) {
384   // AArch64 appears to already come with the necessary relocations. Among other
385   // architectures, only x86_64 is currently implemented here.
386   if (G.getTargetTriple().getArch() != Triple::x86_64)
387     return Error::success();
388 
389   raw_null_ostream CommentStream;
390   auto &STI = Disassembler.getSubtargetInfo();
391 
392   // Determine the function bounds
393   auto &B = Sym.getBlock();
394   assert(!B.isZeroFill() && "expected content block");
395   auto SymAddress = Sym.getAddress();
396   auto SymStartInBlock =
397       (const uint8_t *)B.getContent().data() + Sym.getOffset();
398   auto SymSize = Sym.getSize() ? Sym.getSize() : B.getSize() - Sym.getOffset();
399   auto Content = makeArrayRef(SymStartInBlock, SymSize);
400 
401   LLVM_DEBUG(dbgs() << "Adding self-relocations to " << Sym.getName() << "\n");
402 
403   SmallDenseSet<uintptr_t, 8> ExistingRelocations;
404   for (auto &E : B.edges()) {
405     if (E.isRelocation())
406       ExistingRelocations.insert(E.getOffset());
407   }
408 
409   size_t I = 0;
410   while (I < Content.size()) {
411     MCInst Instr;
412     uint64_t InstrSize = 0;
413     uint64_t InstrStart = SymAddress.getValue() + I;
414     auto DecodeStatus = Disassembler.getInstruction(
415         Instr, InstrSize, Content.drop_front(I), InstrStart, CommentStream);
416     if (DecodeStatus != MCDisassembler::Success) {
417       LLVM_DEBUG(dbgs() << "Aborting due to disassembly failure at address "
418                         << InstrStart);
419       return make_error<StringError>(
420           formatv("failed to disassemble at address {0:x16}", InstrStart),
421           inconvertibleErrorCode());
422     }
423     // Advance to the next instruction.
424     I += InstrSize;
425 
426     // Check for a PC-relative address equal to the symbol itself.
427     auto PCRelAddr =
428         MIA.evaluateMemoryOperandAddress(Instr, &STI, InstrStart, InstrSize);
429     if (!PCRelAddr || *PCRelAddr != SymAddress.getValue())
430       continue;
431 
432     auto RelocOffInInstr =
433         MIA.getMemoryOperandRelocationOffset(Instr, InstrSize);
434     if (!RelocOffInInstr.hasValue() ||
435         InstrSize - RelocOffInInstr.getValue() != 4) {
436       LLVM_DEBUG(dbgs() << "Skipping unknown self-relocation at "
437                         << InstrStart);
438       continue;
439     }
440 
441     auto RelocOffInBlock = orc::ExecutorAddr(InstrStart) + *RelocOffInInstr -
442                            SymAddress + Sym.getOffset();
443     if (ExistingRelocations.contains(RelocOffInBlock))
444       continue;
445 
446     LLVM_DEBUG(dbgs() << "Adding delta32 self-relocation at " << InstrStart);
447     B.addEdge(jitlink::x86_64::Delta32, RelocOffInBlock, Sym, /*Addend=*/-4);
448   }
449   return Error::success();
450 }
451 
452 } // End namespace orc.
453 } // End namespace llvm.
454