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