LLVM 20.0.0git
IRSymtab.cpp
Go to the documentation of this file.
1//===- IRSymtab.cpp - implementation of IR symbol tables ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/StringRef.h"
17#include "llvm/Config/llvm-config.h"
18#include "llvm/IR/Comdat.h"
19#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/GlobalAlias.h"
22#include "llvm/IR/Mangler.h"
23#include "llvm/IR/Metadata.h"
24#include "llvm/IR/Module.h"
32#include "llvm/Support/Error.h"
34#include "llvm/Support/VCSRevision.h"
37#include <cassert>
38#include <string>
39#include <utility>
40#include <vector>
41
42using namespace llvm;
43using namespace irsymtab;
44
46 "disable-bitcode-version-upgrade", cl::Hidden,
47 cl::desc("Disable automatic bitcode upgrade for version mismatch"));
48
49static const char *PreservedSymbols[] = {
50 // There are global variables, so put it here instead of in
51 // RuntimeLibcalls.def.
52 // TODO: Are there similar such variables?
53 "__ssp_canary_word",
54 "__stack_chk_guard",
55};
56
57namespace {
58
59const char *getExpectedProducerName() {
60 static char DefaultName[] = LLVM_VERSION_STRING
61#ifdef LLVM_REVISION
62 " " LLVM_REVISION
63#endif
64 ;
65 // Allows for testing of the irsymtab writer and upgrade mechanism. This
66 // environment variable should not be set by users.
67 if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
68 return OverrideName;
69 return DefaultName;
70}
71
72const char *kExpectedProducerName = getExpectedProducerName();
73
74/// Stores the temporary state that is required to build an IR symbol table.
75struct Builder {
77 StringTableBuilder &StrtabBuilder;
78 StringSaver Saver;
79
80 // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
81 // The StringTableBuilder does not create a copy of any strings added to it,
82 // so this provides somewhere to store any strings that we create.
83 Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
84 BumpPtrAllocator &Alloc)
85 : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
86
88 Mangler Mang;
89 Triple TT;
90
91 std::vector<storage::Comdat> Comdats;
92 std::vector<storage::Module> Mods;
93 std::vector<storage::Symbol> Syms;
94 std::vector<storage::Uncommon> Uncommons;
95
96 std::string COFFLinkerOpts;
97 raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
98
99 std::vector<storage::Str> DependentLibraries;
100
101 void setStr(storage::Str &S, StringRef Value) {
102 S.Offset = StrtabBuilder.add(Value);
103 S.Size = Value.size();
104 }
105
106 template <typename T>
107 void writeRange(storage::Range<T> &R, const std::vector<T> &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<int> getComdatIndex(const Comdat *C, const Module *M);
115
116 Error addModule(Module *M);
117 Error addSymbol(const ModuleSymbolTable &Msymtab,
120
122};
123
124Error Builder::addModule(Module *M) {
125 if (M->getDataLayoutStr().empty())
126 return make_error<StringError>("input module has no datalayout",
128
129 // Symbols in the llvm.used list will get the FB_Used bit and will not be
130 // internalized. We do this for llvm.compiler.used as well:
131 //
132 // IR symbol table tracks module-level asm symbol references but not inline
133 // asm. A symbol only referenced by inline asm is not in the IR symbol table,
134 // so we may not know that the definition (in another translation unit) is
135 // referenced. That definition may have __attribute__((used)) (which lowers to
136 // llvm.compiler.used on ELF targets) to communicate to the compiler that it
137 // may be used by inline asm. The usage is perfectly fine, so we treat
138 // llvm.compiler.used conservatively as llvm.used to work around our own
139 // limitation.
141 collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/false);
142 collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/true);
144
145 ModuleSymbolTable Msymtab;
146 Msymtab.addModule(M);
147
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<MDNode>(MDOptions)->operands())
161 COFFLinkerOptsOS << " " << cast<MDString>(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 =
171 cast<MDString>(cast<MDNode>(MDOptions)->getOperand(0))->getString();
172 storage::Str Specifier;
173 setStr(Specifier, OperandStr);
174 DependentLibraries.emplace_back(Specifier);
175 }
176 }
177 }
178
179 for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
180 if (Error Err = addSymbol(Msymtab, Used, Msym))
181 return Err;
182
183 return Error::success();
184}
185
186Expected<int> 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)
193 return make_error<StringError>("Could not find leader",
195 // Internal leaders do not affect symbol resolution, therefore they do not
196 // appear in the symbol table.
197 if (GV->hasLocalLinkage()) {
198 P.first->second = -1;
199 return -1;
200 }
202 Mang.getNameWithPrefix(OS, GV, false);
203 } else {
204 Name = std::string(C->getName());
205 }
206
208 setStr(Comdat.Name, Saver.save(Name));
209 Comdat.SelectionKind = C->getSelectionKind();
210 Comdats.push_back(Comdat);
211 }
212
213 return P.first->second;
214}
215
216static DenseSet<StringRef> buildPreservedSymbolsSet(const Triple &TT) {
217 DenseSet<StringRef> PreservedSymbolSet(std::begin(PreservedSymbols),
218 std::end(PreservedSymbols));
219
220 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
221 for (const char *Name : Libcalls.getLibcallNames()) {
222 if (Name)
223 PreservedSymbolSet.insert(Name);
224 }
225 return PreservedSymbolSet;
226}
227
228Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
231 Syms.emplace_back();
232 storage::Symbol &Sym = Syms.back();
233 Sym = {};
234
235 storage::Uncommon *Unc = nullptr;
236 auto Uncommon = [&]() -> storage::Uncommon & {
237 if (Unc)
238 return *Unc;
240 Uncommons.emplace_back();
241 Unc = &Uncommons.back();
242 *Unc = {};
243 setStr(Unc->COFFWeakExternFallbackName, "");
244 setStr(Unc->SectionName, "");
245 return *Unc;
246 };
247
249 {
251 Msymtab.printSymbolName(OS, Msym);
252 }
253 setStr(Sym.Name, Saver.save(Name.str()));
254
255 auto Flags = Msymtab.getSymbolFlags(Msym);
270
271 Sym.ComdatIndex = -1;
272 auto *GV = dyn_cast_if_present<GlobalValue *>(Msym);
273 if (!GV) {
274 // Undefined module asm symbols act as GC roots and are implicitly used.
277 setStr(Sym.IRName, "");
278 return Error::success();
279 }
280
281 setStr(Sym.IRName, GV->getName());
282
283 static const DenseSet<StringRef> PreservedSymbolsSet =
284 buildPreservedSymbolsSet(
286 bool IsPreservedSymbol = PreservedSymbolsSet.contains(GV->getName());
287
288 if (Used.count(GV) || IsPreservedSymbol)
290 if (GV->isThreadLocal())
292 if (GV->hasGlobalUnnamedAddr())
297
299 auto *GVar = dyn_cast<GlobalVariable>(GV);
300 if (!GVar)
301 return make_error<StringError>("Only variables can have common linkage!",
303 Uncommon().CommonSize =
305 Uncommon().CommonAlign = GVar->getAlign() ? GVar->getAlign()->value() : 0;
306 }
307
308 const GlobalObject *GO = GV->getAliaseeObject();
309 if (!GO) {
310 if (isa<GlobalIFunc>(GV))
311 GO = cast<GlobalIFunc>(GV)->getResolverFunction();
312 if (!GO)
313 return make_error<StringError>("Unable to determine comdat of alias!",
315 }
316 if (const Comdat *C = GO->getComdat()) {
317 Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
318 if (!ComdatIndexOrErr)
319 return ComdatIndexOrErr.takeError();
320 Sym.ComdatIndex = *ComdatIndexOrErr;
321 }
322
323 if (TT.isOSBinFormatCOFF()) {
324 emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
325
326 if ((Flags & object::BasicSymbolRef::SF_Weak) &&
328 auto *Fallback = dyn_cast<GlobalValue>(
329 cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
330 if (!Fallback)
331 return make_error<StringError>("Invalid weak external",
333 std::string FallbackName;
334 raw_string_ostream OS(FallbackName);
335 Msymtab.printSymbolName(OS, Fallback);
336 OS.flush();
337 setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
338 }
339 }
340
341 if (!GO->getSection().empty())
342 setStr(Uncommon().SectionName, Saver.save(GO->getSection()));
343
344 return Error::success();
345}
346
347Error Builder::build(ArrayRef<Module *> IRMods) {
348 storage::Header Hdr;
349
350 assert(!IRMods.empty());
352 setStr(Hdr.Producer, kExpectedProducerName);
353 setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
354 setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
355 TT = Triple(IRMods[0]->getTargetTriple());
356
357 for (auto *M : IRMods)
358 if (Error Err = addModule(M))
359 return Err;
360
361 COFFLinkerOptsOS.flush();
362 setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
363
364 // We are about to fill in the header's range fields, so reserve space for it
365 // and copy it in afterwards.
366 Symtab.resize(sizeof(storage::Header));
367 writeRange(Hdr.Modules, Mods);
368 writeRange(Hdr.Comdats, Comdats);
369 writeRange(Hdr.Symbols, Syms);
370 writeRange(Hdr.Uncommons, Uncommons);
371 writeRange(Hdr.DependentLibraries, DependentLibraries);
372 *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
373 return Error::success();
374}
375
376} // end anonymous namespace
377
379 StringTableBuilder &StrtabBuilder,
380 BumpPtrAllocator &Alloc) {
381 return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
382}
383
384// Upgrade a vector of bitcode modules created by an old version of LLVM by
385// creating an irsymtab for them in the current format.
387 FileContents FC;
388
389 LLVMContext Ctx;
390 std::vector<Module *> Mods;
391 std::vector<std::unique_ptr<Module>> OwnedMods;
392 for (auto BM : BMs) {
394 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
395 /*IsImporting*/ false);
396 if (!MOrErr)
397 return MOrErr.takeError();
398
399 Mods.push_back(MOrErr->get());
400 OwnedMods.push_back(std::move(*MOrErr));
401 }
402
404 BumpPtrAllocator Alloc;
405 if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
406 return std::move(E);
407
408 StrtabBuilder.finalizeInOrder();
409 FC.Strtab.resize(StrtabBuilder.getSize());
410 StrtabBuilder.write((uint8_t *)FC.Strtab.data());
411
412 FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
413 {FC.Strtab.data(), FC.Strtab.size()}};
414 return std::move(FC);
415}
416
418 if (BFC.Mods.empty())
419 return make_error<StringError>("Bitcode file does not contain any modules",
421
423 if (BFC.StrtabForSymtab.empty() ||
424 BFC.Symtab.size() < sizeof(storage::Header))
425 return upgrade(BFC.Mods);
426
427 // We cannot use the regular reader to read the version and producer,
428 // because it will expect the header to be in the current format. The only
429 // thing we can rely on is that the version and producer will be present as
430 // the first struct elements.
431 auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
432 unsigned Version = Hdr->Version;
433 StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
434 if (Version != storage::Header::kCurrentVersion ||
435 Producer != kExpectedProducerName)
436 return upgrade(BFC.Mods);
437 }
438
439 FileContents FC;
440 FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
442
443 // Finally, make sure that the number of modules in the symbol table matches
444 // the number of modules in the bitcode file. If they differ, it may mean that
445 // the bitcode file was created by binary concatenation, so we need to create
446 // a new symbol table from scratch.
447 if (FC.TheReader.getNumModules() != BFC.Mods.size())
448 return upgrade(std::move(BFC.Mods));
449
450 return std::move(FC);
451}
This file defines the BumpPtrAllocator interface.
This file defines the DenseMap class.
std::string Name
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
Definition: ELFObjcopy.cpp:564
Symbol * Sym
Definition: ELF_riscv.cpp:479
static const char * PreservedSymbols[]
Definition: IRSymtab.cpp:49
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:386
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
#define P(N)
Module * Mod
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
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),...
Definition: ArrayRef.h:41
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:504
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:118
const Comdat * getComdat() const
Definition: GlobalObject.h:129
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:263
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
bool hasLocalLinkage() const
Definition: GlobalValue.h:528
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:394
const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition: Globals.cpp:124
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:215
bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition: Globals.cpp:419
Type * getValueType() const
Definition: GlobalValue.h:296
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Metadata node.
Definition: Metadata.h:1067
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1426
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:889
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:120
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.
Definition: Module.h:65
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:297
size_t size() const
Definition: Module.h:720
A tuple of MDNodes.
Definition: Metadata.h:1729
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:118
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
size_t size() const
Definition: SmallVector.h:91
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:818
void resize(size_type N)
Definition: SmallVector.h:651
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:299
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
StringRef save(const char *S)
Definition: StringSaver.h:30
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.
Definition: Triple.h:44
LLVM Value Representation.
Definition: Value.h:74
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
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.
Definition: CallingConv.h:34
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition: IRSymtab.cpp:417
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:378
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:213
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 ...
Definition: Module.cpp:853
#define N
std::vector< BitcodeModule > Mods
A simple container for information about the supported runtime calls.
The contents of the irsymtab in a bitcode file.
Definition: IRSymtab.h:369
This is equivalent to an IR comdat.
Definition: IRSymtab.h:82
Word Version
Version number of the symtab format.
Definition: IRSymtab.h:138
Str COFFLinkerOpts
COFF-specific: linker directives.
Definition: IRSymtab.h:155
Range< Str > DependentLibraries
Dependent Library Specifiers.
Definition: IRSymtab.h:158
Range< Uncommon > Uncommons
Definition: IRSymtab.h:150
Str Producer
The producer's version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition: IRSymtab.h:145
Describes the range of a particular module's symbols within the symbol table.
Definition: IRSymtab.h:74
A reference to a range of objects in the symbol table.
Definition: IRSymtab.h:64
A reference to a string in the string table.
Definition: IRSymtab.h:55
StringRef get(StringRef Strtab) const
Definition: IRSymtab.h:58
Contains the information needed by linkers for symbol resolution, as well as by the LTO implementatio...
Definition: IRSymtab.h:91
This data structure contains rarely used symbol fields and is optionally referenced by a Symbol.
Definition: IRSymtab.h:122
Str SectionName
Specified section name, if any.
Definition: IRSymtab.h:130
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition: IRSymtab.h:127