xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
10b57cec5SDimitry Andric //===---- ExecutionUtils.cpp - Utilities for executing functions in Orc ---===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
108bcb0991SDimitry Andric #include "llvm/ExecutionEngine/Orc/Layer.h"
11*0eae32dcSDimitry Andric #include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h"
120b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
130b57cec5SDimitry Andric #include "llvm/IR/Function.h"
140b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
150b57cec5SDimitry Andric #include "llvm/IR/Module.h"
16349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
175ffd83dbSDimitry Andric #include "llvm/Object/MachOUniversal.h"
185ffd83dbSDimitry Andric #include "llvm/Support/FormatVariadic.h"
190b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
20fe6060f1SDimitry Andric #include <string>
210b57cec5SDimitry Andric 
220b57cec5SDimitry Andric namespace llvm {
230b57cec5SDimitry Andric namespace orc {
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric CtorDtorIterator::CtorDtorIterator(const GlobalVariable *GV, bool End)
260b57cec5SDimitry Andric   : InitList(
270b57cec5SDimitry Andric       GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
280b57cec5SDimitry Andric     I((InitList && End) ? InitList->getNumOperands() : 0) {
290b57cec5SDimitry Andric }
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric bool CtorDtorIterator::operator==(const CtorDtorIterator &Other) const {
320b57cec5SDimitry Andric   assert(InitList == Other.InitList && "Incomparable iterators.");
330b57cec5SDimitry Andric   return I == Other.I;
340b57cec5SDimitry Andric }
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric bool CtorDtorIterator::operator!=(const CtorDtorIterator &Other) const {
370b57cec5SDimitry Andric   return !(*this == Other);
380b57cec5SDimitry Andric }
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric CtorDtorIterator& CtorDtorIterator::operator++() {
410b57cec5SDimitry Andric   ++I;
420b57cec5SDimitry Andric   return *this;
430b57cec5SDimitry Andric }
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric CtorDtorIterator CtorDtorIterator::operator++(int) {
460b57cec5SDimitry Andric   CtorDtorIterator Temp = *this;
470b57cec5SDimitry Andric   ++I;
480b57cec5SDimitry Andric   return Temp;
490b57cec5SDimitry Andric }
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric CtorDtorIterator::Element CtorDtorIterator::operator*() const {
520b57cec5SDimitry Andric   ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
530b57cec5SDimitry Andric   assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric   Constant *FuncC = CS->getOperand(1);
560b57cec5SDimitry Andric   Function *Func = nullptr;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   // Extract function pointer, pulling off any casts.
590b57cec5SDimitry Andric   while (FuncC) {
600b57cec5SDimitry Andric     if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
610b57cec5SDimitry Andric       Func = F;
620b57cec5SDimitry Andric       break;
630b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
640b57cec5SDimitry Andric       if (CE->isCast())
650b57cec5SDimitry Andric         FuncC = dyn_cast_or_null<ConstantExpr>(CE->getOperand(0));
660b57cec5SDimitry Andric       else
670b57cec5SDimitry Andric         break;
680b57cec5SDimitry Andric     } else {
690b57cec5SDimitry Andric       // This isn't anything we recognize. Bail out with Func left set to null.
700b57cec5SDimitry Andric       break;
710b57cec5SDimitry Andric     }
720b57cec5SDimitry Andric   }
730b57cec5SDimitry Andric 
748bcb0991SDimitry Andric   auto *Priority = cast<ConstantInt>(CS->getOperand(0));
750b57cec5SDimitry Andric   Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
760b57cec5SDimitry Andric   if (Data && !isa<GlobalValue>(Data))
770b57cec5SDimitry Andric     Data = nullptr;
780b57cec5SDimitry Andric   return Element(Priority->getZExtValue(), Func, Data);
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric iterator_range<CtorDtorIterator> getConstructors(const Module &M) {
820b57cec5SDimitry Andric   const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
830b57cec5SDimitry Andric   return make_range(CtorDtorIterator(CtorsList, false),
840b57cec5SDimitry Andric                     CtorDtorIterator(CtorsList, true));
850b57cec5SDimitry Andric }
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric iterator_range<CtorDtorIterator> getDestructors(const Module &M) {
880b57cec5SDimitry Andric   const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
890b57cec5SDimitry Andric   return make_range(CtorDtorIterator(DtorsList, false),
900b57cec5SDimitry Andric                     CtorDtorIterator(DtorsList, true));
910b57cec5SDimitry Andric }
920b57cec5SDimitry Andric 
935ffd83dbSDimitry Andric bool StaticInitGVIterator::isStaticInitGlobal(GlobalValue &GV) {
945ffd83dbSDimitry Andric   if (GV.isDeclaration())
955ffd83dbSDimitry Andric     return false;
965ffd83dbSDimitry Andric 
975ffd83dbSDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
985ffd83dbSDimitry Andric                        GV.getName() == "llvm.global_dtors"))
995ffd83dbSDimitry Andric     return true;
1005ffd83dbSDimitry Andric 
1015ffd83dbSDimitry Andric   if (ObjFmt == Triple::MachO) {
1025ffd83dbSDimitry Andric     // FIXME: These section checks are too strict: We should match first and
1035ffd83dbSDimitry Andric     // second word split by comma.
1045ffd83dbSDimitry Andric     if (GV.hasSection() &&
1055ffd83dbSDimitry Andric         (GV.getSection().startswith("__DATA,__objc_classlist") ||
1065ffd83dbSDimitry Andric          GV.getSection().startswith("__DATA,__objc_selrefs")))
1075ffd83dbSDimitry Andric       return true;
1085ffd83dbSDimitry Andric   }
1095ffd83dbSDimitry Andric 
1105ffd83dbSDimitry Andric   return false;
1115ffd83dbSDimitry Andric }
1125ffd83dbSDimitry Andric 
1130b57cec5SDimitry Andric void CtorDtorRunner::add(iterator_range<CtorDtorIterator> CtorDtors) {
1148bcb0991SDimitry Andric   if (CtorDtors.empty())
1150b57cec5SDimitry Andric     return;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   MangleAndInterner Mangle(
1180b57cec5SDimitry Andric       JD.getExecutionSession(),
1190b57cec5SDimitry Andric       (*CtorDtors.begin()).Func->getParent()->getDataLayout());
1200b57cec5SDimitry Andric 
121480093f4SDimitry Andric   for (auto CtorDtor : CtorDtors) {
1220b57cec5SDimitry Andric     assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
1230b57cec5SDimitry Andric            "Ctor/Dtor function must be named to be runnable under the JIT");
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric     // FIXME: Maybe use a symbol promoter here instead.
1260b57cec5SDimitry Andric     if (CtorDtor.Func->hasLocalLinkage()) {
1270b57cec5SDimitry Andric       CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
1280b57cec5SDimitry Andric       CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
1290b57cec5SDimitry Andric     }
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric     if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
1320b57cec5SDimitry Andric       dbgs() << "  Skipping because why now?\n";
1330b57cec5SDimitry Andric       continue;
1340b57cec5SDimitry Andric     }
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric     CtorDtorsByPriority[CtorDtor.Priority].push_back(
1370b57cec5SDimitry Andric         Mangle(CtorDtor.Func->getName()));
1380b57cec5SDimitry Andric   }
1390b57cec5SDimitry Andric }
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric Error CtorDtorRunner::run() {
1420b57cec5SDimitry Andric   using CtorDtorTy = void (*)();
1430b57cec5SDimitry Andric 
144480093f4SDimitry Andric   SymbolLookupSet LookupSet;
145480093f4SDimitry Andric   for (auto &KV : CtorDtorsByPriority)
146480093f4SDimitry Andric     for (auto &Name : KV.second)
147480093f4SDimitry Andric       LookupSet.add(Name);
148480093f4SDimitry Andric   assert(!LookupSet.containsDuplicates() &&
149480093f4SDimitry Andric          "Ctor/Dtor list contains duplicates");
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   auto &ES = JD.getExecutionSession();
152480093f4SDimitry Andric   if (auto CtorDtorMap = ES.lookup(
153480093f4SDimitry Andric           makeJITDylibSearchOrder(&JD, JITDylibLookupFlags::MatchAllSymbols),
154480093f4SDimitry Andric           std::move(LookupSet))) {
1550b57cec5SDimitry Andric     for (auto &KV : CtorDtorsByPriority) {
1560b57cec5SDimitry Andric       for (auto &Name : KV.second) {
1570b57cec5SDimitry Andric         assert(CtorDtorMap->count(Name) && "No entry for Name");
1580b57cec5SDimitry Andric         auto CtorDtor = reinterpret_cast<CtorDtorTy>(
1590b57cec5SDimitry Andric             static_cast<uintptr_t>((*CtorDtorMap)[Name].getAddress()));
1600b57cec5SDimitry Andric         CtorDtor();
1610b57cec5SDimitry Andric       }
1620b57cec5SDimitry Andric     }
1630b57cec5SDimitry Andric     CtorDtorsByPriority.clear();
1640b57cec5SDimitry Andric     return Error::success();
1650b57cec5SDimitry Andric   } else
1660b57cec5SDimitry Andric     return CtorDtorMap.takeError();
1670b57cec5SDimitry Andric }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric void LocalCXXRuntimeOverridesBase::runDestructors() {
1700b57cec5SDimitry Andric   auto& CXXDestructorDataPairs = DSOHandleOverride;
1710b57cec5SDimitry Andric   for (auto &P : CXXDestructorDataPairs)
1720b57cec5SDimitry Andric     P.first(P.second);
1730b57cec5SDimitry Andric   CXXDestructorDataPairs.clear();
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric int LocalCXXRuntimeOverridesBase::CXAAtExitOverride(DestructorPtr Destructor,
1770b57cec5SDimitry Andric                                                     void *Arg,
1780b57cec5SDimitry Andric                                                     void *DSOHandle) {
1790b57cec5SDimitry Andric   auto& CXXDestructorDataPairs =
1800b57cec5SDimitry Andric     *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
1810b57cec5SDimitry Andric   CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
1820b57cec5SDimitry Andric   return 0;
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric Error LocalCXXRuntimeOverrides::enable(JITDylib &JD,
1860b57cec5SDimitry Andric                                         MangleAndInterner &Mangle) {
1870b57cec5SDimitry Andric   SymbolMap RuntimeInterposes;
1880b57cec5SDimitry Andric   RuntimeInterposes[Mangle("__dso_handle")] =
1890b57cec5SDimitry Andric     JITEvaluatedSymbol(toTargetAddress(&DSOHandleOverride),
1900b57cec5SDimitry Andric                        JITSymbolFlags::Exported);
1910b57cec5SDimitry Andric   RuntimeInterposes[Mangle("__cxa_atexit")] =
1920b57cec5SDimitry Andric     JITEvaluatedSymbol(toTargetAddress(&CXAAtExitOverride),
1930b57cec5SDimitry Andric                        JITSymbolFlags::Exported);
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1985ffd83dbSDimitry Andric void ItaniumCXAAtExitSupport::registerAtExit(void (*F)(void *), void *Ctx,
1995ffd83dbSDimitry Andric                                              void *DSOHandle) {
2005ffd83dbSDimitry Andric   std::lock_guard<std::mutex> Lock(AtExitsMutex);
2015ffd83dbSDimitry Andric   AtExitRecords[DSOHandle].push_back({F, Ctx});
2025ffd83dbSDimitry Andric }
2035ffd83dbSDimitry Andric 
2045ffd83dbSDimitry Andric void ItaniumCXAAtExitSupport::runAtExits(void *DSOHandle) {
2055ffd83dbSDimitry Andric   std::vector<AtExitRecord> AtExitsToRun;
2065ffd83dbSDimitry Andric 
2075ffd83dbSDimitry Andric   {
2085ffd83dbSDimitry Andric     std::lock_guard<std::mutex> Lock(AtExitsMutex);
2095ffd83dbSDimitry Andric     auto I = AtExitRecords.find(DSOHandle);
2105ffd83dbSDimitry Andric     if (I != AtExitRecords.end()) {
2115ffd83dbSDimitry Andric       AtExitsToRun = std::move(I->second);
2125ffd83dbSDimitry Andric       AtExitRecords.erase(I);
2135ffd83dbSDimitry Andric     }
2145ffd83dbSDimitry Andric   }
2155ffd83dbSDimitry Andric 
2165ffd83dbSDimitry Andric   while (!AtExitsToRun.empty()) {
2175ffd83dbSDimitry Andric     AtExitsToRun.back().F(AtExitsToRun.back().Ctx);
2185ffd83dbSDimitry Andric     AtExitsToRun.pop_back();
2195ffd83dbSDimitry Andric   }
2205ffd83dbSDimitry Andric }
2215ffd83dbSDimitry Andric 
2220b57cec5SDimitry Andric DynamicLibrarySearchGenerator::DynamicLibrarySearchGenerator(
2230b57cec5SDimitry Andric     sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow)
2240b57cec5SDimitry Andric     : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
2250b57cec5SDimitry Andric       GlobalPrefix(GlobalPrefix) {}
2260b57cec5SDimitry Andric 
2278bcb0991SDimitry Andric Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
2280b57cec5SDimitry Andric DynamicLibrarySearchGenerator::Load(const char *FileName, char GlobalPrefix,
2290b57cec5SDimitry Andric                                     SymbolPredicate Allow) {
2300b57cec5SDimitry Andric   std::string ErrMsg;
2310b57cec5SDimitry Andric   auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
2320b57cec5SDimitry Andric   if (!Lib.isValid())
2330b57cec5SDimitry Andric     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
2348bcb0991SDimitry Andric   return std::make_unique<DynamicLibrarySearchGenerator>(
2358bcb0991SDimitry Andric       std::move(Lib), GlobalPrefix, std::move(Allow));
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric 
238480093f4SDimitry Andric Error DynamicLibrarySearchGenerator::tryToGenerate(
239e8d8bef9SDimitry Andric     LookupState &LS, LookupKind K, JITDylib &JD,
240e8d8bef9SDimitry Andric     JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
2410b57cec5SDimitry Andric   orc::SymbolMap NewSymbols;
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   bool HasGlobalPrefix = (GlobalPrefix != '\0');
2440b57cec5SDimitry Andric 
245480093f4SDimitry Andric   for (auto &KV : Symbols) {
246480093f4SDimitry Andric     auto &Name = KV.first;
247480093f4SDimitry Andric 
2480b57cec5SDimitry Andric     if ((*Name).empty())
2490b57cec5SDimitry Andric       continue;
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric     if (Allow && !Allow(Name))
2520b57cec5SDimitry Andric       continue;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric     if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
2550b57cec5SDimitry Andric       continue;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     std::string Tmp((*Name).data() + HasGlobalPrefix,
2580b57cec5SDimitry Andric                     (*Name).size() - HasGlobalPrefix);
2590b57cec5SDimitry Andric     if (void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str())) {
2600b57cec5SDimitry Andric       NewSymbols[Name] = JITEvaluatedSymbol(
2610b57cec5SDimitry Andric           static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(Addr)),
2620b57cec5SDimitry Andric           JITSymbolFlags::Exported);
2630b57cec5SDimitry Andric     }
2640b57cec5SDimitry Andric   }
2650b57cec5SDimitry Andric 
266480093f4SDimitry Andric   if (NewSymbols.empty())
267480093f4SDimitry Andric     return Error::success();
2680b57cec5SDimitry Andric 
269480093f4SDimitry Andric   return JD.define(absoluteSymbols(std::move(NewSymbols)));
2700b57cec5SDimitry Andric }
2710b57cec5SDimitry Andric 
2728bcb0991SDimitry Andric Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
273*0eae32dcSDimitry Andric StaticLibraryDefinitionGenerator::Load(
274*0eae32dcSDimitry Andric     ObjectLayer &L, const char *FileName,
275*0eae32dcSDimitry Andric     GetObjectFileInterface GetObjFileInterface) {
2768bcb0991SDimitry Andric   auto ArchiveBuffer = errorOrToExpected(MemoryBuffer::getFile(FileName));
2778bcb0991SDimitry Andric 
2788bcb0991SDimitry Andric   if (!ArchiveBuffer)
2798bcb0991SDimitry Andric     return ArchiveBuffer.takeError();
2808bcb0991SDimitry Andric 
281*0eae32dcSDimitry Andric   return Create(L, std::move(*ArchiveBuffer), std::move(GetObjFileInterface));
2828bcb0991SDimitry Andric }
2838bcb0991SDimitry Andric 
2848bcb0991SDimitry Andric Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
285*0eae32dcSDimitry Andric StaticLibraryDefinitionGenerator::Load(
286*0eae32dcSDimitry Andric     ObjectLayer &L, const char *FileName, const Triple &TT,
287*0eae32dcSDimitry Andric     GetObjectFileInterface GetObjFileInterface) {
288*0eae32dcSDimitry Andric 
2895ffd83dbSDimitry Andric   auto B = object::createBinary(FileName);
2905ffd83dbSDimitry Andric   if (!B)
2915ffd83dbSDimitry Andric     return B.takeError();
2925ffd83dbSDimitry Andric 
2935ffd83dbSDimitry Andric   // If this is a regular archive then create an instance from it.
2945ffd83dbSDimitry Andric   if (isa<object::Archive>(B->getBinary()))
295*0eae32dcSDimitry Andric     return Create(L, std::move(B->takeBinary().second),
296*0eae32dcSDimitry Andric                   std::move(GetObjFileInterface));
2975ffd83dbSDimitry Andric 
2985ffd83dbSDimitry Andric   // If this is a universal binary then search for a slice matching the given
2995ffd83dbSDimitry Andric   // Triple.
3005ffd83dbSDimitry Andric   if (auto *UB = cast<object::MachOUniversalBinary>(B->getBinary())) {
3015ffd83dbSDimitry Andric     for (const auto &Obj : UB->objects()) {
3025ffd83dbSDimitry Andric       auto ObjTT = Obj.getTriple();
3035ffd83dbSDimitry Andric       if (ObjTT.getArch() == TT.getArch() &&
3045ffd83dbSDimitry Andric           ObjTT.getSubArch() == TT.getSubArch() &&
305e8d8bef9SDimitry Andric           (TT.getVendor() == Triple::UnknownVendor ||
306e8d8bef9SDimitry Andric            ObjTT.getVendor() == TT.getVendor())) {
3075ffd83dbSDimitry Andric         // We found a match. Create an instance from a buffer covering this
3085ffd83dbSDimitry Andric         // slice.
3095ffd83dbSDimitry Andric         auto SliceBuffer = MemoryBuffer::getFileSlice(FileName, Obj.getSize(),
3105ffd83dbSDimitry Andric                                                       Obj.getOffset());
3115ffd83dbSDimitry Andric         if (!SliceBuffer)
3125ffd83dbSDimitry Andric           return make_error<StringError>(
3135ffd83dbSDimitry Andric               Twine("Could not create buffer for ") + TT.str() + " slice of " +
3145ffd83dbSDimitry Andric                   FileName + ": [ " + formatv("{0:x}", Obj.getOffset()) +
3155ffd83dbSDimitry Andric                   " .. " + formatv("{0:x}", Obj.getOffset() + Obj.getSize()) +
3165ffd83dbSDimitry Andric                   ": " + SliceBuffer.getError().message(),
3175ffd83dbSDimitry Andric               SliceBuffer.getError());
318*0eae32dcSDimitry Andric         return Create(L, std::move(*SliceBuffer),
319*0eae32dcSDimitry Andric                       std::move(GetObjFileInterface));
3205ffd83dbSDimitry Andric       }
3215ffd83dbSDimitry Andric     }
3225ffd83dbSDimitry Andric 
3235ffd83dbSDimitry Andric     return make_error<StringError>(Twine("Universal binary ") + FileName +
3245ffd83dbSDimitry Andric                                        " does not contain a slice for " +
3255ffd83dbSDimitry Andric                                        TT.str(),
3265ffd83dbSDimitry Andric                                    inconvertibleErrorCode());
3275ffd83dbSDimitry Andric   }
3285ffd83dbSDimitry Andric 
3295ffd83dbSDimitry Andric   return make_error<StringError>(Twine("Unrecognized file type for ") +
3305ffd83dbSDimitry Andric                                      FileName,
3315ffd83dbSDimitry Andric                                  inconvertibleErrorCode());
3325ffd83dbSDimitry Andric }
3335ffd83dbSDimitry Andric 
3345ffd83dbSDimitry Andric Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
3358bcb0991SDimitry Andric StaticLibraryDefinitionGenerator::Create(
336*0eae32dcSDimitry Andric     ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
337*0eae32dcSDimitry Andric     GetObjectFileInterface GetObjFileInterface) {
3388bcb0991SDimitry Andric   Error Err = Error::success();
3398bcb0991SDimitry Andric 
3408bcb0991SDimitry Andric   std::unique_ptr<StaticLibraryDefinitionGenerator> ADG(
341*0eae32dcSDimitry Andric       new StaticLibraryDefinitionGenerator(
342*0eae32dcSDimitry Andric           L, std::move(ArchiveBuffer), std::move(GetObjFileInterface), Err));
3438bcb0991SDimitry Andric 
3448bcb0991SDimitry Andric   if (Err)
3458bcb0991SDimitry Andric     return std::move(Err);
3468bcb0991SDimitry Andric 
3478bcb0991SDimitry Andric   return std::move(ADG);
3488bcb0991SDimitry Andric }
3498bcb0991SDimitry Andric 
350480093f4SDimitry Andric Error StaticLibraryDefinitionGenerator::tryToGenerate(
351e8d8bef9SDimitry Andric     LookupState &LS, LookupKind K, JITDylib &JD,
352e8d8bef9SDimitry Andric     JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
353480093f4SDimitry Andric 
354480093f4SDimitry Andric   // Don't materialize symbols from static archives unless this is a static
355480093f4SDimitry Andric   // lookup.
356480093f4SDimitry Andric   if (K != LookupKind::Static)
357480093f4SDimitry Andric     return Error::success();
358480093f4SDimitry Andric 
359480093f4SDimitry Andric   // Bail out early if we've already freed the archive.
360480093f4SDimitry Andric   if (!Archive)
361480093f4SDimitry Andric     return Error::success();
3628bcb0991SDimitry Andric 
3638bcb0991SDimitry Andric   DenseSet<std::pair<StringRef, StringRef>> ChildBufferInfos;
3648bcb0991SDimitry Andric 
365480093f4SDimitry Andric   for (const auto &KV : Symbols) {
366480093f4SDimitry Andric     const auto &Name = KV.first;
367480093f4SDimitry Andric     auto Child = Archive->findSym(*Name);
3688bcb0991SDimitry Andric     if (!Child)
3698bcb0991SDimitry Andric       return Child.takeError();
3708bcb0991SDimitry Andric     if (*Child == None)
3718bcb0991SDimitry Andric       continue;
3728bcb0991SDimitry Andric     auto ChildBuffer = (*Child)->getMemoryBufferRef();
3738bcb0991SDimitry Andric     if (!ChildBuffer)
3748bcb0991SDimitry Andric       return ChildBuffer.takeError();
3758bcb0991SDimitry Andric     ChildBufferInfos.insert(
3768bcb0991SDimitry Andric         {ChildBuffer->getBuffer(), ChildBuffer->getBufferIdentifier()});
3778bcb0991SDimitry Andric   }
3788bcb0991SDimitry Andric 
3798bcb0991SDimitry Andric   for (auto ChildBufferInfo : ChildBufferInfos) {
3808bcb0991SDimitry Andric     MemoryBufferRef ChildBufferRef(ChildBufferInfo.first,
3818bcb0991SDimitry Andric                                    ChildBufferInfo.second);
3828bcb0991SDimitry Andric 
383*0eae32dcSDimitry Andric     auto I = GetObjFileInterface(L.getExecutionSession(), ChildBufferRef);
384*0eae32dcSDimitry Andric     if (!I)
385*0eae32dcSDimitry Andric       return I.takeError();
386*0eae32dcSDimitry Andric 
387*0eae32dcSDimitry Andric     if (auto Err = L.add(JD, MemoryBuffer::getMemBuffer(ChildBufferRef, false),
388*0eae32dcSDimitry Andric                          std::move(*I)))
389480093f4SDimitry Andric       return Err;
3908bcb0991SDimitry Andric   }
3918bcb0991SDimitry Andric 
392480093f4SDimitry Andric   return Error::success();
3938bcb0991SDimitry Andric }
3948bcb0991SDimitry Andric 
3958bcb0991SDimitry Andric StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
396*0eae32dcSDimitry Andric     ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
397*0eae32dcSDimitry Andric     GetObjectFileInterface GetObjFileInterface, Error &Err)
398*0eae32dcSDimitry Andric     : L(L), GetObjFileInterface(std::move(GetObjFileInterface)),
399*0eae32dcSDimitry Andric       ArchiveBuffer(std::move(ArchiveBuffer)),
400*0eae32dcSDimitry Andric       Archive(std::make_unique<object::Archive>(*this->ArchiveBuffer, Err)) {
401*0eae32dcSDimitry Andric 
402*0eae32dcSDimitry Andric   if (!this->GetObjFileInterface)
403*0eae32dcSDimitry Andric     this->GetObjFileInterface = getObjectFileInterface;
404*0eae32dcSDimitry Andric }
4058bcb0991SDimitry Andric 
4060b57cec5SDimitry Andric } // End namespace orc.
4070b57cec5SDimitry Andric } // End namespace llvm.
408