LLVM 20.0.0git
GlobalVariable.h
Go to the documentation of this file.
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"
27#include "llvm/IR/Value.h"
28#include <cassert>
29#include <cstddef>
30
31namespace llvm {
32
33class Constant;
34class Module;
35
36template <typename ValueSubClass, typename... Args> class SymbolTableListTraits;
38
39class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> {
41
42 AttributeSet Attrs;
43
44 // Is this a global constant?
45 bool isConstantGlobal : 1;
46 // Is this a global whose value can change from its initial value before
47 // global initializers are run?
48 bool isExternallyInitializedConstant : 1;
49
50private:
51 static const unsigned CodeModelBits = LastCodeModelBit - LastAlignmentBit;
52 static const unsigned CodeModelMask = (1 << CodeModelBits) - 1;
53 static const unsigned CodeModelShift = LastAlignmentBit + 1;
54
55public:
56 /// GlobalVariable ctor - If a parent module is specified, the global is
57 /// automatically inserted into the end of the specified modules global list.
59 Constant *Initializer = nullptr, const Twine &Name = "",
61 bool isExternallyInitialized = false);
62 /// GlobalVariable ctor - This creates a global and inserts it before the
63 /// specified other global.
65 Constant *Initializer, const Twine &Name = "",
66 GlobalVariable *InsertBefore = nullptr,
68 std::optional<unsigned> AddressSpace = std::nullopt,
69 bool isExternallyInitialized = false);
70 GlobalVariable(const GlobalVariable &) = delete;
72
75 }
76
77 // allocate space for exactly one operand
78 void *operator new(size_t s) {
79 return User::operator new(s, 1);
80 }
81
82 // delete space for exactly one operand as created in the corresponding new operator
83 void operator delete(void *ptr){
84 assert(ptr != nullptr && "must not be nullptr");
85 User *Obj = static_cast<User *>(ptr);
86 // Number of operands can be set to 0 after construction and initialization. Make sure
87 // that number of operands is reset to 1, as this is needed in User::operator delete
89 User::operator delete(Obj);
90 }
91
92 /// Provide fast operand accessors
94
95 /// Definitions have initializers, declarations don't.
96 ///
97 inline bool hasInitializer() const { return !isDeclaration(); }
98
99 /// hasDefinitiveInitializer - Whether the global variable has an initializer,
100 /// and any other instances of the global (this can happen due to weak
101 /// linkage) are guaranteed to have the same initializer.
102 ///
103 /// Note that if you want to transform a global, you must use
104 /// hasUniqueInitializer() instead, because of the *_odr linkage type.
105 ///
106 /// Example:
107 ///
108 /// @a = global SomeType* null - Initializer is both definitive and unique.
109 ///
110 /// @b = global weak SomeType* null - Initializer is neither definitive nor
111 /// unique.
112 ///
113 /// @c = global weak_odr SomeType* null - Initializer is definitive, but not
114 /// unique.
115 inline bool hasDefinitiveInitializer() const {
116 return hasInitializer() &&
117 // The initializer of a global variable may change to something arbitrary
118 // at link time.
119 !isInterposable() &&
120 // The initializer of a global variable with the externally_initialized
121 // marker may change at runtime before C++ initializers are evaluated.
123 }
124
125 /// hasUniqueInitializer - Whether the global variable has an initializer, and
126 /// any changes made to the initializer will turn up in the final executable.
127 inline bool hasUniqueInitializer() const {
128 return
129 // We need to be sure this is the definition that will actually be used
131 // It is not safe to modify initializers of global variables with the
132 // external_initializer marker since the value may be changed at runtime
133 // before C++ initializers are evaluated.
135 }
136
137 /// getInitializer - Return the initializer for this global variable. It is
138 /// illegal to call this method if the global is external, because we cannot
139 /// tell what the value is initialized to!
140 ///
141 inline const Constant *getInitializer() const {
142 assert(hasInitializer() && "GV doesn't have initializer!");
143 return static_cast<Constant*>(Op<0>().get());
144 }
146 assert(hasInitializer() && "GV doesn't have initializer!");
147 return static_cast<Constant*>(Op<0>().get());
148 }
149 /// setInitializer - Sets the initializer for this global variable, removing
150 /// any existing initializer if InitVal==NULL. The initializer must have the
151 /// type getValueType().
152 void setInitializer(Constant *InitVal);
153
154 /// replaceInitializer - Sets the initializer for this global variable, and
155 /// sets the value type of the global to the type of the initializer. The
156 /// initializer must not be null. This may affect the global's alignment if
157 /// it isn't explicitly set.
158 void replaceInitializer(Constant *InitVal);
159
160 /// If the value is a global constant, its value is immutable throughout the
161 /// runtime execution of the program. Assigning a value into the constant
162 /// leads to undefined behavior.
163 ///
164 bool isConstant() const { return isConstantGlobal; }
165 void setConstant(bool Val) { isConstantGlobal = Val; }
166
168 return isExternallyInitializedConstant;
169 }
171 isExternallyInitializedConstant = Val;
172 }
173
174 /// copyAttributesFrom - copy all additional attributes (those not needed to
175 /// create a GlobalVariable) from the GlobalVariable Src to this one.
176 void copyAttributesFrom(const GlobalVariable *Src);
177
178 /// removeFromParent - This method unlinks 'this' from the containing module,
179 /// but does not delete it.
180 ///
181 void removeFromParent();
182
183 /// eraseFromParent - This method unlinks 'this' from the containing module
184 /// and deletes it.
185 ///
186 void eraseFromParent();
187
188 /// Drop all references in preparation to destroy the GlobalVariable. This
189 /// drops not only the reference to the initializer but also to any metadata.
190 void dropAllReferences();
191
192 /// Attach a DIGlobalVariableExpression.
194
195 /// Fill the vector with all debug info attachements.
197
198 /// Add attribute to this global.
200 Attrs = Attrs.addAttribute(getContext(), Kind);
201 }
202
203 /// Add attribute to this global.
205 Attrs = Attrs.addAttribute(getContext(), Kind, Val);
206 }
207
208 /// Return true if the attribute exists.
210 return Attrs.hasAttribute(Kind);
211 }
212
213 /// Return true if the attribute exists.
214 bool hasAttribute(StringRef Kind) const {
215 return Attrs.hasAttribute(Kind);
216 }
217
218 /// Return true if any attributes exist.
219 bool hasAttributes() const {
220 return Attrs.hasAttributes();
221 }
222
223 /// Return the attribute object.
225 return Attrs.getAttribute(Kind);
226 }
227
228 /// Return the attribute object.
230 return Attrs.getAttribute(Kind);
231 }
232
233 /// Return the attribute set for this global
235 return Attrs;
236 }
237
238 /// Return attribute set as list with index.
239 /// FIXME: This may not be required once ValueEnumerators
240 /// in bitcode-writer can enumerate attribute-set.
241 AttributeList getAttributesAsList(unsigned index) const {
242 if (!hasAttributes())
243 return AttributeList();
244 std::pair<unsigned, AttributeSet> AS[1] = {{index, Attrs}};
245 return AttributeList::get(getContext(), AS);
246 }
247
248 /// Set attribute list for this global
250 Attrs = A;
251 }
252
253 /// Check if section name is present
254 bool hasImplicitSection() const {
255 return getAttributes().hasAttribute("bss-section") ||
256 getAttributes().hasAttribute("data-section") ||
257 getAttributes().hasAttribute("relro-section") ||
258 getAttributes().hasAttribute("rodata-section");
259 }
260
261 /// Get the custom code model raw value of this global.
262 ///
263 unsigned getCodeModelRaw() const {
264 unsigned Data = getGlobalValueSubClassData();
265 return (Data >> CodeModelShift) & CodeModelMask;
266 }
267
268 /// Get the custom code model of this global if it has one.
269 ///
270 /// If this global does not have a custom code model, the empty instance
271 /// will be returned.
272 std::optional<CodeModel::Model> getCodeModel() const {
273 unsigned CodeModelData = getCodeModelRaw();
274 if (CodeModelData > 0)
275 return static_cast<CodeModel::Model>(CodeModelData - 1);
276 return {};
277 }
278
279 /// Change the code model for this global.
280 ///
282
283 // Methods for support type inquiry through isa, cast, and dyn_cast:
284 static bool classof(const Value *V) {
285 return V->getValueID() == Value::GlobalVariableVal;
286 }
287};
288
289template <>
291 public OptionalOperandTraits<GlobalVariable> {
292};
293
295
296} // end namespace llvm
297
298#endif // LLVM_IR_GLOBALVARIABLE_H
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
std::string Name
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS)
Macro for generating out-of-class operand accessor definitions.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition: Attributes.cpp:910
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
This is an important base class in LLVM.
Definition: Constant.h:42
A pair of DIGlobalVariable and DIExpression.
This class represents an Operation in the Expression.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:290
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
Definition: GlobalValue.h:631
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition: Globals.cpp:105
unsigned getGlobalValueSubClassData() const
Definition: GlobalValue.h:175
unsigned Linkage
Definition: GlobalValue.h:98
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:485
unsigned getCodeModelRaw() const
Get the custom code model raw value of this global.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists.
bool isExternallyInitialized() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
Attribute getAttribute(Attribute::AttrKind Kind) const
Return the attribute object.
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition: Globals.cpp:477
bool hasAttributes() const
Return true if any attributes exist.
AttributeSet getAttributes() const
Return the attribute set for this global.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)
Provide fast operand accessors.
std::optional< CodeModel::Model > getCodeModel() const
Get the custom code model of this global if it has one.
void setAttributes(AttributeSet A)
Set attribute list for this global.
void replaceInitializer(Constant *InitVal)
replaceInitializer - Sets the initializer for this global variable, and sets the value type of the gl...
Definition: Globals.cpp:506
void setConstant(bool Val)
GlobalVariable & operator=(const GlobalVariable &)=delete
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:514
GlobalVariable(const GlobalVariable &)=delete
void addAttribute(StringRef Kind, StringRef Val=StringRef())
Add attribute to this global.
Constant * getInitializer()
bool hasImplicitSection() const
Check if section name is present.
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1854
AttributeList getAttributesAsList(unsigned index) const
Return attribute set as list with index.
Attribute getAttribute(StringRef Kind) const
Return the attribute object.
static bool classof(const Value *V)
bool hasAttribute(StringRef Kind) const
Return true if the attribute exists.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition: Globals.cpp:527
bool hasUniqueInitializer() const
hasUniqueInitializer - Whether the global variable has an initializer, and any changes made to the in...
void setExternallyInitialized(bool Val)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:481
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1850
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
void addAttribute(Attribute::AttrKind Kind)
Add attribute to this global.
void dropAllReferences()
Drop all references in preparation to destroy the GlobalVariable.
Definition: Globals.cpp:522
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
void setGlobalVariableNumOperands(unsigned NumOps)
Set the number of operands on a GlobalVariable.
Definition: User.h:207
LLVM Value Representation.
Definition: Value.h:74
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
AddressSpace
Definition: NVPTXBaseInfo.h:21
Compile-time customization of User operands.
Definition: User.h:42
OptionalOperandTraits - when the number of operands may change at runtime.
Definition: OperandTraits.h:53