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/ExecutionEngine/JITLink/x86_64.h"
12 #include "llvm/ExecutionEngine/Orc/OrcABISupport.h"
13 #include "llvm/IR/IRBuilder.h"
14 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
15 #include "llvm/MC/MCInstrAnalysis.h"
16 #include "llvm/Support/Format.h"
17 #include "llvm/TargetParser/Triple.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] = {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() = default;
63 void IndirectStubsManager::anchor() {}
64 
65 Expected<ExecutorAddr>
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 ExecutorAddr
82 JITCompileCallbackManager::executeCompileCallback(ExecutorAddr 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       ES.reportError(
95           make_error<StringError>("No compile callback for trampoline at " +
96                                       formatv("{0:x}", TrampolineAddr),
97                                   inconvertibleErrorCode()));
98       return ErrorHandlerAddress;
99     } else
100       Name = I->second;
101   }
102 
103   if (auto Sym =
104           ES.lookup(makeJITDylibSearchOrder(
105                         &CallbacksJD, JITDylibLookupFlags::MatchAllSymbols),
106                     Name))
107     return Sym->getAddress();
108   else {
109     llvm::dbgs() << "Didn't find callback.\n";
110     // If anything goes wrong materializing Sym then report it to the session
111     // and return the ErrorHandlerAddress;
112     ES.reportError(Sym.takeError());
113     return ErrorHandlerAddress;
114   }
115 }
116 
117 Expected<std::unique_ptr<JITCompileCallbackManager>>
118 createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES,
119                                   ExecutorAddr ErrorHandlerAddress) {
120   switch (T.getArch()) {
121   default:
122     return make_error<StringError>(
123         std::string("No callback manager available for ") + T.str(),
124         inconvertibleErrorCode());
125   case Triple::aarch64:
126   case Triple::aarch64_32: {
127     typedef orc::LocalJITCompileCallbackManager<orc::OrcAArch64> CCMgrT;
128     return CCMgrT::Create(ES, ErrorHandlerAddress);
129     }
130 
131     case Triple::x86: {
132       typedef orc::LocalJITCompileCallbackManager<orc::OrcI386> CCMgrT;
133       return CCMgrT::Create(ES, ErrorHandlerAddress);
134     }
135 
136     case Triple::loongarch64: {
137       typedef orc::LocalJITCompileCallbackManager<orc::OrcLoongArch64> CCMgrT;
138       return CCMgrT::Create(ES, ErrorHandlerAddress);
139     }
140 
141     case Triple::mips: {
142       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Be> CCMgrT;
143       return CCMgrT::Create(ES, ErrorHandlerAddress);
144     }
145     case Triple::mipsel: {
146       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Le> CCMgrT;
147       return CCMgrT::Create(ES, ErrorHandlerAddress);
148     }
149 
150     case Triple::mips64:
151     case Triple::mips64el: {
152       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips64> CCMgrT;
153       return CCMgrT::Create(ES, ErrorHandlerAddress);
154     }
155 
156     case Triple::riscv64: {
157       typedef orc::LocalJITCompileCallbackManager<orc::OrcRiscv64> CCMgrT;
158       return CCMgrT::Create(ES, ErrorHandlerAddress);
159     }
160 
161     case Triple::x86_64: {
162       if (T.getOS() == Triple::OSType::Win32) {
163         typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_Win32> CCMgrT;
164         return CCMgrT::Create(ES, ErrorHandlerAddress);
165       } else {
166         typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_SysV> CCMgrT;
167         return CCMgrT::Create(ES, ErrorHandlerAddress);
168       }
169     }
170 
171   }
172 }
173 
174 std::function<std::unique_ptr<IndirectStubsManager>()>
175 createLocalIndirectStubsManagerBuilder(const Triple &T) {
176   switch (T.getArch()) {
177     default:
178       return [](){
179         return std::make_unique<
180                        orc::LocalIndirectStubsManager<orc::OrcGenericABI>>();
181       };
182 
183     case Triple::aarch64:
184     case Triple::aarch64_32:
185       return [](){
186         return std::make_unique<
187                        orc::LocalIndirectStubsManager<orc::OrcAArch64>>();
188       };
189 
190     case Triple::x86:
191       return [](){
192         return std::make_unique<
193                        orc::LocalIndirectStubsManager<orc::OrcI386>>();
194       };
195 
196     case Triple::loongarch64:
197       return []() {
198         return std::make_unique<
199             orc::LocalIndirectStubsManager<orc::OrcLoongArch64>>();
200       };
201 
202     case Triple::mips:
203       return [](){
204           return std::make_unique<
205                       orc::LocalIndirectStubsManager<orc::OrcMips32Be>>();
206       };
207 
208     case Triple::mipsel:
209       return [](){
210           return std::make_unique<
211                       orc::LocalIndirectStubsManager<orc::OrcMips32Le>>();
212       };
213 
214     case Triple::mips64:
215     case Triple::mips64el:
216       return [](){
217           return std::make_unique<
218                       orc::LocalIndirectStubsManager<orc::OrcMips64>>();
219       };
220 
221     case Triple::riscv64:
222       return []() {
223         return std::make_unique<
224             orc::LocalIndirectStubsManager<orc::OrcRiscv64>>();
225       };
226 
227     case Triple::x86_64:
228       if (T.getOS() == Triple::OSType::Win32) {
229         return [](){
230           return std::make_unique<
231                      orc::LocalIndirectStubsManager<orc::OrcX86_64_Win32>>();
232         };
233       } else {
234         return [](){
235           return std::make_unique<
236                      orc::LocalIndirectStubsManager<orc::OrcX86_64_SysV>>();
237         };
238       }
239 
240   }
241 }
242 
243 Constant* createIRTypedAddress(FunctionType &FT, ExecutorAddr Addr) {
244   Constant *AddrIntVal =
245     ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr.getValue());
246   Constant *AddrPtrVal =
247     ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
248                           PointerType::get(&FT, 0));
249   return AddrPtrVal;
250 }
251 
252 GlobalVariable* createImplPointer(PointerType &PT, Module &M,
253                                   const Twine &Name, Constant *Initializer) {
254   auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
255                                Initializer, Name, nullptr,
256                                GlobalValue::NotThreadLocal, 0, true);
257   IP->setVisibility(GlobalValue::HiddenVisibility);
258   return IP;
259 }
260 
261 void 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 
280 std::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().startswith("\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 
310 Function* cloneFunctionDecl(Module &Dst, const Function &F,
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 
328 GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
329                                         ValueToValueMapTy *VMap) {
330   GlobalVariable *NewGV = new GlobalVariable(
331       Dst, GV.getValueType(), GV.isConstant(),
332       GV.getLinkage(), nullptr, GV.getName(), nullptr,
333       GV.getThreadLocalMode(), GV.getType()->getAddressSpace());
334   NewGV->copyAttributesFrom(&GV);
335   if (VMap)
336     (*VMap)[&GV] = NewGV;
337   return NewGV;
338 }
339 
340 GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
341                                   ValueToValueMapTy &VMap) {
342   assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
343   auto *NewA = GlobalAlias::create(OrigA.getValueType(),
344                                    OrigA.getType()->getPointerAddressSpace(),
345                                    OrigA.getLinkage(), OrigA.getName(), &Dst);
346   NewA->copyAttributesFrom(&OrigA);
347   VMap[&OrigA] = NewA;
348   return NewA;
349 }
350 
351 Error addFunctionPointerRelocationsToCurrentSymbol(jitlink::Symbol &Sym,
352                                                    jitlink::LinkGraph &G,
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);
387     if (DecodeStatus != MCDisassembler::Success) {
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),
392           inconvertibleErrorCode());
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.
424