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/DenseSet.h"
     17 #include "llvm/ADT/STLExtras.h"
     18 #include "llvm/ADT/SmallString.h"
     19 #include "llvm/ADT/StringExtras.h"
     20 #include "llvm/IR/Constants.h"
     21 #include "llvm/IR/DerivedTypes.h"
     22 #include "llvm/IR/GVMaterializer.h"
     23 #include "llvm/IR/InstrTypes.h"
     24 #include "llvm/IR/LLVMContext.h"
     25 #include "llvm/IR/LeakDetector.h"
     26 #include "llvm/Support/Dwarf.h"
     27 #include "llvm/Support/Path.h"
     28 #include "llvm/Support/RandomNumberGenerator.h"
     29 #include <algorithm>
     30 #include <cstdarg>
     31 #include <cstdlib>
     32 using namespace llvm;
     33 
     34 //===----------------------------------------------------------------------===//
     35 // Methods to implement the globals and functions lists.
     36 //
     37 
     38 // Explicit instantiations of SymbolTableListTraits since some of the methods
     39 // are not in the public header file.
     40 template class llvm::SymbolTableListTraits<Function, Module>;
     41 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
     42 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
     43 
     44 //===----------------------------------------------------------------------===//
     45 // Primitive Module methods.
     46 //
     47 
     48 Module::Module(StringRef MID, LLVMContext &C)
     49     : Context(C), Materializer(), ModuleID(MID), RNG(nullptr), DL("") {
     50   ValSymTab = new ValueSymbolTable();
     51   NamedMDSymTab = new StringMap<NamedMDNode *>();
     52   Context.addModule(this);
     53 }
     54 
     55 Module::~Module() {
     56   Context.removeModule(this);
     57   dropAllReferences();
     58   GlobalList.clear();
     59   FunctionList.clear();
     60   AliasList.clear();
     61   NamedMDList.clear();
     62   delete ValSymTab;
     63   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
     64   delete RNG;
     65 }
     66 
     67 /// getNamedValue - Return the first global value in the module with
     68 /// the specified name, of arbitrary type.  This method returns null
     69 /// if a global with the specified name is not found.
     70 GlobalValue *Module::getNamedValue(StringRef Name) const {
     71   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
     72 }
     73 
     74 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
     75 /// This ID is uniqued across modules in the current LLVMContext.
     76 unsigned Module::getMDKindID(StringRef Name) const {
     77   return Context.getMDKindID(Name);
     78 }
     79 
     80 /// getMDKindNames - Populate client supplied SmallVector with the name for
     81 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
     82 /// so it is filled in as an empty string.
     83 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
     84   return Context.getMDKindNames(Result);
     85 }
     86 
     87 
     88 //===----------------------------------------------------------------------===//
     89 // Methods for easy access to the functions in the module.
     90 //
     91 
     92 // getOrInsertFunction - Look up the specified function in the module symbol
     93 // table.  If it does not exist, add a prototype for the function and return
     94 // it.  This is nice because it allows most passes to get away with not handling
     95 // the symbol table directly for this common task.
     96 //
     97 Constant *Module::getOrInsertFunction(StringRef Name,
     98                                       FunctionType *Ty,
     99                                       AttributeSet AttributeList) {
    100   // See if we have a definition for the specified function already.
    101   GlobalValue *F = getNamedValue(Name);
    102   if (!F) {
    103     // Nope, add it
    104     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
    105     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
    106       New->setAttributes(AttributeList);
    107     FunctionList.push_back(New);
    108     return New;                    // Return the new prototype.
    109   }
    110 
    111   // If the function exists but has the wrong type, return a bitcast to the
    112   // right type.
    113   if (F->getType() != PointerType::getUnqual(Ty))
    114     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
    115 
    116   // Otherwise, we just found the existing function or a prototype.
    117   return F;
    118 }
    119 
    120 Constant *Module::getOrInsertFunction(StringRef Name,
    121                                       FunctionType *Ty) {
    122   return getOrInsertFunction(Name, Ty, AttributeSet());
    123 }
    124 
    125 // getOrInsertFunction - Look up the specified function in the module symbol
    126 // table.  If it does not exist, add a prototype for the function and return it.
    127 // This version of the method takes a null terminated list of function
    128 // arguments, which makes it easier for clients to use.
    129 //
    130 Constant *Module::getOrInsertFunction(StringRef Name,
    131                                       AttributeSet AttributeList,
    132                                       Type *RetTy, ...) {
    133   va_list Args;
    134   va_start(Args, RetTy);
    135 
    136   // Build the list of argument types...
    137   std::vector<Type*> ArgTys;
    138   while (Type *ArgTy = va_arg(Args, Type*))
    139     ArgTys.push_back(ArgTy);
    140 
    141   va_end(Args);
    142 
    143   // Build the function type and chain to the other getOrInsertFunction...
    144   return getOrInsertFunction(Name,
    145                              FunctionType::get(RetTy, ArgTys, false),
    146                              AttributeList);
    147 }
    148 
    149 Constant *Module::getOrInsertFunction(StringRef Name,
    150                                       Type *RetTy, ...) {
    151   va_list Args;
    152   va_start(Args, RetTy);
    153 
    154   // Build the list of argument types...
    155   std::vector<Type*> ArgTys;
    156   while (Type *ArgTy = va_arg(Args, Type*))
    157     ArgTys.push_back(ArgTy);
    158 
    159   va_end(Args);
    160 
    161   // Build the function type and chain to the other getOrInsertFunction...
    162   return getOrInsertFunction(Name,
    163                              FunctionType::get(RetTy, ArgTys, false),
    164                              AttributeSet());
    165 }
    166 
    167 // getFunction - Look up the specified function in the module symbol table.
    168 // If it does not exist, return null.
    169 //
    170 Function *Module::getFunction(StringRef Name) const {
    171   return dyn_cast_or_null<Function>(getNamedValue(Name));
    172 }
    173 
    174 //===----------------------------------------------------------------------===//
    175 // Methods for easy access to the global variables in the module.
    176 //
    177 
    178 /// getGlobalVariable - Look up the specified global variable in the module
    179 /// symbol table.  If it does not exist, return null.  The type argument
    180 /// should be the underlying type of the global, i.e., it should not have
    181 /// the top-level PointerType, which represents the address of the global.
    182 /// If AllowLocal is set to true, this function will return types that
    183 /// have an local. By default, these types are not returned.
    184 ///
    185 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
    186   if (GlobalVariable *Result =
    187       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
    188     if (AllowLocal || !Result->hasLocalLinkage())
    189       return Result;
    190   return nullptr;
    191 }
    192 
    193 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
    194 ///   1. If it does not exist, add a declaration of the global and return it.
    195 ///   2. Else, the global exists but has the wrong type: return the function
    196 ///      with a constantexpr cast to the right type.
    197 ///   3. Finally, if the existing global is the correct declaration, return the
    198 ///      existing global.
    199 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
    200   // See if we have a definition for the specified global already.
    201   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
    202   if (!GV) {
    203     // Nope, add it
    204     GlobalVariable *New =
    205       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
    206                          nullptr, Name);
    207      return New;                    // Return the new declaration.
    208   }
    209 
    210   // If the variable exists but has the wrong type, return a bitcast to the
    211   // right type.
    212   Type *GVTy = GV->getType();
    213   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
    214   if (GVTy != PTy)
    215     return ConstantExpr::getBitCast(GV, PTy);
    216 
    217   // Otherwise, we just found the existing function or a prototype.
    218   return GV;
    219 }
    220 
    221 //===----------------------------------------------------------------------===//
    222 // Methods for easy access to the global variables in the module.
    223 //
    224 
    225 // getNamedAlias - Look up the specified global in the module symbol table.
    226 // If it does not exist, return null.
    227 //
    228 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
    229   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
    230 }
    231 
    232 /// getNamedMetadata - Return the first NamedMDNode in the module with the
    233 /// specified name. This method returns null if a NamedMDNode with the
    234 /// specified name is not found.
    235 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
    236   SmallString<256> NameData;
    237   StringRef NameRef = Name.toStringRef(NameData);
    238   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
    239 }
    240 
    241 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
    242 /// with the specified name. This method returns a new NamedMDNode if a
    243 /// NamedMDNode with the specified name is not found.
    244 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
    245   NamedMDNode *&NMD =
    246     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
    247   if (!NMD) {
    248     NMD = new NamedMDNode(Name);
    249     NMD->setParent(this);
    250     NamedMDList.push_back(NMD);
    251   }
    252   return NMD;
    253 }
    254 
    255 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
    256 /// delete it.
    257 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
    258   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
    259   NamedMDList.erase(NMD);
    260 }
    261 
    262 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
    263 void Module::
    264 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
    265   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
    266   if (!ModFlags) return;
    267 
    268   for (const MDNode *Flag : ModFlags->operands()) {
    269     if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
    270         isa<MDString>(Flag->getOperand(1))) {
    271       // Check the operands of the MDNode before accessing the operands.
    272       // The verifier will actually catch these failures.
    273       ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
    274       MDString *Key = cast<MDString>(Flag->getOperand(1));
    275       Value *Val = Flag->getOperand(2);
    276       Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
    277                                       Key, Val));
    278     }
    279   }
    280 }
    281 
    282 /// Return the corresponding value if Key appears in module flags, otherwise
    283 /// return null.
    284 Value *Module::getModuleFlag(StringRef Key) const {
    285   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
    286   getModuleFlagsMetadata(ModuleFlags);
    287   for (const ModuleFlagEntry &MFE : ModuleFlags) {
    288     if (Key == MFE.Key->getString())
    289       return MFE.Val;
    290   }
    291   return nullptr;
    292 }
    293 
    294 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
    295 /// represents module-level flags. This method returns null if there are no
    296 /// module-level flags.
    297 NamedMDNode *Module::getModuleFlagsMetadata() const {
    298   return getNamedMetadata("llvm.module.flags");
    299 }
    300 
    301 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
    302 /// represents module-level flags. If module-level flags aren't found, it
    303 /// creates the named metadata that contains them.
    304 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
    305   return getOrInsertNamedMetadata("llvm.module.flags");
    306 }
    307 
    308 /// addModuleFlag - Add a module-level flag to the module-level flags
    309 /// metadata. It will create the module-level flags named metadata if it doesn't
    310 /// already exist.
    311 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    312                            Value *Val) {
    313   Type *Int32Ty = Type::getInt32Ty(Context);
    314   Value *Ops[3] = {
    315     ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
    316   };
    317   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
    318 }
    319 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    320                            uint32_t Val) {
    321   Type *Int32Ty = Type::getInt32Ty(Context);
    322   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
    323 }
    324 void Module::addModuleFlag(MDNode *Node) {
    325   assert(Node->getNumOperands() == 3 &&
    326          "Invalid number of operands for module flag!");
    327   assert(isa<ConstantInt>(Node->getOperand(0)) &&
    328          isa<MDString>(Node->getOperand(1)) &&
    329          "Invalid operand types for module flag!");
    330   getOrInsertModuleFlagsMetadata()->addOperand(Node);
    331 }
    332 
    333 void Module::setDataLayout(StringRef Desc) {
    334   DL.reset(Desc);
    335 
    336   if (Desc.empty()) {
    337     DataLayoutStr = "";
    338   } else {
    339     DataLayoutStr = DL.getStringRepresentation();
    340     // DataLayoutStr is now equivalent to Desc, but since the representation
    341     // is not unique, they may not be identical.
    342   }
    343 }
    344 
    345 void Module::setDataLayout(const DataLayout *Other) {
    346   if (!Other) {
    347     DataLayoutStr = "";
    348     DL.reset("");
    349   } else {
    350     DL = *Other;
    351     DataLayoutStr = DL.getStringRepresentation();
    352   }
    353 }
    354 
    355 const DataLayout *Module::getDataLayout() const {
    356   if (DataLayoutStr.empty())
    357     return nullptr;
    358   return &DL;
    359 }
    360 
    361 // We want reproducible builds, but ModuleID may be a full path so we just use
    362 // the filename to salt the RNG (although it is not guaranteed to be unique).
    363 RandomNumberGenerator &Module::getRNG() const {
    364   if (RNG == nullptr) {
    365     StringRef Salt = sys::path::filename(ModuleID);
    366     RNG = new RandomNumberGenerator(Salt);
    367   }
    368   return *RNG;
    369 }
    370 
    371 //===----------------------------------------------------------------------===//
    372 // Methods to control the materialization of GlobalValues in the Module.
    373 //
    374 void Module::setMaterializer(GVMaterializer *GVM) {
    375   assert(!Materializer &&
    376          "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
    377          " to clear it out before setting another one.");
    378   Materializer.reset(GVM);
    379 }
    380 
    381 bool Module::isMaterializable(const GlobalValue *GV) const {
    382   if (Materializer)
    383     return Materializer->isMaterializable(GV);
    384   return false;
    385 }
    386 
    387 bool Module::isDematerializable(const GlobalValue *GV) const {
    388   if (Materializer)
    389     return Materializer->isDematerializable(GV);
    390   return false;
    391 }
    392 
    393 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
    394   if (!Materializer)
    395     return false;
    396 
    397   std::error_code EC = Materializer->Materialize(GV);
    398   if (!EC)
    399     return false;
    400   if (ErrInfo)
    401     *ErrInfo = EC.message();
    402   return true;
    403 }
    404 
    405 void Module::Dematerialize(GlobalValue *GV) {
    406   if (Materializer)
    407     return Materializer->Dematerialize(GV);
    408 }
    409 
    410 std::error_code Module::materializeAll() {
    411   if (!Materializer)
    412     return std::error_code();
    413   return Materializer->MaterializeModule(this);
    414 }
    415 
    416 std::error_code Module::materializeAllPermanently(bool ReleaseBuffer) {
    417   if (std::error_code EC = materializeAll())
    418     return EC;
    419 
    420   if (ReleaseBuffer)
    421     Materializer->releaseBuffer();
    422 
    423   Materializer.reset();
    424   return std::error_code();
    425 }
    426 
    427 //===----------------------------------------------------------------------===//
    428 // Other module related stuff.
    429 //
    430 
    431 
    432 // dropAllReferences() - This function causes all the subelements to "let go"
    433 // of all references that they are maintaining.  This allows one to 'delete' a
    434 // whole module at a time, even though there may be circular references... first
    435 // all references are dropped, and all use counts go to zero.  Then everything
    436 // is deleted for real.  Note that no operations are valid on an object that
    437 // has "dropped all references", except operator delete.
    438 //
    439 void Module::dropAllReferences() {
    440   for (Function &F : *this)
    441     F.dropAllReferences();
    442 
    443   for (GlobalVariable &GV : globals())
    444     GV.dropAllReferences();
    445 
    446   for (GlobalAlias &GA : aliases())
    447     GA.dropAllReferences();
    448 }
    449 
    450 unsigned Module::getDwarfVersion() const {
    451   Value *Val = getModuleFlag("Dwarf Version");
    452   if (!Val)
    453     return dwarf::DWARF_VERSION;
    454   return cast<ConstantInt>(Val)->getZExtValue();
    455 }
    456 
    457 Comdat *Module::getOrInsertComdat(StringRef Name) {
    458   Comdat C;
    459   StringMapEntry<Comdat> &Entry =
    460       ComdatSymTab.GetOrCreateValue(Name, std::move(C));
    461   Entry.second.Name = &Entry;
    462   return &Entry.second;
    463 }
    464