LLVM  mainline
Globals.cpp
Go to the documentation of this file.
00001 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the GlobalValue & GlobalVariable classes for the IR
00011 // library.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/ADT/SmallPtrSet.h"
00016 #include "llvm/ADT/Triple.h"
00017 #include "llvm/IR/Constants.h"
00018 #include "llvm/IR/DerivedTypes.h"
00019 #include "llvm/IR/GlobalAlias.h"
00020 #include "llvm/IR/GlobalValue.h"
00021 #include "llvm/IR/GlobalVariable.h"
00022 #include "llvm/IR/Module.h"
00023 #include "llvm/IR/Operator.h"
00024 #include "llvm/Support/ErrorHandling.h"
00025 using namespace llvm;
00026 
00027 //===----------------------------------------------------------------------===//
00028 //                            GlobalValue Class
00029 //===----------------------------------------------------------------------===//
00030 
00031 bool GlobalValue::isMaterializable() const {
00032   if (const Function *F = dyn_cast<Function>(this))
00033     return F->isMaterializable();
00034   return false;
00035 }
00036 std::error_code GlobalValue::materialize() {
00037   return getParent()->materialize(this);
00038 }
00039 
00040 /// Override destroyConstantImpl to make sure it doesn't get called on
00041 /// GlobalValue's because they shouldn't be treated like other constants.
00042 void GlobalValue::destroyConstantImpl() {
00043   llvm_unreachable("You can't GV->destroyConstantImpl()!");
00044 }
00045 
00046 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
00047   llvm_unreachable("Unsupported class for handleOperandChange()!");
00048 }
00049 
00050 /// copyAttributesFrom - copy all additional attributes (those not needed to
00051 /// create a GlobalValue) from the GlobalValue Src to this one.
00052 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
00053   setVisibility(Src->getVisibility());
00054   setUnnamedAddr(Src->hasUnnamedAddr());
00055   setDLLStorageClass(Src->getDLLStorageClass());
00056 }
00057 
00058 unsigned GlobalValue::getAlignment() const {
00059   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
00060     // In general we cannot compute this at the IR level, but we try.
00061     if (const GlobalObject *GO = GA->getBaseObject())
00062       return GO->getAlignment();
00063 
00064     // FIXME: we should also be able to handle:
00065     // Alias = Global + Offset
00066     // Alias = Absolute
00067     return 0;
00068   }
00069   return cast<GlobalObject>(this)->getAlignment();
00070 }
00071 
00072 void GlobalObject::setAlignment(unsigned Align) {
00073   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00074   assert(Align <= MaximumAlignment &&
00075          "Alignment is greater than MaximumAlignment!");
00076   unsigned AlignmentData = Log2_32(Align) + 1;
00077   unsigned OldData = getGlobalValueSubClassData();
00078   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
00079   assert(getAlignment() == Align && "Alignment representation error!");
00080 }
00081 
00082 unsigned GlobalObject::getGlobalObjectSubClassData() const {
00083   unsigned ValueData = getGlobalValueSubClassData();
00084   return ValueData >> AlignmentBits;
00085 }
00086 
00087 void GlobalObject::setGlobalObjectSubClassData(unsigned Val) {
00088   unsigned OldData = getGlobalValueSubClassData();
00089   setGlobalValueSubClassData((OldData & AlignmentMask) |
00090                              (Val << AlignmentBits));
00091   assert(getGlobalObjectSubClassData() == Val && "representation error");
00092 }
00093 
00094 void GlobalObject::copyAttributesFrom(const GlobalValue *Src) {
00095   GlobalValue::copyAttributesFrom(Src);
00096   if (const auto *GV = dyn_cast<GlobalObject>(Src)) {
00097     setAlignment(GV->getAlignment());
00098     setSection(GV->getSection());
00099   }
00100 }
00101 
00102 const char *GlobalValue::getSection() const {
00103   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
00104     // In general we cannot compute this at the IR level, but we try.
00105     if (const GlobalObject *GO = GA->getBaseObject())
00106       return GO->getSection();
00107     return "";
00108   }
00109   return cast<GlobalObject>(this)->getSection();
00110 }
00111 
00112 Comdat *GlobalValue::getComdat() {
00113   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
00114     // In general we cannot compute this at the IR level, but we try.
00115     if (const GlobalObject *GO = GA->getBaseObject())
00116       return const_cast<GlobalObject *>(GO)->getComdat();
00117     return nullptr;
00118   }
00119   return cast<GlobalObject>(this)->getComdat();
00120 }
00121 
00122 void GlobalObject::setSection(StringRef S) { Section = S; }
00123 
00124 bool GlobalValue::isDeclaration() const {
00125   // Globals are definitions if they have an initializer.
00126   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
00127     return GV->getNumOperands() == 0;
00128 
00129   // Functions are definitions if they have a body.
00130   if (const Function *F = dyn_cast<Function>(this))
00131     return F->empty() && !F->isMaterializable();
00132 
00133   // Aliases are always definitions.
00134   assert(isa<GlobalAlias>(this));
00135   return false;
00136 }
00137 
00138 bool GlobalValue::canIncreaseAlignment() const {
00139   // Firstly, can only increase the alignment of a global if it
00140   // is a strong definition.
00141   if (!isStrongDefinitionForLinker())
00142     return false;
00143 
00144   // It also has to either not have a section defined, or, not have
00145   // alignment specified. (If it is assigned a section, the global
00146   // could be densely packed with other objects in the section, and
00147   // increasing the alignment could cause padding issues.)
00148   if (hasSection() && getAlignment() > 0)
00149     return false;
00150 
00151   // On ELF platforms, we're further restricted in that we can't
00152   // increase the alignment of any variable which might be emitted
00153   // into a shared library, and which is exported. If the main
00154   // executable accesses a variable found in a shared-lib, the main
00155   // exe actually allocates memory for and exports the symbol ITSELF,
00156   // overriding the symbol found in the library. That is, at link
00157   // time, the observed alignment of the variable is copied into the
00158   // executable binary. (A COPY relocation is also generated, to copy
00159   // the initial data from the shadowed variable in the shared-lib
00160   // into the location in the main binary, before running code.)
00161   //
00162   // And thus, even though you might think you are defining the
00163   // global, and allocating the memory for the global in your object
00164   // file, and thus should be able to set the alignment arbitrarily,
00165   // that's not actually true. Doing so can cause an ABI breakage; an
00166   // executable might have already been built with the previous
00167   // alignment of the variable, and then assuming an increased
00168   // alignment will be incorrect.
00169 
00170   // Conservatively assume ELF if there's no parent pointer.
00171   bool isELF =
00172       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
00173   if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
00174     return false;
00175 
00176   return true;
00177 }
00178 
00179 //===----------------------------------------------------------------------===//
00180 // GlobalVariable Implementation
00181 //===----------------------------------------------------------------------===//
00182 
00183 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
00184                                Constant *InitVal, const Twine &Name,
00185                                ThreadLocalMode TLMode, unsigned AddressSpace,
00186                                bool isExternallyInitialized)
00187     : GlobalObject(Ty, Value::GlobalVariableVal,
00188                    OperandTraits<GlobalVariable>::op_begin(this),
00189                    InitVal != nullptr, Link, Name, AddressSpace),
00190       isConstantGlobal(constant),
00191       isExternallyInitializedConstant(isExternallyInitialized) {
00192   setThreadLocalMode(TLMode);
00193   if (InitVal) {
00194     assert(InitVal->getType() == Ty &&
00195            "Initializer should be the same type as the GlobalVariable!");
00196     Op<0>() = InitVal;
00197   }
00198 }
00199 
00200 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
00201                                LinkageTypes Link, Constant *InitVal,
00202                                const Twine &Name, GlobalVariable *Before,
00203                                ThreadLocalMode TLMode, unsigned AddressSpace,
00204                                bool isExternallyInitialized)
00205     : GlobalObject(Ty, Value::GlobalVariableVal,
00206                    OperandTraits<GlobalVariable>::op_begin(this),
00207                    InitVal != nullptr, Link, Name, AddressSpace),
00208       isConstantGlobal(constant),
00209       isExternallyInitializedConstant(isExternallyInitialized) {
00210   setThreadLocalMode(TLMode);
00211   if (InitVal) {
00212     assert(InitVal->getType() == Ty &&
00213            "Initializer should be the same type as the GlobalVariable!");
00214     Op<0>() = InitVal;
00215   }
00216 
00217   if (Before)
00218     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
00219   else
00220     M.getGlobalList().push_back(this);
00221 }
00222 
00223 void GlobalVariable::setParent(Module *parent) {
00224   Parent = parent;
00225 }
00226 
00227 void GlobalVariable::removeFromParent() {
00228   getParent()->getGlobalList().remove(getIterator());
00229 }
00230 
00231 void GlobalVariable::eraseFromParent() {
00232   getParent()->getGlobalList().erase(getIterator());
00233 }
00234 
00235 void GlobalVariable::setInitializer(Constant *InitVal) {
00236   if (!InitVal) {
00237     if (hasInitializer()) {
00238       // Note, the num operands is used to compute the offset of the operand, so
00239       // the order here matters.  Clearing the operand then clearing the num
00240       // operands ensures we have the correct offset to the operand.
00241       Op<0>().set(nullptr);
00242       setGlobalVariableNumOperands(0);
00243     }
00244   } else {
00245     assert(InitVal->getType() == getValueType() &&
00246            "Initializer type must match GlobalVariable type");
00247     // Note, the num operands is used to compute the offset of the operand, so
00248     // the order here matters.  We need to set num operands to 1 first so that
00249     // we get the correct offset to the first operand when we set it.
00250     if (!hasInitializer())
00251       setGlobalVariableNumOperands(1);
00252     Op<0>().set(InitVal);
00253   }
00254 }
00255 
00256 /// Copy all additional attributes (those not needed to create a GlobalVariable)
00257 /// from the GlobalVariable Src to this one.
00258 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
00259   GlobalObject::copyAttributesFrom(Src);
00260   if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(Src)) {
00261     setThreadLocalMode(SrcVar->getThreadLocalMode());
00262     setExternallyInitialized(SrcVar->isExternallyInitialized());
00263   }
00264 }
00265 
00266 
00267 //===----------------------------------------------------------------------===//
00268 // GlobalAlias Implementation
00269 //===----------------------------------------------------------------------===//
00270 
00271 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
00272                          const Twine &Name, Constant *Aliasee,
00273                          Module *ParentModule)
00274     : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
00275                   AddressSpace) {
00276   Op<0>() = Aliasee;
00277 
00278   if (ParentModule)
00279     ParentModule->getAliasList().push_back(this);
00280 }
00281 
00282 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
00283                                  LinkageTypes Link, const Twine &Name,
00284                                  Constant *Aliasee, Module *ParentModule) {
00285   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
00286 }
00287 
00288 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
00289                                  LinkageTypes Linkage, const Twine &Name,
00290                                  Module *Parent) {
00291   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
00292 }
00293 
00294 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
00295                                  LinkageTypes Linkage, const Twine &Name,
00296                                  GlobalValue *Aliasee) {
00297   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
00298 }
00299 
00300 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
00301                                  GlobalValue *Aliasee) {
00302   PointerType *PTy = Aliasee->getType();
00303   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
00304                 Aliasee);
00305 }
00306 
00307 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
00308   return create(Aliasee->getLinkage(), Name, Aliasee);
00309 }
00310 
00311 void GlobalAlias::setParent(Module *parent) {
00312   Parent = parent;
00313 }
00314 
00315 void GlobalAlias::removeFromParent() {
00316   getParent()->getAliasList().remove(getIterator());
00317 }
00318 
00319 void GlobalAlias::eraseFromParent() {
00320   getParent()->getAliasList().erase(getIterator());
00321 }
00322 
00323 void GlobalAlias::setAliasee(Constant *Aliasee) {
00324   assert((!Aliasee || Aliasee->getType() == getType()) &&
00325          "Alias and aliasee types should match!");
00326   setOperand(0, Aliasee);
00327 }