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