41 #include <system_error> 47 :
Mod(
std::move(M)), MBRef(MBRef), _target(TM) {
48 SymTab.addModule(
Mod.get());
68 BufferOrErr.
get()->getMemBufferRef());
78 return Result->IsThinLTO;
105 return *ProducerOrErr;
113 if (std::error_code EC = BufferOrErr.
getError()) {
117 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.
get());
118 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
125 return createFromOpenFileSlice(Context, fd, path, size, 0, options);
130 size_t map_size, off_t offset,
135 if (std::error_code EC = BufferOrErr.
getError()) {
139 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.
get());
140 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
150 return makeLTOModule(Buffer, options, Context,
false);
155 const void *mem,
size_t length,
162 makeLTOModule(Buffer, options, *Context,
true);
164 (*Ret)->OwnedContext = std::move(Context);
173 IRObjectFile::findBitcodeInMemBuffer(Buffer);
197 if (std::error_code EC = MOrErr.
getError())
199 std::unique_ptr<Module> &M = *MOrErr;
201 std::string TripleStr = M->getTargetTriple();
202 if (TripleStr.empty())
215 std::string FeatureStr = Features.
getString();
231 std::unique_ptr<LTOModule>
Ret(
new LTOModule(std::move(M), Buffer, target));
233 Ret->parseMetadata();
235 return std::move(Ret);
239 std::unique_ptr<MemoryBuffer>
241 const char *startPtr = (
const char*)mem;
247 LTOModule::objcClassNameFromExpression(
const Constant *c, std::string &
name) {
248 if (
const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
251 Constant *cn = gvn->getInitializer();
253 if (ca->isCString()) {
254 name = (
".objc_class_name_" + ca->getAsCString()).str();
269 std::string superclassName;
270 if (objcClassNameFromExpression(c->
getOperand(1), superclassName)) {
272 _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
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))
308 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
310 if (!IterBool.second)
313 NameAndAttributes &
info = IterBool.first->second;
314 info.name = IterBool.first->first();
316 info.isFunction =
false;
322 std::string targetclassName;
323 if (!objcClassNameFromExpression(clgv->
getInitializer(), targetclassName))
327 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
329 if (!IterBool.second)
332 NameAndAttributes &
info = IterBool.first->second;
333 info.name = IterBool.first->first();
335 info.isFunction =
false;
343 SymTab.printSymbolName(OS, Sym);
348 addDefinedDataSymbol(Buffer, V);
353 addDefinedSymbol(Name, v,
false);
386 else if (Section.
startswith(
"__OBJC,__category,")) {
391 else if (Section.
startswith(
"__OBJC,__cls_refs,")) {
401 SymTab.printSymbolName(OS, Sym);
406 addDefinedFunctionSymbol(Buffer, F);
411 addDefinedSymbol(Name, F,
true);
455 if (isa<GlobalAlias>(def))
458 auto Iter = _defines.insert(Name).first;
461 NameAndAttributes
info;
465 info.attributes = attr;
466 info.isFunction = isFunction;
470 _symbols.push_back(info);
475 void LTOModule::addAsmGlobalSymbol(
StringRef name,
477 auto IterBool = _defines.insert(name);
480 if (!IterBool.second)
483 NameAndAttributes &
info = _undefines[IterBool.first->first()];
485 if (info.symbol ==
nullptr) {
495 info.name = IterBool.first->first();
498 info.isFunction =
false;
499 info.symbol =
nullptr;
502 _symbols.push_back(info);
507 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
509 addDefinedDataSymbol(info.name, info.symbol);
512 _symbols.back().attributes |= scope;
517 void LTOModule::addAsmGlobalSymbolUndef(
StringRef name) {
518 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
520 _asm_undefines.push_back(IterBool.first->first());
523 if (!IterBool.second)
528 NameAndAttributes &
info = IterBool.first->second;
529 info.name = IterBool.first->first();
530 info.attributes = attr;
531 info.isFunction =
false;
532 info.symbol =
nullptr;
541 SymTab.printSymbolName(OS, Sym);
545 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
548 if (!IterBool.second)
551 NameAndAttributes &
info = IterBool.first->second;
553 info.name = IterBool.first->first();
562 info.isFunction = isFunc;
566 void LTOModule::parseSymbols() {
567 for (
auto Sym : SymTab.symbols()) {
569 uint32_t Flags = SymTab.getSymbolFlags(Sym);
579 SymTab.printSymbolName(OS, Sym);
585 addAsmGlobalSymbolUndef(Name);
595 addPotentialUndefinedSymbol(Sym, F !=
nullptr);
600 addDefinedFunctionSymbol(Sym);
604 if (isa<GlobalVariable>(GV)) {
605 addDefinedDataSymbol(Sym);
609 assert(isa<GlobalAlias>(GV));
610 addDefinedDataSymbol(Sym);
615 e = _undefines.end(); u !=
e; ++u) {
618 if (_defines.count(u->getKey()))
continue;
619 NameAndAttributes
info = u->getValue();
620 _symbols.push_back(info);
625 void LTOModule::parseMetadata() {
630 getModule().getNamedMetadata(
"llvm.linker.options")) {
631 for (
unsigned i = 0,
e = LinkerOptions->getNumOperands(); i !=
e; ++i) {
633 for (
unsigned ii = 0, ie = MDOptions->
getNumOperands(); ii != ie; ++ii) {
641 const Triple TT(_target->getTargetTriple());
642 if (!
TT.isOSBinFormatCOFF())
645 for (
const NameAndAttributes &Sym : _symbols) {
653 size_t buffer_size,
const char *path,
654 std::string &outErr) {
662 return ObjOrErr->release();
664 outErr = std::string(path) +
static size_t getDependentLibraryCount(lto::InputFile *input)
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (macOS, iOS, tvOS or watchOS).
Represents either an error or a value T.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasLocalLinkage() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM=None, CodeGenOpt::Level OL=CodeGenOpt::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static ErrorOr< std::unique_ptr< LTOModule > > createFromFile(LLVMContext &Context, StringRef path, const TargetOptions &options)
Create an LTOModule.
static lto::InputFile * createInputFile(const void *buffer, size_t buffer_size, const char *path, std::string &out_error)
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
std::string getString() const
Returns features as a string.
bool isThinLTO()
Returns 'true' if the Module is produced for ThinLTO.
A raw_ostream that writes to an SmallVector or SmallString.
static ErrorOr< std::unique_ptr< LTOModule > > createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path, size_t map_size, off_t offset, const TargetOptions &options)
static std::string getProducerString(MemoryBuffer *Buffer)
Returns a string representing the producer identification stored in the bitcode, or "" if the bitcode...
const MDOperand & getOperand(unsigned I) const
bool hasExternalWeakLinkage() const
Error takeError()
Take ownership of the stored error.
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
T get() const
Returns the value of the specified pointer type.
bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
unsigned countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, int64_t Offset, bool IsVolatile=false)
Given an already-open file descriptor, map some slice of it into a MemoryBuffer.
std::string toString(Error E)
Write all error messages (if any) in E to a string.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
std::error_code make_error_code(BitcodeError E)
Tagged union holding either a T or a Error.
bool hasCommonLinkage() const
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
static ErrorOr< std::unique_ptr< LTOModule > > createFromOpenFile(LLVMContext &Context, int fd, StringRef path, size_t size, const TargetOptions &options)
A constant value that is initialized with an expression using other constant values.
static ErrorOr< std::unique_ptr< Module > > parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldBeLazy)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
LLVM_NODISCARD size_t size() const
size - Get the string size.
unsigned getAlignment() const
bool hasLinkOnceLinkage() const
static bool isBitcodeForTarget(MemoryBuffer *memBuffer, StringRef triplePrefix)
Returns 'true' if the memory buffer is LLVM bitcode for the specified triple.
Value * getOperand(unsigned i) const
StringRef getString() const
Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information...
static const char * getDependentLibrary(lto::InputFile *input, size_t index, size_t *size)
bool hasProtectedVisibility() const
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
This is an important class for using LLVM in a threaded context.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::error_code getError() const
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
C++ class which implements the opaque lto_module_t type.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Triple - Helper class for working with autoconf configuration names.
bool hasWeakLinkage() const
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Module.h This file contains the declarations for the Module class.
MemoryBufferRef getMemBufferRef() const
This interface provides simple read-only access to a block of memory, and provides simple methods for...
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Target - Wrapper for Target specific information.
Manages the enabling and disabling of subtarget specific features.
bool hasHiddenVisibility() const
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
static std::unique_ptr< MemoryBuffer > makeBuffer(const void *mem, size_t length, StringRef name="")
Create a MemoryBuffer from a memory range with an optional name.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
static bool isBitcodeFile(const void *mem, size_t length)
Returns 'true' if the file or memory contents is LLVM bitcode.
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Lightweight error class with error context and mandatory checking.
Primary interface to the complete machine description for the target machine.
StringRef - Represent a constant reference to a string, i.e.
static ErrorOr< std::unique_ptr< LTOModule > > createInLocalContext(std::unique_ptr< LLVMContext > Context, const void *mem, size_t length, const TargetOptions &options, StringRef path)
unsigned getNumOperands() const
Return number of MDNode operands.
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
static ErrorOr< std::unique_ptr< LTOModule > > createFromBuffer(LLVMContext &Context, const void *mem, size_t length, const TargetOptions &options, StringRef path="")