LLVM  7.0.0svn
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"
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 namespace {
45 
46 const char *getExpectedProducerName() {
47  static char DefaultName[] = LLVM_VERSION_STRING
48 #ifdef LLVM_REVISION
49  " " LLVM_REVISION
50 #endif
51  ;
52  // Allows for testing of the irsymtab writer and upgrade mechanism. This
53  // environment variable should not be set by users.
54  if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
55  return OverrideName;
56  return DefaultName;
57 }
58 
59 const char *kExpectedProducerName = getExpectedProducerName();
60 
61 /// Stores the temporary state that is required to build an IR symbol table.
62 struct Builder {
63  SmallVector<char, 0> &Symtab;
64  StringTableBuilder &StrtabBuilder;
65  StringSaver Saver;
66 
67  // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
68  // The StringTableBuilder does not create a copy of any strings added to it,
69  // so this provides somewhere to store any strings that we create.
70  Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
71  BumpPtrAllocator &Alloc)
72  : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
73 
75  Mangler Mang;
76  Triple TT;
77 
78  std::vector<storage::Comdat> Comdats;
79  std::vector<storage::Module> Mods;
80  std::vector<storage::Symbol> Syms;
81  std::vector<storage::Uncommon> Uncommons;
82 
83  std::string COFFLinkerOpts;
84  raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
85 
86  void setStr(storage::Str &S, StringRef Value) {
87  S.Offset = StrtabBuilder.add(Value);
88  S.Size = Value.size();
89  }
90 
91  template <typename T>
92  void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
93  R.Offset = Symtab.size();
94  R.Size = Objs.size();
95  Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
96  reinterpret_cast<const char *>(Objs.data() + Objs.size()));
97  }
98 
99  Expected<int> getComdatIndex(const Comdat *C, const Module *M);
100 
101  Error addModule(Module *M);
102  Error addSymbol(const ModuleSymbolTable &Msymtab,
103  const SmallPtrSet<GlobalValue *, 8> &Used,
105 
107 };
108 
109 Error Builder::addModule(Module *M) {
110  if (M->getDataLayoutStr().empty())
111  return make_error<StringError>("input module has no datalayout",
113 
115  collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
116 
117  ModuleSymbolTable Msymtab;
118  Msymtab.addModule(M);
119 
121  Mod.Begin = Syms.size();
122  Mod.End = Syms.size() + Msymtab.symbols().size();
123  Mod.UncBegin = Uncommons.size();
124  Mods.push_back(Mod);
125 
126  if (TT.isOSBinFormatCOFF()) {
127  if (auto E = M->materializeMetadata())
128  return E;
129  if (NamedMDNode *LinkerOptions =
130  M->getNamedMetadata("llvm.linker.options")) {
131  for (MDNode *MDOptions : LinkerOptions->operands())
132  for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
133  COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
134  }
135  }
136 
137  for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
138  if (Error Err = addSymbol(Msymtab, Used, Msym))
139  return Err;
140 
141  return Error::success();
142 }
143 
144 Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
145  auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
146  if (P.second) {
147  std::string Name;
148  if (TT.isOSBinFormatCOFF()) {
149  const GlobalValue *GV = M->getNamedValue(C->getName());
150  if (!GV)
151  return make_error<StringError>("Could not find leader",
153  // Internal leaders do not affect symbol resolution, therefore they do not
154  // appear in the symbol table.
155  if (GV->hasLocalLinkage()) {
156  P.first->second = -1;
157  return -1;
158  }
159  llvm::raw_string_ostream OS(Name);
160  Mang.getNameWithPrefix(OS, GV, false);
161  } else {
162  Name = C->getName();
163  }
164 
166  setStr(Comdat.Name, Saver.save(Name));
167  Comdats.push_back(Comdat);
168  }
169 
170  return P.first->second;
171 }
172 
173 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
174  const SmallPtrSet<GlobalValue *, 8> &Used,
176  Syms.emplace_back();
177  storage::Symbol &Sym = Syms.back();
178  Sym = {};
179 
180  storage::Uncommon *Unc = nullptr;
181  auto Uncommon = [&]() -> storage::Uncommon & {
182  if (Unc)
183  return *Unc;
185  Uncommons.emplace_back();
186  Unc = &Uncommons.back();
187  *Unc = {};
188  setStr(Unc->COFFWeakExternFallbackName, "");
189  setStr(Unc->SectionName, "");
190  return *Unc;
191  };
192 
194  {
195  raw_svector_ostream OS(Name);
196  Msymtab.printSymbolName(OS, Msym);
197  }
198  setStr(Sym.Name, Saver.save(StringRef(Name)));
199 
200  auto Flags = Msymtab.getSymbolFlags(Msym);
204  Sym.Flags |= 1 << storage::Symbol::FB_weak;
206  Sym.Flags |= 1 << storage::Symbol::FB_common;
210  Sym.Flags |= 1 << storage::Symbol::FB_global;
215 
216  Sym.ComdatIndex = -1;
217  auto *GV = Msym.dyn_cast<GlobalValue *>();
218  if (!GV) {
219  // Undefined module asm symbols act as GC roots and are implicitly used.
220  if (Flags & object::BasicSymbolRef::SF_Undefined)
221  Sym.Flags |= 1 << storage::Symbol::FB_used;
222  setStr(Sym.IRName, "");
223  return Error::success();
224  }
225 
226  setStr(Sym.IRName, GV->getName());
227 
228  if (Used.count(GV))
229  Sym.Flags |= 1 << storage::Symbol::FB_used;
230  if (GV->isThreadLocal())
231  Sym.Flags |= 1 << storage::Symbol::FB_tls;
232  if (GV->hasGlobalUnnamedAddr())
236  Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
237 
238  if (Flags & object::BasicSymbolRef::SF_Common) {
239  Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
240  GV->getType()->getElementType());
241  Uncommon().CommonAlign = GV->getAlignment();
242  }
243 
244  const GlobalObject *Base = GV->getBaseObject();
245  if (!Base)
246  return make_error<StringError>("Unable to determine comdat of alias!",
248  if (const Comdat *C = Base->getComdat()) {
249  Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
250  if (!ComdatIndexOrErr)
251  return ComdatIndexOrErr.takeError();
252  Sym.ComdatIndex = *ComdatIndexOrErr;
253  }
254 
255  if (TT.isOSBinFormatCOFF()) {
256  emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
257 
258  if ((Flags & object::BasicSymbolRef::SF_Weak) &&
259  (Flags & object::BasicSymbolRef::SF_Indirect)) {
260  auto *Fallback = dyn_cast<GlobalValue>(
261  cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
262  if (!Fallback)
263  return make_error<StringError>("Invalid weak external",
265  std::string FallbackName;
266  raw_string_ostream OS(FallbackName);
267  Msymtab.printSymbolName(OS, Fallback);
268  OS.flush();
269  setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
270  }
271  }
272 
273  if (!Base->getSection().empty())
274  setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
275 
276  return Error::success();
277 }
278 
280  storage::Header Hdr;
281 
282  assert(!IRMods.empty());
284  setStr(Hdr.Producer, kExpectedProducerName);
285  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
286  setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
287  TT = Triple(IRMods[0]->getTargetTriple());
288 
289  for (auto *M : IRMods)
290  if (Error Err = addModule(M))
291  return Err;
292 
293  COFFLinkerOptsOS.flush();
294  setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
295 
296  // We are about to fill in the header's range fields, so reserve space for it
297  // and copy it in afterwards.
298  Symtab.resize(sizeof(storage::Header));
299  writeRange(Hdr.Modules, Mods);
300  writeRange(Hdr.Comdats, Comdats);
301  writeRange(Hdr.Symbols, Syms);
302  writeRange(Hdr.Uncommons, Uncommons);
303 
304  *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
305  return Error::success();
306 }
307 
308 } // end anonymous namespace
309 
311  StringTableBuilder &StrtabBuilder,
312  BumpPtrAllocator &Alloc) {
313  return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
314 }
315 
316 // Upgrade a vector of bitcode modules created by an old version of LLVM by
317 // creating an irsymtab for them in the current format.
320 
321  LLVMContext Ctx;
322  std::vector<Module *> Mods;
323  std::vector<std::unique_ptr<Module>> OwnedMods;
324  for (auto BM : BMs) {
326  BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
327  /*IsImporting*/ false);
328  if (!MOrErr)
329  return MOrErr.takeError();
330 
331  Mods.push_back(MOrErr->get());
332  OwnedMods.push_back(std::move(*MOrErr));
333  }
334 
336  BumpPtrAllocator Alloc;
337  if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
338  return std::move(E);
339 
340  StrtabBuilder.finalizeInOrder();
341  FC.Strtab.resize(StrtabBuilder.getSize());
342  StrtabBuilder.write((uint8_t *)FC.Strtab.data());
343 
344  FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
345  {FC.Strtab.data(), FC.Strtab.size()}};
346  return std::move(FC);
347 }
348 
350  if (BFC.Mods.empty())
351  return make_error<StringError>("Bitcode file does not contain any modules",
353 
354  if (BFC.StrtabForSymtab.empty() ||
355  BFC.Symtab.size() < sizeof(storage::Header))
356  return upgrade(BFC.Mods);
357 
358  // We cannot use the regular reader to read the version and producer, because
359  // it will expect the header to be in the current format. The only thing we
360  // can rely on is that the version and producer will be present as the first
361  // struct elements.
362  auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
363  unsigned Version = Hdr->Version;
364  StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
365  if (Version != storage::Header::kCurrentVersion ||
366  Producer != kExpectedProducerName)
367  return upgrade(BFC.Mods);
368 
370  FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
371  {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
372 
373  // Finally, make sure that the number of modules in the symbol table matches
374  // the number of modules in the bitcode file. If they differ, it may mean that
375  // the bitcode file was created by binary concatenation, so we need to create
376  // a new symbol table from scratch.
377  if (FC.TheReader.getNumModules() != BFC.Mods.size())
378  return upgrade(std::move(BFC.Mods));
379 
380  return std::move(FC);
381 }
uint64_t CallInst * C
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:90
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:709
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
uint32_t getSymbolFlags(Symbol S) const
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Definition: IRSymtab.cpp:318
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
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
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
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:96
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:494
const std::string & getDataLayoutStr() const
Get the data layout string for the module&#39;s target platform.
Definition: Module.h:224
Metadata node.
Definition: Metadata.h:862
Str SectionName
Specified section name, if any.
Definition: IRSymtab.h:126
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
Str IRName
The unmangled symbol name, or the empty string if this is not an IR symbol.
Definition: IRSymtab.h:93
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
A reference to a range of objects in the symbol table.
Definition: IRSymtab.h:63
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition: Globals.cpp:284
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:191
A tuple of MDNodes.
Definition: Metadata.h:1323
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
size_t getNumModules() const
Definition: IRSymtab.h:264
The contents of the irsymtab in a bitcode file.
Definition: IRSymtab.h:347
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
void write(raw_ostream &OS) const
Utility for building string tables with deduplicated suffixes.
op_range operands() const
Definition: Metadata.h:1065
size_t add(CachedHashStringRef S)
Add a string to the builder.
SmallVector< char, 0 > Symtab
Definition: IRSymtab.h:348
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:242
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:112
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
unsigned getAlignment() const
Definition: Globals.cpp:97
A reference to a string in the string table.
Definition: IRSymtab.h:54
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:310
#define P(N)
Describes the range of a particular module&#39;s symbols within the symbol table.
Definition: IRSymtab.h:73
StringRef getName() const
Definition: Comdat.cpp:27
Word Version
Version number of the symtab format.
Definition: IRSymtab.h:133
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:232
void finalizeInOrder()
Finalize the string table without reording it.
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:591
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:143
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:89
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:185
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
This data structure contains rarely used symbol fields and is optionally referenced by a Symbol...
Definition: IRSymtab.h:118
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
Definition: PointerUnion.h:142
SmallVector< char, 0 > Strtab
Definition: IRSymtab.h:348
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
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:522
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:418
Module.h This file contains the declarations for the Module class.
reference get()
Returns a reference to the stored T value.
Definition: Error.h:517
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:199
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition: IRSymtab.cpp:349
The access may modify the value stored in memory.
StringRef save(const char *S)
Definition: StringSaver.h:26
void printSymbolName(raw_ostream &OS, Symbol S) const
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:480
Str Producer
The producer&#39;s version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition: IRSymtab.h:140
const Comdat * getComdat() const
Definition: GlobalObject.h:101
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
Saves strings in the inheritor&#39;s stable storage and returns a StringRef with a stable character point...
Definition: StringSaver.h:21
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:120
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:143
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
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:323
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:256
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:467
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
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
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:112
bool isThreadLocal() const
If the value is "Thread Local", its value isn&#39;t shared by the threads.
Definition: GlobalValue.h:246
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
StringRef get(StringRef Strtab) const
Definition: IRSymtab.h:57
Word UncBegin
The index of the first Uncommon for this Module.
Definition: IRSymtab.h:77
const uint64_t Version
Definition: InstrProf.h:895
llvm::Error materializeMetadata()
Definition: Module.cpp:400
Type * getElementType() const
Definition: DerivedTypes.h:486
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
std::vector< BitcodeModule > Mods
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
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:353
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition: IRSymtab.h:123