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