Module.cpp 29 KB

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