LLVM: lib/Object/IRSymtab.cpp Source File (original) (raw)
1
2
3
4
5
6
7
8
17#include "llvm/Config/llvm-config.h"
34#include "llvm/Support/VCSRevision.h"
37#include
38#include
39#include
40#include
41
42using namespace llvm;
44
46 "disable-bitcode-version-upgrade", cl::Hidden,
47 cl::desc("Disable automatic bitcode upgrade for version mismatch"));
48
49namespace {
50
51const char *getExpectedProducerName() {
52 static char DefaultName[] = LLVM_VERSION_STRING
53#ifdef LLVM_REVISION
54 " " LLVM_REVISION
55#endif
56 ;
57
58
59 if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
60 return OverrideName;
61 return DefaultName;
62}
63
64const char *kExpectedProducerName = getExpectedProducerName();
65
66
67struct Builder {
68 SmallVector<char, 0> &Symtab;
69 StringTableBuilder &StrtabBuilder;
70 StringSaver Saver;
71
72
73
74
75 Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
77 : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc), TT(TT),
78 Libcalls(TT) {}
79
80 DenseMap<const Comdat *, int> ComdatMap;
81 Mangler Mang;
82 const Triple &TT;
83
84
85 RTLIB::RuntimeLibcallsInfo Libcalls;
86
87 std::vectorstorage::Comdat Comdats;
88 std::vectorstorage::Module Mods;
89 std::vectorstorage::Symbol Syms;
90 std::vectorstorage::Uncommon Uncommons;
91
92 std::string COFFLinkerOpts;
93 raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
94
95 std::vectorstorage::Str DependentLibraries;
96
97 bool isPreservedName(StringRef Name) {
98 return Libcalls.getSupportedLibcallImpl(Name) != RTLIB::Unsupported;
99 }
100
101 void setStr(storage::Str &S, StringRef Value) {
104 }
105
106 template
107 void writeRange(storage::Range &R, const std::vector &Objs) {
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()));
112 }
113
114 Expected getComdatIndex(const Comdat *C, const Module *M);
115
118 const SmallPtrSet<GlobalValue *, 4> &Used,
120
122};
123
125 if (M->getDataLayoutStr().empty())
128
129
130
131
132
133
134
135
136
137
138
139
144
145 ModuleSymbolTable Msymtab;
147
148 storage::Module Mod;
149 Mod.Begin = Syms.size();
150 Mod.End = Syms.size() + Msymtab.symbols().size();
151 Mod.UncBegin = Uncommons.size();
152 Mods.push_back(Mod);
153
154 if (TT.isOSBinFormatCOFF()) {
155 if (auto E = M->materializeMetadata())
156 return E;
157 if (NamedMDNode *LinkerOptions =
158 M->getNamedMetadata("llvm.linker.options")) {
159 for (MDNode *MDOptions : LinkerOptions->operands())
160 for (const MDOperand &MDOption : cast(MDOptions)->operands())
161 COFFLinkerOptsOS << " " << cast(MDOption)->getString();
162 }
163 }
164
165 if (TT.isOSBinFormatELF()) {
166 if (auto E = M->materializeMetadata())
167 return E;
168 if (NamedMDNode *N = M->getNamedMetadata("llvm.dependent-libraries")) {
169 for (MDNode *MDOptions : N->operands()) {
170 const auto OperandStr =
173 setStr(Specifier, OperandStr);
174 DependentLibraries.emplace_back(Specifier);
175 }
176 }
177 }
178
181 return Err;
182
184}
185
186Expected Builder::getComdatIndex(const Comdat *C, const Module *M) {
187 auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
188 if (P.second) {
189 std::string Name;
190 if (TT.isOSBinFormatCOFF()) {
191 const GlobalValue *GV = M->getNamedValue(C->getName());
192 if (!GV)
195
196
198 P.first->second = -1;
199 return -1;
200 }
201 llvm::raw_string_ostream OS(Name);
203 } else {
204 Name = std::string(C->getName());
205 }
206
207 storage::Comdat Comdat;
208 setStr(Comdat.Name, Saver.save(Name));
210 Comdats.push_back(Comdat);
211 }
212
213 return P.first->second;
214}
215
216Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
217 const SmallPtrSet<GlobalValue *, 4> &Used,
219 Syms.emplace_back();
220 storage::Symbol &Sym = Syms.back();
221 Sym = {};
222
223 storage::Uncommon *Unc = nullptr;
224 auto Uncommon = [&]() -> storage::Uncommon & {
225 if (Unc)
226 return *Unc;
228 Uncommons.emplace_back();
229 Unc = &Uncommons.back();
230 *Unc = {};
233 return *Unc;
234 };
235
236 SmallString<64> Name;
237 {
238 raw_svector_ostream OS(Name);
240 }
242
258
261 if (!GV) {
262
265 setStr(Sym.IRName, "");
267 }
268
269 StringRef GVName = GV->getName();
270 setStr(Sym.IRName, GVName);
271
272 if (Used.count(GV) || isPreservedName(GVName))
281
284 if (!GVar)
287 Uncommon().CommonSize =
289 Uncommon().CommonAlign = GVar->getAlign() ? GVar->getAlign()->value() : 0;
290 }
291
293 if (!GO) {
296 if (!GO)
299 }
300 if (const Comdat *C = GO->getComdat()) {
301 Expected ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
302 if (!ComdatIndexOrErr)
303 return ComdatIndexOrErr.takeError();
305 }
306
307 if (TT.isOSBinFormatCOFF()) {
309
317 std::string FallbackName;
318 raw_string_ostream OS(FallbackName);
320 OS.flush();
321 setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
322 }
323 }
324
326 setStr(Uncommon().SectionName, Saver.save(GO->getSection()));
327
329}
330
332 storage::Header Hdr;
333
336 setStr(Hdr.Producer, kExpectedProducerName);
337 setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple().str());
338 setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
339
340 for (auto *M : IRMods)
341 if (Error Err = addModule(M))
342 return Err;
343
344 COFFLinkerOptsOS.flush();
346
347
348
349 Symtab.resize(sizeof(storage::Header));
350 writeRange(Hdr.Modules, Mods);
351 writeRange(Hdr.Comdats, Comdats);
352 writeRange(Hdr.Symbols, Syms);
353 writeRange(Hdr.Uncommons, Uncommons);
355 *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
357}
358
359}
360
364 const Triple &TT = Mods[0]->getTargetTriple();
365 return Builder(Symtab, StrtabBuilder, Alloc, TT).build(Mods);
366}
367
368
369
372
374 std::vector<Module *> Mods;
375 std::vector<std::unique_ptr> OwnedMods;
376 for (auto BM : BMs) {
378 BM.getLazyModule(Ctx, true,
379 false);
380 if (!MOrErr)
382
383 Mods.push_back(MOrErr->get());
384 OwnedMods.push_back(std::move(*MOrErr));
385 }
386
390 return std::move(E);
391
393 FC.Strtab.resize(StrtabBuilder.getSize());
394 StrtabBuilder.write((uint8_t *)FC.Strtab.data());
395
396 FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
397 {FC.Strtab.data(), FC.Strtab.size()}};
398 return std::move(FC);
399}
400
402 if (BFC.Mods.empty())
405
410
411
412
413
414
419 Producer != kExpectedProducerName)
421 }
422
426
427
428
429
430
431 if (FC.TheReader.getNumModules() != BFC.Mods.size())
433
434 return std::move(FC);
435}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Prepare AGPR Alloc
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
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)
Definition IRSymtab.cpp:370
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
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.
LLVM_ABI 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)
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...
LLVM_ABI const GlobalObject * getAliaseeObject() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
bool hasGlobalUnnamedAddr() const
LLVM_ABI 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.
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
LLVM_ABI void addModule(Module *M)
LLVM_ABI void printSymbolName(raw_ostream &OS, Symbol S) const
PointerUnion< GlobalValue *, AsmSymbol * > Symbol
LLVM_ABI 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.
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).
StringRef save(const char *S)
Utility for building string tables with deduplicated suffixes.
LLVM_ABI void finalizeInOrder()
Finalize the string table without reording it.
LLVM_ABI void write(raw_ostream &OS) const
Triple - Helper class for working with autoconf configuration names.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
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.
LLVM_ABI Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition IRSymtab.cpp:401
LLVM_ABI 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.
Definition IRSymtab.cpp:361
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
decltype(auto) dyn_cast(const From &Val)
dyn_cast - Return the argument parameter cast to the specified type.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present - Functionally identical to dyn_cast, except that a null (or none in the case ...
FunctionAddr VTableAddr uintptr_t uintptr_t Version
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa - Return true if the parameter to the template is an instance of one of the template type argu...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
decltype(auto) cast(const From &Val)
cast - Return the argument parameter cast to the specified type.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI 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
The contents of the irsymtab in a bitcode file.
StringRef get(StringRef Strtab) const
Str Name
The mangled symbol name.
Str IRName
The unmangled symbol name, or the empty string if this is not an IR symbol.
Word ComdatIndex
The index into Header::Comdats, or -1 if not a comdat member.
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.