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