brintos

brintos / llvm-project-archived public Read only

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