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/STLExtras.h" 17 #include "llvm/ADT/SmallPtrSet.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/DebugInfoMetadata.h" 23 #include "llvm/IR/GVMaterializer.h" 24 #include "llvm/IR/InstrTypes.h" 25 #include "llvm/IR/LLVMContext.h" 26 #include "llvm/IR/TypeFinder.h" 27 #include "llvm/Support/Dwarf.h" 28 #include "llvm/Support/Error.h" 29 #include "llvm/Support/MemoryBuffer.h" 30 #include "llvm/Support/Path.h" 31 #include "llvm/Support/RandomNumberGenerator.h" 32 #include <algorithm> 33 #include <cstdarg> 34 #include <cstdlib> 35 36 using namespace llvm; 37 38 //===----------------------------------------------------------------------===// 39 // Methods to implement the globals and functions lists. 40 // 41 42 // Explicit instantiations of SymbolTableListTraits since some of the methods 43 // are not in the public header file. 44 template class llvm::SymbolTableListTraits<Function>; 45 template class llvm::SymbolTableListTraits<GlobalVariable>; 46 template class llvm::SymbolTableListTraits<GlobalAlias>; 47 template class llvm::SymbolTableListTraits<GlobalIFunc>; 48 49 //===----------------------------------------------------------------------===// 50 // Primitive Module methods. 51 // 52 53 Module::Module(StringRef MID, LLVMContext &C) 54 : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") { 55 ValSymTab = new ValueSymbolTable(); 56 NamedMDSymTab = new StringMap<NamedMDNode *>(); 57 Context.addModule(this); 58 } 59 60 Module::~Module() { 61 Context.removeModule(this); 62 dropAllReferences(); 63 GlobalList.clear(); 64 FunctionList.clear(); 65 AliasList.clear(); 66 IFuncList.clear(); 67 NamedMDList.clear(); 68 delete ValSymTab; 69 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab); 70 } 71 72 RandomNumberGenerator *Module::createRNG(const Pass* P) const { 73 SmallString<32> Salt(P->getPassName()); 74 75 // This RNG is guaranteed to produce the same random stream only 76 // when the Module ID and thus the input filename is the same. This 77 // might be problematic if the input filename extension changes 78 // (e.g. from .c to .bc or .ll). 79 // 80 // We could store this salt in NamedMetadata, but this would make 81 // the parameter non-const. This would unfortunately make this 82 // interface unusable by any Machine passes, since they only have a 83 // const reference to their IR Module. Alternatively we can always 84 // store salt metadata from the Module constructor. 85 Salt += sys::path::filename(getModuleIdentifier()); 86 87 return new RandomNumberGenerator(Salt); 88 } 89 90 /// getNamedValue - Return the first global value in the module with 91 /// the specified name, of arbitrary type. This method returns null 92 /// if a global with the specified name is not found. 93 GlobalValue *Module::getNamedValue(StringRef Name) const { 94 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 95 } 96 97 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 98 /// This ID is uniqued across modules in the current LLVMContext. 99 unsigned Module::getMDKindID(StringRef Name) const { 100 return Context.getMDKindID(Name); 101 } 102 103 /// getMDKindNames - Populate client supplied SmallVector with the name for 104 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 105 /// so it is filled in as an empty string. 106 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 107 return Context.getMDKindNames(Result); 108 } 109 110 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 111 return Context.getOperandBundleTags(Result); 112 } 113 114 //===----------------------------------------------------------------------===// 115 // Methods for easy access to the functions in the module. 116 // 117 118 // getOrInsertFunction - Look up the specified function in the module symbol 119 // table. If it does not exist, add a prototype for the function and return 120 // it. This is nice because it allows most passes to get away with not handling 121 // the symbol table directly for this common task. 122 // 123 Constant *Module::getOrInsertFunction(StringRef Name, 124 FunctionType *Ty, 125 AttributeSet AttributeList) { 126 // See if we have a definition for the specified function already. 127 GlobalValue *F = getNamedValue(Name); 128 if (!F) { 129 // Nope, add it 130 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name); 131 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 132 New->setAttributes(AttributeList); 133 FunctionList.push_back(New); 134 return New; // Return the new prototype. 135 } 136 137 // If the function exists but has the wrong type, return a bitcast to the 138 // right type. 139 if (F->getType() != PointerType::getUnqual(Ty)) 140 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty)); 141 142 // Otherwise, we just found the existing function or a prototype. 143 return F; 144 } 145 146 Constant *Module::getOrInsertFunction(StringRef Name, 147 FunctionType *Ty) { 148 return getOrInsertFunction(Name, Ty, AttributeSet()); 149 } 150 151 // getOrInsertFunction - Look up the specified function in the module symbol 152 // table. If it does not exist, add a prototype for the function and return it. 153 // This version of the method takes a null terminated list of function 154 // arguments, which makes it easier for clients to use. 155 // 156 Constant *Module::getOrInsertFunction(StringRef Name, 157 AttributeSet AttributeList, 158 Type *RetTy, ...) { 159 va_list Args; 160 va_start(Args, RetTy); 161 162 // Build the list of argument types... 163 std::vector<Type*> ArgTys; 164 while (Type *ArgTy = va_arg(Args, Type*)) 165 ArgTys.push_back(ArgTy); 166 167 va_end(Args); 168 169 // Build the function type and chain to the other getOrInsertFunction... 170 return getOrInsertFunction(Name, 171 FunctionType::get(RetTy, ArgTys, false), 172 AttributeList); 173 } 174 175 Constant *Module::getOrInsertFunction(StringRef Name, 176 Type *RetTy, ...) { 177 va_list Args; 178 va_start(Args, RetTy); 179 180 // Build the list of argument types... 181 std::vector<Type*> ArgTys; 182 while (Type *ArgTy = va_arg(Args, Type*)) 183 ArgTys.push_back(ArgTy); 184 185 va_end(Args); 186 187 // Build the function type and chain to the other getOrInsertFunction... 188 return getOrInsertFunction(Name, 189 FunctionType::get(RetTy, ArgTys, false), 190 AttributeSet()); 191 } 192 193 // getFunction - Look up the specified function in the module symbol table. 194 // If it does not exist, return null. 195 // 196 Function *Module::getFunction(StringRef Name) const { 197 return dyn_cast_or_null<Function>(getNamedValue(Name)); 198 } 199 200 //===----------------------------------------------------------------------===// 201 // Methods for easy access to the global variables in the module. 202 // 203 204 /// getGlobalVariable - Look up the specified global variable in the module 205 /// symbol table. If it does not exist, return null. The type argument 206 /// should be the underlying type of the global, i.e., it should not have 207 /// the top-level PointerType, which represents the address of the global. 208 /// If AllowLocal is set to true, this function will return types that 209 /// have an local. By default, these types are not returned. 210 /// 211 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) { 212 if (GlobalVariable *Result = 213 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 214 if (AllowLocal || !Result->hasLocalLinkage()) 215 return Result; 216 return nullptr; 217 } 218 219 /// getOrInsertGlobal - Look up the specified global in the module symbol table. 220 /// 1. If it does not exist, add a declaration of the global and return it. 221 /// 2. Else, the global exists but has the wrong type: return the function 222 /// with a constantexpr cast to the right type. 223 /// 3. Finally, if the existing global is the correct declaration, return the 224 /// existing global. 225 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 226 // See if we have a definition for the specified global already. 227 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 228 if (!GV) { 229 // Nope, add it 230 GlobalVariable *New = 231 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 232 nullptr, Name); 233 return New; // Return the new declaration. 234 } 235 236 // If the variable exists but has the wrong type, return a bitcast to the 237 // right type. 238 Type *GVTy = GV->getType(); 239 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 240 if (GVTy != PTy) 241 return ConstantExpr::getBitCast(GV, PTy); 242 243 // Otherwise, we just found the existing function or a prototype. 244 return GV; 245 } 246 247 //===----------------------------------------------------------------------===// 248 // Methods for easy access to the global variables in the module. 249 // 250 251 // getNamedAlias - Look up the specified global in the module symbol table. 252 // If it does not exist, return null. 253 // 254 GlobalAlias *Module::getNamedAlias(StringRef Name) const { 255 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 256 } 257 258 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 259 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 260 } 261 262 /// getNamedMetadata - Return the first NamedMDNode in the module with the 263 /// specified name. This method returns null if a NamedMDNode with the 264 /// specified name is not found. 265 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 266 SmallString<256> NameData; 267 StringRef NameRef = Name.toStringRef(NameData); 268 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef); 269 } 270 271 /// getOrInsertNamedMetadata - Return the first named MDNode in the module 272 /// with the specified name. This method returns a new NamedMDNode if a 273 /// NamedMDNode with the specified name is not found. 274 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 275 NamedMDNode *&NMD = 276 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name]; 277 if (!NMD) { 278 NMD = new NamedMDNode(Name); 279 NMD->setParent(this); 280 NamedMDList.push_back(NMD); 281 } 282 return NMD; 283 } 284 285 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 286 /// delete it. 287 void Module::eraseNamedMetadata(NamedMDNode *NMD) { 288 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName()); 289 NamedMDList.erase(NMD->getIterator()); 290 } 291 292 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) { 293 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) { 294 uint64_t Val = Behavior->getLimitedValue(); 295 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) { 296 MFB = static_cast<ModFlagBehavior>(Val); 297 return true; 298 } 299 } 300 return false; 301 } 302 303 /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 304 void Module:: 305 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 306 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 307 if (!ModFlags) return; 308 309 for (const MDNode *Flag : ModFlags->operands()) { 310 ModFlagBehavior MFB; 311 if (Flag->getNumOperands() >= 3 && 312 isValidModFlagBehavior(Flag->getOperand(0), MFB) && 313 dyn_cast_or_null<MDString>(Flag->getOperand(1))) { 314 // Check the operands of the MDNode before accessing the operands. 315 // The verifier will actually catch these failures. 316 MDString *Key = cast<MDString>(Flag->getOperand(1)); 317 Metadata *Val = Flag->getOperand(2); 318 Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 319 } 320 } 321 } 322 323 /// Return the corresponding value if Key appears in module flags, otherwise 324 /// return null. 325 Metadata *Module::getModuleFlag(StringRef Key) const { 326 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 327 getModuleFlagsMetadata(ModuleFlags); 328 for (const ModuleFlagEntry &MFE : ModuleFlags) { 329 if (Key == MFE.Key->getString()) 330 return MFE.Val; 331 } 332 return nullptr; 333 } 334 335 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 336 /// represents module-level flags. This method returns null if there are no 337 /// module-level flags. 338 NamedMDNode *Module::getModuleFlagsMetadata() const { 339 return getNamedMetadata("llvm.module.flags"); 340 } 341 342 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 343 /// represents module-level flags. If module-level flags aren't found, it 344 /// creates the named metadata that contains them. 345 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 346 return getOrInsertNamedMetadata("llvm.module.flags"); 347 } 348 349 /// addModuleFlag - Add a module-level flag to the module-level flags 350 /// metadata. It will create the module-level flags named metadata if it doesn't 351 /// already exist. 352 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 353 Metadata *Val) { 354 Type *Int32Ty = Type::getInt32Ty(Context); 355 Metadata *Ops[3] = { 356 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 357 MDString::get(Context, Key), Val}; 358 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 359 } 360 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 361 Constant *Val) { 362 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 363 } 364 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 365 uint32_t Val) { 366 Type *Int32Ty = Type::getInt32Ty(Context); 367 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 368 } 369 void Module::addModuleFlag(MDNode *Node) { 370 assert(Node->getNumOperands() == 3 && 371 "Invalid number of operands for module flag!"); 372 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 373 isa<MDString>(Node->getOperand(1)) && 374 "Invalid operand types for module flag!"); 375 getOrInsertModuleFlagsMetadata()->addOperand(Node); 376 } 377 378 void Module::setDataLayout(StringRef Desc) { 379 DL.reset(Desc); 380 } 381 382 void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 383 384 const DataLayout &Module::getDataLayout() const { return DL; } 385 386 DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 387 return cast<DICompileUnit>(CUs->getOperand(Idx)); 388 } 389 DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 390 return cast<DICompileUnit>(CUs->getOperand(Idx)); 391 } 392 393 void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 394 while (CUs && (Idx < CUs->getNumOperands()) && 395 ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 396 ++Idx; 397 } 398 399 //===----------------------------------------------------------------------===// 400 // Methods to control the materialization of GlobalValues in the Module. 401 // 402 void Module::setMaterializer(GVMaterializer *GVM) { 403 assert(!Materializer && 404 "Module already has a GVMaterializer. Call materializeAll" 405 " to clear it out before setting another one."); 406 Materializer.reset(GVM); 407 } 408 409 Error Module::materialize(GlobalValue *GV) { 410 if (!Materializer) 411 return Error::success(); 412 413 return Materializer->materialize(GV); 414 } 415 416 Error Module::materializeAll() { 417 if (!Materializer) 418 return Error::success(); 419 std::unique_ptr<GVMaterializer> M = std::move(Materializer); 420 return M->materializeModule(); 421 } 422 423 Error Module::materializeMetadata() { 424 if (!Materializer) 425 return Error::success(); 426 return Materializer->materializeMetadata(); 427 } 428 429 //===----------------------------------------------------------------------===// 430 // Other module related stuff. 431 // 432 433 std::vector<StructType *> Module::getIdentifiedStructTypes() const { 434 // If we have a materializer, it is possible that some unread function 435 // uses a type that is currently not visible to a TypeFinder, so ask 436 // the materializer which types it created. 437 if (Materializer) 438 return Materializer->getIdentifiedStructTypes(); 439 440 std::vector<StructType *> Ret; 441 TypeFinder SrcStructTypes; 442 SrcStructTypes.run(*this, true); 443 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 444 return Ret; 445 } 446 447 // dropAllReferences() - This function causes all the subelements to "let go" 448 // of all references that they are maintaining. This allows one to 'delete' a 449 // whole module at a time, even though there may be circular references... first 450 // all references are dropped, and all use counts go to zero. Then everything 451 // is deleted for real. Note that no operations are valid on an object that 452 // has "dropped all references", except operator delete. 453 // 454 void Module::dropAllReferences() { 455 for (Function &F : *this) 456 F.dropAllReferences(); 457 458 for (GlobalVariable &GV : globals()) 459 GV.dropAllReferences(); 460 461 for (GlobalAlias &GA : aliases()) 462 GA.dropAllReferences(); 463 464 for (GlobalIFunc &GIF : ifuncs()) 465 GIF.dropAllReferences(); 466 } 467 468 unsigned Module::getDwarfVersion() const { 469 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 470 if (!Val) 471 return 0; 472 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 473 } 474 475 unsigned Module::getCodeViewFlag() const { 476 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 477 if (!Val) 478 return 0; 479 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 480 } 481 482 Comdat *Module::getOrInsertComdat(StringRef Name) { 483 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 484 Entry.second.Name = &Entry; 485 return &Entry.second; 486 } 487 488 PICLevel::Level Module::getPICLevel() const { 489 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 490 491 if (!Val) 492 return PICLevel::NotPIC; 493 494 return static_cast<PICLevel::Level>( 495 cast<ConstantInt>(Val->getValue())->getZExtValue()); 496 } 497 498 void Module::setPICLevel(PICLevel::Level PL) { 499 addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL); 500 } 501 502 PIELevel::Level Module::getPIELevel() const { 503 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 504 505 if (!Val) 506 return PIELevel::Default; 507 508 return static_cast<PIELevel::Level>( 509 cast<ConstantInt>(Val->getValue())->getZExtValue()); 510 } 511 512 void Module::setPIELevel(PIELevel::Level PL) { 513 addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL); 514 } 515 516 void Module::setProfileSummary(Metadata *M) { 517 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 518 } 519 520 Metadata *Module::getProfileSummary() { 521 return getModuleFlag("ProfileSummary"); 522 } 523 524 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 525 OwnedMemoryBuffer = std::move(MB); 526 } 527 528 GlobalVariable *llvm::collectUsedGlobalVariables( 529 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) { 530 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 531 GlobalVariable *GV = M.getGlobalVariable(Name); 532 if (!GV || !GV->hasInitializer()) 533 return GV; 534 535 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 536 for (Value *Op : Init->operands()) { 537 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases()); 538 Set.insert(G); 539 } 540 return GV; 541 } 542