e52a34601b091da1ec162e1b2af0c3c07d391e9e
[oota-llvm.git] / include / llvm / MC / MCSymbol.h
1 //===- MCSymbol.h - Machine Code Symbols ------------------------*- C++ -*-===//
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 // This file contains the declaration of the MCSymbol class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_MC_MCSYMBOL_H
15 #define LLVM_MC_MCSYMBOL_H
16
17 #include "llvm/ADT/PointerIntPair.h"
18 #include "llvm/ADT/PointerUnion.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/Support/Compiler.h"
22
23 namespace llvm {
24 class MCAsmInfo;
25 class MCExpr;
26 class MCSymbol;
27 class MCFragment;
28 class MCSection;
29 class MCContext;
30 class raw_ostream;
31
32 /// MCSymbol - Instances of this class represent a symbol name in the MC file,
33 /// and MCSymbols are created and uniqued by the MCContext class.  MCSymbols
34 /// should only be constructed with valid names for the object file.
35 ///
36 /// If the symbol is defined/emitted into the current translation unit, the
37 /// Section member is set to indicate what section it lives in.  Otherwise, if
38 /// it is a reference to an external entity, it has a null section.
39 class MCSymbol {
40 protected:
41   /// The kind of the symbol.  If it is any value other than unset then this
42   /// class is actually one of the appropriate subclasses of MCSymbol.
43   enum SymbolKind {
44     SymbolKindUnset,
45     SymbolKindCOFF,
46     SymbolKindELF,
47     SymbolKindMachO,
48   };
49
50   /// A symbol can contain an Offset, or Value, or be Common, but never more
51   /// than one of these.
52   enum Contents : uint8_t {
53     SymContentsUnset,
54     SymContentsOffset,
55     SymContentsVariable,
56     SymContentsCommon,
57   };
58
59   // Special sentinal value for the absolute pseudo section.
60   //
61   // FIXME: Use a PointerInt wrapper for this?
62   static MCSection *AbsolutePseudoSection;
63
64   /// If a symbol has a Fragment, the section is implied, so we only need
65   /// one pointer.
66   /// FIXME: We might be able to simplify this by having the asm streamer create
67   /// dummy fragments.
68   /// If this is a section, then it gives the symbol is defined in. This is null
69   /// for undefined symbols, and the special AbsolutePseudoSection value for
70   /// absolute symbols. If this is a variable symbol, this caches the variable
71   /// value's section.
72   ///
73   /// If this is a fragment, then it gives the fragment this symbol's value is
74   /// relative to, if any.
75   ///
76   /// For the 'HasName' integer, this is true if this symbol is named.
77   /// A named symbol will have a pointer to the name allocated in the bytes
78   /// immediately prior to the MCSymbol.
79   mutable PointerIntPair<PointerUnion<MCSection *, MCFragment *>, 1>
80       SectionOrFragmentAndHasName;
81
82   /// IsTemporary - True if this is an assembler temporary label, which
83   /// typically does not survive in the .o file's symbol table.  Usually
84   /// "Lfoo" or ".foo".
85   unsigned IsTemporary : 1;
86
87   /// \brief True if this symbol can be redefined.
88   unsigned IsRedefinable : 1;
89
90   /// IsUsed - True if this symbol has been used.
91   mutable unsigned IsUsed : 1;
92
93   mutable bool IsRegistered : 1;
94
95   /// This symbol is visible outside this translation unit.
96   mutable unsigned IsExternal : 1;
97
98   /// This symbol is private extern.
99   mutable unsigned IsPrivateExtern : 1;
100
101   /// LLVM RTTI discriminator. This is actually a SymbolKind enumerator, but is
102   /// unsigned to avoid sign extension and achieve better bitpacking with MSVC.
103   unsigned Kind : 2;
104
105   /// True if we have created a relocation that uses this symbol.
106   mutable unsigned IsUsedInReloc : 1;
107
108   /// This is actually a Contents enumerator, but is unsigned to avoid sign
109   /// extension and achieve better bitpacking with MSVC.
110   unsigned SymbolContents : 2;
111
112   /// The alignment of the symbol, if it is 'common', or -1.
113   ///
114   /// The alignment is stored as log2(align) + 1.  This allows all values from
115   /// 0 to 2^31 to be stored which is every power of 2 representable by an
116   /// unsigned.
117   static const unsigned NumCommonAlignmentBits = 5;
118   unsigned CommonAlignLog2 : NumCommonAlignmentBits;
119
120   /// Index field, for use by the object file implementation.
121   mutable uint32_t Index = 0;
122
123   union {
124     /// The offset to apply to the fragment address to form this symbol's value.
125     uint64_t Offset;
126
127     /// The size of the symbol, if it is 'common'.
128     uint64_t CommonSize;
129
130     /// If non-null, the value for a variable symbol.
131     const MCExpr *Value;
132   };
133
134   /// The Flags field is used by object file implementations to store
135   /// additional per symbol information which is not easily classified.
136   mutable uint32_t Flags = 0;
137
138 protected: // MCContext creates and uniques these.
139   friend class MCExpr;
140   friend class MCContext;
141
142   /// \brief The name for a symbol.
143   /// MCSymbol contains a uint64_t so is probably aligned to 8.  On a 32-bit
144   /// system, the name is a pointer so isn't going to satisfy the 8 byte
145   /// alignment of uint64_t.  Account for that here.
146   typedef union {
147     const StringMapEntry<bool> *NameEntry;
148     uint64_t AlignmentPadding;
149   } NameEntryStorageTy;
150
151   MCSymbol(SymbolKind Kind, const StringMapEntry<bool> *Name, bool isTemporary)
152       : IsTemporary(isTemporary), IsRedefinable(false), IsUsed(false),
153         IsRegistered(false), IsExternal(false), IsPrivateExtern(false),
154         Kind(Kind), IsUsedInReloc(false), SymbolContents(SymContentsUnset),
155         CommonAlignLog2(0) {
156     Offset = 0;
157     SectionOrFragmentAndHasName.setInt(!!Name);
158     if (Name)
159       getNameEntryPtr() = Name;
160   }
161
162   // Provide custom new/delete as we will only allocate space for a name
163   // if we need one.
164   void *operator new(size_t s, const StringMapEntry<bool> *Name,
165                      MCContext &Ctx);
166
167 private:
168
169   void operator delete(void *);
170   /// \brief Placement delete - required by std, but never called.
171   void operator delete(void*, unsigned) {
172     llvm_unreachable("Constructor throws?");
173   }
174   /// \brief Placement delete - required by std, but never called.
175   void operator delete(void*, unsigned, bool) {
176     llvm_unreachable("Constructor throws?");
177   }
178
179   MCSymbol(const MCSymbol &) = delete;
180   void operator=(const MCSymbol &) = delete;
181   MCSection *getSectionPtr() const {
182     if (MCFragment *F = getFragment())
183       return F->getParent();
184     const auto &SectionOrFragment = SectionOrFragmentAndHasName.getPointer();
185     assert(!SectionOrFragment.is<MCFragment *>() && "Section or null expected");
186     MCSection *Section = SectionOrFragment.dyn_cast<MCSection *>();
187     if (Section || !isVariable())
188       return Section;
189     return Section = getVariableValue()->findAssociatedSection();
190   }
191
192   /// \brief Get a reference to the name field.  Requires that we have a name
193   const StringMapEntry<bool> *&getNameEntryPtr() {
194     assert(SectionOrFragmentAndHasName.getInt() && "Name is required");
195     NameEntryStorageTy *Name = reinterpret_cast<NameEntryStorageTy *>(this);
196     return (*(Name - 1)).NameEntry;
197   }
198   const StringMapEntry<bool> *&getNameEntryPtr() const {
199     return const_cast<MCSymbol*>(this)->getNameEntryPtr();
200   }
201
202 public:
203   /// getName - Get the symbol name.
204   StringRef getName() const {
205     if (!SectionOrFragmentAndHasName.getInt())
206       return StringRef();
207
208     return getNameEntryPtr()->first();
209   }
210
211   bool isRegistered() const { return IsRegistered; }
212   void setIsRegistered(bool Value) const { IsRegistered = Value; }
213
214   void setUsedInReloc() const { IsUsedInReloc = true; }
215   bool isUsedInReloc() const { return IsUsedInReloc; }
216
217   /// \name Accessors
218   /// @{
219
220   /// isTemporary - Check if this is an assembler temporary symbol.
221   bool isTemporary() const { return IsTemporary; }
222
223   /// isUsed - Check if this is used.
224   bool isUsed() const { return IsUsed; }
225   void setUsed(bool Value) const { IsUsed = Value; }
226
227   /// \brief Check if this symbol is redefinable.
228   bool isRedefinable() const { return IsRedefinable; }
229   /// \brief Mark this symbol as redefinable.
230   void setRedefinable(bool Value) { IsRedefinable = Value; }
231   /// \brief Prepare this symbol to be redefined.
232   void redefineIfPossible() {
233     if (IsRedefinable) {
234       if (SymbolContents == SymContentsVariable) {
235         Value = nullptr;
236         SymbolContents = SymContentsUnset;
237       }
238       setUndefined();
239       IsRedefinable = false;
240     }
241   }
242
243   /// @}
244   /// \name Associated Sections
245   /// @{
246
247   /// isDefined - Check if this symbol is defined (i.e., it has an address).
248   ///
249   /// Defined symbols are either absolute or in some section.
250   bool isDefined() const { return getSectionPtr() != nullptr; }
251
252   /// isInSection - Check if this symbol is defined in some section (i.e., it
253   /// is defined but not absolute).
254   bool isInSection() const { return isDefined() && !isAbsolute(); }
255
256   /// isUndefined - Check if this symbol undefined (i.e., implicitly defined).
257   bool isUndefined() const { return !isDefined(); }
258
259   /// isAbsolute - Check if this is an absolute symbol.
260   bool isAbsolute() const { return getSectionPtr() == AbsolutePseudoSection; }
261
262   /// Get the section associated with a defined, non-absolute symbol.
263   MCSection &getSection() const {
264     assert(isInSection() && "Invalid accessor!");
265     return *getSectionPtr();
266   }
267
268   /// Mark the symbol as defined in the section \p S.
269   void setSection(MCSection &S) {
270     assert(!isVariable() && "Cannot set section of variable");
271     assert(!SectionOrFragmentAndHasName.getPointer().is<MCFragment *>() &&
272            "Section or null expected");
273     SectionOrFragmentAndHasName.setPointer(&S);
274   }
275
276   /// Mark the symbol as undefined.
277   void setUndefined() {
278     SectionOrFragmentAndHasName.setPointer(
279         PointerUnion<MCSection *, MCFragment *>());
280   }
281
282   bool isELF() const { return Kind == SymbolKindELF; }
283
284   bool isCOFF() const { return Kind == SymbolKindCOFF; }
285
286   bool isMachO() const { return Kind == SymbolKindMachO; }
287
288   /// @}
289   /// \name Variable Symbols
290   /// @{
291
292   /// isVariable - Check if this is a variable symbol.
293   bool isVariable() const {
294     return SymbolContents == SymContentsVariable;
295   }
296
297   /// getVariableValue() - Get the value for variable symbols.
298   const MCExpr *getVariableValue() const {
299     assert(isVariable() && "Invalid accessor!");
300     IsUsed = true;
301     return Value;
302   }
303
304   void setVariableValue(const MCExpr *Value);
305
306   /// @}
307
308   /// Get the (implementation defined) index.
309   uint32_t getIndex() const {
310     return Index;
311   }
312
313   /// Set the (implementation defined) index.
314   void setIndex(uint32_t Value) const {
315     Index = Value;
316   }
317
318   uint64_t getOffset() const {
319     assert((SymbolContents == SymContentsUnset ||
320             SymbolContents == SymContentsOffset) &&
321            "Cannot get offset for a common/variable symbol");
322     return Offset;
323   }
324   void setOffset(uint64_t Value) {
325     assert((SymbolContents == SymContentsUnset ||
326             SymbolContents == SymContentsOffset) &&
327            "Cannot set offset for a common/variable symbol");
328     Offset = Value;
329     SymbolContents = SymContentsOffset;
330   }
331
332   /// Return the size of a 'common' symbol.
333   uint64_t getCommonSize() const {
334     assert(isCommon() && "Not a 'common' symbol!");
335     return CommonSize;
336   }
337
338   /// Mark this symbol as being 'common'.
339   ///
340   /// \param Size - The size of the symbol.
341   /// \param Align - The alignment of the symbol.
342   void setCommon(uint64_t Size, unsigned Align) {
343     assert(getOffset() == 0);
344     CommonSize = Size;
345     SymbolContents = SymContentsCommon;
346
347     assert((!Align || isPowerOf2_32(Align)) &&
348            "Alignment must be a power of 2");
349     unsigned Log2Align = Log2_32(Align) + 1;
350     assert(Log2Align < (1U << NumCommonAlignmentBits) &&
351            "Out of range alignment");
352     CommonAlignLog2 = Log2Align;
353   }
354
355   ///  Return the alignment of a 'common' symbol.
356   unsigned getCommonAlignment() const {
357     assert(isCommon() && "Not a 'common' symbol!");
358     return CommonAlignLog2 ? (1U << (CommonAlignLog2 - 1)) : 0;
359   }
360
361   /// Declare this symbol as being 'common'.
362   ///
363   /// \param Size - The size of the symbol.
364   /// \param Align - The alignment of the symbol.
365   /// \return True if symbol was already declared as a different type
366   bool declareCommon(uint64_t Size, unsigned Align) {
367     assert(isCommon() || getOffset() == 0);
368     if(isCommon()) {
369       if(CommonSize != Size || getCommonAlignment() != Align)
370        return true;
371     } else
372       setCommon(Size, Align);
373     return false;
374   }
375
376   /// Is this a 'common' symbol.
377   bool isCommon() const {
378     return SymbolContents == SymContentsCommon;
379   }
380
381   MCFragment *getFragment() const {
382     return SectionOrFragmentAndHasName.getPointer().dyn_cast<MCFragment *>();
383   }
384   void setFragment(MCFragment *Value) const {
385     SectionOrFragmentAndHasName.setPointer(Value);
386   }
387
388   bool isExternal() const { return IsExternal; }
389   void setExternal(bool Value) const { IsExternal = Value; }
390
391   bool isPrivateExtern() const { return IsPrivateExtern; }
392   void setPrivateExtern(bool Value) { IsPrivateExtern = Value; }
393
394   /// print - Print the value to the stream \p OS.
395   void print(raw_ostream &OS, const MCAsmInfo *MAI) const;
396
397   /// dump - Print the value to stderr.
398   void dump() const;
399
400 protected:
401   /// Get the (implementation defined) symbol flags.
402   uint32_t getFlags() const { return Flags; }
403
404   /// Set the (implementation defined) symbol flags.
405   void setFlags(uint32_t Value) const { Flags = Value; }
406
407   /// Modify the flags via a mask
408   void modifyFlags(uint32_t Value, uint32_t Mask) const {
409     Flags = (Flags & ~Mask) | Value;
410   }
411 };
412
413 inline raw_ostream &operator<<(raw_ostream &OS, const MCSymbol &Sym) {
414   Sym.print(OS, nullptr);
415   return OS;
416 }
417 } // end namespace llvm
418
419 #endif