Home | History | Annotate | Download | only in IR
      1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the GlobalValue & GlobalVariable classes for the IR
     11 // library.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "llvm/ADT/SmallPtrSet.h"
     16 #include "llvm/ADT/Triple.h"
     17 #include "llvm/IR/Constants.h"
     18 #include "llvm/IR/DerivedTypes.h"
     19 #include "llvm/IR/GlobalAlias.h"
     20 #include "llvm/IR/GlobalValue.h"
     21 #include "llvm/IR/GlobalVariable.h"
     22 #include "llvm/IR/Module.h"
     23 #include "llvm/IR/Operator.h"
     24 #include "llvm/Support/ErrorHandling.h"
     25 using namespace llvm;
     26 
     27 //===----------------------------------------------------------------------===//
     28 //                            GlobalValue Class
     29 //===----------------------------------------------------------------------===//
     30 
     31 bool GlobalValue::isMaterializable() const {
     32   if (const Function *F = dyn_cast<Function>(this))
     33     return F->isMaterializable();
     34   return false;
     35 }
     36 std::error_code GlobalValue::materialize() {
     37   return getParent()->materialize(this);
     38 }
     39 
     40 /// Override destroyConstantImpl to make sure it doesn't get called on
     41 /// GlobalValue's because they shouldn't be treated like other constants.
     42 void GlobalValue::destroyConstantImpl() {
     43   llvm_unreachable("You can't GV->destroyConstantImpl()!");
     44 }
     45 
     46 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
     47   llvm_unreachable("Unsupported class for handleOperandChange()!");
     48 }
     49 
     50 /// copyAttributesFrom - copy all additional attributes (those not needed to
     51 /// create a GlobalValue) from the GlobalValue Src to this one.
     52 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
     53   setVisibility(Src->getVisibility());
     54   setUnnamedAddr(Src->getUnnamedAddr());
     55   setDLLStorageClass(Src->getDLLStorageClass());
     56 }
     57 
     58 unsigned GlobalValue::getAlignment() const {
     59   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
     60     // In general we cannot compute this at the IR level, but we try.
     61     if (const GlobalObject *GO = GA->getBaseObject())
     62       return GO->getAlignment();
     63 
     64     // FIXME: we should also be able to handle:
     65     // Alias = Global + Offset
     66     // Alias = Absolute
     67     return 0;
     68   }
     69   return cast<GlobalObject>(this)->getAlignment();
     70 }
     71 
     72 void GlobalObject::setAlignment(unsigned Align) {
     73   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
     74   assert(Align <= MaximumAlignment &&
     75          "Alignment is greater than MaximumAlignment!");
     76   unsigned AlignmentData = Log2_32(Align) + 1;
     77   unsigned OldData = getGlobalValueSubClassData();
     78   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
     79   assert(getAlignment() == Align && "Alignment representation error!");
     80 }
     81 
     82 unsigned GlobalObject::getGlobalObjectSubClassData() const {
     83   unsigned ValueData = getGlobalValueSubClassData();
     84   return ValueData >> GlobalObjectBits;
     85 }
     86 
     87 void GlobalObject::setGlobalObjectSubClassData(unsigned Val) {
     88   unsigned OldData = getGlobalValueSubClassData();
     89   setGlobalValueSubClassData((OldData & GlobalObjectMask) |
     90                              (Val << GlobalObjectBits));
     91   assert(getGlobalObjectSubClassData() == Val && "representation error");
     92 }
     93 
     94 void GlobalObject::copyAttributesFrom(const GlobalValue *Src) {
     95   GlobalValue::copyAttributesFrom(Src);
     96   if (const auto *GV = dyn_cast<GlobalObject>(Src)) {
     97     setAlignment(GV->getAlignment());
     98     setSection(GV->getSection());
     99   }
    100 }
    101 
    102 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
    103                                              GlobalValue::LinkageTypes Linkage,
    104                                              StringRef FileName) {
    105 
    106   // Value names may be prefixed with a binary '1' to indicate
    107   // that the backend should not modify the symbols due to any platform
    108   // naming convention. Do not include that '1' in the PGO profile name.
    109   if (Name[0] == '\1')
    110     Name = Name.substr(1);
    111 
    112   std::string NewName = Name;
    113   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
    114     // For local symbols, prepend the main file name to distinguish them.
    115     // Do not include the full path in the file name since there's no guarantee
    116     // that it will stay the same, e.g., if the files are checked out from
    117     // version control in different locations.
    118     if (FileName.empty())
    119       NewName = NewName.insert(0, "<unknown>:");
    120     else
    121       NewName = NewName.insert(0, FileName.str() + ":");
    122   }
    123   return NewName;
    124 }
    125 
    126 std::string GlobalValue::getGlobalIdentifier() const {
    127   return getGlobalIdentifier(getName(), getLinkage(),
    128                              getParent()->getSourceFileName());
    129 }
    130 
    131 StringRef GlobalValue::getSection() const {
    132   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
    133     // In general we cannot compute this at the IR level, but we try.
    134     if (const GlobalObject *GO = GA->getBaseObject())
    135       return GO->getSection();
    136     return "";
    137   }
    138   return cast<GlobalObject>(this)->getSection();
    139 }
    140 
    141 Comdat *GlobalValue::getComdat() {
    142   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
    143     // In general we cannot compute this at the IR level, but we try.
    144     if (const GlobalObject *GO = GA->getBaseObject())
    145       return const_cast<GlobalObject *>(GO)->getComdat();
    146     return nullptr;
    147   }
    148   // ifunc and its resolver are separate things so don't use resolver comdat.
    149   if (isa<GlobalIFunc>(this))
    150     return nullptr;
    151   return cast<GlobalObject>(this)->getComdat();
    152 }
    153 
    154 void GlobalObject::setSection(StringRef S) {
    155   Section = S;
    156 
    157   // The C api requires this to be null terminated.
    158   Section.c_str();
    159 }
    160 
    161 bool GlobalValue::isDeclaration() const {
    162   // Globals are definitions if they have an initializer.
    163   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
    164     return GV->getNumOperands() == 0;
    165 
    166   // Functions are definitions if they have a body.
    167   if (const Function *F = dyn_cast<Function>(this))
    168     return F->empty() && !F->isMaterializable();
    169 
    170   // Aliases and ifuncs are always definitions.
    171   assert(isa<GlobalIndirectSymbol>(this));
    172   return false;
    173 }
    174 
    175 bool GlobalValue::canIncreaseAlignment() const {
    176   // Firstly, can only increase the alignment of a global if it
    177   // is a strong definition.
    178   if (!isStrongDefinitionForLinker())
    179     return false;
    180 
    181   // It also has to either not have a section defined, or, not have
    182   // alignment specified. (If it is assigned a section, the global
    183   // could be densely packed with other objects in the section, and
    184   // increasing the alignment could cause padding issues.)
    185   if (hasSection() && getAlignment() > 0)
    186     return false;
    187 
    188   // On ELF platforms, we're further restricted in that we can't
    189   // increase the alignment of any variable which might be emitted
    190   // into a shared library, and which is exported. If the main
    191   // executable accesses a variable found in a shared-lib, the main
    192   // exe actually allocates memory for and exports the symbol ITSELF,
    193   // overriding the symbol found in the library. That is, at link
    194   // time, the observed alignment of the variable is copied into the
    195   // executable binary. (A COPY relocation is also generated, to copy
    196   // the initial data from the shadowed variable in the shared-lib
    197   // into the location in the main binary, before running code.)
    198   //
    199   // And thus, even though you might think you are defining the
    200   // global, and allocating the memory for the global in your object
    201   // file, and thus should be able to set the alignment arbitrarily,
    202   // that's not actually true. Doing so can cause an ABI breakage; an
    203   // executable might have already been built with the previous
    204   // alignment of the variable, and then assuming an increased
    205   // alignment will be incorrect.
    206 
    207   // Conservatively assume ELF if there's no parent pointer.
    208   bool isELF =
    209       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
    210   if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
    211     return false;
    212 
    213   return true;
    214 }
    215 
    216 //===----------------------------------------------------------------------===//
    217 // GlobalVariable Implementation
    218 //===----------------------------------------------------------------------===//
    219 
    220 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
    221                                Constant *InitVal, const Twine &Name,
    222                                ThreadLocalMode TLMode, unsigned AddressSpace,
    223                                bool isExternallyInitialized)
    224     : GlobalObject(Ty, Value::GlobalVariableVal,
    225                    OperandTraits<GlobalVariable>::op_begin(this),
    226                    InitVal != nullptr, Link, Name, AddressSpace),
    227       isConstantGlobal(constant),
    228       isExternallyInitializedConstant(isExternallyInitialized) {
    229   setThreadLocalMode(TLMode);
    230   if (InitVal) {
    231     assert(InitVal->getType() == Ty &&
    232            "Initializer should be the same type as the GlobalVariable!");
    233     Op<0>() = InitVal;
    234   }
    235 }
    236 
    237 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
    238                                LinkageTypes Link, Constant *InitVal,
    239                                const Twine &Name, GlobalVariable *Before,
    240                                ThreadLocalMode TLMode, unsigned AddressSpace,
    241                                bool isExternallyInitialized)
    242     : GlobalObject(Ty, Value::GlobalVariableVal,
    243                    OperandTraits<GlobalVariable>::op_begin(this),
    244                    InitVal != nullptr, Link, Name, AddressSpace),
    245       isConstantGlobal(constant),
    246       isExternallyInitializedConstant(isExternallyInitialized) {
    247   setThreadLocalMode(TLMode);
    248   if (InitVal) {
    249     assert(InitVal->getType() == Ty &&
    250            "Initializer should be the same type as the GlobalVariable!");
    251     Op<0>() = InitVal;
    252   }
    253 
    254   if (Before)
    255     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
    256   else
    257     M.getGlobalList().push_back(this);
    258 }
    259 
    260 void GlobalVariable::setParent(Module *parent) {
    261   Parent = parent;
    262 }
    263 
    264 void GlobalVariable::removeFromParent() {
    265   getParent()->getGlobalList().remove(getIterator());
    266 }
    267 
    268 void GlobalVariable::eraseFromParent() {
    269   getParent()->getGlobalList().erase(getIterator());
    270 }
    271 
    272 void GlobalVariable::setInitializer(Constant *InitVal) {
    273   if (!InitVal) {
    274     if (hasInitializer()) {
    275       // Note, the num operands is used to compute the offset of the operand, so
    276       // the order here matters.  Clearing the operand then clearing the num
    277       // operands ensures we have the correct offset to the operand.
    278       Op<0>().set(nullptr);
    279       setGlobalVariableNumOperands(0);
    280     }
    281   } else {
    282     assert(InitVal->getType() == getValueType() &&
    283            "Initializer type must match GlobalVariable type");
    284     // Note, the num operands is used to compute the offset of the operand, so
    285     // the order here matters.  We need to set num operands to 1 first so that
    286     // we get the correct offset to the first operand when we set it.
    287     if (!hasInitializer())
    288       setGlobalVariableNumOperands(1);
    289     Op<0>().set(InitVal);
    290   }
    291 }
    292 
    293 /// Copy all additional attributes (those not needed to create a GlobalVariable)
    294 /// from the GlobalVariable Src to this one.
    295 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
    296   GlobalObject::copyAttributesFrom(Src);
    297   if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(Src)) {
    298     setThreadLocalMode(SrcVar->getThreadLocalMode());
    299     setExternallyInitialized(SrcVar->isExternallyInitialized());
    300   }
    301 }
    302 
    303 void GlobalVariable::dropAllReferences() {
    304   User::dropAllReferences();
    305   clearMetadata();
    306 }
    307 
    308 //===----------------------------------------------------------------------===//
    309 // GlobalIndirectSymbol Implementation
    310 //===----------------------------------------------------------------------===//
    311 
    312 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
    313     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
    314     Constant *Symbol)
    315     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
    316     Op<0>() = Symbol;
    317 }
    318 
    319 
    320 //===----------------------------------------------------------------------===//
    321 // GlobalAlias Implementation
    322 //===----------------------------------------------------------------------===//
    323 
    324 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
    325                          const Twine &Name, Constant *Aliasee,
    326                          Module *ParentModule)
    327     : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
    328                            Aliasee) {
    329   if (ParentModule)
    330     ParentModule->getAliasList().push_back(this);
    331 }
    332 
    333 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
    334                                  LinkageTypes Link, const Twine &Name,
    335                                  Constant *Aliasee, Module *ParentModule) {
    336   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
    337 }
    338 
    339 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
    340                                  LinkageTypes Linkage, const Twine &Name,
    341                                  Module *Parent) {
    342   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
    343 }
    344 
    345 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
    346                                  LinkageTypes Linkage, const Twine &Name,
    347                                  GlobalValue *Aliasee) {
    348   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
    349 }
    350 
    351 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
    352                                  GlobalValue *Aliasee) {
    353   PointerType *PTy = Aliasee->getType();
    354   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
    355                 Aliasee);
    356 }
    357 
    358 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
    359   return create(Aliasee->getLinkage(), Name, Aliasee);
    360 }
    361 
    362 void GlobalAlias::setParent(Module *parent) {
    363   Parent = parent;
    364 }
    365 
    366 void GlobalAlias::removeFromParent() {
    367   getParent()->getAliasList().remove(getIterator());
    368 }
    369 
    370 void GlobalAlias::eraseFromParent() {
    371   getParent()->getAliasList().erase(getIterator());
    372 }
    373 
    374 void GlobalAlias::setAliasee(Constant *Aliasee) {
    375   assert((!Aliasee || Aliasee->getType() == getType()) &&
    376          "Alias and aliasee types should match!");
    377   setIndirectSymbol(Aliasee);
    378 }
    379 
    380 //===----------------------------------------------------------------------===//
    381 // GlobalIFunc Implementation
    382 //===----------------------------------------------------------------------===//
    383 
    384 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
    385                          const Twine &Name, Constant *Resolver,
    386                          Module *ParentModule)
    387     : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
    388                            Resolver) {
    389   if (ParentModule)
    390     ParentModule->getIFuncList().push_back(this);
    391 }
    392 
    393 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
    394                                  LinkageTypes Link, const Twine &Name,
    395                                  Constant *Resolver, Module *ParentModule) {
    396   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
    397 }
    398 
    399 void GlobalIFunc::setParent(Module *parent) {
    400   Parent = parent;
    401 }
    402 
    403 void GlobalIFunc::removeFromParent() {
    404   getParent()->getIFuncList().remove(getIterator());
    405 }
    406 
    407 void GlobalIFunc::eraseFromParent() {
    408   getParent()->getIFuncList().erase(getIterator());
    409 }
    410