Home | History | Annotate | Download | only in IR
      1 //===- Module.cpp - Implement the Module 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 Module class for the IR library.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/IR/Module.h"
     15 #include "SymbolTableListTraitsImpl.h"
     16 #include "llvm/ADT/SmallPtrSet.h"
     17 #include "llvm/ADT/SmallString.h"
     18 #include "llvm/ADT/SmallVector.h"
     19 #include "llvm/ADT/StringMap.h"
     20 #include "llvm/ADT/StringRef.h"
     21 #include "llvm/ADT/Twine.h"
     22 #include "llvm/IR/Attributes.h"
     23 #include "llvm/IR/Comdat.h"
     24 #include "llvm/IR/Constants.h"
     25 #include "llvm/IR/DataLayout.h"
     26 #include "llvm/IR/DebugInfoMetadata.h"
     27 #include "llvm/IR/DerivedTypes.h"
     28 #include "llvm/IR/Function.h"
     29 #include "llvm/IR/GVMaterializer.h"
     30 #include "llvm/IR/GlobalAlias.h"
     31 #include "llvm/IR/GlobalIFunc.h"
     32 #include "llvm/IR/GlobalValue.h"
     33 #include "llvm/IR/GlobalVariable.h"
     34 #include "llvm/IR/LLVMContext.h"
     35 #include "llvm/IR/Metadata.h"
     36 #include "llvm/IR/SymbolTableListTraits.h"
     37 #include "llvm/IR/Type.h"
     38 #include "llvm/IR/TypeFinder.h"
     39 #include "llvm/IR/Value.h"
     40 #include "llvm/IR/ValueSymbolTable.h"
     41 #include "llvm/Pass.h"
     42 #include "llvm/Support/Casting.h"
     43 #include "llvm/Support/CodeGen.h"
     44 #include "llvm/Support/Error.h"
     45 #include "llvm/Support/MemoryBuffer.h"
     46 #include "llvm/Support/Path.h"
     47 #include "llvm/Support/RandomNumberGenerator.h"
     48 #include <algorithm>
     49 #include <cassert>
     50 #include <cstdint>
     51 #include <memory>
     52 #include <utility>
     53 #include <vector>
     54 
     55 using namespace llvm;
     56 
     57 //===----------------------------------------------------------------------===//
     58 // Methods to implement the globals and functions lists.
     59 //
     60 
     61 // Explicit instantiations of SymbolTableListTraits since some of the methods
     62 // are not in the public header file.
     63 template class llvm::SymbolTableListTraits<Function>;
     64 template class llvm::SymbolTableListTraits<GlobalVariable>;
     65 template class llvm::SymbolTableListTraits<GlobalAlias>;
     66 template class llvm::SymbolTableListTraits<GlobalIFunc>;
     67 
     68 //===----------------------------------------------------------------------===//
     69 // Primitive Module methods.
     70 //
     71 
     72 Module::Module(StringRef MID, LLVMContext &C)
     73     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
     74   ValSymTab = new ValueSymbolTable();
     75   NamedMDSymTab = new StringMap<NamedMDNode *>();
     76   Context.addModule(this);
     77 }
     78 
     79 Module::~Module() {
     80   Context.removeModule(this);
     81   dropAllReferences();
     82   GlobalList.clear();
     83   FunctionList.clear();
     84   AliasList.clear();
     85   IFuncList.clear();
     86   NamedMDList.clear();
     87   delete ValSymTab;
     88   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
     89 }
     90 
     91 std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
     92   SmallString<32> Salt(P->getPassName());
     93 
     94   // This RNG is guaranteed to produce the same random stream only
     95   // when the Module ID and thus the input filename is the same. This
     96   // might be problematic if the input filename extension changes
     97   // (e.g. from .c to .bc or .ll).
     98   //
     99   // We could store this salt in NamedMetadata, but this would make
    100   // the parameter non-const. This would unfortunately make this
    101   // interface unusable by any Machine passes, since they only have a
    102   // const reference to their IR Module. Alternatively we can always
    103   // store salt metadata from the Module constructor.
    104   Salt += sys::path::filename(getModuleIdentifier());
    105 
    106   return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
    107 }
    108 
    109 /// getNamedValue - Return the first global value in the module with
    110 /// the specified name, of arbitrary type.  This method returns null
    111 /// if a global with the specified name is not found.
    112 GlobalValue *Module::getNamedValue(StringRef Name) const {
    113   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
    114 }
    115 
    116 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
    117 /// This ID is uniqued across modules in the current LLVMContext.
    118 unsigned Module::getMDKindID(StringRef Name) const {
    119   return Context.getMDKindID(Name);
    120 }
    121 
    122 /// getMDKindNames - Populate client supplied SmallVector with the name for
    123 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
    124 /// so it is filled in as an empty string.
    125 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
    126   return Context.getMDKindNames(Result);
    127 }
    128 
    129 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
    130   return Context.getOperandBundleTags(Result);
    131 }
    132 
    133 //===----------------------------------------------------------------------===//
    134 // Methods for easy access to the functions in the module.
    135 //
    136 
    137 // getOrInsertFunction - Look up the specified function in the module symbol
    138 // table.  If it does not exist, add a prototype for the function and return
    139 // it.  This is nice because it allows most passes to get away with not handling
    140 // the symbol table directly for this common task.
    141 //
    142 Constant *Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
    143                                       AttributeList AttributeList) {
    144   // See if we have a definition for the specified function already.
    145   GlobalValue *F = getNamedValue(Name);
    146   if (!F) {
    147     // Nope, add it
    148     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
    149     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
    150       New->setAttributes(AttributeList);
    151     FunctionList.push_back(New);
    152     return New;                    // Return the new prototype.
    153   }
    154 
    155   // If the function exists but has the wrong type, return a bitcast to the
    156   // right type.
    157   if (F->getType() != PointerType::getUnqual(Ty))
    158     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
    159 
    160   // Otherwise, we just found the existing function or a prototype.
    161   return F;
    162 }
    163 
    164 Constant *Module::getOrInsertFunction(StringRef Name,
    165                                       FunctionType *Ty) {
    166   return getOrInsertFunction(Name, Ty, AttributeList());
    167 }
    168 
    169 // getFunction - Look up the specified function in the module symbol table.
    170 // If it does not exist, return null.
    171 //
    172 Function *Module::getFunction(StringRef Name) const {
    173   return dyn_cast_or_null<Function>(getNamedValue(Name));
    174 }
    175 
    176 //===----------------------------------------------------------------------===//
    177 // Methods for easy access to the global variables in the module.
    178 //
    179 
    180 /// getGlobalVariable - Look up the specified global variable in the module
    181 /// symbol table.  If it does not exist, return null.  The type argument
    182 /// should be the underlying type of the global, i.e., it should not have
    183 /// the top-level PointerType, which represents the address of the global.
    184 /// If AllowLocal is set to true, this function will return types that
    185 /// have an local. By default, these types are not returned.
    186 ///
    187 GlobalVariable *Module::getGlobalVariable(StringRef Name,
    188                                           bool AllowLocal) const {
    189   if (GlobalVariable *Result =
    190       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
    191     if (AllowLocal || !Result->hasLocalLinkage())
    192       return Result;
    193   return nullptr;
    194 }
    195 
    196 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
    197 ///   1. If it does not exist, add a declaration of the global and return it.
    198 ///   2. Else, the global exists but has the wrong type: return the function
    199 ///      with a constantexpr cast to the right type.
    200 ///   3. Finally, if the existing global is the correct declaration, return the
    201 ///      existing global.
    202 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
    203   // See if we have a definition for the specified global already.
    204   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
    205   if (!GV) {
    206     // Nope, add it
    207     GlobalVariable *New =
    208       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
    209                          nullptr, Name);
    210      return New;                    // Return the new declaration.
    211   }
    212 
    213   // If the variable exists but has the wrong type, return a bitcast to the
    214   // right type.
    215   Type *GVTy = GV->getType();
    216   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
    217   if (GVTy != PTy)
    218     return ConstantExpr::getBitCast(GV, PTy);
    219 
    220   // Otherwise, we just found the existing function or a prototype.
    221   return GV;
    222 }
    223 
    224 //===----------------------------------------------------------------------===//
    225 // Methods for easy access to the global variables in the module.
    226 //
    227 
    228 // getNamedAlias - Look up the specified global in the module symbol table.
    229 // If it does not exist, return null.
    230 //
    231 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
    232   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
    233 }
    234 
    235 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
    236   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
    237 }
    238 
    239 /// getNamedMetadata - Return the first NamedMDNode in the module with the
    240 /// specified name. This method returns null if a NamedMDNode with the
    241 /// specified name is not found.
    242 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
    243   SmallString<256> NameData;
    244   StringRef NameRef = Name.toStringRef(NameData);
    245   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
    246 }
    247 
    248 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
    249 /// with the specified name. This method returns a new NamedMDNode if a
    250 /// NamedMDNode with the specified name is not found.
    251 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
    252   NamedMDNode *&NMD =
    253     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
    254   if (!NMD) {
    255     NMD = new NamedMDNode(Name);
    256     NMD->setParent(this);
    257     NamedMDList.push_back(NMD);
    258   }
    259   return NMD;
    260 }
    261 
    262 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
    263 /// delete it.
    264 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
    265   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
    266   NamedMDList.erase(NMD->getIterator());
    267 }
    268 
    269 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
    270   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
    271     uint64_t Val = Behavior->getLimitedValue();
    272     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
    273       MFB = static_cast<ModFlagBehavior>(Val);
    274       return true;
    275     }
    276   }
    277   return false;
    278 }
    279 
    280 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
    281 void Module::
    282 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
    283   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
    284   if (!ModFlags) return;
    285 
    286   for (const MDNode *Flag : ModFlags->operands()) {
    287     ModFlagBehavior MFB;
    288     if (Flag->getNumOperands() >= 3 &&
    289         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
    290         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
    291       // Check the operands of the MDNode before accessing the operands.
    292       // The verifier will actually catch these failures.
    293       MDString *Key = cast<MDString>(Flag->getOperand(1));
    294       Metadata *Val = Flag->getOperand(2);
    295       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
    296     }
    297   }
    298 }
    299 
    300 /// Return the corresponding value if Key appears in module flags, otherwise
    301 /// return null.
    302 Metadata *Module::getModuleFlag(StringRef Key) const {
    303   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
    304   getModuleFlagsMetadata(ModuleFlags);
    305   for (const ModuleFlagEntry &MFE : ModuleFlags) {
    306     if (Key == MFE.Key->getString())
    307       return MFE.Val;
    308   }
    309   return nullptr;
    310 }
    311 
    312 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
    313 /// represents module-level flags. This method returns null if there are no
    314 /// module-level flags.
    315 NamedMDNode *Module::getModuleFlagsMetadata() const {
    316   return getNamedMetadata("llvm.module.flags");
    317 }
    318 
    319 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
    320 /// represents module-level flags. If module-level flags aren't found, it
    321 /// creates the named metadata that contains them.
    322 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
    323   return getOrInsertNamedMetadata("llvm.module.flags");
    324 }
    325 
    326 /// addModuleFlag - Add a module-level flag to the module-level flags
    327 /// metadata. It will create the module-level flags named metadata if it doesn't
    328 /// already exist.
    329 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    330                            Metadata *Val) {
    331   Type *Int32Ty = Type::getInt32Ty(Context);
    332   Metadata *Ops[3] = {
    333       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
    334       MDString::get(Context, Key), Val};
    335   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
    336 }
    337 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    338                            Constant *Val) {
    339   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
    340 }
    341 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    342                            uint32_t Val) {
    343   Type *Int32Ty = Type::getInt32Ty(Context);
    344   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
    345 }
    346 void Module::addModuleFlag(MDNode *Node) {
    347   assert(Node->getNumOperands() == 3 &&
    348          "Invalid number of operands for module flag!");
    349   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
    350          isa<MDString>(Node->getOperand(1)) &&
    351          "Invalid operand types for module flag!");
    352   getOrInsertModuleFlagsMetadata()->addOperand(Node);
    353 }
    354 
    355 void Module::setDataLayout(StringRef Desc) {
    356   DL.reset(Desc);
    357 }
    358 
    359 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
    360 
    361 const DataLayout &Module::getDataLayout() const { return DL; }
    362 
    363 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
    364   return cast<DICompileUnit>(CUs->getOperand(Idx));
    365 }
    366 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
    367   return cast<DICompileUnit>(CUs->getOperand(Idx));
    368 }
    369 
    370 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
    371   while (CUs && (Idx < CUs->getNumOperands()) &&
    372          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
    373     ++Idx;
    374 }
    375 
    376 //===----------------------------------------------------------------------===//
    377 // Methods to control the materialization of GlobalValues in the Module.
    378 //
    379 void Module::setMaterializer(GVMaterializer *GVM) {
    380   assert(!Materializer &&
    381          "Module already has a GVMaterializer.  Call materializeAll"
    382          " to clear it out before setting another one.");
    383   Materializer.reset(GVM);
    384 }
    385 
    386 Error Module::materialize(GlobalValue *GV) {
    387   if (!Materializer)
    388     return Error::success();
    389 
    390   return Materializer->materialize(GV);
    391 }
    392 
    393 Error Module::materializeAll() {
    394   if (!Materializer)
    395     return Error::success();
    396   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
    397   return M->materializeModule();
    398 }
    399 
    400 Error Module::materializeMetadata() {
    401   if (!Materializer)
    402     return Error::success();
    403   return Materializer->materializeMetadata();
    404 }
    405 
    406 //===----------------------------------------------------------------------===//
    407 // Other module related stuff.
    408 //
    409 
    410 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
    411   // If we have a materializer, it is possible that some unread function
    412   // uses a type that is currently not visible to a TypeFinder, so ask
    413   // the materializer which types it created.
    414   if (Materializer)
    415     return Materializer->getIdentifiedStructTypes();
    416 
    417   std::vector<StructType *> Ret;
    418   TypeFinder SrcStructTypes;
    419   SrcStructTypes.run(*this, true);
    420   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
    421   return Ret;
    422 }
    423 
    424 // dropAllReferences() - This function causes all the subelements to "let go"
    425 // of all references that they are maintaining.  This allows one to 'delete' a
    426 // whole module at a time, even though there may be circular references... first
    427 // all references are dropped, and all use counts go to zero.  Then everything
    428 // is deleted for real.  Note that no operations are valid on an object that
    429 // has "dropped all references", except operator delete.
    430 //
    431 void Module::dropAllReferences() {
    432   for (Function &F : *this)
    433     F.dropAllReferences();
    434 
    435   for (GlobalVariable &GV : globals())
    436     GV.dropAllReferences();
    437 
    438   for (GlobalAlias &GA : aliases())
    439     GA.dropAllReferences();
    440 
    441   for (GlobalIFunc &GIF : ifuncs())
    442     GIF.dropAllReferences();
    443 }
    444 
    445 unsigned Module::getNumberRegisterParameters() const {
    446   auto *Val =
    447       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
    448   if (!Val)
    449     return 0;
    450   return cast<ConstantInt>(Val->getValue())->getZExtValue();
    451 }
    452 
    453 unsigned Module::getDwarfVersion() const {
    454   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
    455   if (!Val)
    456     return 0;
    457   return cast<ConstantInt>(Val->getValue())->getZExtValue();
    458 }
    459 
    460 unsigned Module::getCodeViewFlag() const {
    461   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
    462   if (!Val)
    463     return 0;
    464   return cast<ConstantInt>(Val->getValue())->getZExtValue();
    465 }
    466 
    467 unsigned Module::getInstructionCount() {
    468   unsigned NumInstrs = 0;
    469   for (Function &F : FunctionList)
    470     NumInstrs += F.getInstructionCount();
    471   return NumInstrs;
    472 }
    473 
    474 Comdat *Module::getOrInsertComdat(StringRef Name) {
    475   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
    476   Entry.second.Name = &Entry;
    477   return &Entry.second;
    478 }
    479 
    480 PICLevel::Level Module::getPICLevel() const {
    481   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
    482 
    483   if (!Val)
    484     return PICLevel::NotPIC;
    485 
    486   return static_cast<PICLevel::Level>(
    487       cast<ConstantInt>(Val->getValue())->getZExtValue());
    488 }
    489 
    490 void Module::setPICLevel(PICLevel::Level PL) {
    491   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
    492 }
    493 
    494 PIELevel::Level Module::getPIELevel() const {
    495   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
    496 
    497   if (!Val)
    498     return PIELevel::Default;
    499 
    500   return static_cast<PIELevel::Level>(
    501       cast<ConstantInt>(Val->getValue())->getZExtValue());
    502 }
    503 
    504 void Module::setPIELevel(PIELevel::Level PL) {
    505   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
    506 }
    507 
    508 void Module::setProfileSummary(Metadata *M) {
    509   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
    510 }
    511 
    512 Metadata *Module::getProfileSummary() {
    513   return getModuleFlag("ProfileSummary");
    514 }
    515 
    516 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
    517   OwnedMemoryBuffer = std::move(MB);
    518 }
    519 
    520 bool Module::getRtLibUseGOT() const {
    521   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
    522   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
    523 }
    524 
    525 void Module::setRtLibUseGOT() {
    526   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
    527 }
    528 
    529 GlobalVariable *llvm::collectUsedGlobalVariables(
    530     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
    531   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
    532   GlobalVariable *GV = M.getGlobalVariable(Name);
    533   if (!GV || !GV->hasInitializer())
    534     return GV;
    535 
    536   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
    537   for (Value *Op : Init->operands()) {
    538     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
    539     Set.insert(G);
    540   }
    541   return GV;
    542 }
    543