LLVM  5.0.0
IRSymtab.cpp
Go to the documentation of this file.
1 //===- IRSymtab.cpp - implementation of IR symbol tables ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Object/IRSymtab.h"
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/Comdat.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalObject.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/Module.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/Error.h"
35 #include "llvm/Support/VCSRevision.h"
37 #include <cassert>
38 #include <string>
39 #include <utility>
40 #include <vector>
41 
42 using namespace llvm;
43 using namespace irsymtab;
44 
45 namespace {
46 
47 const char *getExpectedProducerName() {
48  static char DefaultName[] = LLVM_VERSION_STRING
49 #ifdef LLVM_REVISION
50  " " LLVM_REVISION
51 #endif
52  ;
53  // Allows for testing of the irsymtab writer and upgrade mechanism. This
54  // environment variable should not be set by users.
55  if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
56  return OverrideName;
57  return DefaultName;
58 }
59 
60 const char *kExpectedProducerName = getExpectedProducerName();
61 
62 /// Stores the temporary state that is required to build an IR symbol table.
63 struct Builder {
64  SmallVector<char, 0> &Symtab;
65  StringTableBuilder &StrtabBuilder;
66  StringSaver Saver;
67 
68  // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
69  // The StringTableBuilder does not create a copy of any strings added to it,
70  // so this provides somewhere to store any strings that we create.
71  Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
73  : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
74 
76  Mangler Mang;
77  Triple TT;
78 
79  std::vector<storage::Comdat> Comdats;
80  std::vector<storage::Module> Mods;
81  std::vector<storage::Symbol> Syms;
82  std::vector<storage::Uncommon> Uncommons;
83 
84  std::string COFFLinkerOpts;
85  raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
86 
87  void setStr(storage::Str &S, StringRef Value) {
88  S.Offset = StrtabBuilder.add(Value);
89  S.Size = Value.size();
90  }
91 
92  template <typename T>
93  void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
94  R.Offset = Symtab.size();
95  R.Size = Objs.size();
96  Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
97  reinterpret_cast<const char *>(Objs.data() + Objs.size()));
98  }
99 
100  Error addModule(Module *M);
101  Error addSymbol(const ModuleSymbolTable &Msymtab,
102  const SmallPtrSet<GlobalValue *, 8> &Used,
104 
106 };
107 
108 Error Builder::addModule(Module *M) {
109  if (M->getDataLayoutStr().empty())
110  return make_error<StringError>("input module has no datalayout",
112 
114  collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
115 
116  ModuleSymbolTable Msymtab;
117  Msymtab.addModule(M);
118 
119  storage::Module Mod;
120  Mod.Begin = Syms.size();
121  Mod.End = Syms.size() + Msymtab.symbols().size();
122  Mod.UncBegin = Uncommons.size();
123  Mods.push_back(Mod);
124 
125  if (TT.isOSBinFormatCOFF()) {
126  if (auto E = M->materializeMetadata())
127  return E;
128  if (NamedMDNode *LinkerOptions =
129  M->getNamedMetadata("llvm.linker.options")) {
130  for (MDNode *MDOptions : LinkerOptions->operands())
131  for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
132  COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
133  }
134  }
135 
136  for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
137  if (Error Err = addSymbol(Msymtab, Used, Msym))
138  return Err;
139 
140  return Error::success();
141 }
142 
143 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
144  const SmallPtrSet<GlobalValue *, 8> &Used,
146  Syms.emplace_back();
147  storage::Symbol &Sym = Syms.back();
148  Sym = {};
149 
150  storage::Uncommon *Unc = nullptr;
151  auto Uncommon = [&]() -> storage::Uncommon & {
152  if (Unc)
153  return *Unc;
155  Uncommons.emplace_back();
156  Unc = &Uncommons.back();
157  *Unc = {};
158  setStr(Unc->COFFWeakExternFallbackName, "");
159  return *Unc;
160  };
161 
163  {
164  raw_svector_ostream OS(Name);
165  Msymtab.printSymbolName(OS, Msym);
166  }
167  setStr(Sym.Name, Saver.save(StringRef(Name)));
168 
169  auto Flags = Msymtab.getSymbolFlags(Msym);
173  Sym.Flags |= 1 << storage::Symbol::FB_weak;
175  Sym.Flags |= 1 << storage::Symbol::FB_common;
179  Sym.Flags |= 1 << storage::Symbol::FB_global;
184 
185  Sym.ComdatIndex = -1;
186  auto *GV = Msym.dyn_cast<GlobalValue *>();
187  if (!GV) {
188  // Undefined module asm symbols act as GC roots and are implicitly used.
189  if (Flags & object::BasicSymbolRef::SF_Undefined)
190  Sym.Flags |= 1 << storage::Symbol::FB_used;
191  setStr(Sym.IRName, "");
192  return Error::success();
193  }
194 
195  setStr(Sym.IRName, GV->getName());
196 
197  if (Used.count(GV))
198  Sym.Flags |= 1 << storage::Symbol::FB_used;
199  if (GV->isThreadLocal())
200  Sym.Flags |= 1 << storage::Symbol::FB_tls;
201  if (GV->hasGlobalUnnamedAddr())
205  Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
206 
207  if (Flags & object::BasicSymbolRef::SF_Common) {
208  Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
209  GV->getType()->getElementType());
210  Uncommon().CommonAlign = GV->getAlignment();
211  }
212 
213  const GlobalObject *Base = GV->getBaseObject();
214  if (!Base)
215  return make_error<StringError>("Unable to determine comdat of alias!",
217  if (const Comdat *C = Base->getComdat()) {
218  auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
219  Sym.ComdatIndex = P.first->second;
220 
221  if (P.second) {
223  setStr(Comdat.Name, C->getName());
224  Comdats.push_back(Comdat);
225  }
226  }
227 
228  if (TT.isOSBinFormatCOFF()) {
229  emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
230 
231  if ((Flags & object::BasicSymbolRef::SF_Weak) &&
232  (Flags & object::BasicSymbolRef::SF_Indirect)) {
233  std::string FallbackName;
234  raw_string_ostream OS(FallbackName);
235  Msymtab.printSymbolName(
236  OS, cast<GlobalValue>(
237  cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts()));
238  OS.flush();
239  setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
240  }
241  }
242 
243  return Error::success();
244 }
245 
247  storage::Header Hdr;
248 
249  assert(!IRMods.empty());
251  setStr(Hdr.Producer, kExpectedProducerName);
252  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
253  setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
254  TT = Triple(IRMods[0]->getTargetTriple());
255 
256  for (auto *M : IRMods)
257  if (Error Err = addModule(M))
258  return Err;
259 
260  COFFLinkerOptsOS.flush();
261  setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
262 
263  // We are about to fill in the header's range fields, so reserve space for it
264  // and copy it in afterwards.
265  Symtab.resize(sizeof(storage::Header));
266  writeRange(Hdr.Modules, Mods);
267  writeRange(Hdr.Comdats, Comdats);
268  writeRange(Hdr.Symbols, Syms);
269  writeRange(Hdr.Uncommons, Uncommons);
270 
271  *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
272  return Error::success();
273 }
274 
275 } // end anonymous namespace
276 
278  StringTableBuilder &StrtabBuilder,
280  return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
281 }
282 
283 // Upgrade a vector of bitcode modules created by an old version of LLVM by
284 // creating an irsymtab for them in the current format.
287 
288  LLVMContext Ctx;
289  std::vector<Module *> Mods;
290  std::vector<std::unique_ptr<Module>> OwnedMods;
291  for (auto BM : BMs) {
293  BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
294  /*IsImporting*/ false);
295  if (!MOrErr)
296  return MOrErr.takeError();
297 
298  Mods.push_back(MOrErr->get());
299  OwnedMods.push_back(std::move(*MOrErr));
300  }
301 
304  if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
305  return std::move(E);
306 
307  StrtabBuilder.finalizeInOrder();
308  FC.Strtab.resize(StrtabBuilder.getSize());
309  StrtabBuilder.write((uint8_t *)FC.Strtab.data());
310 
311  FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
312  {FC.Strtab.data(), FC.Strtab.size()}};
313  return std::move(FC);
314 }
315 
317  if (BFC.Mods.empty())
318  return make_error<StringError>("Bitcode file does not contain any modules",
320 
321  if (BFC.StrtabForSymtab.empty() ||
322  BFC.Symtab.size() < sizeof(storage::Header))
323  return upgrade(BFC.Mods);
324 
325  // We cannot use the regular reader to read the version and producer, because
326  // it will expect the header to be in the current format. The only thing we
327  // can rely on is that the version and producer will be present as the first
328  // struct elements.
329  auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
330  unsigned Version = Hdr->Version;
331  StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
332  if (Version != storage::Header::kCurrentVersion ||
333  Producer != kExpectedProducerName)
334  return upgrade(BFC.Mods);
335 
337  FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
338  {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
339 
340  // Finally, make sure that the number of modules in the symbol table matches
341  // the number of modules in the bitcode file. If they differ, it may mean that
342  // the bitcode file was created by binary concatenation, so we need to create
343  // a new symbol table from scratch.
344  if (FC.TheReader.getNumModules() != BFC.Mods.size())
345  return upgrade(std::move(BFC.Mods));
346 
347  return std::move(FC);
348 }
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:709
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Definition: IRSymtab.cpp:285
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallPtrSetImpl< GlobalValue * > &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition: Module.cpp:513
Contains the information needed by linkers for symbol resolution, as well as by the LTO implementatio...
Definition: IRSymtab.h:87
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
bool canBeOmittedFromSymbolTable(const GlobalValue *GV)
True if GV can be left out of the object symbol table.
Definition: ObjectUtils.h:22
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
Definition: PointerUnion.h:142
This file contains the declarations for metadata subclasses.
Word ComdatIndex
The index into Header::Comdats, or -1 if not a comdat member.
Definition: IRSymtab.h:96
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
Metadata node.
Definition: Metadata.h:862
Error takeError()
Take ownership of the stored error.
Definition: Error.h:764
Str IRName
The unmangled symbol name, or the empty string if this is not an IR symbol.
Definition: IRSymtab.h:93
A reference to a range of objects in the symbol table.
Definition: IRSymtab.h:63
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
A tuple of MDNodes.
Definition: Metadata.h:1316
The contents of the irsymtab in a bitcode file.
Definition: IRSymtab.h:338
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
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:277
Utility for building string tables with deduplicated suffixes.
SmallVector< char, 0 > Symtab
Definition: IRSymtab.h:339
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
A reference to a string in the string table.
Definition: IRSymtab.h:54
const char * Name
#define P(N)
Describes the range of a particular module's symbols within the symbol table.
Definition: IRSymtab.h:73
Word Version
Version number of the symtab format.
Definition: IRSymtab.h:130
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void finalizeInOrder()
Finalize the string table without reording it.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:138
const Comdat * getComdat() const
Definition: GlobalObject.h:101
Str COFFLinkerOpts
COFF-specific: linker directives.
Definition: IRSymtab.h:147
Str Name
The mangled symbol name.
Definition: IRSymtab.h:89
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:177
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
This data structure contains rarely used symbol fields and is optionally referenced by a Symbol...
Definition: IRSymtab.h:118
SmallVector< char, 0 > Strtab
Definition: IRSymtab.h:339
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
void write(raw_ostream &OS) const
Range< Uncommon > Uncommons
Definition: IRSymtab.h:142
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
Module.h This file contains the declarations for the Module class.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
reference get()
Returns a reference to the stored T value.
Definition: Error.h:744
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition: IRSymtab.cpp:316
size_t getNumModules() const
Definition: IRSymtab.h:258
uint32_t getSymbolFlags(Symbol S) const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
Str Producer
The producer's version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition: IRSymtab.h:137
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
Saves strings in the inheritor's stable storage and returns a StringRef with a stable character point...
Definition: StringSaver.h:21
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:242
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:142
#define C
Definition: LargeTest.cpp:25
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
ArrayRef< Symbol > symbols() const
op_range operands() const
Definition: Metadata.h:1065
StringRef get(StringRef Strtab) const
Definition: IRSymtab.h:57
void printSymbolName(raw_ostream &OS, Symbol S) const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
LLVM Value Representation.
Definition: Value.h:73
This is equivalent to an IR comdat.
Definition: IRSymtab.h:81
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
BumpPtrAllocator Alloc
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
const std::string & getDataLayoutStr() const
Get the data layout string for the module's target platform.
Definition: Module.h:224
Word UncBegin
The index of the first Uncommon for this Module.
Definition: IRSymtab.h:77
const uint64_t Version
Definition: InstrProf.h:864
llvm::Error materializeMetadata()
Definition: Module.cpp:400
std::vector< BitcodeModule > Mods
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:73
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:87
void resize(size_type N)
Definition: SmallVector.h:352
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition: IRSymtab.h:123