38#include <system_error>
45 assert(_target &&
"target machine is null");
46 SymTab.addModule(
Mod.get());
66 BufferOrErr.
get()->getMemBufferRef());
76 return Result->IsThinLTO;
103 return *ProducerOrErr;
111 if (std::error_code EC = BufferOrErr.
getError()) {
112 Context.emitError(EC.message());
115 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.
get());
116 return makeLTOModule(Buffer->getMemBufferRef(), options,
Context,
128 size_t map_size, off_t offset,
133 if (std::error_code EC = BufferOrErr.
getError()) {
134 Context.emitError(EC.message());
137 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.
get());
138 return makeLTOModule(Buffer->getMemBufferRef(), options,
Context,
148 return makeLTOModule(Buffer, options,
Context,
false);
153 const void *mem,
size_t length,
160 makeLTOModule(Buffer, options, *
Context,
true);
162 (*Ret)->OwnedContext = std::move(
Context);
174 Context.emitError(EC.message());
195 if (std::error_code EC = MOrErr.
getError())
197 std::unique_ptr<Module> &
M = *MOrErr;
214 std::string FeatureStr = Features.
getString();
230 options, std::nullopt);
232 std::unique_ptr<LTOModule>
Ret(
new LTOModule(std::move(M), Buffer, target));
234 Ret->parseMetadata();
236 return std::move(Ret);
240std::unique_ptr<MemoryBuffer>
242 const char *startPtr = (
const char*)mem;
248LTOModule::objcClassNameFromExpression(
const Constant *c, std::string &
name) {
249 if (
const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
252 Constant *cn = gvn->getInitializer();
254 if (ca->isCString()) {
255 name = (
".objc_class_name_" + ca->getAsCString()).str();
270 std::string superclassName;
271 if (objcClassNameFromExpression(c->
getOperand(1), superclassName)) {
272 auto IterBool = _undefines.
try_emplace(superclassName);
273 if (IterBool.second) {
274 NameAndAttributes &
info = IterBool.first->second;
275 info.name = IterBool.first->first();
277 info.isFunction =
false;
283 std::string className;
284 if (objcClassNameFromExpression(c->
getOperand(2), className)) {
285 auto Iter = _defines.
insert(className).first;
287 NameAndAttributes
info;
288 info.name = Iter->first();
291 info.isFunction =
false;
293 _symbols.push_back(
info);
303 std::string targetclassName;
304 if (!objcClassNameFromExpression(c->
getOperand(1), targetclassName))
307 auto IterBool = _undefines.
try_emplace(targetclassName);
309 if (!IterBool.second)
312 NameAndAttributes &
info = IterBool.first->second;
313 info.name = IterBool.first->first();
315 info.isFunction =
false;
321 std::string targetclassName;
322 if (!objcClassNameFromExpression(clgv->
getInitializer(), targetclassName))
325 auto IterBool = _undefines.
try_emplace(targetclassName);
327 if (!IterBool.second)
330 NameAndAttributes &
info = IterBool.first->second;
331 info.name = IterBool.first->first();
333 info.isFunction =
false;
346 addDefinedDataSymbol(Buffer, V);
351 addDefinedSymbol(
Name, v,
false);
353 if (!
v->hasSection() )
379 if (
Section.starts_with(
"__OBJC,__class,")) {
384 else if (
Section.starts_with(
"__OBJC,__category,")) {
389 else if (
Section.starts_with(
"__OBJC,__cls_refs,")) {
403 auto *GV = cast<GlobalValue *>(
Sym);
404 assert((isa<Function>(GV) ||
405 (isa<GlobalAlias>(GV) &&
406 isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))) &&
407 "Not function or function alias");
409 addDefinedFunctionSymbol(Buffer, GV);
414 addDefinedSymbol(
Name,
F,
true);
420 if (
auto *gv = dyn_cast<GlobalVariable>(def))
421 attr =
Log2(gv->getAlign().valueOrOne());
422 else if (
auto *f = dyn_cast<Function>(def))
423 attr =
Log2(
f->getAlign().valueOrOne());
460 if (isa<GlobalAlias>(def))
466 NameAndAttributes
info;
470 info.attributes = attr;
475 _symbols.push_back(
info);
485 if (!IterBool.second)
488 NameAndAttributes &
info = _undefines[IterBool.first->first()];
490 if (
info.symbol ==
nullptr) {
500 info.name = IterBool.first->first();
503 info.isFunction =
false;
504 info.symbol =
nullptr;
507 _symbols.push_back(
info);
512 addDefinedFunctionSymbol(
info.name, cast<Function>(
info.symbol));
514 addDefinedDataSymbol(
info.name,
info.symbol);
516 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
517 _symbols.back().attributes |= scope;
525 _asm_undefines.push_back(IterBool.first->first());
528 if (!IterBool.second)
533 NameAndAttributes &
info = IterBool.first->second;
534 info.name = IterBool.first->first();
535 info.attributes = attr;
536 info.isFunction =
false;
537 info.symbol =
nullptr;
553 if (!IterBool.second)
556 NameAndAttributes &
info = IterBool.first->second;
558 info.name = IterBool.first->first();
560 const GlobalValue *decl = dyn_cast_if_present<GlobalValue *>(
Sym);
567 info.isFunction = isFunc;
571void LTOModule::parseSymbols() {
573 auto *GV = dyn_cast_if_present<GlobalValue *>(
Sym);
590 addAsmGlobalSymbolUndef(
Name);
598 auto *
F = dyn_cast<Function>(GV);
600 addPotentialUndefinedSymbol(
Sym,
F !=
nullptr);
605 addDefinedFunctionSymbol(
Sym);
609 if (isa<GlobalVariable>(GV)) {
610 addDefinedDataSymbol(
Sym);
614 assert(isa<GlobalAlias>(GV));
616 if (isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))
617 addDefinedFunctionSymbol(
Sym);
619 addDefinedDataSymbol(
Sym);
624 e = _undefines.
end(); u != e; ++u) {
627 if (_defines.
count(
u->getKey()))
continue;
628 NameAndAttributes
info =
u->getValue();
629 _symbols.push_back(
info);
634void LTOModule::parseMetadata() {
639 getModule().getNamedMetadata(
"llvm.linker.options")) {
640 for (
unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
642 for (
unsigned ii = 0, ie = MDOptions->
getNumOperands(); ii != ie; ++ii) {
650 const Triple TT(_target->getTargetTriple());
651 if (!
TT.isOSBinFormatCOFF())
654 for (
const NameAndAttributes &
Sym : _symbols) {
662 size_t buffer_size,
const char *path,
663 std::string &outErr) {
671 return ObjOrErr->release();
673 outErr = std::string(path) +
699 if (
auto *GV = dyn_cast_if_present<GlobalValue *>(
Sym)) {
701 if (
Name.consume_front(
"llvm.global_")) {
702 if (
Name ==
"ctors" ||
Name ==
"dtors")
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
static ErrorOr< std::unique_ptr< Module > > parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldBeLazy)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
static bool isFunction(SDValue Op)
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
A constant value that is initialized with an expression using other constant values.
This is an important base class in LLVM.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
bool hasLinkOnceLinkage() const
bool hasLocalLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasWeakLinkage() const
bool hasCommonLinkage() const
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
bool hasProtectedVisibility() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This is an important class for using LLVM in a threaded context.
const MDOperand & getOperand(unsigned I) const
unsigned getNumOperands() const
Return number of MDNode operands.
LLVM_ABI StringRef getString() const
This interface provides simple read-only access to a block of memory, and provides simple methods for...
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, int64_t Offset, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, map some slice of it into a MemoryBuffer.
MemoryBufferRef getMemBufferRef() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
LLVM_ABI void printSymbolName(raw_ostream &OS, Symbol S) const
LLVM_ABI uint32_t getSymbolFlags(Symbol S) const
ArrayRef< Symbol > symbols() const
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
StringRef - Represent a constant reference to a string, i.e.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
std::pair< typename Base::iterator, bool > insert(StringRef key)
Manages the enabling and disabling of subtarget specific features.
LLVM_ABI void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
LLVM_ABI std::string getString() const
Returns features as a string.
Primary interface to the complete machine description for the target machine.
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
Triple - Helper class for working with autoconf configuration names.
bool isArm64e() const
Tests whether the target is the Apple "arm64e" AArch64 subarch.
ArchType getArch() const
Get the parsed architecture type of this triple.
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
bool empty() const
Whether the triple is empty / default constructed.
Value * getOperand(unsigned i) const
static Expected< MemoryBufferRef > findBitcodeInMemBuffer(MemoryBufferRef Object)
Finds and returns bitcode in the given memory buffer (which may be either a bitcode file or a native ...
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
@ LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN
@ LTO_SYMBOL_PERMISSIONS_CODE
@ LTO_SYMBOL_DEFINITION_REGULAR
@ LTO_SYMBOL_SCOPE_DEFAULT
@ LTO_SYMBOL_SCOPE_INTERNAL
@ LTO_SYMBOL_SCOPE_HIDDEN
@ LTO_SYMBOL_DEFINITION_TENTATIVE
@ LTO_SYMBOL_PERMISSIONS_DATA
@ LTO_SYMBOL_SCOPE_PROTECTED
@ LTO_SYMBOL_PERMISSIONS_RODATA
@ LTO_SYMBOL_DEFINITION_WEAKUNDEF
@ LTO_SYMBOL_DEFINITION_UNDEFINED
@ LTO_SYMBOL_DEFINITION_WEAK
LLVM_ABI Expected< uint32_t > getCPUSubType(const Triple &T)
LLVM_ABI Expected< uint32_t > getCPUType(const Triple &T)
LLVM_ABI file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
LLVM_ABI std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
std::error_code make_error_code(BitcodeError E)
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
const char * toString(DWARFSectionKind Kind)
unsigned Log2(Align A)
Returns the log2 of the alignment.
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Implement std::hash so that hash_code can be used in STL containers.
C++ class which implements the opaque lto_module_t type.
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromFile(LLVMContext &Context, StringRef path, const TargetOptions &options)
Create an LTOModule.
static LLVM_ABI bool isBitcodeFile(const void *mem, size_t length)
Returns 'true' if the file or memory contents is LLVM bitcode.
LLVM_ABI Expected< uint32_t > getMachOCPUType() const
static LLVM_ABI std::unique_ptr< MemoryBuffer > makeBuffer(const void *mem, size_t length, StringRef name="")
Create a MemoryBuffer from a memory range with an optional name.
static LLVM_ABI size_t getDependentLibraryCount(lto::InputFile *input)
LLVM_ABI bool hasCtorDtor() const
Returns true if the module has either the @llvm.global_ctors or the @llvm.global_dtors symbol.
static LLVM_ABI const char * getDependentLibrary(lto::InputFile *input, size_t index, size_t *size)
const Module & getModule() const
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path, size_t map_size, off_t offset, const TargetOptions &options)
static LLVM_ABI std::string getProducerString(MemoryBuffer *Buffer)
Returns a string representing the producer identification stored in the bitcode, or "" if the bitcode...
static LLVM_ABI bool isBitcodeForTarget(MemoryBuffer *memBuffer, StringRef triplePrefix)
Returns 'true' if the memory buffer is LLVM bitcode for the specified triple.
LLVM_ABI bool isThinLTO()
Returns 'true' if the Module is produced for ThinLTO.
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromOpenFile(LLVMContext &Context, int fd, StringRef path, size_t size, const TargetOptions &options)
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createInLocalContext(std::unique_ptr< LLVMContext > Context, const void *mem, size_t length, const TargetOptions &options, StringRef path)
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromBuffer(LLVMContext &Context, const void *mem, size_t length, const TargetOptions &options, StringRef path="")
LLVM_ABI Expected< uint32_t > getMachOCPUSubType() const
static LLVM_ABI lto::InputFile * createInputFile(const void *buffer, size_t buffer_size, const char *path, std::string &out_error)
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.