LLVM  10.0.0svn
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 
9 #include "llvm/Object/IRSymtab.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include "llvm/ADT/SmallPtrSet.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Triple.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"
21 #include "llvm/IR/GlobalObject.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/IR/Module.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/Error.h"
34 #include "llvm/Support/VCSRevision.h"
36 #include <cassert>
37 #include <string>
38 #include <utility>
39 #include <vector>
40 
41 using namespace llvm;
42 using namespace irsymtab;
43 
44 static const char *LibcallRoutineNames[] = {
45 #define HANDLE_LIBCALL(code, name) name,
46 #include "llvm/IR/RuntimeLibcalls.def"
47 #undef HANDLE_LIBCALL
48 };
49 
50 namespace {
51 
52 const char *getExpectedProducerName() {
53  static char DefaultName[] = LLVM_VERSION_STRING
54 #ifdef LLVM_REVISION
55  " " LLVM_REVISION
56 #endif
57  ;
58  // Allows for testing of the irsymtab writer and upgrade mechanism. This
59  // environment variable should not be set by users.
60  if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
61  return OverrideName;
62  return DefaultName;
63 }
64 
65 const char *kExpectedProducerName = getExpectedProducerName();
66 
67 /// Stores the temporary state that is required to build an IR symbol table.
68 struct Builder {
69  SmallVector<char, 0> &Symtab;
70  StringTableBuilder &StrtabBuilder;
71  StringSaver Saver;
72 
73  // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
74  // The StringTableBuilder does not create a copy of any strings added to it,
75  // so this provides somewhere to store any strings that we create.
76  Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
77  BumpPtrAllocator &Alloc)
78  : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
79 
81  Mangler Mang;
82  Triple TT;
83 
84  std::vector<storage::Comdat> Comdats;
85  std::vector<storage::Module> Mods;
86  std::vector<storage::Symbol> Syms;
87  std::vector<storage::Uncommon> Uncommons;
88 
89  std::string COFFLinkerOpts;
90  raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
91 
92  std::vector<storage::Str> DependentLibraries;
93 
94  void setStr(storage::Str &S, StringRef Value) {
95  S.Offset = StrtabBuilder.add(Value);
96  S.Size = Value.size();
97  }
98 
99  template <typename T>
100  void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
101  R.Offset = Symtab.size();
102  R.Size = Objs.size();
103  Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
104  reinterpret_cast<const char *>(Objs.data() + Objs.size()));
105  }
106 
107  Expected<int> getComdatIndex(const Comdat *C, const Module *M);
108 
109  Error addModule(Module *M);
110  Error addSymbol(const ModuleSymbolTable &Msymtab,
111  const SmallPtrSet<GlobalValue *, 8> &Used,
113 
115 };
116 
117 Error Builder::addModule(Module *M) {
118  if (M->getDataLayoutStr().empty())
119  return make_error<StringError>("input module has no datalayout",
121 
123  collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
124 
125  ModuleSymbolTable Msymtab;
126  Msymtab.addModule(M);
127 
129  Mod.Begin = Syms.size();
130  Mod.End = Syms.size() + Msymtab.symbols().size();
131  Mod.UncBegin = Uncommons.size();
132  Mods.push_back(Mod);
133 
134  if (TT.isOSBinFormatCOFF()) {
135  if (auto E = M->materializeMetadata())
136  return E;
137  if (NamedMDNode *LinkerOptions =
138  M->getNamedMetadata("llvm.linker.options")) {
139  for (MDNode *MDOptions : LinkerOptions->operands())
140  for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
141  COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
142  }
143  }
144 
145  if (TT.isOSBinFormatELF()) {
146  if (auto E = M->materializeMetadata())
147  return E;
148  if (NamedMDNode *N = M->getNamedMetadata("llvm.dependent-libraries")) {
149  for (MDNode *MDOptions : N->operands()) {
150  const auto OperandStr =
151  cast<MDString>(cast<MDNode>(MDOptions)->getOperand(0))->getString();
152  storage::Str Specifier;
153  setStr(Specifier, OperandStr);
154  DependentLibraries.emplace_back(Specifier);
155  }
156  }
157  }
158 
159  for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
160  if (Error Err = addSymbol(Msymtab, Used, Msym))
161  return Err;
162 
163  return Error::success();
164 }
165 
166 Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
167  auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
168  if (P.second) {
169  std::string Name;
170  if (TT.isOSBinFormatCOFF()) {
171  const GlobalValue *GV = M->getNamedValue(C->getName());
172  if (!GV)
173  return make_error<StringError>("Could not find leader",
175  // Internal leaders do not affect symbol resolution, therefore they do not
176  // appear in the symbol table.
177  if (GV->hasLocalLinkage()) {
178  P.first->second = -1;
179  return -1;
180  }
181  llvm::raw_string_ostream OS(Name);
182  Mang.getNameWithPrefix(OS, GV, false);
183  } else {
184  Name = C->getName();
185  }
186 
188  setStr(Comdat.Name, Saver.save(Name));
189  Comdats.push_back(Comdat);
190  }
191 
192  return P.first->second;
193 }
194 
195 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
196  const SmallPtrSet<GlobalValue *, 8> &Used,
198  Syms.emplace_back();
199  storage::Symbol &Sym = Syms.back();
200  Sym = {};
201 
202  storage::Uncommon *Unc = nullptr;
203  auto Uncommon = [&]() -> storage::Uncommon & {
204  if (Unc)
205  return *Unc;
207  Uncommons.emplace_back();
208  Unc = &Uncommons.back();
209  *Unc = {};
210  setStr(Unc->COFFWeakExternFallbackName, "");
211  setStr(Unc->SectionName, "");
212  return *Unc;
213  };
214 
216  {
217  raw_svector_ostream OS(Name);
218  Msymtab.printSymbolName(OS, Msym);
219  }
220  setStr(Sym.Name, Saver.save(StringRef(Name)));
221 
222  auto Flags = Msymtab.getSymbolFlags(Msym);
226  Sym.Flags |= 1 << storage::Symbol::FB_weak;
228  Sym.Flags |= 1 << storage::Symbol::FB_common;
232  Sym.Flags |= 1 << storage::Symbol::FB_global;
237 
238  Sym.ComdatIndex = -1;
239  auto *GV = Msym.dyn_cast<GlobalValue *>();
240  if (!GV) {
241  // Undefined module asm symbols act as GC roots and are implicitly used.
242  if (Flags & object::BasicSymbolRef::SF_Undefined)
243  Sym.Flags |= 1 << storage::Symbol::FB_used;
244  setStr(Sym.IRName, "");
245  return Error::success();
246  }
247 
248  setStr(Sym.IRName, GV->getName());
249 
250  bool IsBuiltinFunc = false;
251 
252  for (const char *LibcallName : LibcallRoutineNames)
253  if (GV->getName() == LibcallName)
254  IsBuiltinFunc = true;
255 
256  if (Used.count(GV) || IsBuiltinFunc)
257  Sym.Flags |= 1 << storage::Symbol::FB_used;
258  if (GV->isThreadLocal())
259  Sym.Flags |= 1 << storage::Symbol::FB_tls;
260  if (GV->hasGlobalUnnamedAddr())
262  if (GV->canBeOmittedFromSymbolTable())
264  Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
265 
266  if (Flags & object::BasicSymbolRef::SF_Common) {
267  Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
268  GV->getType()->getElementType());
269  Uncommon().CommonAlign = GV->getAlignment();
270  }
271 
272  const GlobalObject *Base = GV->getBaseObject();
273  if (!Base)
274  return make_error<StringError>("Unable to determine comdat of alias!",
276  if (const Comdat *C = Base->getComdat()) {
277  Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
278  if (!ComdatIndexOrErr)
279  return ComdatIndexOrErr.takeError();
280  Sym.ComdatIndex = *ComdatIndexOrErr;
281  }
282 
283  if (TT.isOSBinFormatCOFF()) {
284  emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
285 
286  if ((Flags & object::BasicSymbolRef::SF_Weak) &&
287  (Flags & object::BasicSymbolRef::SF_Indirect)) {
288  auto *Fallback = dyn_cast<GlobalValue>(
289  cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
290  if (!Fallback)
291  return make_error<StringError>("Invalid weak external",
293  std::string FallbackName;
294  raw_string_ostream OS(FallbackName);
295  Msymtab.printSymbolName(OS, Fallback);
296  OS.flush();
297  setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
298  }
299  }
300 
301  if (!Base->getSection().empty())
302  setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
303 
304  return Error::success();
305 }
306 
308  storage::Header Hdr;
309 
310  assert(!IRMods.empty());
312  setStr(Hdr.Producer, kExpectedProducerName);
313  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
314  setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
315  TT = Triple(IRMods[0]->getTargetTriple());
316 
317  for (auto *M : IRMods)
318  if (Error Err = addModule(M))
319  return Err;
320 
321  COFFLinkerOptsOS.flush();
322  setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
323 
324  // We are about to fill in the header's range fields, so reserve space for it
325  // and copy it in afterwards.
326  Symtab.resize(sizeof(storage::Header));
327  writeRange(Hdr.Modules, Mods);
328  writeRange(Hdr.Comdats, Comdats);
329  writeRange(Hdr.Symbols, Syms);
330  writeRange(Hdr.Uncommons, Uncommons);
331  writeRange(Hdr.DependentLibraries, DependentLibraries);
332  *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
333  return Error::success();
334 }
335 
336 } // end anonymous namespace
337 
339  StringTableBuilder &StrtabBuilder,
340  BumpPtrAllocator &Alloc) {
341  return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
342 }
343 
344 // Upgrade a vector of bitcode modules created by an old version of LLVM by
345 // creating an irsymtab for them in the current format.
348 
349  LLVMContext Ctx;
350  std::vector<Module *> Mods;
351  std::vector<std::unique_ptr<Module>> OwnedMods;
352  for (auto BM : BMs) {
354  BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
355  /*IsImporting*/ false);
356  if (!MOrErr)
357  return MOrErr.takeError();
358 
359  Mods.push_back(MOrErr->get());
360  OwnedMods.push_back(std::move(*MOrErr));
361  }
362 
364  BumpPtrAllocator Alloc;
365  if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
366  return std::move(E);
367 
368  StrtabBuilder.finalizeInOrder();
369  FC.Strtab.resize(StrtabBuilder.getSize());
370  StrtabBuilder.write((uint8_t *)FC.Strtab.data());
371 
372  FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
373  {FC.Strtab.data(), FC.Strtab.size()}};
374  return std::move(FC);
375 }
376 
378  if (BFC.Mods.empty())
379  return make_error<StringError>("Bitcode file does not contain any modules",
381 
382  if (BFC.StrtabForSymtab.empty() ||
383  BFC.Symtab.size() < sizeof(storage::Header))
384  return upgrade(BFC.Mods);
385 
386  // We cannot use the regular reader to read the version and producer, because
387  // it will expect the header to be in the current format. The only thing we
388  // can rely on is that the version and producer will be present as the first
389  // struct elements.
390  auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
391  unsigned Version = Hdr->Version;
392  StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
393  if (Version != storage::Header::kCurrentVersion ||
394  Producer != kExpectedProducerName)
395  return upgrade(BFC.Mods);
396 
398  FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
399  {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
400 
401  // Finally, make sure that the number of modules in the symbol table matches
402  // the number of modules in the bitcode file. If they differ, it may mean that
403  // the bitcode file was created by binary concatenation, so we need to create
404  // a new symbol table from scratch.
405  if (FC.TheReader.getNumModules() != BFC.Mods.size())
406  return upgrade(std::move(BFC.Mods));
407 
408  return std::move(FC);
409 }
uint64_t CallInst * C
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:108
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:710
bool hasLocalLinkage() const
Definition: GlobalValue.h:445
uint32_t getSymbolFlags(Symbol S) const
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Definition: IRSymtab.cpp:346
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Contains the information needed by linkers for symbol resolution, as well as by the LTO implementatio...
Definition: IRSymtab.h:86
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
This file contains the declarations for metadata subclasses.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
Word ComdatIndex
The index into Header::Comdats, or -1 if not a comdat member.
Definition: IRSymtab.h:95
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:530
const std::string & getDataLayoutStr() const
Get the data layout string for the module&#39;s target platform.
Definition: Module.h:231
Metadata node.
Definition: Metadata.h:863
Str SectionName
Specified section name, if any.
Definition: IRSymtab.h:125
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
Str IRName
The unmangled symbol name, or the empty string if this is not an IR symbol.
Definition: IRSymtab.h:92
A reference to a range of objects in the symbol table.
Definition: IRSymtab.h:62
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
Definition: PointerUnion.h:201
A tuple of MDNodes.
Definition: Metadata.h:1325
size_t getNumModules() const
Definition: IRSymtab.h:269
The contents of the irsymtab in a bitcode file.
Definition: IRSymtab.h:362
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:140
void write(raw_ostream &OS) const
Utility for building string tables with deduplicated suffixes.
op_range operands() const
Definition: Metadata.h:1066
size_t add(CachedHashStringRef S)
Add a string to the builder.
SmallVector< char, 0 > Symtab
Definition: IRSymtab.h:363
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:250
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:113
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:144
A reference to a string in the string table.
Definition: IRSymtab.h:53
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:338
#define P(N)
Describes the range of a particular module&#39;s symbols within the symbol table.
Definition: IRSymtab.h:72
StringRef getName() const
Definition: Comdat.cpp:26
Word Version
Version number of the symtab format.
Definition: IRSymtab.h:133
* 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:64
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:140
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Str COFFLinkerOpts
COFF-specific: linker directives.
Definition: IRSymtab.h:150
Str Name
The mangled symbol name.
Definition: IRSymtab.h:88
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:184
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
This data structure contains rarely used symbol fields and is optionally referenced by a Symbol...
Definition: IRSymtab.h:117
SmallVector< char, 0 > Strtab
Definition: IRSymtab.h:363
size_t size() const
Definition: SmallVector.h:52
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
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:598
Range< Uncommon > Uncommons
Definition: IRSymtab.h:145
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
Module.h This file contains the declarations for the Module class.
reference get()
Returns a reference to the stored T value.
Definition: Error.h:532
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition: IRSymtab.cpp:377
The access may modify the value stored in memory.
void printSymbolName(raw_ostream &OS, Symbol S) const
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:467
Str Producer
The producer&#39;s version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition: IRSymtab.h:140
const Comdat * getComdat() const
Definition: GlobalObject.h:119
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer...
Definition: StringSaver.h:21
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
#define N
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:136
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:503
Range< Str > DependentLibraries
Dependent Library Specifiers.
Definition: IRSymtab.h:153
LLVM Value Representation.
Definition: Value.h:73
This is equivalent to an IR comdat.
Definition: IRSymtab.h:80
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Word UncBegin
The index of the first Uncommon for this Module.
Definition: IRSymtab.h:76
const uint64_t Version
Definition: InstrProf.h:980
llvm::Error materializeMetadata()
Definition: Module.cpp:408
std::vector< BitcodeModule > Mods
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:156
static const char * LibcallRoutineNames[]
Definition: IRSymtab.cpp:44
void resize(size_type N)
Definition: SmallVector.h:344
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition: IRSymtab.h:122