17#include "llvm/Config/llvm-config.h"
34#include "llvm/Support/VCSRevision.h"
43using namespace irsymtab;
47 cl::desc(
"Disable automatic bitcode upgrade for version mismatch"));
59const char *getExpectedProducerName() {
60 static char DefaultName[] = LLVM_VERSION_STRING
67 if (
char *OverrideName = getenv(
"LLVM_OVERRIDE_PRODUCER"))
72const char *kExpectedProducerName = getExpectedProducerName();
85 : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
91 std::vector<storage::Comdat> Comdats;
92 std::vector<storage::Module> Mods;
93 std::vector<storage::Symbol> Syms;
94 std::vector<storage::Uncommon> Uncommons;
96 std::string COFFLinkerOpts;
99 std::vector<storage::Str> DependentLibraries;
106 template <
typename T>
108 R.Offset = Symtab.
size();
109 R.Size = Objs.size();
110 Symtab.
insert(Symtab.
end(),
reinterpret_cast<const char *
>(Objs.data()),
111 reinterpret_cast<const char *
>(Objs.data() + Objs.size()));
125 if (
M->getDataLayoutStr().empty())
126 return make_error<StringError>(
"input module has no datalayout",
149 Mod.Begin = Syms.size();
150 Mod.End = Syms.size() + Msymtab.
symbols().size();
151 Mod.UncBegin = Uncommons.size();
154 if (
TT.isOSBinFormatCOFF()) {
155 if (
auto E =
M->materializeMetadata())
158 M->getNamedMetadata(
"llvm.linker.options")) {
160 for (
const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
161 COFFLinkerOptsOS <<
" " << cast<MDString>(MDOption)->getString();
165 if (
TT.isOSBinFormatELF()) {
166 if (
auto E =
M->materializeMetadata())
168 if (
NamedMDNode *
N =
M->getNamedMetadata(
"llvm.dependent-libraries")) {
169 for (
MDNode *MDOptions :
N->operands()) {
170 const auto OperandStr =
171 cast<MDString>(cast<MDNode>(MDOptions)->getOperand(0))->getString();
173 setStr(Specifier, OperandStr);
174 DependentLibraries.emplace_back(Specifier);
187 auto P = ComdatMap.
insert(std::make_pair(
C, Comdats.size()));
190 if (
TT.isOSBinFormatCOFF()) {
193 return make_error<StringError>(
"Could not find leader",
198 P.first->second = -1;
204 Name = std::string(
C->getName());
210 Comdats.push_back(
Comdat);
213 return P.first->second;
221 for (
const char *
Name : Libcalls.getLibcallNames()) {
223 PreservedSymbolSet.insert(
Name);
225 return PreservedSymbolSet;
240 Uncommons.emplace_back();
241 Unc = &Uncommons.back();
272 auto *GV = dyn_cast_if_present<GlobalValue *>(Msym);
284 buildPreservedSymbolsSet(
288 if (
Used.count(GV) || IsPreservedSymbol)
299 auto *GVar = dyn_cast<GlobalVariable>(GV);
301 return make_error<StringError>(
"Only variables can have common linkage!",
303 Uncommon().CommonSize =
305 Uncommon().CommonAlign = GVar->getAlign() ? GVar->getAlign()->value() : 0;
310 if (isa<GlobalIFunc>(GV))
311 GO = cast<GlobalIFunc>(GV)->getResolverFunction();
313 return make_error<StringError>(
"Unable to determine comdat of alias!",
318 if (!ComdatIndexOrErr)
323 if (
TT.isOSBinFormatCOFF()) {
328 auto *
Fallback = dyn_cast<GlobalValue>(
329 cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
331 return make_error<StringError>(
"Invalid weak external",
333 std::string FallbackName;
337 setStr(Uncommon().COFFWeakExternFallbackName, Saver.
save(FallbackName));
352 setStr(Hdr.
Producer, kExpectedProducerName);
355 TT =
Triple(IRMods[0]->getTargetTriple());
357 for (
auto *M : IRMods)
358 if (
Error Err = addModule(M))
361 COFFLinkerOptsOS.flush();
368 writeRange(Hdr.
Comdats, Comdats);
381 return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
390 std::vector<Module *> Mods;
391 std::vector<std::unique_ptr<Module>> OwnedMods;
392 for (
auto BM : BMs) {
394 BM.getLazyModule(Ctx,
true,
399 Mods.push_back(MOrErr->
get());
400 OwnedMods.push_back(std::move(*MOrErr));
405 if (
Error E =
build(Mods, FC.Symtab, StrtabBuilder, Alloc))
409 FC.Strtab.resize(StrtabBuilder.
getSize());
412 FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
413 {FC.Strtab.data(), FC.Strtab.size()}};
414 return std::move(FC);
418 if (BFC.
Mods.empty())
419 return make_error<StringError>(
"Bitcode file does not contain any modules",
432 unsigned Version = Hdr->
Version;
435 Producer != kExpectedProducerName)
447 if (FC.TheReader.getNumModules() != BFC.
Mods.size())
450 return std::move(FC);
This file defines the BumpPtrAllocator interface.
This file defines the DenseMap class.
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
static const char * PreservedSymbols[]
static cl::opt< bool > DisableBitcodeVersionUpgrade("disable-bitcode-version-upgrade", cl::Hidden, cl::desc("Disable automatic bitcode upgrade for version mismatch"))
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Module.h This file contains the declarations for the Module class.
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
Allocate memory in an ever growing pool, as if by bump-pointer.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
StringRef getSection() const
Get the custom section of this global if it has one.
const Comdat * getComdat() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
VisibilityTypes getVisibility() const
bool hasLocalLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
const GlobalObject * getAliaseeObject() const
const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
bool hasGlobalUnnamedAddr() const
bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Type * getValueType() const
This is an important class for using LLVM in a threaded context.
ArrayRef< MDOperand > operands() const
Tracking metadata reference owned by Metadata.
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
void addModule(Module *M)
void printSymbolName(raw_ostream &OS, Symbol S) const
uint32_t getSymbolFlags(Symbol S) const
ArrayRef< Symbol > symbols() const
A Module instance is used to store all the information related to an LLVM module.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
iterator insert(iterator I, T &&Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
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).
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
StringRef save(const char *S)
Utility for building string tables with deduplicated suffixes.
void finalizeInOrder()
Finalize the string table without reording it.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
Triple - Helper class for working with autoconf configuration names.
LLVM Value Representation.
StringRef getName() const
Return a constant reference to the value's name.
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
@ C
The default llvm calling convention, compatible with C.
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
This is an optimization pass for GlobalISel generic memory operations.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
StringRef StrtabForSymtab
std::vector< BitcodeModule > Mods
A simple container for information about the supported runtime calls.
The contents of the irsymtab in a bitcode file.
This is equivalent to an IR comdat.
Describes the range of a particular module's symbols within the symbol table.
A reference to a range of objects in the symbol table.
A reference to a string in the string table.
StringRef get(StringRef Strtab) const
Contains the information needed by linkers for symbol resolution, as well as by the LTO implementatio...
This data structure contains rarely used symbol fields and is optionally referenced by a Symbol.
Str SectionName
Specified section name, if any.
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.