Line data Source code
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/Config/llvm-config.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"
26 : #include "llvm/Bitcode/BitcodeReader.h"
27 : #include "llvm/MC/StringTableBuilder.h"
28 : #include "llvm/Object/IRObjectFile.h"
29 : #include "llvm/Object/ModuleSymbolTable.h"
30 : #include "llvm/Object/SymbolicFile.h"
31 : #include "llvm/Support/Allocator.h"
32 : #include "llvm/Support/Casting.h"
33 : #include "llvm/Support/Error.h"
34 : #include "llvm/Support/StringSaver.h"
35 : #include "llvm/Support/VCSRevision.h"
36 : #include "llvm/Support/raw_ostream.h"
37 : #include <cassert>
38 : #include <string>
39 : #include <utility>
40 : #include <vector>
41 :
42 : using namespace llvm;
43 : using namespace irsymtab;
44 :
45 : static const char *LibcallRoutineNames[] = {
46 : #define HANDLE_LIBCALL(code, name) name,
47 : #include "llvm/IR/RuntimeLibcalls.def"
48 : #undef HANDLE_LIBCALL
49 : };
50 :
51 : namespace {
52 :
53 : const char *getExpectedProducerName() {
54 : static char DefaultName[] = LLVM_VERSION_STRING
55 : #ifdef LLVM_REVISION
56 : " " LLVM_REVISION
57 : #endif
58 : ;
59 : // Allows for testing of the irsymtab writer and upgrade mechanism. This
60 : // environment variable should not be set by users.
61 : if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
62 : return OverrideName;
63 : return DefaultName;
64 : }
65 :
66 : const char *kExpectedProducerName = getExpectedProducerName();
67 :
68 : /// Stores the temporary state that is required to build an IR symbol table.
69 : struct Builder {
70 : SmallVector<char, 0> &Symtab;
71 : StringTableBuilder &StrtabBuilder;
72 : StringSaver Saver;
73 :
74 : // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
75 : // The StringTableBuilder does not create a copy of any strings added to it,
76 : // so this provides somewhere to store any strings that we create.
77 4671 : Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
78 : BumpPtrAllocator &Alloc)
79 9342 : : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
80 :
81 : DenseMap<const Comdat *, int> ComdatMap;
82 : Mangler Mang;
83 : Triple TT;
84 :
85 : std::vector<storage::Comdat> Comdats;
86 : std::vector<storage::Module> Mods;
87 : std::vector<storage::Symbol> Syms;
88 : std::vector<storage::Uncommon> Uncommons;
89 :
90 : std::string COFFLinkerOpts;
91 : raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
92 :
93 0 : void setStr(storage::Str &S, StringRef Value) {
94 50923 : S.Offset = StrtabBuilder.add(Value);
95 50721 : S.Size = Value.size();
96 0 : }
97 :
98 : template <typename T>
99 0 : void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
100 0 : R.Offset = Symtab.size();
101 0 : R.Size = Objs.size();
102 0 : Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
103 0 : reinterpret_cast<const char *>(Objs.data() + Objs.size()));
104 0 : }
105 0 :
106 0 : Expected<int> getComdatIndex(const Comdat *C, const Module *M);
107 0 :
108 0 : Error addModule(Module *M);
109 0 : Error addSymbol(const ModuleSymbolTable &Msymtab,
110 0 : const SmallPtrSet<GlobalValue *, 8> &Used,
111 0 : ModuleSymbolTable::Symbol Sym);
112 0 :
113 0 : Error build(ArrayRef<Module *> Mods);
114 0 : };
115 0 :
116 0 : Error Builder::addModule(Module *M) {
117 0 : if (M->getDataLayoutStr().empty())
118 0 : return make_error<StringError>("input module has no datalayout",
119 0 : inconvertibleErrorCode());
120 0 :
121 0 : SmallPtrSet<GlobalValue *, 8> Used;
122 0 : collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
123 0 :
124 0 : ModuleSymbolTable Msymtab;
125 0 : Msymtab.addModule(M);
126 0 :
127 0 : storage::Module Mod;
128 0 : Mod.Begin = Syms.size();
129 : Mod.End = Syms.size() + Msymtab.symbols().size();
130 : Mod.UncBegin = Uncommons.size();
131 : Mods.push_back(Mod);
132 :
133 : if (TT.isOSBinFormatCOFF()) {
134 : if (auto E = M->materializeMetadata())
135 : return E;
136 : if (NamedMDNode *LinkerOptions =
137 : M->getNamedMetadata("llvm.linker.options")) {
138 : for (MDNode *MDOptions : LinkerOptions->operands())
139 : for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
140 4689 : COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
141 4689 : }
142 : }
143 4380 :
144 : for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
145 : if (Error Err = addSymbol(Msymtab, Used, Msym))
146 2499 : return Err;
147 :
148 4998 : return Error::success();
149 2499 : }
150 :
151 : Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
152 4998 : auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
153 2499 : if (P.second) {
154 4998 : std::string Name;
155 2499 : if (TT.isOSBinFormatCOFF()) {
156 : const GlobalValue *GV = M->getNamedValue(C->getName());
157 2499 : if (!GV)
158 228 : return make_error<StringError>("Could not find leader",
159 : inconvertibleErrorCode());
160 114 : // Internal leaders do not affect symbol resolution, therefore they do not
161 114 : // appear in the symbol table.
162 6 : if (GV->hasLocalLinkage()) {
163 6 : P.first->second = -1;
164 3 : return -1;
165 : }
166 : llvm::raw_string_ostream OS(Name);
167 : Mang.getNameWithPrefix(OS, GV, false);
168 22798 : } else {
169 40638 : Name = C->getName();
170 : }
171 :
172 : storage::Comdat Comdat;
173 : setStr(Comdat.Name, Saver.save(Name));
174 : Comdats.push_back(Comdat);
175 2697 : }
176 2697 :
177 2697 : return P.first->second;
178 : }
179 2043 :
180 20 : Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
181 20 : const SmallPtrSet<GlobalValue *, 8> &Used,
182 0 : ModuleSymbolTable::Symbol Msym) {
183 0 : Syms.emplace_back();
184 : storage::Symbol &Sym = Syms.back();
185 : Sym = {};
186 :
187 3 : storage::Uncommon *Unc = nullptr;
188 : auto Uncommon = [&]() -> storage::Uncommon & {
189 : if (Unc)
190 17 : return *Unc;
191 17 : Sym.Flags |= 1 << storage::Symbol::FB_has_uncommon;
192 : Uncommons.emplace_back();
193 6069 : Unc = &Uncommons.back();
194 : *Unc = {};
195 : setStr(Unc->COFFWeakExternFallbackName, "");
196 : setStr(Unc->SectionName, "");
197 2040 : return *Unc;
198 2040 : };
199 :
200 : SmallString<64> Name;
201 : {
202 : raw_svector_ostream OS(Name);
203 : Msymtab.printSymbolName(OS, Msym);
204 20319 : }
205 : setStr(Sym.Name, Saver.save(StringRef(Name)));
206 :
207 20319 : auto Flags = Msymtab.getSymbolFlags(Msym);
208 : if (Flags & object::BasicSymbolRef::SF_Undefined)
209 20319 : Sym.Flags |= 1 << storage::Symbol::FB_undefined;
210 : if (Flags & object::BasicSymbolRef::SF_Weak)
211 20319 : Sym.Flags |= 1 << storage::Symbol::FB_weak;
212 : if (Flags & object::BasicSymbolRef::SF_Common)
213 : Sym.Flags |= 1 << storage::Symbol::FB_common;
214 : if (Flags & object::BasicSymbolRef::SF_Indirect)
215 : Sym.Flags |= 1 << storage::Symbol::FB_indirect;
216 : if (Flags & object::BasicSymbolRef::SF_Global)
217 : Sym.Flags |= 1 << storage::Symbol::FB_global;
218 : if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
219 : Sym.Flags |= 1 << storage::Symbol::FB_format_specific;
220 : if (Flags & object::BasicSymbolRef::SF_Executable)
221 : Sym.Flags |= 1 << storage::Symbol::FB_executable;
222 20319 :
223 : Sym.ComdatIndex = -1;
224 : auto *GV = Msym.dyn_cast<GlobalValue *>();
225 : if (!GV) {
226 : // Undefined module asm symbols act as GC roots and are implicitly used.
227 20319 : if (Flags & object::BasicSymbolRef::SF_Undefined)
228 : Sym.Flags |= 1 << storage::Symbol::FB_used;
229 40638 : setStr(Sym.IRName, "");
230 : return Error::success();
231 20319 : }
232 20319 :
233 : setStr(Sym.IRName, GV->getName());
234 20319 :
235 : bool IsBuiltinFunc = false;
236 20319 :
237 : for (const char *LibcallName : LibcallRoutineNames)
238 20319 : if (GV->getName() == LibcallName)
239 : IsBuiltinFunc = true;
240 20319 :
241 : if (Used.count(GV) || IsBuiltinFunc)
242 20319 : Sym.Flags |= 1 << storage::Symbol::FB_used;
243 : if (GV->isThreadLocal())
244 20319 : Sym.Flags |= 1 << storage::Symbol::FB_tls;
245 : if (GV->hasGlobalUnnamedAddr())
246 : Sym.Flags |= 1 << storage::Symbol::FB_unnamed_addr;
247 : if (GV->canBeOmittedFromSymbolTable())
248 : Sym.Flags |= 1 << storage::Symbol::FB_may_omit;
249 20117 : Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
250 :
251 202 : if (Flags & object::BasicSymbolRef::SF_Common) {
252 : Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
253 202 : GV->getType()->getElementType());
254 : Uncommon().CommonAlign = GV->getAlignment();
255 : }
256 :
257 20117 : const GlobalObject *Base = GV->getBaseObject();
258 : if (!Base)
259 : return make_error<StringError>("Unable to determine comdat of alias!",
260 : inconvertibleErrorCode());
261 9495224 : if (const Comdat *C = Base->getComdat()) {
262 9475107 : Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
263 : if (!ComdatIndexOrErr)
264 : return ComdatIndexOrErr.takeError();
265 20117 : Sym.ComdatIndex = *ComdatIndexOrErr;
266 : }
267 20117 :
268 : if (TT.isOSBinFormatCOFF()) {
269 20117 : emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
270 :
271 20117 : if ((Flags & object::BasicSymbolRef::SF_Weak) &&
272 : (Flags & object::BasicSymbolRef::SF_Indirect)) {
273 : auto *Fallback = dyn_cast<GlobalValue>(
274 : cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
275 20117 : if (!Fallback)
276 100 : return make_error<StringError>("Invalid weak external",
277 : inconvertibleErrorCode());
278 100 : std::string FallbackName;
279 : raw_string_ostream OS(FallbackName);
280 : Msymtab.printSymbolName(OS, Fallback);
281 : OS.flush();
282 20117 : setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
283 : }
284 36 : }
285 20099 :
286 2697 : if (!Base->getSection().empty())
287 2697 : setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
288 :
289 2697 : return Error::success();
290 : }
291 :
292 20099 : Error Builder::build(ArrayRef<Module *> IRMods) {
293 221 : storage::Header Hdr;
294 :
295 221 : assert(!IRMods.empty());
296 : Hdr.Version = storage::Header::kCurrentVersion;
297 : setStr(Hdr.Producer, kExpectedProducerName);
298 : setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
299 : setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
300 : TT = Triple(IRMods[0]->getTargetTriple());
301 4 :
302 : for (auto *M : IRMods)
303 2 : if (Error Err = addModule(M))
304 2 : return Err;
305 :
306 2 : COFFLinkerOptsOS.flush();
307 : setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
308 :
309 : // We are about to fill in the header's range fields, so reserve space for it
310 20097 : // and copy it in afterwards.
311 1111 : Symtab.resize(sizeof(storage::Header));
312 : writeRange(Hdr.Modules, Mods);
313 : writeRange(Hdr.Comdats, Comdats);
314 : writeRange(Hdr.Symbols, Syms);
315 : writeRange(Hdr.Uncommons, Uncommons);
316 4671 :
317 : *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
318 : return Error::success();
319 : }
320 :
321 9342 : } // end anonymous namespace
322 9342 :
323 9342 : Error irsymtab::build(ArrayRef<Module *> Mods, SmallVector<char, 0> &Symtab,
324 9342 : StringTableBuilder &StrtabBuilder,
325 : BumpPtrAllocator &Alloc) {
326 7150 : return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
327 9378 : }
328 :
329 : // Upgrade a vector of bitcode modules created by an old version of LLVM by
330 2461 : // creating an irsymtab for them in the current format.
331 2461 : static Expected<FileContents> upgrade(ArrayRef<BitcodeModule> BMs) {
332 : FileContents FC;
333 :
334 : LLVMContext Ctx;
335 2461 : std::vector<Module *> Mods;
336 2461 : std::vector<std::unique_ptr<Module>> OwnedMods;
337 2461 : for (auto BM : BMs) {
338 2461 : Expected<std::unique_ptr<Module>> MOrErr =
339 2461 : BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
340 : /*IsImporting*/ false);
341 2461 : if (!MOrErr)
342 : return MOrErr.takeError();
343 :
344 : Mods.push_back(MOrErr->get());
345 : OwnedMods.push_back(std::move(*MOrErr));
346 : }
347 4671 :
348 : StringTableBuilder StrtabBuilder(StringTableBuilder::RAW);
349 : BumpPtrAllocator Alloc;
350 4671 : if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
351 : return std::move(E);
352 :
353 : StrtabBuilder.finalizeInOrder();
354 : FC.Strtab.resize(StrtabBuilder.getSize());
355 22 : StrtabBuilder.write((uint8_t *)FC.Strtab.data());
356 22 :
357 : FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
358 44 : {FC.Strtab.data(), FC.Strtab.size()}};
359 : return std::move(FC);
360 22 : }
361 46 :
362 : Expected<FileContents> irsymtab::readBitcode(const BitcodeFileContents &BFC) {
363 : if (BFC.Mods.empty())
364 48 : return make_error<StringError>("Bitcode file does not contain any modules",
365 24 : inconvertibleErrorCode());
366 :
367 : if (BFC.StrtabForSymtab.empty() ||
368 24 : BFC.Symtab.size() < sizeof(storage::Header))
369 : return upgrade(BFC.Mods);
370 :
371 : // We cannot use the regular reader to read the version and producer, because
372 44 : // it will expect the header to be in the current format. The only thing we
373 22 : // can rely on is that the version and producer will be present as the first
374 26 : // struct elements.
375 : auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
376 : unsigned Version = Hdr->Version;
377 18 : StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
378 18 : if (Version != storage::Header::kCurrentVersion ||
379 18 : Producer != kExpectedProducerName)
380 : return upgrade(BFC.Mods);
381 36 :
382 18 : FileContents FC;
383 : FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
384 : {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
385 :
386 912 : // Finally, make sure that the number of modules in the symbol table matches
387 912 : // the number of modules in the bitcode file. If they differ, it may mean that
388 1 : // the bitcode file was created by binary concatenation, so we need to create
389 2 : // a new symbol table from scratch.
390 : if (FC.TheReader.getNumModules() != BFC.Mods.size())
391 911 : return upgrade(std::move(BFC.Mods));
392 :
393 21 : return std::move(FC);
394 : }
|