]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/GlobalValue.h
Merge compiler-rt trunk r321414 to contrib/compiler-rt.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / IR / GlobalValue.h
1 //===-- llvm/GlobalValue.h - Class to represent a global value --*- 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 is a common base class of all globally definable objects.  As such,
11 // it is subclassed by GlobalVariable, GlobalAlias and by Function.  This is
12 // used because you can do certain things with these global objects that you
13 // can't do to anything else.  For example, use the address of one as a
14 // constant.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #ifndef LLVM_IR_GLOBALVALUE_H
19 #define LLVM_IR_GLOBALVALUE_H
20
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MD5.h"
29 #include <cassert>
30 #include <cstdint>
31 #include <string>
32
33 namespace llvm {
34
35 class Comdat;
36 class ConstantRange;
37 class Error;
38 class GlobalObject;
39 class Module;
40
41 namespace Intrinsic {
42   enum ID : unsigned;
43 } // end namespace Intrinsic
44
45 class GlobalValue : public Constant {
46 public:
47   /// @brief An enumeration for the kinds of linkage for global values.
48   enum LinkageTypes {
49     ExternalLinkage = 0,///< Externally visible function
50     AvailableExternallyLinkage, ///< Available for inspection, not emission.
51     LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
52     LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
53     WeakAnyLinkage,     ///< Keep one copy of named function when linking (weak)
54     WeakODRLinkage,     ///< Same, but only replaced by something equivalent.
55     AppendingLinkage,   ///< Special purpose, only applies to global arrays
56     InternalLinkage,    ///< Rename collisions when linking (static functions).
57     PrivateLinkage,     ///< Like Internal, but omit from symbol table.
58     ExternalWeakLinkage,///< ExternalWeak linkage description.
59     CommonLinkage       ///< Tentative definitions.
60   };
61
62   /// @brief An enumeration for the kinds of visibility of global values.
63   enum VisibilityTypes {
64     DefaultVisibility = 0,  ///< The GV is visible
65     HiddenVisibility,       ///< The GV is hidden
66     ProtectedVisibility     ///< The GV is protected
67   };
68
69   /// @brief Storage classes of global values for PE targets.
70   enum DLLStorageClassTypes {
71     DefaultStorageClass   = 0,
72     DLLImportStorageClass = 1, ///< Function to be imported from DLL
73     DLLExportStorageClass = 2  ///< Function to be accessible from DLL.
74   };
75
76 protected:
77   GlobalValue(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
78               LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace)
79       : Constant(PointerType::get(Ty, AddressSpace), VTy, Ops, NumOps),
80         ValueType(Ty), Linkage(Linkage), Visibility(DefaultVisibility),
81         UnnamedAddrVal(unsigned(UnnamedAddr::None)),
82         DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal),
83         HasLLVMReservedName(false), IsDSOLocal(false),
84         IntID((Intrinsic::ID)0U), Parent(nullptr) {
85     setName(Name);
86   }
87
88   Type *ValueType;
89
90   static const unsigned GlobalValueSubClassDataBits = 17;
91
92   // All bitfields use unsigned as the underlying type so that MSVC will pack
93   // them.
94   unsigned Linkage : 4;       // The linkage of this global
95   unsigned Visibility : 2;    // The visibility style of this global
96   unsigned UnnamedAddrVal : 2; // This value's address is not significant
97   unsigned DllStorageClass : 2; // DLL storage class
98
99   unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
100                             // the desired model?
101
102   /// True if the function's name starts with "llvm.".  This corresponds to the
103   /// value of Function::isIntrinsic(), which may be true even if
104   /// Function::intrinsicID() returns Intrinsic::not_intrinsic.
105   unsigned HasLLVMReservedName : 1;
106
107   /// If true then there is a definition within the same linkage unit and that
108   /// definition cannot be runtime preempted.
109   unsigned IsDSOLocal : 1;
110
111 private:
112   friend class Constant;
113
114   // Give subclasses access to what otherwise would be wasted padding.
115   // (17 + 4 + 2 + 2 + 2 + 3 + 1 + 1) == 32.
116   unsigned SubClassData : GlobalValueSubClassDataBits;
117
118   void destroyConstantImpl();
119   Value *handleOperandChangeImpl(Value *From, Value *To);
120
121   /// Returns true if the definition of this global may be replaced by a
122   /// differently optimized variant of the same source level function at link
123   /// time.
124   bool mayBeDerefined() const {
125     switch (getLinkage()) {
126     case WeakODRLinkage:
127     case LinkOnceODRLinkage:
128     case AvailableExternallyLinkage:
129       return true;
130
131     case WeakAnyLinkage:
132     case LinkOnceAnyLinkage:
133     case CommonLinkage:
134     case ExternalWeakLinkage:
135     case ExternalLinkage:
136     case AppendingLinkage:
137     case InternalLinkage:
138     case PrivateLinkage:
139       return isInterposable();
140     }
141
142     llvm_unreachable("Fully covered switch above!");
143   }
144
145 protected:
146   /// \brief The intrinsic ID for this subclass (which must be a Function).
147   ///
148   /// This member is defined by this class, but not used for anything.
149   /// Subclasses can use it to store their intrinsic ID, if they have one.
150   ///
151   /// This is stored here to save space in Function on 64-bit hosts.
152   Intrinsic::ID IntID;
153
154   unsigned getGlobalValueSubClassData() const {
155     return SubClassData;
156   }
157   void setGlobalValueSubClassData(unsigned V) {
158     assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
159     SubClassData = V;
160   }
161
162   Module *Parent;             // The containing module.
163
164   // Used by SymbolTableListTraits.
165   void setParent(Module *parent) {
166     Parent = parent;
167   }
168
169   ~GlobalValue() {
170     removeDeadConstantUsers();   // remove any dead constants using this.
171   }
172
173 public:
174   enum ThreadLocalMode {
175     NotThreadLocal = 0,
176     GeneralDynamicTLSModel,
177     LocalDynamicTLSModel,
178     InitialExecTLSModel,
179     LocalExecTLSModel
180   };
181
182   GlobalValue(const GlobalValue &) = delete;
183
184   unsigned getAlignment() const;
185
186   enum class UnnamedAddr {
187     None,
188     Local,
189     Global,
190   };
191
192   bool hasGlobalUnnamedAddr() const {
193     return getUnnamedAddr() == UnnamedAddr::Global;
194   }
195
196   /// Returns true if this value's address is not significant in this module.
197   /// This attribute is intended to be used only by the code generator and LTO
198   /// to allow the linker to decide whether the global needs to be in the symbol
199   /// table. It should probably not be used in optimizations, as the value may
200   /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
201   bool hasAtLeastLocalUnnamedAddr() const {
202     return getUnnamedAddr() != UnnamedAddr::None;
203   }
204
205   UnnamedAddr getUnnamedAddr() const {
206     return UnnamedAddr(UnnamedAddrVal);
207   }
208   void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
209
210   static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
211     if (A == UnnamedAddr::None || B == UnnamedAddr::None)
212       return UnnamedAddr::None;
213     if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
214       return UnnamedAddr::Local;
215     return UnnamedAddr::Global;
216   }
217
218   bool hasComdat() const { return getComdat() != nullptr; }
219   const Comdat *getComdat() const;
220   Comdat *getComdat() {
221     return const_cast<Comdat *>(
222                            static_cast<const GlobalValue *>(this)->getComdat());
223   }
224
225   VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
226   bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
227   bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
228   bool hasProtectedVisibility() const {
229     return Visibility == ProtectedVisibility;
230   }
231   void setVisibility(VisibilityTypes V) {
232     assert((!hasLocalLinkage() || V == DefaultVisibility) &&
233            "local linkage requires default visibility");
234     Visibility = V;
235   }
236
237   /// If the value is "Thread Local", its value isn't shared by the threads.
238   bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
239   void setThreadLocal(bool Val) {
240     setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
241   }
242   void setThreadLocalMode(ThreadLocalMode Val) {
243     assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
244     ThreadLocal = Val;
245   }
246   ThreadLocalMode getThreadLocalMode() const {
247     return static_cast<ThreadLocalMode>(ThreadLocal);
248   }
249
250   DLLStorageClassTypes getDLLStorageClass() const {
251     return DLLStorageClassTypes(DllStorageClass);
252   }
253   bool hasDLLImportStorageClass() const {
254     return DllStorageClass == DLLImportStorageClass;
255   }
256   bool hasDLLExportStorageClass() const {
257     return DllStorageClass == DLLExportStorageClass;
258   }
259   void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
260
261   bool hasSection() const { return !getSection().empty(); }
262   StringRef getSection() const;
263
264   /// Global values are always pointers.
265   PointerType *getType() const { return cast<PointerType>(User::getType()); }
266
267   Type *getValueType() const { return ValueType; }
268
269   void setDSOLocal(bool Local) { IsDSOLocal = Local; }
270
271   bool isDSOLocal() const {
272     return IsDSOLocal;
273   }
274
275   static LinkageTypes getLinkOnceLinkage(bool ODR) {
276     return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
277   }
278   static LinkageTypes getWeakLinkage(bool ODR) {
279     return ODR ? WeakODRLinkage : WeakAnyLinkage;
280   }
281
282   static bool isExternalLinkage(LinkageTypes Linkage) {
283     return Linkage == ExternalLinkage;
284   }
285   static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
286     return Linkage == AvailableExternallyLinkage;
287   }
288   static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
289     return Linkage == LinkOnceODRLinkage;
290   }
291   static bool isLinkOnceLinkage(LinkageTypes Linkage) {
292     return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage;
293   }
294   static bool isWeakAnyLinkage(LinkageTypes Linkage) {
295     return Linkage == WeakAnyLinkage;
296   }
297   static bool isWeakODRLinkage(LinkageTypes Linkage) {
298     return Linkage == WeakODRLinkage;
299   }
300   static bool isWeakLinkage(LinkageTypes Linkage) {
301     return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
302   }
303   static bool isAppendingLinkage(LinkageTypes Linkage) {
304     return Linkage == AppendingLinkage;
305   }
306   static bool isInternalLinkage(LinkageTypes Linkage) {
307     return Linkage == InternalLinkage;
308   }
309   static bool isPrivateLinkage(LinkageTypes Linkage) {
310     return Linkage == PrivateLinkage;
311   }
312   static bool isLocalLinkage(LinkageTypes Linkage) {
313     return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
314   }
315   static bool isExternalWeakLinkage(LinkageTypes Linkage) {
316     return Linkage == ExternalWeakLinkage;
317   }
318   static bool isCommonLinkage(LinkageTypes Linkage) {
319     return Linkage == CommonLinkage;
320   }
321   static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
322     return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
323   }
324
325   /// Whether the definition of this global may be replaced by something
326   /// non-equivalent at link time. For example, if a function has weak linkage
327   /// then the code defining it may be replaced by different code.
328   static bool isInterposableLinkage(LinkageTypes Linkage) {
329     switch (Linkage) {
330     case WeakAnyLinkage:
331     case LinkOnceAnyLinkage:
332     case CommonLinkage:
333     case ExternalWeakLinkage:
334       return true;
335
336     case AvailableExternallyLinkage:
337     case LinkOnceODRLinkage:
338     case WeakODRLinkage:
339     // The above three cannot be overridden but can be de-refined.
340
341     case ExternalLinkage:
342     case AppendingLinkage:
343     case InternalLinkage:
344     case PrivateLinkage:
345       return false;
346     }
347     llvm_unreachable("Fully covered switch above!");
348   }
349
350   /// Whether the definition of this global may be discarded if it is not used
351   /// in its compilation unit.
352   static bool isDiscardableIfUnused(LinkageTypes Linkage) {
353     return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
354            isAvailableExternallyLinkage(Linkage);
355   }
356
357   /// Whether the definition of this global may be replaced at link time.  NB:
358   /// Using this method outside of the code generators is almost always a
359   /// mistake: when working at the IR level use isInterposable instead as it
360   /// knows about ODR semantics.
361   static bool isWeakForLinker(LinkageTypes Linkage)  {
362     return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
363            Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
364            Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
365   }
366
367   /// Return true if the currently visible definition of this global (if any) is
368   /// exactly the definition we will see at runtime.
369   ///
370   /// Non-exact linkage types inhibits most non-inlining IPO, since a
371   /// differently optimized variant of the same function can have different
372   /// observable or undefined behavior than in the variant currently visible.
373   /// For instance, we could have started with
374   ///
375   ///   void foo(int *v) {
376   ///     int t = 5 / v[0];
377   ///     (void) t;
378   ///   }
379   ///
380   /// and "refined" it to
381   ///
382   ///   void foo(int *v) { }
383   ///
384   /// However, we cannot infer readnone for `foo`, since that would justify
385   /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
386   /// undefined behavior if the linker replaces the actual call destination with
387   /// the unoptimized `foo`.
388   ///
389   /// Inlining is okay across non-exact linkage types as long as they're not
390   /// interposable (see \c isInterposable), since in such cases the currently
391   /// visible variant is *a* correct implementation of the original source
392   /// function; it just isn't the *only* correct implementation.
393   bool isDefinitionExact() const {
394     return !mayBeDerefined();
395   }
396
397   /// Return true if this global has an exact defintion.
398   bool hasExactDefinition() const {
399     // While this computes exactly the same thing as
400     // isStrongDefinitionForLinker, the intended uses are different.  This
401     // function is intended to help decide if specific inter-procedural
402     // transforms are correct, while isStrongDefinitionForLinker's intended use
403     // is in low level code generation.
404     return !isDeclaration() && isDefinitionExact();
405   }
406
407   /// Return true if this global's definition can be substituted with an
408   /// *arbitrary* definition at link time.  We cannot do any IPO or inlinining
409   /// across interposable call edges, since the callee can be replaced with
410   /// something arbitrary at link time.
411   bool isInterposable() const { return isInterposableLinkage(getLinkage()); }
412
413   bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
414   bool hasAvailableExternallyLinkage() const {
415     return isAvailableExternallyLinkage(getLinkage());
416   }
417   bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
418   bool hasLinkOnceODRLinkage() const {
419     return isLinkOnceODRLinkage(getLinkage());
420   }
421   bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
422   bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
423   bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
424   bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
425   bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
426   bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
427   bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
428   bool hasExternalWeakLinkage() const {
429     return isExternalWeakLinkage(getLinkage());
430   }
431   bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
432   bool hasValidDeclarationLinkage() const {
433     return isValidDeclarationLinkage(getLinkage());
434   }
435
436   void setLinkage(LinkageTypes LT) {
437     if (isLocalLinkage(LT))
438       Visibility = DefaultVisibility;
439     Linkage = LT;
440   }
441   LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
442
443   bool isDiscardableIfUnused() const {
444     return isDiscardableIfUnused(getLinkage());
445   }
446
447   bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
448
449 protected:
450   /// Copy all additional attributes (those not needed to create a GlobalValue)
451   /// from the GlobalValue Src to this one.
452   void copyAttributesFrom(const GlobalValue *Src);
453
454 public:
455   /// If the given string begins with the GlobalValue name mangling escape
456   /// character '\1', drop it.
457   ///
458   /// This function applies a specific mangling that is used in PGO profiles,
459   /// among other things. If you're trying to get a symbol name for an
460   /// arbitrary GlobalValue, this is not the function you're looking for; see
461   /// Mangler.h.
462   static StringRef dropLLVMManglingEscape(StringRef Name) {
463     if (!Name.empty() && Name[0] == '\1')
464       return Name.substr(1);
465     return Name;
466   }
467
468   /// Return the modified name for a global value suitable to be
469   /// used as the key for a global lookup (e.g. profile or ThinLTO).
470   /// The value's original name is \c Name and has linkage of type
471   /// \c Linkage. The value is defined in module \c FileName.
472   static std::string getGlobalIdentifier(StringRef Name,
473                                          GlobalValue::LinkageTypes Linkage,
474                                          StringRef FileName);
475
476   /// Return the modified name for this global value suitable to be
477   /// used as the key for a global lookup (e.g. profile or ThinLTO).
478   std::string getGlobalIdentifier() const;
479
480   /// Declare a type to represent a global unique identifier for a global value.
481   /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
482   /// unique way to identify a symbol.
483   using GUID = uint64_t;
484
485   /// Return a 64-bit global unique ID constructed from global value name
486   /// (i.e. returned by getGlobalIdentifier()).
487   static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
488
489   /// Return a 64-bit global unique ID constructed from global value name
490   /// (i.e. returned by getGlobalIdentifier()).
491   GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
492
493   /// @name Materialization
494   /// Materialization is used to construct functions only as they're needed.
495   /// This
496   /// is useful to reduce memory usage in LLVM or parsing work done by the
497   /// BitcodeReader to load the Module.
498   /// @{
499
500   /// If this function's Module is being lazily streamed in functions from disk
501   /// or some other source, this method can be used to check to see if the
502   /// function has been read in yet or not.
503   bool isMaterializable() const;
504
505   /// Make sure this GlobalValue is fully read.
506   Error materialize();
507
508 /// @}
509
510   /// Return true if the primary definition of this global value is outside of
511   /// the current translation unit.
512   bool isDeclaration() const;
513
514   bool isDeclarationForLinker() const {
515     if (hasAvailableExternallyLinkage())
516       return true;
517
518     return isDeclaration();
519   }
520
521   /// Returns true if this global's definition will be the one chosen by the
522   /// linker.
523   ///
524   /// NB! Ideally this should not be used at the IR level at all.  If you're
525   /// interested in optimization constraints implied by the linker's ability to
526   /// choose an implementation, prefer using \c hasExactDefinition.
527   bool isStrongDefinitionForLinker() const {
528     return !(isDeclarationForLinker() || isWeakForLinker());
529   }
530
531   // Returns true if the alignment of the value can be unilaterally
532   // increased.
533   bool canIncreaseAlignment() const;
534
535   const GlobalObject *getBaseObject() const;
536   GlobalObject *getBaseObject() {
537     return const_cast<GlobalObject *>(
538                        static_cast<const GlobalValue *>(this)->getBaseObject());
539   }
540
541   /// Returns whether this is a reference to an absolute symbol.
542   bool isAbsoluteSymbolRef() const;
543
544   /// If this is an absolute symbol reference, returns the range of the symbol,
545   /// otherwise returns None.
546   Optional<ConstantRange> getAbsoluteSymbolRange() const;
547
548   /// This method unlinks 'this' from the containing module, but does not delete
549   /// it.
550   void removeFromParent();
551
552   /// This method unlinks 'this' from the containing module and deletes it.
553   void eraseFromParent();
554
555   /// Get the module that this global value is contained inside of...
556   Module *getParent() { return Parent; }
557   const Module *getParent() const { return Parent; }
558
559   // Methods for support type inquiry through isa, cast, and dyn_cast:
560   static bool classof(const Value *V) {
561     return V->getValueID() == Value::FunctionVal ||
562            V->getValueID() == Value::GlobalVariableVal ||
563            V->getValueID() == Value::GlobalAliasVal ||
564            V->getValueID() == Value::GlobalIFuncVal;
565   }
566 };
567
568 } // end namespace llvm
569
570 #endif // LLVM_IR_GLOBALVALUE_H