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