LLVM API Documentation

Module.cpp
Go to the documentation of this file.
00001 //===-- Module.cpp - Implement the Module 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 Module class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Module.h"
00015 #include "SymbolTableListTraitsImpl.h"
00016 #include "llvm/ADT/DenseSet.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DerivedTypes.h"
00022 #include "llvm/IR/GVMaterializer.h"
00023 #include "llvm/IR/InstrTypes.h"
00024 #include "llvm/IR/LLVMContext.h"
00025 #include "llvm/IR/LeakDetector.h"
00026 #include "llvm/Support/Dwarf.h"
00027 #include "llvm/Support/Path.h"
00028 #include "llvm/Support/RandomNumberGenerator.h"
00029 #include <algorithm>
00030 #include <cstdarg>
00031 #include <cstdlib>
00032 using namespace llvm;
00033 
00034 //===----------------------------------------------------------------------===//
00035 // Methods to implement the globals and functions lists.
00036 //
00037 
00038 // Explicit instantiations of SymbolTableListTraits since some of the methods
00039 // are not in the public header file.
00040 template class llvm::SymbolTableListTraits<Function, Module>;
00041 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
00042 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
00043 
00044 //===----------------------------------------------------------------------===//
00045 // Primitive Module methods.
00046 //
00047 
00048 Module::Module(StringRef MID, LLVMContext &C)
00049     : Context(C), Materializer(), ModuleID(MID), RNG(nullptr), DL("") {
00050   ValSymTab = new ValueSymbolTable();
00051   NamedMDSymTab = new StringMap<NamedMDNode *>();
00052   Context.addModule(this);
00053 }
00054 
00055 Module::~Module() {
00056   Context.removeModule(this);
00057   dropAllReferences();
00058   GlobalList.clear();
00059   FunctionList.clear();
00060   AliasList.clear();
00061   NamedMDList.clear();
00062   delete ValSymTab;
00063   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
00064   delete RNG;
00065 }
00066 
00067 /// getNamedValue - Return the first global value in the module with
00068 /// the specified name, of arbitrary type.  This method returns null
00069 /// if a global with the specified name is not found.
00070 GlobalValue *Module::getNamedValue(StringRef Name) const {
00071   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
00072 }
00073 
00074 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
00075 /// This ID is uniqued across modules in the current LLVMContext.
00076 unsigned Module::getMDKindID(StringRef Name) const {
00077   return Context.getMDKindID(Name);
00078 }
00079 
00080 /// getMDKindNames - Populate client supplied SmallVector with the name for
00081 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
00082 /// so it is filled in as an empty string.
00083 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
00084   return Context.getMDKindNames(Result);
00085 }
00086 
00087 
00088 //===----------------------------------------------------------------------===//
00089 // Methods for easy access to the functions in the module.
00090 //
00091 
00092 // getOrInsertFunction - Look up the specified function in the module symbol
00093 // table.  If it does not exist, add a prototype for the function and return
00094 // it.  This is nice because it allows most passes to get away with not handling
00095 // the symbol table directly for this common task.
00096 //
00097 Constant *Module::getOrInsertFunction(StringRef Name,
00098                                       FunctionType *Ty,
00099                                       AttributeSet AttributeList) {
00100   // See if we have a definition for the specified function already.
00101   GlobalValue *F = getNamedValue(Name);
00102   if (!F) {
00103     // Nope, add it
00104     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
00105     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
00106       New->setAttributes(AttributeList);
00107     FunctionList.push_back(New);
00108     return New;                    // Return the new prototype.
00109   }
00110 
00111   // If the function exists but has the wrong type, return a bitcast to the
00112   // right type.
00113   if (F->getType() != PointerType::getUnqual(Ty))
00114     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
00115 
00116   // Otherwise, we just found the existing function or a prototype.
00117   return F;
00118 }
00119 
00120 Constant *Module::getOrInsertFunction(StringRef Name,
00121                                       FunctionType *Ty) {
00122   return getOrInsertFunction(Name, Ty, AttributeSet());
00123 }
00124 
00125 // getOrInsertFunction - Look up the specified function in the module symbol
00126 // table.  If it does not exist, add a prototype for the function and return it.
00127 // This version of the method takes a null terminated list of function
00128 // arguments, which makes it easier for clients to use.
00129 //
00130 Constant *Module::getOrInsertFunction(StringRef Name,
00131                                       AttributeSet AttributeList,
00132                                       Type *RetTy, ...) {
00133   va_list Args;
00134   va_start(Args, RetTy);
00135 
00136   // Build the list of argument types...
00137   std::vector<Type*> ArgTys;
00138   while (Type *ArgTy = va_arg(Args, Type*))
00139     ArgTys.push_back(ArgTy);
00140 
00141   va_end(Args);
00142 
00143   // Build the function type and chain to the other getOrInsertFunction...
00144   return getOrInsertFunction(Name,
00145                              FunctionType::get(RetTy, ArgTys, false),
00146                              AttributeList);
00147 }
00148 
00149 Constant *Module::getOrInsertFunction(StringRef Name,
00150                                       Type *RetTy, ...) {
00151   va_list Args;
00152   va_start(Args, RetTy);
00153 
00154   // Build the list of argument types...
00155   std::vector<Type*> ArgTys;
00156   while (Type *ArgTy = va_arg(Args, Type*))
00157     ArgTys.push_back(ArgTy);
00158 
00159   va_end(Args);
00160 
00161   // Build the function type and chain to the other getOrInsertFunction...
00162   return getOrInsertFunction(Name,
00163                              FunctionType::get(RetTy, ArgTys, false),
00164                              AttributeSet());
00165 }
00166 
00167 // getFunction - Look up the specified function in the module symbol table.
00168 // If it does not exist, return null.
00169 //
00170 Function *Module::getFunction(StringRef Name) const {
00171   return dyn_cast_or_null<Function>(getNamedValue(Name));
00172 }
00173 
00174 //===----------------------------------------------------------------------===//
00175 // Methods for easy access to the global variables in the module.
00176 //
00177 
00178 /// getGlobalVariable - Look up the specified global variable in the module
00179 /// symbol table.  If it does not exist, return null.  The type argument
00180 /// should be the underlying type of the global, i.e., it should not have
00181 /// the top-level PointerType, which represents the address of the global.
00182 /// If AllowLocal is set to true, this function will return types that
00183 /// have an local. By default, these types are not returned.
00184 ///
00185 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
00186   if (GlobalVariable *Result =
00187       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
00188     if (AllowLocal || !Result->hasLocalLinkage())
00189       return Result;
00190   return nullptr;
00191 }
00192 
00193 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
00194 ///   1. If it does not exist, add a declaration of the global and return it.
00195 ///   2. Else, the global exists but has the wrong type: return the function
00196 ///      with a constantexpr cast to the right type.
00197 ///   3. Finally, if the existing global is the correct declaration, return the
00198 ///      existing global.
00199 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
00200   // See if we have a definition for the specified global already.
00201   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
00202   if (!GV) {
00203     // Nope, add it
00204     GlobalVariable *New =
00205       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
00206                          nullptr, Name);
00207      return New;                    // Return the new declaration.
00208   }
00209 
00210   // If the variable exists but has the wrong type, return a bitcast to the
00211   // right type.
00212   Type *GVTy = GV->getType();
00213   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
00214   if (GVTy != PTy)
00215     return ConstantExpr::getBitCast(GV, PTy);
00216 
00217   // Otherwise, we just found the existing function or a prototype.
00218   return GV;
00219 }
00220 
00221 //===----------------------------------------------------------------------===//
00222 // Methods for easy access to the global variables in the module.
00223 //
00224 
00225 // getNamedAlias - Look up the specified global in the module symbol table.
00226 // If it does not exist, return null.
00227 //
00228 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
00229   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
00230 }
00231 
00232 /// getNamedMetadata - Return the first NamedMDNode in the module with the
00233 /// specified name. This method returns null if a NamedMDNode with the
00234 /// specified name is not found.
00235 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
00236   SmallString<256> NameData;
00237   StringRef NameRef = Name.toStringRef(NameData);
00238   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
00239 }
00240 
00241 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
00242 /// with the specified name. This method returns a new NamedMDNode if a
00243 /// NamedMDNode with the specified name is not found.
00244 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
00245   NamedMDNode *&NMD =
00246     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
00247   if (!NMD) {
00248     NMD = new NamedMDNode(Name);
00249     NMD->setParent(this);
00250     NamedMDList.push_back(NMD);
00251   }
00252   return NMD;
00253 }
00254 
00255 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
00256 /// delete it.
00257 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
00258   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
00259   NamedMDList.erase(NMD);
00260 }
00261 
00262 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
00263 void Module::
00264 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
00265   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
00266   if (!ModFlags) return;
00267 
00268   for (const MDNode *Flag : ModFlags->operands()) {
00269     if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
00270         isa<MDString>(Flag->getOperand(1))) {
00271       // Check the operands of the MDNode before accessing the operands.
00272       // The verifier will actually catch these failures.
00273       ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
00274       MDString *Key = cast<MDString>(Flag->getOperand(1));
00275       Value *Val = Flag->getOperand(2);
00276       Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
00277                                       Key, Val));
00278     }
00279   }
00280 }
00281 
00282 /// Return the corresponding value if Key appears in module flags, otherwise
00283 /// return null.
00284 Value *Module::getModuleFlag(StringRef Key) const {
00285   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
00286   getModuleFlagsMetadata(ModuleFlags);
00287   for (const ModuleFlagEntry &MFE : ModuleFlags) {
00288     if (Key == MFE.Key->getString())
00289       return MFE.Val;
00290   }
00291   return nullptr;
00292 }
00293 
00294 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
00295 /// represents module-level flags. This method returns null if there are no
00296 /// module-level flags.
00297 NamedMDNode *Module::getModuleFlagsMetadata() const {
00298   return getNamedMetadata("llvm.module.flags");
00299 }
00300 
00301 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
00302 /// represents module-level flags. If module-level flags aren't found, it
00303 /// creates the named metadata that contains them.
00304 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
00305   return getOrInsertNamedMetadata("llvm.module.flags");
00306 }
00307 
00308 /// addModuleFlag - Add a module-level flag to the module-level flags
00309 /// metadata. It will create the module-level flags named metadata if it doesn't
00310 /// already exist.
00311 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00312                            Value *Val) {
00313   Type *Int32Ty = Type::getInt32Ty(Context);
00314   Value *Ops[3] = {
00315     ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
00316   };
00317   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
00318 }
00319 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00320                            uint32_t Val) {
00321   Type *Int32Ty = Type::getInt32Ty(Context);
00322   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
00323 }
00324 void Module::addModuleFlag(MDNode *Node) {
00325   assert(Node->getNumOperands() == 3 &&
00326          "Invalid number of operands for module flag!");
00327   assert(isa<ConstantInt>(Node->getOperand(0)) &&
00328          isa<MDString>(Node->getOperand(1)) &&
00329          "Invalid operand types for module flag!");
00330   getOrInsertModuleFlagsMetadata()->addOperand(Node);
00331 }
00332 
00333 void Module::setDataLayout(StringRef Desc) {
00334   DL.reset(Desc);
00335 
00336   if (Desc.empty()) {
00337     DataLayoutStr = "";
00338   } else {
00339     DataLayoutStr = DL.getStringRepresentation();
00340     // DataLayoutStr is now equivalent to Desc, but since the representation
00341     // is not unique, they may not be identical.
00342   }
00343 }
00344 
00345 void Module::setDataLayout(const DataLayout *Other) {
00346   if (!Other) {
00347     DataLayoutStr = "";
00348     DL.reset("");
00349   } else {
00350     DL = *Other;
00351     DataLayoutStr = DL.getStringRepresentation();
00352   }
00353 }
00354 
00355 const DataLayout *Module::getDataLayout() const {
00356   if (DataLayoutStr.empty())
00357     return nullptr;
00358   return &DL;
00359 }
00360 
00361 // We want reproducible builds, but ModuleID may be a full path so we just use
00362 // the filename to salt the RNG (although it is not guaranteed to be unique).
00363 RandomNumberGenerator &Module::getRNG() const {
00364   if (RNG == nullptr) {
00365     StringRef Salt = sys::path::filename(ModuleID);
00366     RNG = new RandomNumberGenerator(Salt);
00367   }
00368   return *RNG;
00369 }
00370 
00371 //===----------------------------------------------------------------------===//
00372 // Methods to control the materialization of GlobalValues in the Module.
00373 //
00374 void Module::setMaterializer(GVMaterializer *GVM) {
00375   assert(!Materializer &&
00376          "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
00377          " to clear it out before setting another one.");
00378   Materializer.reset(GVM);
00379 }
00380 
00381 bool Module::isMaterializable(const GlobalValue *GV) const {
00382   if (Materializer)
00383     return Materializer->isMaterializable(GV);
00384   return false;
00385 }
00386 
00387 bool Module::isDematerializable(const GlobalValue *GV) const {
00388   if (Materializer)
00389     return Materializer->isDematerializable(GV);
00390   return false;
00391 }
00392 
00393 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
00394   if (!Materializer)
00395     return false;
00396 
00397   std::error_code EC = Materializer->Materialize(GV);
00398   if (!EC)
00399     return false;
00400   if (ErrInfo)
00401     *ErrInfo = EC.message();
00402   return true;
00403 }
00404 
00405 void Module::Dematerialize(GlobalValue *GV) {
00406   if (Materializer)
00407     return Materializer->Dematerialize(GV);
00408 }
00409 
00410 std::error_code Module::materializeAll() {
00411   if (!Materializer)
00412     return std::error_code();
00413   return Materializer->MaterializeModule(this);
00414 }
00415 
00416 std::error_code Module::materializeAllPermanently(bool ReleaseBuffer) {
00417   if (std::error_code EC = materializeAll())
00418     return EC;
00419 
00420   if (ReleaseBuffer)
00421     Materializer->releaseBuffer();
00422 
00423   Materializer.reset();
00424   return std::error_code();
00425 }
00426 
00427 //===----------------------------------------------------------------------===//
00428 // Other module related stuff.
00429 //
00430 
00431 
00432 // dropAllReferences() - This function causes all the subelements to "let go"
00433 // of all references that they are maintaining.  This allows one to 'delete' a
00434 // whole module at a time, even though there may be circular references... first
00435 // all references are dropped, and all use counts go to zero.  Then everything
00436 // is deleted for real.  Note that no operations are valid on an object that
00437 // has "dropped all references", except operator delete.
00438 //
00439 void Module::dropAllReferences() {
00440   for (Function &F : *this)
00441     F.dropAllReferences();
00442 
00443   for (GlobalVariable &GV : globals())
00444     GV.dropAllReferences();
00445 
00446   for (GlobalAlias &GA : aliases())
00447     GA.dropAllReferences();
00448 }
00449 
00450 unsigned Module::getDwarfVersion() const {
00451   Value *Val = getModuleFlag("Dwarf Version");
00452   if (!Val)
00453     return dwarf::DWARF_VERSION;
00454   return cast<ConstantInt>(Val)->getZExtValue();
00455 }
00456 
00457 Comdat *Module::getOrInsertComdat(StringRef Name) {
00458   Comdat C;
00459   StringMapEntry<Comdat> &Entry =
00460       ComdatSymTab.GetOrCreateValue(Name, std::move(C));
00461   Entry.second.Name = &Entry;
00462   return &Entry.second;
00463 }