1 //===-- llvm/GlobalVariable.h - GlobalVariable class ------------*- 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 contains the declaration of the GlobalVariable class, which
10 // represents a single global variable (or constant) in the VM.
11 //
12 // Global variables are constant pointers that refer to hunks of space that are
13 // allocated by either the VM, or by the linker in a static compiler.  A global
14 // variable may have an initial value, which is copied into the executables .data
15 // area.  Global Constants are required to have initializers.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #ifndef LLVM_IR_GLOBALVARIABLE_H
20 #define LLVM_IR_GLOBALVARIABLE_H
21 
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/ADT/ilist_node.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/GlobalObject.h"
26 #include "llvm/IR/OperandTraits.h"
27 #include "llvm/IR/Value.h"
28 #include <cassert>
29 #include <cstddef>
30 
31 namespace llvm {
32 
33 class Constant;
34 class Module;
35 
36 template <typename ValueSubClass> class SymbolTableListTraits;
37 class DIGlobalVariable;
38 class DIGlobalVariableExpression;
39 
40 class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> {
41   friend class SymbolTableListTraits<GlobalVariable>;
42 
43   AttributeSet Attrs;
44   bool isConstantGlobal : 1;                   // Is this a global constant?
45   bool isExternallyInitializedConstant : 1;    // Is this a global whose value
46                                                // can change from its initial
47                                                // value before global
48                                                // initializers are run?
49 
50 public:
51   /// GlobalVariable ctor - If a parent module is specified, the global is
52   /// automatically inserted into the end of the specified modules global list.
53   LLVM_ATTRIBUTE_DEPRECATED(
54       GlobalVariable(Type *Ty, bool isConstant, LinkageTypes Linkage,
55                      Constant *Initializer = nullptr, const Twine &Name = "",
56                      ThreadLocalMode TLMode = NotThreadLocal),
57       "use the overload with a Module& or an explicit address space")
58       : GlobalVariable(Ty, isConstant, Linkage, Initializer, Name, TLMode, 0,
59                        false) {}
60 
61   GlobalVariable(Type *Ty, bool isConstant, LinkageTypes Linkage,
62                  Constant *Initializer, const Twine &Name,
63                  ThreadLocalMode, unsigned AddressSpace,
64                  bool isExternallyInitialized = false);
65   /// GlobalVariable ctor - This creates a global and inserts it before the
66   /// specified other global.
67   GlobalVariable(Module &M, Type *Ty, bool isConstant, LinkageTypes Linkage,
68                  Constant *Initializer, const Twine &Name = "",
69                  GlobalVariable *InsertBefore = nullptr,
70                  ThreadLocalMode = NotThreadLocal,
71                  unsigned AddressSpace = UINT_MAX,
72                  bool isExternallyInitialized = false);
73   GlobalVariable(const GlobalVariable &) = delete;
74   GlobalVariable &operator=(const GlobalVariable &) = delete;
75 
~GlobalVariable()76   ~GlobalVariable() {
77     dropAllReferences();
78   }
79 
80   // allocate space for exactly one operand
new(size_t s)81   void *operator new(size_t s) {
82     return User::operator new(s, 1);
83   }
84 
85   // delete space for exactly one operand as created in the corresponding new operator
delete(void * ptr)86   void operator delete(void *ptr){
87     assert(ptr != nullptr && "must not be nullptr");
88     User *Obj = static_cast<User *>(ptr);
89     // Number of operands can be set to 0 after construction and initialization. Make sure
90     // that number of operands is reset to 1, as this is needed in User::operator delete
91     Obj->setGlobalVariableNumOperands(1);
92     User::operator delete(Obj);
93   }
94 
95   /// Provide fast operand accessors
96   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
97 
98   /// Definitions have initializers, declarations don't.
99   ///
hasInitializer()100   inline bool hasInitializer() const { return !isDeclaration(); }
101 
102   /// hasDefinitiveInitializer - Whether the global variable has an initializer,
103   /// and any other instances of the global (this can happen due to weak
104   /// linkage) are guaranteed to have the same initializer.
105   ///
106   /// Note that if you want to transform a global, you must use
107   /// hasUniqueInitializer() instead, because of the *_odr linkage type.
108   ///
109   /// Example:
110   ///
111   /// @a = global SomeType* null - Initializer is both definitive and unique.
112   ///
113   /// @b = global weak SomeType* null - Initializer is neither definitive nor
114   /// unique.
115   ///
116   /// @c = global weak_odr SomeType* null - Initializer is definitive, but not
117   /// unique.
hasDefinitiveInitializer()118   inline bool hasDefinitiveInitializer() const {
119     return hasInitializer() &&
120       // The initializer of a global variable may change to something arbitrary
121       // at link time.
122       !isInterposable() &&
123       // The initializer of a global variable with the externally_initialized
124       // marker may change at runtime before C++ initializers are evaluated.
125       !isExternallyInitialized();
126   }
127 
128   /// hasUniqueInitializer - Whether the global variable has an initializer, and
129   /// any changes made to the initializer will turn up in the final executable.
hasUniqueInitializer()130   inline bool hasUniqueInitializer() const {
131     return
132         // We need to be sure this is the definition that will actually be used
133         isStrongDefinitionForLinker() &&
134         // It is not safe to modify initializers of global variables with the
135         // external_initializer marker since the value may be changed at runtime
136         // before C++ initializers are evaluated.
137         !isExternallyInitialized();
138   }
139 
140   /// getInitializer - Return the initializer for this global variable.  It is
141   /// illegal to call this method if the global is external, because we cannot
142   /// tell what the value is initialized to!
143   ///
getInitializer()144   inline const Constant *getInitializer() const {
145     assert(hasInitializer() && "GV doesn't have initializer!");
146     return static_cast<Constant*>(Op<0>().get());
147   }
getInitializer()148   inline Constant *getInitializer() {
149     assert(hasInitializer() && "GV doesn't have initializer!");
150     return static_cast<Constant*>(Op<0>().get());
151   }
152   /// setInitializer - Sets the initializer for this global variable, removing
153   /// any existing initializer if InitVal==NULL.  If this GV has type T*, the
154   /// initializer must have type T.
155   void setInitializer(Constant *InitVal);
156 
157   /// If the value is a global constant, its value is immutable throughout the
158   /// runtime execution of the program.  Assigning a value into the constant
159   /// leads to undefined behavior.
160   ///
isConstant()161   bool isConstant() const { return isConstantGlobal; }
setConstant(bool Val)162   void setConstant(bool Val) { isConstantGlobal = Val; }
163 
isExternallyInitialized()164   bool isExternallyInitialized() const {
165     return isExternallyInitializedConstant;
166   }
setExternallyInitialized(bool Val)167   void setExternallyInitialized(bool Val) {
168     isExternallyInitializedConstant = Val;
169   }
170 
171   /// copyAttributesFrom - copy all additional attributes (those not needed to
172   /// create a GlobalVariable) from the GlobalVariable Src to this one.
173   void copyAttributesFrom(const GlobalVariable *Src);
174 
175   /// removeFromParent - This method unlinks 'this' from the containing module,
176   /// but does not delete it.
177   ///
178   void removeFromParent();
179 
180   /// eraseFromParent - This method unlinks 'this' from the containing module
181   /// and deletes it.
182   ///
183   void eraseFromParent();
184 
185   /// Drop all references in preparation to destroy the GlobalVariable. This
186   /// drops not only the reference to the initializer but also to any metadata.
187   void dropAllReferences();
188 
189   /// Attach a DIGlobalVariableExpression.
190   void addDebugInfo(DIGlobalVariableExpression *GV);
191 
192   /// Fill the vector with all debug info attachements.
193   void getDebugInfo(SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const;
194 
195   /// Add attribute to this global.
addAttribute(Attribute::AttrKind Kind)196   void addAttribute(Attribute::AttrKind Kind) {
197     Attrs = Attrs.addAttribute(getContext(), Kind);
198   }
199 
200   /// Add attribute to this global.
201   void addAttribute(StringRef Kind, StringRef Val = StringRef()) {
202     Attrs = Attrs.addAttribute(getContext(), Kind, Val);
203   }
204 
205   /// Return true if the attribute exists.
hasAttribute(Attribute::AttrKind Kind)206   bool hasAttribute(Attribute::AttrKind Kind) const {
207     return Attrs.hasAttribute(Kind);
208   }
209 
210   /// Return true if the attribute exists.
hasAttribute(StringRef Kind)211   bool hasAttribute(StringRef Kind) const {
212     return Attrs.hasAttribute(Kind);
213   }
214 
215   /// Return true if any attributes exist.
hasAttributes()216   bool hasAttributes() const {
217     return Attrs.hasAttributes();
218   }
219 
220   /// Return the attribute object.
getAttribute(Attribute::AttrKind Kind)221   Attribute getAttribute(Attribute::AttrKind Kind) const {
222     return Attrs.getAttribute(Kind);
223   }
224 
225   /// Return the attribute object.
getAttribute(StringRef Kind)226   Attribute getAttribute(StringRef Kind) const {
227     return Attrs.getAttribute(Kind);
228   }
229 
230   /// Return the attribute set for this global
getAttributes()231   AttributeSet getAttributes() const {
232     return Attrs;
233   }
234 
235   /// Return attribute set as list with index.
236   /// FIXME: This may not be required once ValueEnumerators
237   /// in bitcode-writer can enumerate attribute-set.
getAttributesAsList(unsigned index)238   AttributeList getAttributesAsList(unsigned index) const {
239     if (!hasAttributes())
240       return AttributeList();
241     std::pair<unsigned, AttributeSet> AS[1] = {{index, Attrs}};
242     return AttributeList::get(getContext(), AS);
243   }
244 
245   /// Set attribute list for this global
setAttributes(AttributeSet A)246   void setAttributes(AttributeSet A) {
247     Attrs = A;
248   }
249 
250   /// Check if section name is present
hasImplicitSection()251   bool hasImplicitSection() const {
252     return getAttributes().hasAttribute("bss-section") ||
253            getAttributes().hasAttribute("data-section") ||
254            getAttributes().hasAttribute("relro-section") ||
255            getAttributes().hasAttribute("rodata-section");
256   }
257 
258   // Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Value * V)259   static bool classof(const Value *V) {
260     return V->getValueID() == Value::GlobalVariableVal;
261   }
262 };
263 
264 template <>
265 struct OperandTraits<GlobalVariable> :
266   public OptionalOperandTraits<GlobalVariable> {
267 };
268 
269 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GlobalVariable, Value)
270 
271 } // end namespace llvm
272 
273 #endif // LLVM_IR_GLOBALVARIABLE_H
274