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