Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lld / ELF / Symbols.h
blob4addb79d1257914aea759be7bd9025c56e14fe14
1 //===- Symbols.h ------------------------------------------------*- C++ -*-===//
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 // This file defines various types of Symbols.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLD_ELF_SYMBOLS_H
14 #define LLD_ELF_SYMBOLS_H
16 #include "Config.h"
17 #include "lld/Common/LLVM.h"
18 #include "lld/Common/Memory.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/Object/ELF.h"
21 #include "llvm/Support/Compiler.h"
22 #include <tuple>
24 namespace lld {
25 namespace elf {
26 class Symbol;
28 // Returns a string representation for a symbol for diagnostics.
29 std::string toString(const elf::Symbol &);
31 namespace elf {
32 class CommonSymbol;
33 class Defined;
34 class OutputSection;
35 class SectionBase;
36 class InputSectionBase;
37 class SharedSymbol;
38 class Symbol;
39 class Undefined;
40 class LazyObject;
41 class InputFile;
43 void printTraceSymbol(const Symbol &sym, StringRef name);
45 enum {
46 NEEDS_GOT = 1 << 0,
47 NEEDS_PLT = 1 << 1,
48 HAS_DIRECT_RELOC = 1 << 2,
49 // True if this symbol needs a canonical PLT entry, or (during
50 // postScanRelocations) a copy relocation.
51 NEEDS_COPY = 1 << 3,
52 NEEDS_TLSDESC = 1 << 4,
53 NEEDS_TLSGD = 1 << 5,
54 NEEDS_TLSGD_TO_IE = 1 << 6,
55 NEEDS_GOT_DTPREL = 1 << 7,
56 NEEDS_TLSIE = 1 << 8,
59 // Some index properties of a symbol are stored separately in this auxiliary
60 // struct to decrease sizeof(SymbolUnion) in the majority of cases.
61 struct SymbolAux {
62 uint32_t gotIdx = -1;
63 uint32_t pltIdx = -1;
64 uint32_t tlsDescIdx = -1;
65 uint32_t tlsGdIdx = -1;
68 LLVM_LIBRARY_VISIBILITY extern SmallVector<SymbolAux, 0> symAux;
70 // The base class for real symbol classes.
71 class Symbol {
72 public:
73 enum Kind {
74 PlaceholderKind,
75 DefinedKind,
76 CommonKind,
77 SharedKind,
78 UndefinedKind,
79 LazyObjectKind,
82 Kind kind() const { return static_cast<Kind>(symbolKind); }
84 // The file from which this symbol was created.
85 InputFile *file;
87 // The default copy constructor is deleted due to atomic flags. Define one for
88 // places where no atomic is needed.
89 Symbol(const Symbol &o) { memcpy(this, &o, sizeof(o)); }
91 protected:
92 const char *nameData;
93 // 32-bit size saves space.
94 uint32_t nameSize;
96 public:
97 // The next three fields have the same meaning as the ELF symbol attributes.
98 // type and binding are placed in this order to optimize generating st_info,
99 // which is defined as (binding << 4) + (type & 0xf), on a little-endian
100 // system.
101 uint8_t type : 4; // symbol type
103 // Symbol binding. This is not overwritten by replace() to track
104 // changes during resolution. In particular:
105 // - An undefined weak is still weak when it resolves to a shared library.
106 // - An undefined weak will not extract archive members, but we have to
107 // remember it is weak.
108 uint8_t binding : 4;
110 uint8_t stOther; // st_other field value
112 uint8_t symbolKind;
114 // The partition whose dynamic symbol table contains this symbol's definition.
115 uint8_t partition;
117 // True if this symbol is preemptible at load time.
118 uint8_t isPreemptible : 1;
120 // True if the symbol was used for linking and thus need to be added to the
121 // output file's symbol table. This is true for all symbols except for
122 // unreferenced DSO symbols, lazy (archive) symbols, and bitcode symbols that
123 // are unreferenced except by other bitcode objects.
124 uint8_t isUsedInRegularObj : 1;
126 // True if an undefined or shared symbol is used from a live section.
128 // NOTE: In Writer.cpp the field is used to mark local defined symbols
129 // which are referenced by relocations when -r or --emit-relocs is given.
130 uint8_t used : 1;
132 // Used by a Defined symbol with protected or default visibility, to record
133 // whether it is required to be exported into .dynsym. This is set when any of
134 // the following conditions hold:
136 // - If there is an interposable symbol from a DSO. Note: We also do this for
137 // STV_PROTECTED symbols which can't be interposed (to match BFD behavior).
138 // - If -shared or --export-dynamic is specified, any symbol in an object
139 // file/bitcode sets this property, unless suppressed by LTO
140 // canBeOmittedFromSymbolTable().
141 uint8_t exportDynamic : 1;
143 // True if the symbol is in the --dynamic-list file. A Defined symbol with
144 // protected or default visibility with this property is required to be
145 // exported into .dynsym.
146 uint8_t inDynamicList : 1;
148 // Used to track if there has been at least one undefined reference to the
149 // symbol. For Undefined and SharedSymbol, the binding may change to STB_WEAK
150 // if the first undefined reference from a non-shared object is weak.
151 uint8_t referenced : 1;
153 // Used to track if this symbol will be referenced after wrapping is performed
154 // (i.e. this will be true for foo if __real_foo is referenced, and will be
155 // true for __wrap_foo if foo is referenced).
156 uint8_t referencedAfterWrap : 1;
158 // True if this symbol is specified by --trace-symbol option.
159 uint8_t traced : 1;
161 // True if the name contains '@'.
162 uint8_t hasVersionSuffix : 1;
164 // Symbol visibility. This is the computed minimum visibility of all
165 // observed non-DSO symbols.
166 uint8_t visibility() const { return stOther & 3; }
167 void setVisibility(uint8_t visibility) {
168 stOther = (stOther & ~3) | visibility;
171 bool includeInDynsym() const;
172 uint8_t computeBinding() const;
173 bool isGlobal() const { return binding == llvm::ELF::STB_GLOBAL; }
174 bool isWeak() const { return binding == llvm::ELF::STB_WEAK; }
176 bool isUndefined() const { return symbolKind == UndefinedKind; }
177 bool isCommon() const { return symbolKind == CommonKind; }
178 bool isDefined() const { return symbolKind == DefinedKind; }
179 bool isShared() const { return symbolKind == SharedKind; }
180 bool isPlaceholder() const { return symbolKind == PlaceholderKind; }
182 bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; }
184 bool isLazy() const { return symbolKind == LazyObjectKind; }
186 // True if this is an undefined weak symbol. This only works once
187 // all input files have been added.
188 bool isUndefWeak() const { return isWeak() && isUndefined(); }
190 StringRef getName() const { return {nameData, nameSize}; }
192 void setName(StringRef s) {
193 nameData = s.data();
194 nameSize = s.size();
197 void parseSymbolVersion();
199 // Get the NUL-terminated version suffix ("", "@...", or "@@...").
201 // For @@, the name has been truncated by insert(). For @, the name has been
202 // truncated by Symbol::parseSymbolVersion().
203 const char *getVersionSuffix() const { return nameData + nameSize; }
205 uint32_t getGotIdx() const { return symAux[auxIdx].gotIdx; }
206 uint32_t getPltIdx() const { return symAux[auxIdx].pltIdx; }
207 uint32_t getTlsDescIdx() const { return symAux[auxIdx].tlsDescIdx; }
208 uint32_t getTlsGdIdx() const { return symAux[auxIdx].tlsGdIdx; }
210 bool isInGot() const { return getGotIdx() != uint32_t(-1); }
211 bool isInPlt() const { return getPltIdx() != uint32_t(-1); }
213 uint64_t getVA(int64_t addend = 0) const;
215 uint64_t getGotOffset() const;
216 uint64_t getGotVA() const;
217 uint64_t getGotPltOffset() const;
218 uint64_t getGotPltVA() const;
219 uint64_t getPltVA() const;
220 uint64_t getSize() const;
221 OutputSection *getOutputSection() const;
223 // The following two functions are used for symbol resolution.
225 // You are expected to call mergeProperties for all symbols in input
226 // files so that attributes that are attached to names rather than
227 // indivisual symbol (such as visibility) are merged together.
229 // Every time you read a new symbol from an input, you are supposed
230 // to call resolve() with the new symbol. That function replaces
231 // "this" object as a result of name resolution if the new symbol is
232 // more appropriate to be included in the output.
234 // For example, if "this" is an undefined symbol and a new symbol is
235 // a defined symbol, "this" is replaced with the new symbol.
236 void mergeProperties(const Symbol &other);
237 void resolve(const Undefined &other);
238 void resolve(const CommonSymbol &other);
239 void resolve(const Defined &other);
240 void resolve(const LazyObject &other);
241 void resolve(const SharedSymbol &other);
243 // If this is a lazy symbol, extract an input file and add the symbol
244 // in the file to the symbol table. Calling this function on
245 // non-lazy object causes a runtime error.
246 void extract() const;
248 void checkDuplicate(const Defined &other) const;
250 private:
251 bool shouldReplace(const Defined &other) const;
253 protected:
254 Symbol(Kind k, InputFile *file, StringRef name, uint8_t binding,
255 uint8_t stOther, uint8_t type)
256 : file(file), nameData(name.data()), nameSize(name.size()), type(type),
257 binding(binding), stOther(stOther), symbolKind(k), exportDynamic(false),
258 archSpecificBit(false) {}
260 void overwrite(Symbol &sym, Kind k) const {
261 if (sym.traced)
262 printTraceSymbol(*this, sym.getName());
263 sym.file = file;
264 sym.type = type;
265 sym.binding = binding;
266 sym.stOther = (stOther & ~3) | sym.visibility();
267 sym.symbolKind = k;
270 public:
271 // True if this symbol is in the Iplt sub-section of the Plt and the Igot
272 // sub-section of the .got.plt or .got.
273 uint8_t isInIplt : 1;
275 // True if this symbol needs a GOT entry and its GOT entry is actually in
276 // Igot. This will be true only for certain non-preemptible ifuncs.
277 uint8_t gotInIgot : 1;
279 // True if defined relative to a section discarded by ICF.
280 uint8_t folded : 1;
282 // Allow reuse of a bit between architecture-exclusive symbol flags.
283 // - needsTocRestore(): On PPC64, true if a call to this symbol needs to be
284 // followed by a restore of the toc pointer.
285 // - isTagged(): On AArch64, true if the symbol needs special relocation and
286 // metadata semantics because it's tagged, under the AArch64 MemtagABI.
287 uint8_t archSpecificBit : 1;
288 bool needsTocRestore() const { return archSpecificBit; }
289 bool isTagged() const { return archSpecificBit; }
290 void setNeedsTocRestore(bool v) { archSpecificBit = v; }
291 void setIsTagged(bool v) {
292 archSpecificBit = v;
295 // True if this symbol is defined by a symbol assignment or wrapped by --wrap.
297 // LTO shouldn't inline the symbol because it doesn't know the final content
298 // of the symbol.
299 uint8_t scriptDefined : 1;
301 // True if defined in a DSO as protected visibility.
302 uint8_t dsoProtected : 1;
304 // True if targeted by a range extension thunk.
305 uint8_t thunkAccessed : 1;
307 // Temporary flags used to communicate which symbol entries need PLT and GOT
308 // entries during postScanRelocations();
309 std::atomic<uint16_t> flags;
311 // A symAux index used to access GOT/PLT entry indexes. This is allocated in
312 // postScanRelocations().
313 uint32_t auxIdx;
314 uint32_t dynsymIndex;
316 // This field is a index to the symbol's version definition.
317 uint16_t verdefIndex;
319 // Version definition index.
320 uint16_t versionId;
322 void setFlags(uint16_t bits) {
323 flags.fetch_or(bits, std::memory_order_relaxed);
325 bool hasFlag(uint16_t bit) const {
326 assert(bit && (bit & (bit - 1)) == 0 && "bit must be a power of 2");
327 return flags.load(std::memory_order_relaxed) & bit;
330 bool needsDynReloc() const {
331 return flags.load(std::memory_order_relaxed) &
332 (NEEDS_COPY | NEEDS_GOT | NEEDS_PLT | NEEDS_TLSDESC | NEEDS_TLSGD |
333 NEEDS_TLSGD_TO_IE | NEEDS_GOT_DTPREL | NEEDS_TLSIE);
335 void allocateAux() {
336 assert(auxIdx == 0);
337 auxIdx = symAux.size();
338 symAux.emplace_back();
341 bool isSection() const { return type == llvm::ELF::STT_SECTION; }
342 bool isTls() const { return type == llvm::ELF::STT_TLS; }
343 bool isFunc() const { return type == llvm::ELF::STT_FUNC; }
344 bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }
345 bool isObject() const { return type == llvm::ELF::STT_OBJECT; }
346 bool isFile() const { return type == llvm::ELF::STT_FILE; }
349 // Represents a symbol that is defined in the current output file.
350 class Defined : public Symbol {
351 public:
352 Defined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,
353 uint8_t type, uint64_t value, uint64_t size, SectionBase *section)
354 : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),
355 size(size), section(section) {
356 exportDynamic = config->exportDynamic;
358 void overwrite(Symbol &sym) const {
359 Symbol::overwrite(sym, DefinedKind);
360 sym.verdefIndex = -1;
361 auto &s = static_cast<Defined &>(sym);
362 s.value = value;
363 s.size = size;
364 s.section = section;
367 static bool classof(const Symbol *s) { return s->isDefined(); }
369 uint64_t value;
370 uint64_t size;
371 SectionBase *section;
374 // Represents a common symbol.
376 // On Unix, it is traditionally allowed to write variable definitions
377 // without initialization expressions (such as "int foo;") to header
378 // files. Such definition is called "tentative definition".
380 // Using tentative definition is usually considered a bad practice
381 // because you should write only declarations (such as "extern int
382 // foo;") to header files. Nevertheless, the linker and the compiler
383 // have to do something to support bad code by allowing duplicate
384 // definitions for this particular case.
386 // Common symbols represent variable definitions without initializations.
387 // The compiler creates common symbols when it sees variable definitions
388 // without initialization (you can suppress this behavior and let the
389 // compiler create a regular defined symbol by -fno-common).
391 // The linker allows common symbols to be replaced by regular defined
392 // symbols. If there are remaining common symbols after name resolution is
393 // complete, they are converted to regular defined symbols in a .bss
394 // section. (Therefore, the later passes don't see any CommonSymbols.)
395 class CommonSymbol : public Symbol {
396 public:
397 CommonSymbol(InputFile *file, StringRef name, uint8_t binding,
398 uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)
399 : Symbol(CommonKind, file, name, binding, stOther, type),
400 alignment(alignment), size(size) {
401 exportDynamic = config->exportDynamic;
403 void overwrite(Symbol &sym) const {
404 Symbol::overwrite(sym, CommonKind);
405 auto &s = static_cast<CommonSymbol &>(sym);
406 s.alignment = alignment;
407 s.size = size;
410 static bool classof(const Symbol *s) { return s->isCommon(); }
412 uint32_t alignment;
413 uint64_t size;
416 class Undefined : public Symbol {
417 public:
418 Undefined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,
419 uint8_t type, uint32_t discardedSecIdx = 0)
420 : Symbol(UndefinedKind, file, name, binding, stOther, type),
421 discardedSecIdx(discardedSecIdx) {}
422 void overwrite(Symbol &sym) const {
423 Symbol::overwrite(sym, UndefinedKind);
424 auto &s = static_cast<Undefined &>(sym);
425 s.discardedSecIdx = discardedSecIdx;
426 s.nonPrevailing = nonPrevailing;
429 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
431 // The section index if in a discarded section, 0 otherwise.
432 uint32_t discardedSecIdx;
433 bool nonPrevailing = false;
436 class SharedSymbol : public Symbol {
437 public:
438 static bool classof(const Symbol *s) { return s->kind() == SharedKind; }
440 SharedSymbol(InputFile &file, StringRef name, uint8_t binding,
441 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
442 uint32_t alignment)
443 : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),
444 size(size), alignment(alignment) {
445 exportDynamic = true;
446 dsoProtected = visibility() == llvm::ELF::STV_PROTECTED;
447 // GNU ifunc is a mechanism to allow user-supplied functions to
448 // resolve PLT slot values at load-time. This is contrary to the
449 // regular symbol resolution scheme in which symbols are resolved just
450 // by name. Using this hook, you can program how symbols are solved
451 // for you program. For example, you can make "memcpy" to be resolved
452 // to a SSE-enabled version of memcpy only when a machine running the
453 // program supports the SSE instruction set.
455 // Naturally, such symbols should always be called through their PLT
456 // slots. What GNU ifunc symbols point to are resolver functions, and
457 // calling them directly doesn't make sense (unless you are writing a
458 // loader).
460 // For DSO symbols, we always call them through PLT slots anyway.
461 // So there's no difference between GNU ifunc and regular function
462 // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
463 if (this->type == llvm::ELF::STT_GNU_IFUNC)
464 this->type = llvm::ELF::STT_FUNC;
466 void overwrite(Symbol &sym) const {
467 Symbol::overwrite(sym, SharedKind);
468 auto &s = static_cast<SharedSymbol &>(sym);
469 s.dsoProtected = dsoProtected;
470 s.value = value;
471 s.size = size;
472 s.alignment = alignment;
475 uint64_t value; // st_value
476 uint64_t size; // st_size
477 uint32_t alignment;
480 // LazyObject symbols represent symbols in object files between --start-lib and
481 // --end-lib options. LLD also handles traditional archives as if all the files
482 // in the archive are surrounded by --start-lib and --end-lib.
484 // A special complication is the handling of weak undefined symbols. They should
485 // not load a file, but we have to remember we have seen both the weak undefined
486 // and the lazy. We represent that with a lazy symbol with a weak binding. This
487 // means that code looking for undefined symbols normally also has to take lazy
488 // symbols into consideration.
489 class LazyObject : public Symbol {
490 public:
491 LazyObject(InputFile &file)
492 : Symbol(LazyObjectKind, &file, {}, llvm::ELF::STB_GLOBAL,
493 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}
494 void overwrite(Symbol &sym) const { Symbol::overwrite(sym, LazyObjectKind); }
496 static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
499 // Some linker-generated symbols need to be created as
500 // Defined symbols.
501 struct ElfSym {
502 // __bss_start
503 static Defined *bss;
505 // etext and _etext
506 static Defined *etext1;
507 static Defined *etext2;
509 // edata and _edata
510 static Defined *edata1;
511 static Defined *edata2;
513 // end and _end
514 static Defined *end1;
515 static Defined *end2;
517 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
518 // be at some offset from the base of the .got section, usually 0 or
519 // the end of the .got.
520 static Defined *globalOffsetTable;
522 // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS.
523 static Defined *mipsGp;
524 static Defined *mipsGpDisp;
525 static Defined *mipsLocalGp;
527 // __global_pointer$ for RISC-V.
528 static Defined *riscvGlobalPointer;
530 // __rel{,a}_iplt_{start,end} symbols.
531 static Defined *relaIpltStart;
532 static Defined *relaIpltEnd;
534 // _TLS_MODULE_BASE_ on targets that support TLSDESC.
535 static Defined *tlsModuleBase;
538 // A buffer class that is large enough to hold any Symbol-derived
539 // object. We allocate memory using this class and instantiate a symbol
540 // using the placement new.
542 // It is important to keep the size of SymbolUnion small for performance and
543 // memory usage reasons. 64 bytes is a soft limit based on the size of Defined
544 // on a 64-bit system. This is enforced by a static_assert in Symbols.cpp.
545 union SymbolUnion {
546 alignas(Defined) char a[sizeof(Defined)];
547 alignas(CommonSymbol) char b[sizeof(CommonSymbol)];
548 alignas(Undefined) char c[sizeof(Undefined)];
549 alignas(SharedSymbol) char d[sizeof(SharedSymbol)];
550 alignas(LazyObject) char e[sizeof(LazyObject)];
553 template <typename... T> Defined *makeDefined(T &&...args) {
554 auto *sym = getSpecificAllocSingleton<SymbolUnion>().Allocate();
555 memset(sym, 0, sizeof(Symbol));
556 auto &s = *new (reinterpret_cast<Defined *>(sym)) Defined(std::forward<T>(args)...);
557 return &s;
560 void reportDuplicate(const Symbol &sym, const InputFile *newFile,
561 InputSectionBase *errSec, uint64_t errOffset);
562 void maybeWarnUnorderableSymbol(const Symbol *sym);
563 bool computeIsPreemptible(const Symbol &sym);
565 } // namespace elf
566 } // namespace lld
568 #endif