LLVM  9.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  void setStr(storage::Str &S, StringRef Value) {
93  S.Offset = StrtabBuilder.add(Value);
94  S.Size = Value.size();
95  }
96 
97  template <typename T>
98  void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
99  R.Offset = Symtab.size();
100  R.Size = Objs.size();
101  Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
102  reinterpret_cast<const char *>(Objs.data() + Objs.size()));
103  }
104 
105  Expected<int> getComdatIndex(const Comdat *C, const Module *M);
106 
107  Error addModule(Module *M);
108  Error addSymbol(const ModuleSymbolTable &Msymtab,
109  const SmallPtrSet<GlobalValue *, 8> &Used,
111 
113 };
114 
115 Error Builder::addModule(Module *M) {
116  if (M->getDataLayoutStr().empty())
117  return make_error<StringError>("input module has no datalayout",
119 
121  collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
122 
123  ModuleSymbolTable Msymtab;
124  Msymtab.addModule(M);
125 
127  Mod.Begin = Syms.size();
128  Mod.End = Syms.size() + Msymtab.symbols().size();
129  Mod.UncBegin = Uncommons.size();
130  Mods.push_back(Mod);
131 
132  if (TT.isOSBinFormatCOFF()) {
133  if (auto E = M->materializeMetadata())
134  return E;
135  if (NamedMDNode *LinkerOptions =
136  M->getNamedMetadata("llvm.linker.options")) {
137  for (MDNode *MDOptions : LinkerOptions->operands())
138  for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
139  COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
140  }
141  }
142 
143  for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
144  if (Error Err = addSymbol(Msymtab, Used, Msym))
145  return Err;
146 
147  return Error::success();
148 }
149 
150 Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
151  auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
152  if (P.second) {
153  std::string Name;
154  if (TT.isOSBinFormatCOFF()) {
155  const GlobalValue *GV = M->getNamedValue(C->getName());
156  if (!GV)
157  return make_error<StringError>("Could not find leader",
159  // Internal leaders do not affect symbol resolution, therefore they do not
160  // appear in the symbol table.
161  if (GV->hasLocalLinkage()) {
162  P.first->second = -1;
163  return -1;
164  }
165  llvm::raw_string_ostream OS(Name);
166  Mang.getNameWithPrefix(OS, GV, false);
167  } else {
168  Name = C->getName();
169  }
170 
172  setStr(Comdat.Name, Saver.save(Name));
173  Comdats.push_back(Comdat);
174  }
175 
176  return P.first->second;
177 }
178 
179 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
180  const SmallPtrSet<GlobalValue *, 8> &Used,
182  Syms.emplace_back();
183  storage::Symbol &Sym = Syms.back();
184  Sym = {};
185 
186  storage::Uncommon *Unc = nullptr;
187  auto Uncommon = [&]() -> storage::Uncommon & {
188  if (Unc)
189  return *Unc;
191  Uncommons.emplace_back();
192  Unc = &Uncommons.back();
193  *Unc = {};
194  setStr(Unc->COFFWeakExternFallbackName, "");
195  setStr(Unc->SectionName, "");
196  return *Unc;
197  };
198 
200  {
201  raw_svector_ostream OS(Name);
202  Msymtab.printSymbolName(OS, Msym);
203  }
204  setStr(Sym.Name, Saver.save(StringRef(Name)));
205 
206  auto Flags = Msymtab.getSymbolFlags(Msym);
210  Sym.Flags |= 1 << storage::Symbol::FB_weak;
212  Sym.Flags |= 1 << storage::Symbol::FB_common;
216  Sym.Flags |= 1 << storage::Symbol::FB_global;
221 
222  Sym.ComdatIndex = -1;
223  auto *GV = Msym.dyn_cast<GlobalValue *>();
224  if (!GV) {
225  // Undefined module asm symbols act as GC roots and are implicitly used.
226  if (Flags & object::BasicSymbolRef::SF_Undefined)
227  Sym.Flags |= 1 << storage::Symbol::FB_used;
228  setStr(Sym.IRName, "");
229  return Error::success();
230  }
231 
232  setStr(Sym.IRName, GV->getName());
233 
234  bool IsBuiltinFunc = false;
235 
236  for (const char *LibcallName : LibcallRoutineNames)
237  if (GV->getName() == LibcallName)
238  IsBuiltinFunc = true;
239 
240  if (Used.count(GV) || IsBuiltinFunc)
241  Sym.Flags |= 1 << storage::Symbol::FB_used;
242  if (GV->isThreadLocal())
243  Sym.Flags |= 1 << storage::Symbol::FB_tls;
244  if (GV->hasGlobalUnnamedAddr())
246  if (GV->canBeOmittedFromSymbolTable())
248  Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
249 
250  if (Flags & object::BasicSymbolRef::SF_Common) {
251  Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
252  GV->getType()->getElementType());
253  Uncommon().CommonAlign = GV->getAlignment();
254  }
255 
256  const GlobalObject *Base = GV->getBaseObject();
257  if (!Base)
258  return make_error<StringError>("Unable to determine comdat of alias!",
260  if (const Comdat *C = Base->getComdat()) {
261  Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
262  if (!ComdatIndexOrErr)
263  return ComdatIndexOrErr.takeError();
264  Sym.ComdatIndex = *ComdatIndexOrErr;
265  }
266 
267  if (TT.isOSBinFormatCOFF()) {
268  emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
269 
270  if ((Flags & object::BasicSymbolRef::SF_Weak) &&
271  (Flags & object::BasicSymbolRef::SF_Indirect)) {
272  auto *Fallback = dyn_cast<GlobalValue>(
273  cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
274  if (!Fallback)
275  return make_error<StringError>("Invalid weak external",
277  std::string FallbackName;
278  raw_string_ostream OS(FallbackName);
279  Msymtab.printSymbolName(OS, Fallback);
280  OS.flush();
281  setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
282  }
283  }
284 
285  if (!Base->getSection().empty())
286  setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
287 
288  return Error::success();
289 }
290 
292  storage::Header Hdr;
293 
294  assert(!IRMods.empty());
296  setStr(Hdr.Producer, kExpectedProducerName);
297  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
298  setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
299  TT = Triple(IRMods[0]->getTargetTriple());
300 
301  for (auto *M : IRMods)
302  if (Error Err = addModule(M))
303  return Err;
304 
305  COFFLinkerOptsOS.flush();
306  setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
307 
308  // We are about to fill in the header's range fields, so reserve space for it
309  // and copy it in afterwards.
310  Symtab.resize(sizeof(storage::Header));
311  writeRange(Hdr.Modules, Mods);
312  writeRange(Hdr.Comdats, Comdats);
313  writeRange(Hdr.Symbols, Syms);
314  writeRange(Hdr.Uncommons, Uncommons);
315 
316  *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
317  return Error::success();
318 }
319 
320 } // end anonymous namespace
321 
323  StringTableBuilder &StrtabBuilder,
324  BumpPtrAllocator &Alloc) {
325  return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
326 }
327 
328 // Upgrade a vector of bitcode modules created by an old version of LLVM by
329 // creating an irsymtab for them in the current format.
332 
333  LLVMContext Ctx;
334  std::vector<Module *> Mods;
335  std::vector<std::unique_ptr<Module>> OwnedMods;
336  for (auto BM : BMs) {
338  BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
339  /*IsImporting*/ false);
340  if (!MOrErr)
341  return MOrErr.takeError();
342 
343  Mods.push_back(MOrErr->get());
344  OwnedMods.push_back(std::move(*MOrErr));
345  }
346 
348  BumpPtrAllocator Alloc;
349  if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
350  return std::move(E);
351 
352  StrtabBuilder.finalizeInOrder();
353  FC.Strtab.resize(StrtabBuilder.getSize());
354  StrtabBuilder.write((uint8_t *)FC.Strtab.data());
355 
356  FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
357  {FC.Strtab.data(), FC.Strtab.size()}};
358  return std::move(FC);
359 }
360 
362  if (BFC.Mods.empty())
363  return make_error<StringError>("Bitcode file does not contain any modules",
365 
366  if (BFC.StrtabForSymtab.empty() ||
367  BFC.Symtab.size() < sizeof(storage::Header))
368  return upgrade(BFC.Mods);
369 
370  // We cannot use the regular reader to read the version and producer, because
371  // it will expect the header to be in the current format. The only thing we
372  // can rely on is that the version and producer will be present as the first
373  // struct elements.
374  auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
375  unsigned Version = Hdr->Version;
376  StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
377  if (Version != storage::Header::kCurrentVersion ||
378  Producer != kExpectedProducerName)
379  return upgrade(BFC.Mods);
380 
382  FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
383  {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
384 
385  // Finally, make sure that the number of modules in the symbol table matches
386  // the number of modules in the bitcode file. If they differ, it may mean that
387  // the bitcode file was created by binary concatenation, so we need to create
388  // a new symbol table from scratch.
389  if (FC.TheReader.getNumModules() != BFC.Mods.size())
390  return upgrade(std::move(BFC.Mods));
391 
392  return std::move(FC);
393 }
uint64_t CallInst * C
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:89
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:710
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
uint32_t getSymbolFlags(Symbol S) const
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Definition: IRSymtab.cpp:330
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:64
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:509
const std::string & getDataLayoutStr() const
Get the data layout string for the module&#39;s target platform.
Definition: Module.h:230
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.
A tuple of MDNodes.
Definition: Metadata.h:1325
size_t getNumModules() const
Definition: IRSymtab.h:263
The contents of the irsymtab in a bitcode file.
Definition: IRSymtab.h:346
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
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:347
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:130
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:322
#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:132
* 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:140
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Str COFFLinkerOpts
COFF-specific: linker directives.
Definition: IRSymtab.h:149
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
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
Definition: PointerUnion.h:141
SmallVector< char, 0 > Strtab
Definition: IRSymtab.h:347
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:594
Range< Uncommon > Uncommons
Definition: IRSymtab.h:144
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:361
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:470
Str Producer
The producer&#39;s version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition: IRSymtab.h:139
const Comdat * getComdat() const
Definition: GlobalObject.h:100
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
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:322
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:122
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:482
LLVM Value Representation.
Definition: Value.h:72
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:894
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 pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:86
static const char * LibcallRoutineNames[]
Definition: IRSymtab.cpp:44
void resize(size_type N)
Definition: SmallVector.h:343
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition: IRSymtab.h:122