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