1 //===- Module.cpp - Implement the Module class ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Module class for the IR library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Module.h" 14 #include "SymbolTableListTraitsImpl.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/IR/Attributes.h" 21 #include "llvm/IR/Comdat.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DebugInfoMetadata.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/GVMaterializer.h" 28 #include "llvm/IR/GlobalAlias.h" 29 #include "llvm/IR/GlobalIFunc.h" 30 #include "llvm/IR/GlobalValue.h" 31 #include "llvm/IR/GlobalVariable.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/Metadata.h" 34 #include "llvm/IR/ModuleSummaryIndex.h" 35 #include "llvm/IR/SymbolTableListTraits.h" 36 #include "llvm/IR/Type.h" 37 #include "llvm/IR/TypeFinder.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/IR/ValueSymbolTable.h" 40 #include "llvm/Support/Casting.h" 41 #include "llvm/Support/CodeGen.h" 42 #include "llvm/Support/Error.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/Path.h" 45 #include "llvm/Support/RandomNumberGenerator.h" 46 #include "llvm/Support/VersionTuple.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <cstdint> 50 #include <memory> 51 #include <optional> 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), ValSymTab(std::make_unique<ValueSymbolTable>(-1)), 74 ModuleID(std::string(MID)), SourceFileName(std::string(MID)), DL("") { 75 Context.addModule(this); 76 } 77 78 Module::~Module() { 79 Context.removeModule(this); 80 dropAllReferences(); 81 GlobalList.clear(); 82 FunctionList.clear(); 83 AliasList.clear(); 84 IFuncList.clear(); 85 } 86 87 std::unique_ptr<RandomNumberGenerator> 88 Module::createRNG(const StringRef Name) const { 89 SmallString<32> Salt(Name); 90 91 // This RNG is guaranteed to produce the same random stream only 92 // when the Module ID and thus the input filename is the same. This 93 // might be problematic if the input filename extension changes 94 // (e.g. from .c to .bc or .ll). 95 // 96 // We could store this salt in NamedMetadata, but this would make 97 // the parameter non-const. This would unfortunately make this 98 // interface unusable by any Machine passes, since they only have a 99 // const reference to their IR Module. Alternatively we can always 100 // store salt metadata from the Module constructor. 101 Salt += sys::path::filename(getModuleIdentifier()); 102 103 return std::unique_ptr<RandomNumberGenerator>( 104 new RandomNumberGenerator(Salt)); 105 } 106 107 /// getNamedValue - Return the first global value in the module with 108 /// the specified name, of arbitrary type. This method returns null 109 /// if a global with the specified name is not found. 110 GlobalValue *Module::getNamedValue(StringRef Name) const { 111 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 112 } 113 114 unsigned Module::getNumNamedValues() const { 115 return getValueSymbolTable().size(); 116 } 117 118 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 119 /// This ID is uniqued across modules in the current LLVMContext. 120 unsigned Module::getMDKindID(StringRef Name) const { 121 return Context.getMDKindID(Name); 122 } 123 124 /// getMDKindNames - Populate client supplied SmallVector with the name for 125 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 126 /// so it is filled in as an empty string. 127 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 128 return Context.getMDKindNames(Result); 129 } 130 131 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 132 return Context.getOperandBundleTags(Result); 133 } 134 135 //===----------------------------------------------------------------------===// 136 // Methods for easy access to the functions in the module. 137 // 138 139 // getOrInsertFunction - Look up the specified function in the module symbol 140 // table. If it does not exist, add a prototype for the function and return 141 // it. This is nice because it allows most passes to get away with not handling 142 // the symbol table directly for this common task. 143 // 144 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty, 145 AttributeList AttributeList) { 146 // See if we have a definition for the specified function already. 147 GlobalValue *F = getNamedValue(Name); 148 if (!F) { 149 // Nope, add it 150 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, 151 DL.getProgramAddressSpace(), Name); 152 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 153 New->setAttributes(AttributeList); 154 FunctionList.push_back(New); 155 return {Ty, New}; // Return the new prototype. 156 } 157 158 // If the function exists but has the wrong type, return a bitcast to the 159 // right type. 160 auto *PTy = PointerType::get(Ty, F->getAddressSpace()); 161 if (F->getType() != PTy) 162 return {Ty, ConstantExpr::getBitCast(F, PTy)}; 163 164 // Otherwise, we just found the existing function or a prototype. 165 return {Ty, F}; 166 } 167 168 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) { 169 return getOrInsertFunction(Name, Ty, AttributeList()); 170 } 171 172 // getFunction - Look up the specified function in the module symbol table. 173 // If it does not exist, return null. 174 // 175 Function *Module::getFunction(StringRef Name) const { 176 return dyn_cast_or_null<Function>(getNamedValue(Name)); 177 } 178 179 //===----------------------------------------------------------------------===// 180 // Methods for easy access to the global variables in the module. 181 // 182 183 /// getGlobalVariable - Look up the specified global variable in the module 184 /// symbol table. If it does not exist, return null. The type argument 185 /// should be the underlying type of the global, i.e., it should not have 186 /// the top-level PointerType, which represents the address of the global. 187 /// If AllowLocal is set to true, this function will return types that 188 /// have an local. By default, these types are not returned. 189 /// 190 GlobalVariable *Module::getGlobalVariable(StringRef Name, 191 bool AllowLocal) const { 192 if (GlobalVariable *Result = 193 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 194 if (AllowLocal || !Result->hasLocalLinkage()) 195 return Result; 196 return nullptr; 197 } 198 199 /// getOrInsertGlobal - Look up the specified global in the module symbol table. 200 /// 1. If it does not exist, add a declaration of the global and return it. 201 /// 2. Else, the global exists but has the wrong type: return the function 202 /// with a constantexpr cast to the right type. 203 /// 3. Finally, if the existing global is the correct declaration, return the 204 /// existing global. 205 Constant *Module::getOrInsertGlobal( 206 StringRef Name, Type *Ty, 207 function_ref<GlobalVariable *()> CreateGlobalCallback) { 208 // See if we have a definition for the specified global already. 209 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 210 if (!GV) 211 GV = CreateGlobalCallback(); 212 assert(GV && "The CreateGlobalCallback is expected to create a global"); 213 214 // If the variable exists but has the wrong type, return a bitcast to the 215 // right type. 216 Type *GVTy = GV->getType(); 217 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 218 if (GVTy != PTy) 219 return ConstantExpr::getBitCast(GV, PTy); 220 221 // Otherwise, we just found the existing function or a prototype. 222 return GV; 223 } 224 225 // Overload to construct a global variable using its constructor's defaults. 226 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 227 return getOrInsertGlobal(Name, Ty, [&] { 228 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 229 nullptr, Name); 230 }); 231 } 232 233 //===----------------------------------------------------------------------===// 234 // Methods for easy access to the global variables in the module. 235 // 236 237 // getNamedAlias - Look up the specified global in the module symbol table. 238 // If it does not exist, return null. 239 // 240 GlobalAlias *Module::getNamedAlias(StringRef Name) const { 241 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 242 } 243 244 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 245 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 246 } 247 248 /// getNamedMetadata - Return the first NamedMDNode in the module with the 249 /// specified name. This method returns null if a NamedMDNode with the 250 /// specified name is not found. 251 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 252 SmallString<256> NameData; 253 StringRef NameRef = Name.toStringRef(NameData); 254 return NamedMDSymTab.lookup(NameRef); 255 } 256 257 /// getOrInsertNamedMetadata - Return the first named MDNode in the module 258 /// with the specified name. This method returns a new NamedMDNode if a 259 /// NamedMDNode with the specified name is not found. 260 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 261 NamedMDNode *&NMD = NamedMDSymTab[Name]; 262 if (!NMD) { 263 NMD = new NamedMDNode(Name); 264 NMD->setParent(this); 265 insertNamedMDNode(NMD); 266 } 267 return NMD; 268 } 269 270 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 271 /// delete it. 272 void Module::eraseNamedMetadata(NamedMDNode *NMD) { 273 NamedMDSymTab.erase(NMD->getName()); 274 eraseNamedMDNode(NMD); 275 } 276 277 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) { 278 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) { 279 uint64_t Val = Behavior->getLimitedValue(); 280 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) { 281 MFB = static_cast<ModFlagBehavior>(Val); 282 return true; 283 } 284 } 285 return false; 286 } 287 288 bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB, 289 MDString *&Key, Metadata *&Val) { 290 if (ModFlag.getNumOperands() < 3) 291 return false; 292 if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB)) 293 return false; 294 MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1)); 295 if (!K) 296 return false; 297 Key = K; 298 Val = ModFlag.getOperand(2); 299 return true; 300 } 301 302 /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 303 void Module:: 304 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 305 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 306 if (!ModFlags) return; 307 308 for (const MDNode *Flag : ModFlags->operands()) { 309 ModFlagBehavior MFB; 310 MDString *Key = nullptr; 311 Metadata *Val = nullptr; 312 if (isValidModuleFlag(*Flag, MFB, Key, Val)) { 313 // Check the operands of the MDNode before accessing the operands. 314 // The verifier will actually catch these failures. 315 Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 316 } 317 } 318 } 319 320 /// Return the corresponding value if Key appears in module flags, otherwise 321 /// return null. 322 Metadata *Module::getModuleFlag(StringRef Key) const { 323 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 324 getModuleFlagsMetadata(ModuleFlags); 325 for (const ModuleFlagEntry &MFE : ModuleFlags) { 326 if (Key == MFE.Key->getString()) 327 return MFE.Val; 328 } 329 return nullptr; 330 } 331 332 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 333 /// represents module-level flags. This method returns null if there are no 334 /// module-level flags. 335 NamedMDNode *Module::getModuleFlagsMetadata() const { 336 return getNamedMetadata("llvm.module.flags"); 337 } 338 339 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 340 /// represents module-level flags. If module-level flags aren't found, it 341 /// creates the named metadata that contains them. 342 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 343 return getOrInsertNamedMetadata("llvm.module.flags"); 344 } 345 346 /// addModuleFlag - Add a module-level flag to the module-level flags 347 /// metadata. It will create the module-level flags named metadata if it doesn't 348 /// already exist. 349 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 350 Metadata *Val) { 351 Type *Int32Ty = Type::getInt32Ty(Context); 352 Metadata *Ops[3] = { 353 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 354 MDString::get(Context, Key), Val}; 355 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 356 } 357 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 358 Constant *Val) { 359 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 360 } 361 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 362 uint32_t Val) { 363 Type *Int32Ty = Type::getInt32Ty(Context); 364 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 365 } 366 void Module::addModuleFlag(MDNode *Node) { 367 assert(Node->getNumOperands() == 3 && 368 "Invalid number of operands for module flag!"); 369 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 370 isa<MDString>(Node->getOperand(1)) && 371 "Invalid operand types for module flag!"); 372 getOrInsertModuleFlagsMetadata()->addOperand(Node); 373 } 374 375 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key, 376 Metadata *Val) { 377 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata(); 378 // Replace the flag if it already exists. 379 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) { 380 MDNode *Flag = ModFlags->getOperand(I); 381 ModFlagBehavior MFB; 382 MDString *K = nullptr; 383 Metadata *V = nullptr; 384 if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) { 385 Flag->replaceOperandWith(2, Val); 386 return; 387 } 388 } 389 addModuleFlag(Behavior, Key, Val); 390 } 391 392 void Module::setDataLayout(StringRef Desc) { 393 DL.reset(Desc); 394 } 395 396 void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 397 398 DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 399 return cast<DICompileUnit>(CUs->getOperand(Idx)); 400 } 401 DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 402 return cast<DICompileUnit>(CUs->getOperand(Idx)); 403 } 404 405 void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 406 while (CUs && (Idx < CUs->getNumOperands()) && 407 ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 408 ++Idx; 409 } 410 411 iterator_range<Module::global_object_iterator> Module::global_objects() { 412 return concat<GlobalObject>(functions(), globals()); 413 } 414 iterator_range<Module::const_global_object_iterator> 415 Module::global_objects() const { 416 return concat<const GlobalObject>(functions(), globals()); 417 } 418 419 iterator_range<Module::global_value_iterator> Module::global_values() { 420 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs()); 421 } 422 iterator_range<Module::const_global_value_iterator> 423 Module::global_values() const { 424 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs()); 425 } 426 427 //===----------------------------------------------------------------------===// 428 // Methods to control the materialization of GlobalValues in the Module. 429 // 430 void Module::setMaterializer(GVMaterializer *GVM) { 431 assert(!Materializer && 432 "Module already has a GVMaterializer. Call materializeAll" 433 " to clear it out before setting another one."); 434 Materializer.reset(GVM); 435 } 436 437 Error Module::materialize(GlobalValue *GV) { 438 if (!Materializer) 439 return Error::success(); 440 441 return Materializer->materialize(GV); 442 } 443 444 Error Module::materializeAll() { 445 if (!Materializer) 446 return Error::success(); 447 std::unique_ptr<GVMaterializer> M = std::move(Materializer); 448 return M->materializeModule(); 449 } 450 451 Error Module::materializeMetadata() { 452 if (!Materializer) 453 return Error::success(); 454 return Materializer->materializeMetadata(); 455 } 456 457 //===----------------------------------------------------------------------===// 458 // Other module related stuff. 459 // 460 461 std::vector<StructType *> Module::getIdentifiedStructTypes() const { 462 // If we have a materializer, it is possible that some unread function 463 // uses a type that is currently not visible to a TypeFinder, so ask 464 // the materializer which types it created. 465 if (Materializer) 466 return Materializer->getIdentifiedStructTypes(); 467 468 std::vector<StructType *> Ret; 469 TypeFinder SrcStructTypes; 470 SrcStructTypes.run(*this, true); 471 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 472 return Ret; 473 } 474 475 std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id, 476 const FunctionType *Proto) { 477 auto Encode = [&BaseName](unsigned Suffix) { 478 return (Twine(BaseName) + "." + Twine(Suffix)).str(); 479 }; 480 481 { 482 // fast path - the prototype is already known 483 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0}); 484 if (!UinItInserted.second) 485 return Encode(UinItInserted.first->second); 486 } 487 488 // Not known yet. A new entry was created with index 0. Check if there already 489 // exists a matching declaration, or select a new entry. 490 491 // Start looking for names with the current known maximum count (or 0). 492 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0}); 493 unsigned Count = NiidItInserted.first->second; 494 495 // This might be slow if a whole population of intrinsics already existed, but 496 // we cache the values for later usage. 497 std::string NewName; 498 while (true) { 499 NewName = Encode(Count); 500 GlobalValue *F = getNamedValue(NewName); 501 if (!F) { 502 // Reserve this entry for the new proto 503 UniquedIntrinsicNames[{Id, Proto}] = Count; 504 break; 505 } 506 507 // A declaration with this name already exists. Remember it. 508 FunctionType *FT = dyn_cast<FunctionType>(F->getValueType()); 509 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count}); 510 if (FT == Proto) { 511 // It was a declaration for our prototype. This entry was allocated in the 512 // beginning. Update the count to match the existing declaration. 513 UinItInserted.first->second = Count; 514 break; 515 } 516 517 ++Count; 518 } 519 520 NiidItInserted.first->second = Count + 1; 521 522 return NewName; 523 } 524 525 // dropAllReferences() - This function causes all the subelements to "let go" 526 // of all references that they are maintaining. This allows one to 'delete' a 527 // whole module at a time, even though there may be circular references... first 528 // all references are dropped, and all use counts go to zero. Then everything 529 // is deleted for real. Note that no operations are valid on an object that 530 // has "dropped all references", except operator delete. 531 // 532 void Module::dropAllReferences() { 533 for (Function &F : *this) 534 F.dropAllReferences(); 535 536 for (GlobalVariable &GV : globals()) 537 GV.dropAllReferences(); 538 539 for (GlobalAlias &GA : aliases()) 540 GA.dropAllReferences(); 541 542 for (GlobalIFunc &GIF : ifuncs()) 543 GIF.dropAllReferences(); 544 } 545 546 unsigned Module::getNumberRegisterParameters() const { 547 auto *Val = 548 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 549 if (!Val) 550 return 0; 551 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 552 } 553 554 unsigned Module::getDwarfVersion() const { 555 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 556 if (!Val) 557 return 0; 558 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 559 } 560 561 bool Module::isDwarf64() const { 562 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64")); 563 return Val && cast<ConstantInt>(Val->getValue())->isOne(); 564 } 565 566 unsigned Module::getCodeViewFlag() const { 567 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 568 if (!Val) 569 return 0; 570 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 571 } 572 573 unsigned Module::getInstructionCount() const { 574 unsigned NumInstrs = 0; 575 for (const Function &F : FunctionList) 576 NumInstrs += F.getInstructionCount(); 577 return NumInstrs; 578 } 579 580 Comdat *Module::getOrInsertComdat(StringRef Name) { 581 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 582 Entry.second.Name = &Entry; 583 return &Entry.second; 584 } 585 586 PICLevel::Level Module::getPICLevel() const { 587 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 588 589 if (!Val) 590 return PICLevel::NotPIC; 591 592 return static_cast<PICLevel::Level>( 593 cast<ConstantInt>(Val->getValue())->getZExtValue()); 594 } 595 596 void Module::setPICLevel(PICLevel::Level PL) { 597 // The merge result of a non-PIC object and a PIC object can only be reliably 598 // used as a non-PIC object, so use the Min merge behavior. 599 addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL); 600 } 601 602 PIELevel::Level Module::getPIELevel() const { 603 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 604 605 if (!Val) 606 return PIELevel::Default; 607 608 return static_cast<PIELevel::Level>( 609 cast<ConstantInt>(Val->getValue())->getZExtValue()); 610 } 611 612 void Module::setPIELevel(PIELevel::Level PL) { 613 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 614 } 615 616 std::optional<CodeModel::Model> Module::getCodeModel() const { 617 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 618 619 if (!Val) 620 return std::nullopt; 621 622 return static_cast<CodeModel::Model>( 623 cast<ConstantInt>(Val->getValue())->getZExtValue()); 624 } 625 626 void Module::setCodeModel(CodeModel::Model CL) { 627 // Linking object files with different code models is undefined behavior 628 // because the compiler would have to generate additional code (to span 629 // longer jumps) if a larger code model is used with a smaller one. 630 // Therefore we will treat attempts to mix code models as an error. 631 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 632 } 633 634 std::optional<uint64_t> Module::getLargeDataThreshold() const { 635 auto *Val = 636 cast_or_null<ConstantAsMetadata>(getModuleFlag("Large Data Threshold")); 637 638 if (!Val) 639 return std::nullopt; 640 641 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 642 } 643 644 void Module::setLargeDataThreshold(uint64_t Threshold) { 645 // Since the large data threshold goes along with the code model, the merge 646 // behavior is the same. 647 addModuleFlag(ModFlagBehavior::Error, "Large Data Threshold", 648 ConstantInt::get(Type::getInt64Ty(Context), Threshold)); 649 } 650 651 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 652 if (Kind == ProfileSummary::PSK_CSInstr) 653 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 654 else 655 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 656 } 657 658 Metadata *Module::getProfileSummary(bool IsCS) const { 659 return (IsCS ? getModuleFlag("CSProfileSummary") 660 : getModuleFlag("ProfileSummary")); 661 } 662 663 bool Module::getSemanticInterposition() const { 664 Metadata *MF = getModuleFlag("SemanticInterposition"); 665 666 auto *Val = cast_or_null<ConstantAsMetadata>(MF); 667 if (!Val) 668 return false; 669 670 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 671 } 672 673 void Module::setSemanticInterposition(bool SI) { 674 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI); 675 } 676 677 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 678 OwnedMemoryBuffer = std::move(MB); 679 } 680 681 bool Module::getRtLibUseGOT() const { 682 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 683 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 684 } 685 686 void Module::setRtLibUseGOT() { 687 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 688 } 689 690 bool Module::getDirectAccessExternalData() const { 691 auto *Val = cast_or_null<ConstantAsMetadata>( 692 getModuleFlag("direct-access-external-data")); 693 if (Val) 694 return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0; 695 return getPICLevel() == PICLevel::NotPIC; 696 } 697 698 void Module::setDirectAccessExternalData(bool Value) { 699 addModuleFlag(ModFlagBehavior::Max, "direct-access-external-data", Value); 700 } 701 702 UWTableKind Module::getUwtable() const { 703 if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable"))) 704 return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue()); 705 return UWTableKind::None; 706 } 707 708 void Module::setUwtable(UWTableKind Kind) { 709 addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind)); 710 } 711 712 FramePointerKind Module::getFramePointer() const { 713 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer")); 714 return static_cast<FramePointerKind>( 715 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0); 716 } 717 718 void Module::setFramePointer(FramePointerKind Kind) { 719 addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind)); 720 } 721 722 StringRef Module::getStackProtectorGuard() const { 723 Metadata *MD = getModuleFlag("stack-protector-guard"); 724 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 725 return MDS->getString(); 726 return {}; 727 } 728 729 void Module::setStackProtectorGuard(StringRef Kind) { 730 MDString *ID = MDString::get(getContext(), Kind); 731 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID); 732 } 733 734 StringRef Module::getStackProtectorGuardReg() const { 735 Metadata *MD = getModuleFlag("stack-protector-guard-reg"); 736 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 737 return MDS->getString(); 738 return {}; 739 } 740 741 void Module::setStackProtectorGuardReg(StringRef Reg) { 742 MDString *ID = MDString::get(getContext(), Reg); 743 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID); 744 } 745 746 StringRef Module::getStackProtectorGuardSymbol() const { 747 Metadata *MD = getModuleFlag("stack-protector-guard-symbol"); 748 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 749 return MDS->getString(); 750 return {}; 751 } 752 753 void Module::setStackProtectorGuardSymbol(StringRef Symbol) { 754 MDString *ID = MDString::get(getContext(), Symbol); 755 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID); 756 } 757 758 int Module::getStackProtectorGuardOffset() const { 759 Metadata *MD = getModuleFlag("stack-protector-guard-offset"); 760 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 761 return CI->getSExtValue(); 762 return INT_MAX; 763 } 764 765 void Module::setStackProtectorGuardOffset(int Offset) { 766 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset); 767 } 768 769 unsigned Module::getOverrideStackAlignment() const { 770 Metadata *MD = getModuleFlag("override-stack-alignment"); 771 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 772 return CI->getZExtValue(); 773 return 0; 774 } 775 776 unsigned Module::getMaxTLSAlignment() const { 777 Metadata *MD = getModuleFlag("MaxTLSAlign"); 778 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 779 return CI->getZExtValue(); 780 return 0; 781 } 782 783 void Module::setOverrideStackAlignment(unsigned Align) { 784 addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align); 785 } 786 787 static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) { 788 SmallVector<unsigned, 3> Entries; 789 Entries.push_back(V.getMajor()); 790 if (auto Minor = V.getMinor()) { 791 Entries.push_back(*Minor); 792 if (auto Subminor = V.getSubminor()) 793 Entries.push_back(*Subminor); 794 // Ignore the 'build' component as it can't be represented in the object 795 // file. 796 } 797 M.addModuleFlag(Module::ModFlagBehavior::Warning, Name, 798 ConstantDataArray::get(M.getContext(), Entries)); 799 } 800 801 void Module::setSDKVersion(const VersionTuple &V) { 802 addSDKVersionMD(V, *this, "SDK Version"); 803 } 804 805 static VersionTuple getSDKVersionMD(Metadata *MD) { 806 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD); 807 if (!CM) 808 return {}; 809 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 810 if (!Arr) 811 return {}; 812 auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> { 813 if (Index >= Arr->getNumElements()) 814 return std::nullopt; 815 return (unsigned)Arr->getElementAsInteger(Index); 816 }; 817 auto Major = getVersionComponent(0); 818 if (!Major) 819 return {}; 820 VersionTuple Result = VersionTuple(*Major); 821 if (auto Minor = getVersionComponent(1)) { 822 Result = VersionTuple(*Major, *Minor); 823 if (auto Subminor = getVersionComponent(2)) { 824 Result = VersionTuple(*Major, *Minor, *Subminor); 825 } 826 } 827 return Result; 828 } 829 830 VersionTuple Module::getSDKVersion() const { 831 return getSDKVersionMD(getModuleFlag("SDK Version")); 832 } 833 834 GlobalVariable *llvm::collectUsedGlobalVariables( 835 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) { 836 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 837 GlobalVariable *GV = M.getGlobalVariable(Name); 838 if (!GV || !GV->hasInitializer()) 839 return GV; 840 841 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 842 for (Value *Op : Init->operands()) { 843 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 844 Vec.push_back(G); 845 } 846 return GV; 847 } 848 849 void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) { 850 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) { 851 std::unique_ptr<ProfileSummary> ProfileSummary( 852 ProfileSummary::getFromMD(SummaryMD)); 853 if (ProfileSummary) { 854 if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample || 855 !ProfileSummary->isPartialProfile()) 856 return; 857 uint64_t BlockCount = Index.getBlockCount(); 858 uint32_t NumCounts = ProfileSummary->getNumCounts(); 859 if (!NumCounts) 860 return; 861 double Ratio = (double)BlockCount / NumCounts; 862 ProfileSummary->setPartialProfileRatio(Ratio); 863 setProfileSummary(ProfileSummary->getMD(getContext()), 864 ProfileSummary::PSK_Sample); 865 } 866 } 867 } 868 869 StringRef Module::getDarwinTargetVariantTriple() const { 870 if (const auto *MD = getModuleFlag("darwin.target_variant.triple")) 871 return cast<MDString>(MD)->getString(); 872 return ""; 873 } 874 875 void Module::setDarwinTargetVariantTriple(StringRef T) { 876 addModuleFlag(ModFlagBehavior::Override, "darwin.target_variant.triple", 877 MDString::get(getContext(), T)); 878 } 879 880 VersionTuple Module::getDarwinTargetVariantSDKVersion() const { 881 return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version")); 882 } 883 884 void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) { 885 addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version"); 886 } 887