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