Module.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
1//===-- Module.cpp - Implement the Module class ---------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Module class for the IR library. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/IR/Module.h" 15#include "SymbolTableListTraitsImpl.h" 16#include "llvm/ADT/DenseSet.h" 17#include "llvm/ADT/STLExtras.h" 18#include "llvm/ADT/SmallString.h" 19#include "llvm/ADT/StringExtras.h" 20#include "llvm/IR/Constants.h" 21#include "llvm/IR/DerivedTypes.h" 22#include "llvm/IR/GVMaterializer.h" 23#include "llvm/IR/InstrTypes.h" 24#include "llvm/IR/LLVMContext.h" 25#include "llvm/IR/LeakDetector.h" 26#include "llvm/Support/Dwarf.h" 27#include <algorithm> 28#include <cstdarg> 29#include <cstdlib> 30using namespace llvm; 31 32//===----------------------------------------------------------------------===// 33// Methods to implement the globals and functions lists. 34// 35 36// Explicit instantiations of SymbolTableListTraits since some of the methods 37// are not in the public header file. 38template class llvm::SymbolTableListTraits<Function, Module>; 39template class llvm::SymbolTableListTraits<GlobalVariable, Module>; 40template class llvm::SymbolTableListTraits<GlobalAlias, Module>; 41 42//===----------------------------------------------------------------------===// 43// Primitive Module methods. 44// 45 46Module::Module(StringRef MID, LLVMContext &C) 47 : Context(C), Materializer(), ModuleID(MID), DL("") { 48 ValSymTab = new ValueSymbolTable(); 49 NamedMDSymTab = new StringMap<NamedMDNode *>(); 50 Context.addModule(this); 51} 52 53Module::~Module() { 54 Context.removeModule(this); 55 dropAllReferences(); 56 GlobalList.clear(); 57 FunctionList.clear(); 58 AliasList.clear(); 59 NamedMDList.clear(); 60 delete ValSymTab; 61 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab); 62} 63 64/// getNamedValue - Return the first global value in the module with 65/// the specified name, of arbitrary type. This method returns null 66/// if a global with the specified name is not found. 67GlobalValue *Module::getNamedValue(StringRef Name) const { 68 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 69} 70 71/// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 72/// This ID is uniqued across modules in the current LLVMContext. 73unsigned Module::getMDKindID(StringRef Name) const { 74 return Context.getMDKindID(Name); 75} 76 77/// getMDKindNames - Populate client supplied SmallVector with the name for 78/// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 79/// so it is filled in as an empty string. 80void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 81 return Context.getMDKindNames(Result); 82} 83 84 85//===----------------------------------------------------------------------===// 86// Methods for easy access to the functions in the module. 87// 88 89// getOrInsertFunction - Look up the specified function in the module symbol 90// table. If it does not exist, add a prototype for the function and return 91// it. This is nice because it allows most passes to get away with not handling 92// the symbol table directly for this common task. 93// 94Constant *Module::getOrInsertFunction(StringRef Name, 95 FunctionType *Ty, 96 AttributeSet AttributeList) { 97 // See if we have a definition for the specified function already. 98 GlobalValue *F = getNamedValue(Name); 99 if (!F) { 100 // Nope, add it 101 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name); 102 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 103 New->setAttributes(AttributeList); 104 FunctionList.push_back(New); 105 return New; // Return the new prototype. 106 } 107 108 // If the function exists but has the wrong type, return a bitcast to the 109 // right type. 110 if (F->getType() != PointerType::getUnqual(Ty)) 111 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty)); 112 113 // Otherwise, we just found the existing function or a prototype. 114 return F; 115} 116 117Constant *Module::getOrInsertFunction(StringRef Name, 118 FunctionType *Ty) { 119 return getOrInsertFunction(Name, Ty, AttributeSet()); 120} 121 122// getOrInsertFunction - Look up the specified function in the module symbol 123// table. If it does not exist, add a prototype for the function and return it. 124// This version of the method takes a null terminated list of function 125// arguments, which makes it easier for clients to use. 126// 127Constant *Module::getOrInsertFunction(StringRef Name, 128 AttributeSet AttributeList, 129 Type *RetTy, ...) { 130 va_list Args; 131 va_start(Args, RetTy); 132 133 // Build the list of argument types... 134 std::vector<Type*> ArgTys; 135 while (Type *ArgTy = va_arg(Args, Type*)) 136 ArgTys.push_back(ArgTy); 137 138 va_end(Args); 139 140 // Build the function type and chain to the other getOrInsertFunction... 141 return getOrInsertFunction(Name, 142 FunctionType::get(RetTy, ArgTys, false), 143 AttributeList); 144} 145 146Constant *Module::getOrInsertFunction(StringRef Name, 147 Type *RetTy, ...) { 148 va_list Args; 149 va_start(Args, RetTy); 150 151 // Build the list of argument types... 152 std::vector<Type*> ArgTys; 153 while (Type *ArgTy = va_arg(Args, Type*)) 154 ArgTys.push_back(ArgTy); 155 156 va_end(Args); 157 158 // Build the function type and chain to the other getOrInsertFunction... 159 return getOrInsertFunction(Name, 160 FunctionType::get(RetTy, ArgTys, false), 161 AttributeSet()); 162} 163 164// getFunction - Look up the specified function in the module symbol table. 165// If it does not exist, return null. 166// 167Function *Module::getFunction(StringRef Name) const { 168 return dyn_cast_or_null<Function>(getNamedValue(Name)); 169} 170 171//===----------------------------------------------------------------------===// 172// Methods for easy access to the global variables in the module. 173// 174 175/// getGlobalVariable - Look up the specified global variable in the module 176/// symbol table. If it does not exist, return null. The type argument 177/// should be the underlying type of the global, i.e., it should not have 178/// the top-level PointerType, which represents the address of the global. 179/// If AllowLocal is set to true, this function will return types that 180/// have an local. By default, these types are not returned. 181/// 182GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) { 183 if (GlobalVariable *Result = 184 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 185 if (AllowLocal || !Result->hasLocalLinkage()) 186 return Result; 187 return nullptr; 188} 189 190/// getOrInsertGlobal - Look up the specified global in the module symbol table. 191/// 1. If it does not exist, add a declaration of the global and return it. 192/// 2. Else, the global exists but has the wrong type: return the function 193/// with a constantexpr cast to the right type. 194/// 3. Finally, if the existing global is the correct declaration, return the 195/// existing global. 196Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 197 // See if we have a definition for the specified global already. 198 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 199 if (!GV) { 200 // Nope, add it 201 GlobalVariable *New = 202 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 203 nullptr, Name); 204 return New; // Return the new declaration. 205 } 206 207 // If the variable exists but has the wrong type, return a bitcast to the 208 // right type. 209 Type *GVTy = GV->getType(); 210 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 211 if (GVTy != PTy) 212 return ConstantExpr::getBitCast(GV, PTy); 213 214 // Otherwise, we just found the existing function or a prototype. 215 return GV; 216} 217 218//===----------------------------------------------------------------------===// 219// Methods for easy access to the global variables in the module. 220// 221 222// getNamedAlias - Look up the specified global in the module symbol table. 223// If it does not exist, return null. 224// 225GlobalAlias *Module::getNamedAlias(StringRef Name) const { 226 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 227} 228 229/// getNamedMetadata - Return the first NamedMDNode in the module with the 230/// specified name. This method returns null if a NamedMDNode with the 231/// specified name is not found. 232NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 233 SmallString<256> NameData; 234 StringRef NameRef = Name.toStringRef(NameData); 235 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef); 236} 237 238/// getOrInsertNamedMetadata - Return the first named MDNode in the module 239/// with the specified name. This method returns a new NamedMDNode if a 240/// NamedMDNode with the specified name is not found. 241NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 242 NamedMDNode *&NMD = 243 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name]; 244 if (!NMD) { 245 NMD = new NamedMDNode(Name); 246 NMD->setParent(this); 247 NamedMDList.push_back(NMD); 248 } 249 return NMD; 250} 251 252/// eraseNamedMetadata - Remove the given NamedMDNode from this module and 253/// delete it. 254void Module::eraseNamedMetadata(NamedMDNode *NMD) { 255 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName()); 256 NamedMDList.erase(NMD); 257} 258 259/// getModuleFlagsMetadata - Returns the module flags in the provided vector. 260void Module:: 261getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 262 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 263 if (!ModFlags) return; 264 265 for (const MDNode *Flag : ModFlags->operands()) { 266 if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) && 267 isa<MDString>(Flag->getOperand(1))) { 268 // Check the operands of the MDNode before accessing the operands. 269 // The verifier will actually catch these failures. 270 ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0)); 271 MDString *Key = cast<MDString>(Flag->getOperand(1)); 272 Value *Val = Flag->getOperand(2); 273 Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()), 274 Key, Val)); 275 } 276 } 277} 278 279/// Return the corresponding value if Key appears in module flags, otherwise 280/// return null. 281Value *Module::getModuleFlag(StringRef Key) const { 282 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 283 getModuleFlagsMetadata(ModuleFlags); 284 for (const ModuleFlagEntry &MFE : ModuleFlags) { 285 if (Key == MFE.Key->getString()) 286 return MFE.Val; 287 } 288 return nullptr; 289} 290 291/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 292/// represents module-level flags. This method returns null if there are no 293/// module-level flags. 294NamedMDNode *Module::getModuleFlagsMetadata() const { 295 return getNamedMetadata("llvm.module.flags"); 296} 297 298/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 299/// represents module-level flags. If module-level flags aren't found, it 300/// creates the named metadata that contains them. 301NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 302 return getOrInsertNamedMetadata("llvm.module.flags"); 303} 304 305/// addModuleFlag - Add a module-level flag to the module-level flags 306/// metadata. It will create the module-level flags named metadata if it doesn't 307/// already exist. 308void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 309 Value *Val) { 310 Type *Int32Ty = Type::getInt32Ty(Context); 311 Value *Ops[3] = { 312 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val 313 }; 314 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 315} 316void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 317 uint32_t Val) { 318 Type *Int32Ty = Type::getInt32Ty(Context); 319 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 320} 321void Module::addModuleFlag(MDNode *Node) { 322 assert(Node->getNumOperands() == 3 && 323 "Invalid number of operands for module flag!"); 324 assert(isa<ConstantInt>(Node->getOperand(0)) && 325 isa<MDString>(Node->getOperand(1)) && 326 "Invalid operand types for module flag!"); 327 getOrInsertModuleFlagsMetadata()->addOperand(Node); 328} 329 330void Module::setDataLayout(StringRef Desc) { 331 DL.reset(Desc); 332 333 if (Desc.empty()) { 334 DataLayoutStr = ""; 335 } else { 336 DataLayoutStr = DL.getStringRepresentation(); 337 // DataLayoutStr is now equivalent to Desc, but since the representation 338 // is not unique, they may not be identical. 339 } 340} 341 342void Module::setDataLayout(const DataLayout *Other) { 343 if (!Other) { 344 DataLayoutStr = ""; 345 DL.reset(""); 346 } else { 347 DL = *Other; 348 DataLayoutStr = DL.getStringRepresentation(); 349 } 350} 351 352const DataLayout *Module::getDataLayout() const { 353 if (DataLayoutStr.empty()) 354 return nullptr; 355 return &DL; 356} 357 358//===----------------------------------------------------------------------===// 359// Methods to control the materialization of GlobalValues in the Module. 360// 361void Module::setMaterializer(GVMaterializer *GVM) { 362 assert(!Materializer && 363 "Module already has a GVMaterializer. Call MaterializeAllPermanently" 364 " to clear it out before setting another one."); 365 Materializer.reset(GVM); 366} 367 368bool Module::isMaterializable(const GlobalValue *GV) const { 369 if (Materializer) 370 return Materializer->isMaterializable(GV); 371 return false; 372} 373 374bool Module::isDematerializable(const GlobalValue *GV) const { 375 if (Materializer) 376 return Materializer->isDematerializable(GV); 377 return false; 378} 379 380bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) { 381 if (!Materializer) 382 return false; 383 384 error_code EC = Materializer->Materialize(GV); 385 if (!EC) 386 return false; 387 if (ErrInfo) 388 *ErrInfo = EC.message(); 389 return true; 390} 391 392void Module::Dematerialize(GlobalValue *GV) { 393 if (Materializer) 394 return Materializer->Dematerialize(GV); 395} 396 397error_code Module::materializeAll() { 398 if (!Materializer) 399 return error_code::success(); 400 return Materializer->MaterializeModule(this); 401} 402 403error_code Module::materializeAllPermanently() { 404 if (error_code EC = materializeAll()) 405 return EC; 406 407 Materializer.reset(); 408 return error_code::success(); 409} 410 411//===----------------------------------------------------------------------===// 412// Other module related stuff. 413// 414 415 416// dropAllReferences() - This function causes all the subelements to "let go" 417// of all references that they are maintaining. This allows one to 'delete' a 418// whole module at a time, even though there may be circular references... first 419// all references are dropped, and all use counts go to zero. Then everything 420// is deleted for real. Note that no operations are valid on an object that 421// has "dropped all references", except operator delete. 422// 423void Module::dropAllReferences() { 424 for(Module::iterator I = begin(), E = end(); I != E; ++I) 425 I->dropAllReferences(); 426 427 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I) 428 I->dropAllReferences(); 429 430 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I) 431 I->dropAllReferences(); 432} 433 434unsigned Module::getDwarfVersion() const { 435 Value *Val = getModuleFlag("Dwarf Version"); 436 if (!Val) 437 return dwarf::DWARF_VERSION; 438 return cast<ConstantInt>(Val)->getZExtValue(); 439} 440