IRSymtab.h revision d111c7844ec26448764ced627e153f406d730c5f
1//===- IRSymtab.h - data definitions for IR symbol tables -------*- C++ -*-===//
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//
9// This file contains data definitions and a reader and builder for a symbol
10// table for LLVM IR. Its purpose is to allow linkers and other consumers of
11// bitcode files to efficiently read the symbol table for symbol resolution
12// purposes without needing to construct a module in memory.
13//
14// As with most object files the symbol table has two parts: the symbol table
15// itself and a string table which is referenced by the symbol table.
16//
17// A symbol table corresponds to a single bitcode file, which may consist of
18// multiple modules, so symbol tables may likewise contain symbols for multiple
19// modules.
20//
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_OBJECT_IRSYMTAB_H
24#define LLVM_OBJECT_IRSYMTAB_H
25
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/iterator_range.h"
29#include "llvm/IR/GlobalValue.h"
30#include "llvm/Object/SymbolicFile.h"
31#include "llvm/Support/Endian.h"
32#include "llvm/Support/Error.h"
33#include <cassert>
34#include <cstdint>
35#include <vector>
36
37namespace llvm {
38
39struct BitcodeFileContents;
40class StringTableBuilder;
41
42namespace irsymtab {
43
44namespace storage {
45
46// The data structures in this namespace define the low-level serialization
47// format. Clients that just want to read a symbol table should use the
48// irsymtab::Reader class.
49
50using Word = support::ulittle32_t;
51
52/// A reference to a string in the string table.
53struct Str {
54  Word Offset, Size;
55
56  StringRef get(StringRef Strtab) const {
57    return {Strtab.data() + Offset, Size};
58  }
59};
60
61/// A reference to a range of objects in the symbol table.
62template <typename T> struct Range {
63  Word Offset, Size;
64
65  ArrayRef<T> get(StringRef Symtab) const {
66    return {reinterpret_cast<const T *>(Symtab.data() + Offset), Size};
67  }
68};
69
70/// Describes the range of a particular module's symbols within the symbol
71/// table.
72struct Module {
73  Word Begin, End;
74
75  /// The index of the first Uncommon for this Module.
76  Word UncBegin;
77};
78
79/// This is equivalent to an IR comdat.
80struct Comdat {
81  Str Name;
82};
83
84/// Contains the information needed by linkers for symbol resolution, as well as
85/// by the LTO implementation itself.
86struct Symbol {
87  /// The mangled symbol name.
88  Str Name;
89
90  /// The unmangled symbol name, or the empty string if this is not an IR
91  /// symbol.
92  Str IRName;
93
94  /// The index into Header::Comdats, or -1 if not a comdat member.
95  Word ComdatIndex;
96
97  Word Flags;
98  enum FlagBits {
99    FB_visibility, // 2 bits
100    FB_has_uncommon = FB_visibility + 2,
101    FB_undefined,
102    FB_weak,
103    FB_common,
104    FB_indirect,
105    FB_used,
106    FB_tls,
107    FB_may_omit,
108    FB_global,
109    FB_format_specific,
110    FB_unnamed_addr,
111    FB_executable,
112  };
113};
114
115/// This data structure contains rarely used symbol fields and is optionally
116/// referenced by a Symbol.
117struct Uncommon {
118  Word CommonSize, CommonAlign;
119
120  /// COFF-specific: the name of the symbol that a weak external resolves to
121  /// if not defined.
122  Str COFFWeakExternFallbackName;
123
124  /// Specified section name, if any.
125  Str SectionName;
126};
127
128
129struct Header {
130  /// Version number of the symtab format. This number should be incremented
131  /// when the format changes, but it does not need to be incremented if a
132  /// change to LLVM would cause it to create a different symbol table.
133  Word Version;
134  enum { kCurrentVersion = 2 };
135
136  /// The producer's version string (LLVM_VERSION_STRING " " LLVM_REVISION).
137  /// Consumers should rebuild the symbol table from IR if the producer's
138  /// version does not match the consumer's version due to potential differences
139  /// in symbol table format, symbol enumeration order and so on.
140  Str Producer;
141
142  Range<Module> Modules;
143  Range<Comdat> Comdats;
144  Range<Symbol> Symbols;
145  Range<Uncommon> Uncommons;
146
147  Str TargetTriple, SourceFileName;
148
149  /// COFF-specific: linker directives.
150  Str COFFLinkerOpts;
151
152  /// Dependent Library Specifiers
153  Range<Str> DependentLibraries;
154};
155
156} // end namespace storage
157
158/// Fills in Symtab and StrtabBuilder with a valid symbol and string table for
159/// Mods.
160Error build(ArrayRef<Module *> Mods, SmallVector<char, 0> &Symtab,
161            StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc);
162
163/// This represents a symbol that has been read from a storage::Symbol and
164/// possibly a storage::Uncommon.
165struct Symbol {
166  // Copied from storage::Symbol.
167  StringRef Name, IRName;
168  int ComdatIndex;
169  uint32_t Flags;
170
171  // Copied from storage::Uncommon.
172  uint32_t CommonSize, CommonAlign;
173  StringRef COFFWeakExternFallbackName;
174  StringRef SectionName;
175
176  /// Returns the mangled symbol name.
177  StringRef getName() const { return Name; }
178
179  /// Returns the unmangled symbol name, or the empty string if this is not an
180  /// IR symbol.
181  StringRef getIRName() const { return IRName; }
182
183  /// Returns the index into the comdat table (see Reader::getComdatTable()), or
184  /// -1 if not a comdat member.
185  int getComdatIndex() const { return ComdatIndex; }
186
187  using S = storage::Symbol;
188
189  GlobalValue::VisibilityTypes getVisibility() const {
190    return GlobalValue::VisibilityTypes((Flags >> S::FB_visibility) & 3);
191  }
192
193  bool isUndefined() const { return (Flags >> S::FB_undefined) & 1; }
194  bool isWeak() const { return (Flags >> S::FB_weak) & 1; }
195  bool isCommon() const { return (Flags >> S::FB_common) & 1; }
196  bool isIndirect() const { return (Flags >> S::FB_indirect) & 1; }
197  bool isUsed() const { return (Flags >> S::FB_used) & 1; }
198  bool isTLS() const { return (Flags >> S::FB_tls) & 1; }
199
200  bool canBeOmittedFromSymbolTable() const {
201    return (Flags >> S::FB_may_omit) & 1;
202  }
203
204  bool isGlobal() const { return (Flags >> S::FB_global) & 1; }
205  bool isFormatSpecific() const { return (Flags >> S::FB_format_specific) & 1; }
206  bool isUnnamedAddr() const { return (Flags >> S::FB_unnamed_addr) & 1; }
207  bool isExecutable() const { return (Flags >> S::FB_executable) & 1; }
208
209  uint64_t getCommonSize() const {
210    assert(isCommon());
211    return CommonSize;
212  }
213
214  uint32_t getCommonAlignment() const {
215    assert(isCommon());
216    return CommonAlign;
217  }
218
219  /// COFF-specific: for weak externals, returns the name of the symbol that is
220  /// used as a fallback if the weak external remains undefined.
221  StringRef getCOFFWeakExternalFallback() const {
222    assert(isWeak() && isIndirect());
223    return COFFWeakExternFallbackName;
224  }
225
226  StringRef getSectionName() const { return SectionName; }
227};
228
229/// This class can be used to read a Symtab and Strtab produced by
230/// irsymtab::build.
231class Reader {
232  StringRef Symtab, Strtab;
233
234  ArrayRef<storage::Module> Modules;
235  ArrayRef<storage::Comdat> Comdats;
236  ArrayRef<storage::Symbol> Symbols;
237  ArrayRef<storage::Uncommon> Uncommons;
238  ArrayRef<storage::Str> DependentLibraries;
239
240  StringRef str(storage::Str S) const { return S.get(Strtab); }
241
242  template <typename T> ArrayRef<T> range(storage::Range<T> R) const {
243    return R.get(Symtab);
244  }
245
246  const storage::Header &header() const {
247    return *reinterpret_cast<const storage::Header *>(Symtab.data());
248  }
249
250public:
251  class SymbolRef;
252
253  Reader() = default;
254  Reader(StringRef Symtab, StringRef Strtab) : Symtab(Symtab), Strtab(Strtab) {
255    Modules = range(header().Modules);
256    Comdats = range(header().Comdats);
257    Symbols = range(header().Symbols);
258    Uncommons = range(header().Uncommons);
259    DependentLibraries = range(header().DependentLibraries);
260  }
261
262  using symbol_range = iterator_range<object::content_iterator<SymbolRef>>;
263
264  /// Returns the symbol table for the entire bitcode file.
265  /// The symbols enumerated by this method are ephemeral, but they can be
266  /// copied into an irsymtab::Symbol object.
267  symbol_range symbols() const;
268
269  size_t getNumModules() const { return Modules.size(); }
270
271  /// Returns a slice of the symbol table for the I'th module in the file.
272  /// The symbols enumerated by this method are ephemeral, but they can be
273  /// copied into an irsymtab::Symbol object.
274  symbol_range module_symbols(unsigned I) const;
275
276  StringRef getTargetTriple() const { return str(header().TargetTriple); }
277
278  /// Returns the source file path specified at compile time.
279  StringRef getSourceFileName() const { return str(header().SourceFileName); }
280
281  /// Returns a table with all the comdats used by this file.
282  std::vector<StringRef> getComdatTable() const {
283    std::vector<StringRef> ComdatTable;
284    ComdatTable.reserve(Comdats.size());
285    for (auto C : Comdats)
286      ComdatTable.push_back(str(C.Name));
287    return ComdatTable;
288  }
289
290  /// COFF-specific: returns linker options specified in the input file.
291  StringRef getCOFFLinkerOpts() const { return str(header().COFFLinkerOpts); }
292
293  /// Returns dependent library specifiers
294  std::vector<StringRef> getDependentLibraries() const {
295    std::vector<StringRef> Specifiers;
296    Specifiers.reserve(DependentLibraries.size());
297    for (auto S : DependentLibraries) {
298      Specifiers.push_back(str(S));
299    }
300    return Specifiers;
301  }
302};
303
304/// Ephemeral symbols produced by Reader::symbols() and
305/// Reader::module_symbols().
306class Reader::SymbolRef : public Symbol {
307  const storage::Symbol *SymI, *SymE;
308  const storage::Uncommon *UncI;
309  const Reader *R;
310
311  void read() {
312    if (SymI == SymE)
313      return;
314
315    Name = R->str(SymI->Name);
316    IRName = R->str(SymI->IRName);
317    ComdatIndex = SymI->ComdatIndex;
318    Flags = SymI->Flags;
319
320    if (Flags & (1 << storage::Symbol::FB_has_uncommon)) {
321      CommonSize = UncI->CommonSize;
322      CommonAlign = UncI->CommonAlign;
323      COFFWeakExternFallbackName = R->str(UncI->COFFWeakExternFallbackName);
324      SectionName = R->str(UncI->SectionName);
325    } else
326      // Reset this field so it can be queried unconditionally for all symbols.
327      SectionName = "";
328  }
329
330public:
331  SymbolRef(const storage::Symbol *SymI, const storage::Symbol *SymE,
332            const storage::Uncommon *UncI, const Reader *R)
333      : SymI(SymI), SymE(SymE), UncI(UncI), R(R) {
334    read();
335  }
336
337  void moveNext() {
338    ++SymI;
339    if (Flags & (1 << storage::Symbol::FB_has_uncommon))
340      ++UncI;
341    read();
342  }
343
344  bool operator==(const SymbolRef &Other) const { return SymI == Other.SymI; }
345};
346
347inline Reader::symbol_range Reader::symbols() const {
348  return {SymbolRef(Symbols.begin(), Symbols.end(), Uncommons.begin(), this),
349          SymbolRef(Symbols.end(), Symbols.end(), nullptr, this)};
350}
351
352inline Reader::symbol_range Reader::module_symbols(unsigned I) const {
353  const storage::Module &M = Modules[I];
354  const storage::Symbol *MBegin = Symbols.begin() + M.Begin,
355                        *MEnd = Symbols.begin() + M.End;
356  return {SymbolRef(MBegin, MEnd, Uncommons.begin() + M.UncBegin, this),
357          SymbolRef(MEnd, MEnd, nullptr, this)};
358}
359
360/// The contents of the irsymtab in a bitcode file. Any underlying data for the
361/// irsymtab are owned by Symtab and Strtab.
362struct FileContents {
363  SmallVector<char, 0> Symtab, Strtab;
364  Reader TheReader;
365};
366
367/// Reads the contents of a bitcode file, creating its irsymtab if necessary.
368Expected<FileContents> readBitcode(const BitcodeFileContents &BFC);
369
370} // end namespace irsymtab
371} // end namespace llvm
372
373#endif // LLVM_OBJECT_IRSYMTAB_H
374