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 bool Module::isValidModFlagBehavior(Value *V, ModFlagBehavior &MFB) {
00263   if (ConstantInt *Behavior = dyn_cast<ConstantInt>(V)) {
00264     uint64_t Val = Behavior->getLimitedValue();
00265     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
00266       MFB = static_cast<ModFlagBehavior>(Val);
00267       return true;
00268     }
00269   }
00270   return false;
00271 }
00272 
00273 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
00274 void Module::
00275 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
00276   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
00277   if (!ModFlags) return;
00278 
00279   for (const MDNode *Flag : ModFlags->operands()) {
00280     ModFlagBehavior MFB;
00281     if (Flag->getNumOperands() >= 3 &&
00282         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
00283         isa<MDString>(Flag->getOperand(1))) {
00284       // Check the operands of the MDNode before accessing the operands.
00285       // The verifier will actually catch these failures.
00286       MDString *Key = cast<MDString>(Flag->getOperand(1));
00287       Value *Val = Flag->getOperand(2);
00288       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
00289     }
00290   }
00291 }
00292 
00293 /// Return the corresponding value if Key appears in module flags, otherwise
00294 /// return null.
00295 Value *Module::getModuleFlag(StringRef Key) const {
00296   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
00297   getModuleFlagsMetadata(ModuleFlags);
00298   for (const ModuleFlagEntry &MFE : ModuleFlags) {
00299     if (Key == MFE.Key->getString())
00300       return MFE.Val;
00301   }
00302   return nullptr;
00303 }
00304 
00305 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
00306 /// represents module-level flags. This method returns null if there are no
00307 /// module-level flags.
00308 NamedMDNode *Module::getModuleFlagsMetadata() const {
00309   return getNamedMetadata("llvm.module.flags");
00310 }
00311 
00312 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
00313 /// represents module-level flags. If module-level flags aren't found, it
00314 /// creates the named metadata that contains them.
00315 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
00316   return getOrInsertNamedMetadata("llvm.module.flags");
00317 }
00318 
00319 /// addModuleFlag - Add a module-level flag to the module-level flags
00320 /// metadata. It will create the module-level flags named metadata if it doesn't
00321 /// already exist.
00322 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00323                            Value *Val) {
00324   Type *Int32Ty = Type::getInt32Ty(Context);
00325   Value *Ops[3] = {
00326     ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
00327   };
00328   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
00329 }
00330 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00331                            uint32_t Val) {
00332   Type *Int32Ty = Type::getInt32Ty(Context);
00333   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
00334 }
00335 void Module::addModuleFlag(MDNode *Node) {
00336   assert(Node->getNumOperands() == 3 &&
00337          "Invalid number of operands for module flag!");
00338   assert(isa<ConstantInt>(Node->getOperand(0)) &&
00339          isa<MDString>(Node->getOperand(1)) &&
00340          "Invalid operand types for module flag!");
00341   getOrInsertModuleFlagsMetadata()->addOperand(Node);
00342 }
00343 
00344 void Module::setDataLayout(StringRef Desc) {
00345   DL.reset(Desc);
00346 
00347   if (Desc.empty()) {
00348     DataLayoutStr = "";
00349   } else {
00350     DataLayoutStr = DL.getStringRepresentation();
00351     // DataLayoutStr is now equivalent to Desc, but since the representation
00352     // is not unique, they may not be identical.
00353   }
00354 }
00355 
00356 void Module::setDataLayout(const DataLayout *Other) {
00357   if (!Other) {
00358     DataLayoutStr = "";
00359     DL.reset("");
00360   } else {
00361     DL = *Other;
00362     DataLayoutStr = DL.getStringRepresentation();
00363   }
00364 }
00365 
00366 const DataLayout *Module::getDataLayout() const {
00367   if (DataLayoutStr.empty())
00368     return nullptr;
00369   return &DL;
00370 }
00371 
00372 // We want reproducible builds, but ModuleID may be a full path so we just use
00373 // the filename to salt the RNG (although it is not guaranteed to be unique).
00374 RandomNumberGenerator &Module::getRNG() const {
00375   if (RNG == nullptr) {
00376     StringRef Salt = sys::path::filename(ModuleID);
00377     RNG = new RandomNumberGenerator(Salt);
00378   }
00379   return *RNG;
00380 }
00381 
00382 //===----------------------------------------------------------------------===//
00383 // Methods to control the materialization of GlobalValues in the Module.
00384 //
00385 void Module::setMaterializer(GVMaterializer *GVM) {
00386   assert(!Materializer &&
00387          "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
00388          " to clear it out before setting another one.");
00389   Materializer.reset(GVM);
00390 }
00391 
00392 bool Module::isMaterializable(const GlobalValue *GV) const {
00393   if (Materializer)
00394     return Materializer->isMaterializable(GV);
00395   return false;
00396 }
00397 
00398 bool Module::isDematerializable(const GlobalValue *GV) const {
00399   if (Materializer)
00400     return Materializer->isDematerializable(GV);
00401   return false;
00402 }
00403 
00404 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
00405   if (!Materializer)
00406     return false;
00407 
00408   std::error_code EC = Materializer->Materialize(GV);
00409   if (!EC)
00410     return false;
00411   if (ErrInfo)
00412     *ErrInfo = EC.message();
00413   return true;
00414 }
00415 
00416 void Module::Dematerialize(GlobalValue *GV) {
00417   if (Materializer)
00418     return Materializer->Dematerialize(GV);
00419 }
00420 
00421 std::error_code Module::materializeAll() {
00422   if (!Materializer)
00423     return std::error_code();
00424   return Materializer->MaterializeModule(this);
00425 }
00426 
00427 std::error_code Module::materializeAllPermanently() {
00428   if (std::error_code EC = materializeAll())
00429     return EC;
00430 
00431   Materializer.reset();
00432   return std::error_code();
00433 }
00434 
00435 //===----------------------------------------------------------------------===//
00436 // Other module related stuff.
00437 //
00438 
00439 
00440 // dropAllReferences() - This function causes all the subelements to "let go"
00441 // of all references that they are maintaining.  This allows one to 'delete' a
00442 // whole module at a time, even though there may be circular references... first
00443 // all references are dropped, and all use counts go to zero.  Then everything
00444 // is deleted for real.  Note that no operations are valid on an object that
00445 // has "dropped all references", except operator delete.
00446 //
00447 void Module::dropAllReferences() {
00448   for (Function &F : *this)
00449     F.dropAllReferences();
00450 
00451   for (GlobalVariable &GV : globals())
00452     GV.dropAllReferences();
00453 
00454   for (GlobalAlias &GA : aliases())
00455     GA.dropAllReferences();
00456 }
00457 
00458 unsigned Module::getDwarfVersion() const {
00459   Value *Val = getModuleFlag("Dwarf Version");
00460   if (!Val)
00461     return dwarf::DWARF_VERSION;
00462   return cast<ConstantInt>(Val)->getZExtValue();
00463 }
00464 
00465 Comdat *Module::getOrInsertComdat(StringRef Name) {
00466   Comdat C;
00467   StringMapEntry<Comdat> &Entry =
00468       ComdatSymTab.GetOrCreateValue(Name, std::move(C));
00469   Entry.second.Name = &Entry;
00470   return &Entry.second;
00471 }