Module.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Module.h - C++ class to represent a VM module -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// @file
  15. /// Module.h This file contains the declarations for the Module class.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_MODULE_H
  19. #define LLVM_IR_MODULE_H
  20. #include "llvm-c/Types.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/StringMap.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/iterator_range.h"
  26. #include "llvm/IR/Attributes.h"
  27. #include "llvm/IR/Comdat.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/GlobalAlias.h"
  31. #include "llvm/IR/GlobalIFunc.h"
  32. #include "llvm/IR/GlobalVariable.h"
  33. #include "llvm/IR/Metadata.h"
  34. #include "llvm/IR/ProfileSummary.h"
  35. #include "llvm/IR/SymbolTableListTraits.h"
  36. #include "llvm/Support/CBindingWrapping.h"
  37. #include "llvm/Support/CodeGen.h"
  38. #include <cstddef>
  39. #include <cstdint>
  40. #include <iterator>
  41. #include <memory>
  42. #include <string>
  43. #include <vector>
  44. namespace llvm {
  45. class Error;
  46. class FunctionType;
  47. class GVMaterializer;
  48. class LLVMContext;
  49. class MemoryBuffer;
  50. class ModuleSummaryIndex;
  51. class RandomNumberGenerator;
  52. class StructType;
  53. class VersionTuple;
  54. /// A Module instance is used to store all the information related to an
  55. /// LLVM module. Modules are the top level container of all other LLVM
  56. /// Intermediate Representation (IR) objects. Each module directly contains a
  57. /// list of globals variables, a list of functions, a list of libraries (or
  58. /// other modules) this module depends on, a symbol table, and various data
  59. /// about the target's characteristics.
  60. ///
  61. /// A module maintains a GlobalValRefMap object that is used to hold all
  62. /// constant references to global variables in the module. When a global
  63. /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
  64. /// The main container class for the LLVM Intermediate Representation.
  65. class LLVM_EXTERNAL_VISIBILITY Module {
  66. /// @name Types And Enumerations
  67. /// @{
  68. public:
  69. /// The type for the list of global variables.
  70. using GlobalListType = SymbolTableList<GlobalVariable>;
  71. /// The type for the list of functions.
  72. using FunctionListType = SymbolTableList<Function>;
  73. /// The type for the list of aliases.
  74. using AliasListType = SymbolTableList<GlobalAlias>;
  75. /// The type for the list of ifuncs.
  76. using IFuncListType = SymbolTableList<GlobalIFunc>;
  77. /// The type for the list of named metadata.
  78. using NamedMDListType = ilist<NamedMDNode>;
  79. /// The type of the comdat "symbol" table.
  80. using ComdatSymTabType = StringMap<Comdat>;
  81. /// The type for mapping names to named metadata.
  82. using NamedMDSymTabType = StringMap<NamedMDNode *>;
  83. /// The Global Variable iterator.
  84. using global_iterator = GlobalListType::iterator;
  85. /// The Global Variable constant iterator.
  86. using const_global_iterator = GlobalListType::const_iterator;
  87. /// The Function iterators.
  88. using iterator = FunctionListType::iterator;
  89. /// The Function constant iterator
  90. using const_iterator = FunctionListType::const_iterator;
  91. /// The Function reverse iterator.
  92. using reverse_iterator = FunctionListType::reverse_iterator;
  93. /// The Function constant reverse iterator.
  94. using const_reverse_iterator = FunctionListType::const_reverse_iterator;
  95. /// The Global Alias iterators.
  96. using alias_iterator = AliasListType::iterator;
  97. /// The Global Alias constant iterator
  98. using const_alias_iterator = AliasListType::const_iterator;
  99. /// The Global IFunc iterators.
  100. using ifunc_iterator = IFuncListType::iterator;
  101. /// The Global IFunc constant iterator
  102. using const_ifunc_iterator = IFuncListType::const_iterator;
  103. /// The named metadata iterators.
  104. using named_metadata_iterator = NamedMDListType::iterator;
  105. /// The named metadata constant iterators.
  106. using const_named_metadata_iterator = NamedMDListType::const_iterator;
  107. /// This enumeration defines the supported behaviors of module flags.
  108. enum ModFlagBehavior {
  109. /// Emits an error if two values disagree, otherwise the resulting value is
  110. /// that of the operands.
  111. Error = 1,
  112. /// Emits a warning if two values disagree. The result value will be the
  113. /// operand for the flag from the first module being linked.
  114. Warning = 2,
  115. /// Adds a requirement that another module flag be present and have a
  116. /// specified value after linking is performed. The value must be a metadata
  117. /// pair, where the first element of the pair is the ID of the module flag
  118. /// to be restricted, and the second element of the pair is the value the
  119. /// module flag should be restricted to. This behavior can be used to
  120. /// restrict the allowable results (via triggering of an error) of linking
  121. /// IDs with the **Override** behavior.
  122. Require = 3,
  123. /// Uses the specified value, regardless of the behavior or value of the
  124. /// other module. If both modules specify **Override**, but the values
  125. /// differ, an error will be emitted.
  126. Override = 4,
  127. /// Appends the two values, which are required to be metadata nodes.
  128. Append = 5,
  129. /// Appends the two values, which are required to be metadata
  130. /// nodes. However, duplicate entries in the second list are dropped
  131. /// during the append operation.
  132. AppendUnique = 6,
  133. /// Takes the max of the two values, which are required to be integers.
  134. Max = 7,
  135. // Markers:
  136. ModFlagBehaviorFirstVal = Error,
  137. ModFlagBehaviorLastVal = Max
  138. };
  139. /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
  140. /// converted result in MFB.
  141. static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
  142. /// Check if the given module flag metadata represents a valid module flag,
  143. /// and store the flag behavior, the key string and the value metadata.
  144. static bool isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
  145. MDString *&Key, Metadata *&Val);
  146. struct ModuleFlagEntry {
  147. ModFlagBehavior Behavior;
  148. MDString *Key;
  149. Metadata *Val;
  150. ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
  151. : Behavior(B), Key(K), Val(V) {}
  152. };
  153. /// @}
  154. /// @name Member Variables
  155. /// @{
  156. private:
  157. LLVMContext &Context; ///< The LLVMContext from which types and
  158. ///< constants are allocated.
  159. GlobalListType GlobalList; ///< The Global Variables in the module
  160. FunctionListType FunctionList; ///< The Functions in the module
  161. AliasListType AliasList; ///< The Aliases in the module
  162. IFuncListType IFuncList; ///< The IFuncs in the module
  163. NamedMDListType NamedMDList; ///< The named metadata in the module
  164. std::string GlobalScopeAsm; ///< Inline Asm at global scope.
  165. std::unique_ptr<ValueSymbolTable> ValSymTab; ///< Symbol table for values
  166. ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
  167. std::unique_ptr<MemoryBuffer>
  168. OwnedMemoryBuffer; ///< Memory buffer directly owned by this
  169. ///< module, for legacy clients only.
  170. std::unique_ptr<GVMaterializer>
  171. Materializer; ///< Used to materialize GlobalValues
  172. std::string ModuleID; ///< Human readable identifier for the module
  173. std::string SourceFileName; ///< Original source file name for module,
  174. ///< recorded in bitcode.
  175. std::string TargetTriple; ///< Platform target triple Module compiled on
  176. ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
  177. NamedMDSymTabType NamedMDSymTab; ///< NamedMDNode names.
  178. DataLayout DL; ///< DataLayout associated with the module
  179. StringMap<unsigned>
  180. CurrentIntrinsicIds; ///< Keep track of the current unique id count for
  181. ///< the specified intrinsic basename.
  182. DenseMap<std::pair<Intrinsic::ID, const FunctionType *>, unsigned>
  183. UniquedIntrinsicNames; ///< Keep track of uniqued names of intrinsics
  184. ///< based on unnamed types. The combination of
  185. ///< ID and FunctionType maps to the extension that
  186. ///< is used to make the intrinsic name unique.
  187. friend class Constant;
  188. /// @}
  189. /// @name Constructors
  190. /// @{
  191. public:
  192. /// The Module constructor. Note that there is no default constructor. You
  193. /// must provide a name for the module upon construction.
  194. explicit Module(StringRef ModuleID, LLVMContext& C);
  195. /// The module destructor. This will dropAllReferences.
  196. ~Module();
  197. /// @}
  198. /// @name Module Level Accessors
  199. /// @{
  200. /// Get the module identifier which is, essentially, the name of the module.
  201. /// @returns the module identifier as a string
  202. const std::string &getModuleIdentifier() const { return ModuleID; }
  203. /// Returns the number of non-debug IR instructions in the module.
  204. /// This is equivalent to the sum of the IR instruction counts of each
  205. /// function contained in the module.
  206. unsigned getInstructionCount() const;
  207. /// Get the module's original source file name. When compiling from
  208. /// bitcode, this is taken from a bitcode record where it was recorded.
  209. /// For other compiles it is the same as the ModuleID, which would
  210. /// contain the source file name.
  211. const std::string &getSourceFileName() const { return SourceFileName; }
  212. /// Get a short "name" for the module.
  213. ///
  214. /// This is useful for debugging or logging. It is essentially a convenience
  215. /// wrapper around getModuleIdentifier().
  216. StringRef getName() const { return ModuleID; }
  217. /// Get the data layout string for the module's target platform. This is
  218. /// equivalent to getDataLayout()->getStringRepresentation().
  219. const std::string &getDataLayoutStr() const {
  220. return DL.getStringRepresentation();
  221. }
  222. /// Get the data layout for the module's target platform.
  223. const DataLayout &getDataLayout() const;
  224. /// Get the target triple which is a string describing the target host.
  225. /// @returns a string containing the target triple.
  226. const std::string &getTargetTriple() const { return TargetTriple; }
  227. /// Get the global data context.
  228. /// @returns LLVMContext - a container for LLVM's global information
  229. LLVMContext &getContext() const { return Context; }
  230. /// Get any module-scope inline assembly blocks.
  231. /// @returns a string containing the module-scope inline assembly blocks.
  232. const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
  233. /// Get a RandomNumberGenerator salted for use with this module. The
  234. /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
  235. /// ModuleID and the provided pass salt. The returned RNG should not
  236. /// be shared across threads or passes.
  237. ///
  238. /// A unique RNG per pass ensures a reproducible random stream even
  239. /// when other randomness consuming passes are added or removed. In
  240. /// addition, the random stream will be reproducible across LLVM
  241. /// versions when the pass does not change.
  242. std::unique_ptr<RandomNumberGenerator> createRNG(const StringRef Name) const;
  243. /// Return true if size-info optimization remark is enabled, false
  244. /// otherwise.
  245. bool shouldEmitInstrCountChangedRemark() {
  246. return getContext().getDiagHandlerPtr()->isAnalysisRemarkEnabled(
  247. "size-info");
  248. }
  249. /// @}
  250. /// @name Module Level Mutators
  251. /// @{
  252. /// Set the module identifier.
  253. void setModuleIdentifier(StringRef ID) { ModuleID = std::string(ID); }
  254. /// Set the module's original source file name.
  255. void setSourceFileName(StringRef Name) { SourceFileName = std::string(Name); }
  256. /// Set the data layout
  257. void setDataLayout(StringRef Desc);
  258. void setDataLayout(const DataLayout &Other);
  259. /// Set the target triple.
  260. void setTargetTriple(StringRef T) { TargetTriple = std::string(T); }
  261. /// Set the module-scope inline assembly blocks.
  262. /// A trailing newline is added if the input doesn't have one.
  263. void setModuleInlineAsm(StringRef Asm) {
  264. GlobalScopeAsm = std::string(Asm);
  265. if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
  266. GlobalScopeAsm += '\n';
  267. }
  268. /// Append to the module-scope inline assembly blocks.
  269. /// A trailing newline is added if the input doesn't have one.
  270. void appendModuleInlineAsm(StringRef Asm) {
  271. GlobalScopeAsm += Asm;
  272. if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
  273. GlobalScopeAsm += '\n';
  274. }
  275. /// @}
  276. /// @name Generic Value Accessors
  277. /// @{
  278. /// Return the global value in the module with the specified name, of
  279. /// arbitrary type. This method returns null if a global with the specified
  280. /// name is not found.
  281. GlobalValue *getNamedValue(StringRef Name) const;
  282. /// Return the number of global values in the module.
  283. unsigned getNumNamedValues() const;
  284. /// Return a unique non-zero ID for the specified metadata kind. This ID is
  285. /// uniqued across modules in the current LLVMContext.
  286. unsigned getMDKindID(StringRef Name) const;
  287. /// Populate client supplied SmallVector with the name for custom metadata IDs
  288. /// registered in this LLVMContext.
  289. void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
  290. /// Populate client supplied SmallVector with the bundle tags registered in
  291. /// this LLVMContext. The bundle tags are ordered by increasing bundle IDs.
  292. /// \see LLVMContext::getOperandBundleTagID
  293. void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
  294. std::vector<StructType *> getIdentifiedStructTypes() const;
  295. /// Return a unique name for an intrinsic whose mangling is based on an
  296. /// unnamed type. The Proto represents the function prototype.
  297. std::string getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
  298. const FunctionType *Proto);
  299. /// @}
  300. /// @name Function Accessors
  301. /// @{
  302. /// Look up the specified function in the module symbol table. Four
  303. /// possibilities:
  304. /// 1. If it does not exist, add a prototype for the function and return it.
  305. /// 2. Otherwise, if the existing function has the correct prototype, return
  306. /// the existing function.
  307. /// 3. Finally, the function exists but has the wrong prototype: return the
  308. /// function with a constantexpr cast to the right prototype.
  309. ///
  310. /// In all cases, the returned value is a FunctionCallee wrapper around the
  311. /// 'FunctionType *T' passed in, as well as a 'Value*' either of the Function or
  312. /// the bitcast to the function.
  313. FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T,
  314. AttributeList AttributeList);
  315. FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T);
  316. /// Look up the specified function in the module symbol table. If it does not
  317. /// exist, add a prototype for the function and return it. This function
  318. /// guarantees to return a constant of pointer to the specified function type
  319. /// or a ConstantExpr BitCast of that type if the named function has a
  320. /// different type. This version of the method takes a list of
  321. /// function arguments, which makes it easier for clients to use.
  322. template <typename... ArgsTy>
  323. FunctionCallee getOrInsertFunction(StringRef Name,
  324. AttributeList AttributeList, Type *RetTy,
  325. ArgsTy... Args) {
  326. SmallVector<Type*, sizeof...(ArgsTy)> ArgTys{Args...};
  327. return getOrInsertFunction(Name,
  328. FunctionType::get(RetTy, ArgTys, false),
  329. AttributeList);
  330. }
  331. /// Same as above, but without the attributes.
  332. template <typename... ArgsTy>
  333. FunctionCallee getOrInsertFunction(StringRef Name, Type *RetTy,
  334. ArgsTy... Args) {
  335. return getOrInsertFunction(Name, AttributeList{}, RetTy, Args...);
  336. }
  337. // Avoid an incorrect ordering that'd otherwise compile incorrectly.
  338. template <typename... ArgsTy>
  339. FunctionCallee
  340. getOrInsertFunction(StringRef Name, AttributeList AttributeList,
  341. FunctionType *Invalid, ArgsTy... Args) = delete;
  342. /// Look up the specified function in the module symbol table. If it does not
  343. /// exist, return null.
  344. Function *getFunction(StringRef Name) const;
  345. /// @}
  346. /// @name Global Variable Accessors
  347. /// @{
  348. /// Look up the specified global variable in the module symbol table. If it
  349. /// does not exist, return null. If AllowInternal is set to true, this
  350. /// function will return types that have InternalLinkage. By default, these
  351. /// types are not returned.
  352. GlobalVariable *getGlobalVariable(StringRef Name) const {
  353. return getGlobalVariable(Name, false);
  354. }
  355. GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const;
  356. GlobalVariable *getGlobalVariable(StringRef Name,
  357. bool AllowInternal = false) {
  358. return static_cast<const Module *>(this)->getGlobalVariable(Name,
  359. AllowInternal);
  360. }
  361. /// Return the global variable in the module with the specified name, of
  362. /// arbitrary type. This method returns null if a global with the specified
  363. /// name is not found.
  364. const GlobalVariable *getNamedGlobal(StringRef Name) const {
  365. return getGlobalVariable(Name, true);
  366. }
  367. GlobalVariable *getNamedGlobal(StringRef Name) {
  368. return const_cast<GlobalVariable *>(
  369. static_cast<const Module *>(this)->getNamedGlobal(Name));
  370. }
  371. /// Look up the specified global in the module symbol table.
  372. /// If it does not exist, invoke a callback to create a declaration of the
  373. /// global and return it. The global is constantexpr casted to the expected
  374. /// type if necessary.
  375. Constant *
  376. getOrInsertGlobal(StringRef Name, Type *Ty,
  377. function_ref<GlobalVariable *()> CreateGlobalCallback);
  378. /// Look up the specified global in the module symbol table. If required, this
  379. /// overload constructs the global variable using its constructor's defaults.
  380. Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
  381. /// @}
  382. /// @name Global Alias Accessors
  383. /// @{
  384. /// Return the global alias in the module with the specified name, of
  385. /// arbitrary type. This method returns null if a global with the specified
  386. /// name is not found.
  387. GlobalAlias *getNamedAlias(StringRef Name) const;
  388. /// @}
  389. /// @name Global IFunc Accessors
  390. /// @{
  391. /// Return the global ifunc in the module with the specified name, of
  392. /// arbitrary type. This method returns null if a global with the specified
  393. /// name is not found.
  394. GlobalIFunc *getNamedIFunc(StringRef Name) const;
  395. /// @}
  396. /// @name Named Metadata Accessors
  397. /// @{
  398. /// Return the first NamedMDNode in the module with the specified name. This
  399. /// method returns null if a NamedMDNode with the specified name is not found.
  400. NamedMDNode *getNamedMetadata(const Twine &Name) const;
  401. /// Return the named MDNode in the module with the specified name. This method
  402. /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
  403. /// found.
  404. NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
  405. /// Remove the given NamedMDNode from this module and delete it.
  406. void eraseNamedMetadata(NamedMDNode *NMD);
  407. /// @}
  408. /// @name Comdat Accessors
  409. /// @{
  410. /// Return the Comdat in the module with the specified name. It is created
  411. /// if it didn't already exist.
  412. Comdat *getOrInsertComdat(StringRef Name);
  413. /// @}
  414. /// @name Module Flags Accessors
  415. /// @{
  416. /// Returns the module flags in the provided vector.
  417. void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
  418. /// Return the corresponding value if Key appears in module flags, otherwise
  419. /// return null.
  420. Metadata *getModuleFlag(StringRef Key) const;
  421. /// Returns the NamedMDNode in the module that represents module-level flags.
  422. /// This method returns null if there are no module-level flags.
  423. NamedMDNode *getModuleFlagsMetadata() const;
  424. /// Returns the NamedMDNode in the module that represents module-level flags.
  425. /// If module-level flags aren't found, it creates the named metadata that
  426. /// contains them.
  427. NamedMDNode *getOrInsertModuleFlagsMetadata();
  428. /// Add a module-level flag to the module-level flags metadata. It will create
  429. /// the module-level flags named metadata if it doesn't already exist.
  430. void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
  431. void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
  432. void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
  433. void addModuleFlag(MDNode *Node);
  434. /// Like addModuleFlag but replaces the old module flag if it already exists.
  435. void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
  436. /// @}
  437. /// @name Materialization
  438. /// @{
  439. /// Sets the GVMaterializer to GVM. This module must not yet have a
  440. /// Materializer. To reset the materializer for a module that already has one,
  441. /// call materializeAll first. Destroying this module will destroy
  442. /// its materializer without materializing any more GlobalValues. Without
  443. /// destroying the Module, there is no way to detach or destroy a materializer
  444. /// without materializing all the GVs it controls, to avoid leaving orphan
  445. /// unmaterialized GVs.
  446. void setMaterializer(GVMaterializer *GVM);
  447. /// Retrieves the GVMaterializer, if any, for this Module.
  448. GVMaterializer *getMaterializer() const { return Materializer.get(); }
  449. bool isMaterialized() const { return !getMaterializer(); }
  450. /// Make sure the GlobalValue is fully read.
  451. llvm::Error materialize(GlobalValue *GV);
  452. /// Make sure all GlobalValues in this Module are fully read and clear the
  453. /// Materializer.
  454. llvm::Error materializeAll();
  455. llvm::Error materializeMetadata();
  456. /// @}
  457. /// @name Direct access to the globals list, functions list, and symbol table
  458. /// @{
  459. /// Get the Module's list of global variables (constant).
  460. const GlobalListType &getGlobalList() const { return GlobalList; }
  461. /// Get the Module's list of global variables.
  462. GlobalListType &getGlobalList() { return GlobalList; }
  463. static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
  464. return &Module::GlobalList;
  465. }
  466. /// Get the Module's list of functions (constant).
  467. const FunctionListType &getFunctionList() const { return FunctionList; }
  468. /// Get the Module's list of functions.
  469. FunctionListType &getFunctionList() { return FunctionList; }
  470. static FunctionListType Module::*getSublistAccess(Function*) {
  471. return &Module::FunctionList;
  472. }
  473. /// Get the Module's list of aliases (constant).
  474. const AliasListType &getAliasList() const { return AliasList; }
  475. /// Get the Module's list of aliases.
  476. AliasListType &getAliasList() { return AliasList; }
  477. static AliasListType Module::*getSublistAccess(GlobalAlias*) {
  478. return &Module::AliasList;
  479. }
  480. /// Get the Module's list of ifuncs (constant).
  481. const IFuncListType &getIFuncList() const { return IFuncList; }
  482. /// Get the Module's list of ifuncs.
  483. IFuncListType &getIFuncList() { return IFuncList; }
  484. static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
  485. return &Module::IFuncList;
  486. }
  487. /// Get the Module's list of named metadata (constant).
  488. const NamedMDListType &getNamedMDList() const { return NamedMDList; }
  489. /// Get the Module's list of named metadata.
  490. NamedMDListType &getNamedMDList() { return NamedMDList; }
  491. static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
  492. return &Module::NamedMDList;
  493. }
  494. /// Get the symbol table of global variable and function identifiers
  495. const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
  496. /// Get the Module's symbol table of global variable and function identifiers.
  497. ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
  498. /// Get the Module's symbol table for COMDATs (constant).
  499. const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
  500. /// Get the Module's symbol table for COMDATs.
  501. ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
  502. /// @}
  503. /// @name Global Variable Iteration
  504. /// @{
  505. global_iterator global_begin() { return GlobalList.begin(); }
  506. const_global_iterator global_begin() const { return GlobalList.begin(); }
  507. global_iterator global_end () { return GlobalList.end(); }
  508. const_global_iterator global_end () const { return GlobalList.end(); }
  509. size_t global_size () const { return GlobalList.size(); }
  510. bool global_empty() const { return GlobalList.empty(); }
  511. iterator_range<global_iterator> globals() {
  512. return make_range(global_begin(), global_end());
  513. }
  514. iterator_range<const_global_iterator> globals() const {
  515. return make_range(global_begin(), global_end());
  516. }
  517. /// @}
  518. /// @name Function Iteration
  519. /// @{
  520. iterator begin() { return FunctionList.begin(); }
  521. const_iterator begin() const { return FunctionList.begin(); }
  522. iterator end () { return FunctionList.end(); }
  523. const_iterator end () const { return FunctionList.end(); }
  524. reverse_iterator rbegin() { return FunctionList.rbegin(); }
  525. const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
  526. reverse_iterator rend() { return FunctionList.rend(); }
  527. const_reverse_iterator rend() const { return FunctionList.rend(); }
  528. size_t size() const { return FunctionList.size(); }
  529. bool empty() const { return FunctionList.empty(); }
  530. iterator_range<iterator> functions() {
  531. return make_range(begin(), end());
  532. }
  533. iterator_range<const_iterator> functions() const {
  534. return make_range(begin(), end());
  535. }
  536. /// @}
  537. /// @name Alias Iteration
  538. /// @{
  539. alias_iterator alias_begin() { return AliasList.begin(); }
  540. const_alias_iterator alias_begin() const { return AliasList.begin(); }
  541. alias_iterator alias_end () { return AliasList.end(); }
  542. const_alias_iterator alias_end () const { return AliasList.end(); }
  543. size_t alias_size () const { return AliasList.size(); }
  544. bool alias_empty() const { return AliasList.empty(); }
  545. iterator_range<alias_iterator> aliases() {
  546. return make_range(alias_begin(), alias_end());
  547. }
  548. iterator_range<const_alias_iterator> aliases() const {
  549. return make_range(alias_begin(), alias_end());
  550. }
  551. /// @}
  552. /// @name IFunc Iteration
  553. /// @{
  554. ifunc_iterator ifunc_begin() { return IFuncList.begin(); }
  555. const_ifunc_iterator ifunc_begin() const { return IFuncList.begin(); }
  556. ifunc_iterator ifunc_end () { return IFuncList.end(); }
  557. const_ifunc_iterator ifunc_end () const { return IFuncList.end(); }
  558. size_t ifunc_size () const { return IFuncList.size(); }
  559. bool ifunc_empty() const { return IFuncList.empty(); }
  560. iterator_range<ifunc_iterator> ifuncs() {
  561. return make_range(ifunc_begin(), ifunc_end());
  562. }
  563. iterator_range<const_ifunc_iterator> ifuncs() const {
  564. return make_range(ifunc_begin(), ifunc_end());
  565. }
  566. /// @}
  567. /// @name Convenience iterators
  568. /// @{
  569. using global_object_iterator =
  570. concat_iterator<GlobalObject, iterator, global_iterator>;
  571. using const_global_object_iterator =
  572. concat_iterator<const GlobalObject, const_iterator,
  573. const_global_iterator>;
  574. iterator_range<global_object_iterator> global_objects();
  575. iterator_range<const_global_object_iterator> global_objects() const;
  576. using global_value_iterator =
  577. concat_iterator<GlobalValue, iterator, global_iterator, alias_iterator,
  578. ifunc_iterator>;
  579. using const_global_value_iterator =
  580. concat_iterator<const GlobalValue, const_iterator, const_global_iterator,
  581. const_alias_iterator, const_ifunc_iterator>;
  582. iterator_range<global_value_iterator> global_values();
  583. iterator_range<const_global_value_iterator> global_values() const;
  584. /// @}
  585. /// @name Named Metadata Iteration
  586. /// @{
  587. named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
  588. const_named_metadata_iterator named_metadata_begin() const {
  589. return NamedMDList.begin();
  590. }
  591. named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
  592. const_named_metadata_iterator named_metadata_end() const {
  593. return NamedMDList.end();
  594. }
  595. size_t named_metadata_size() const { return NamedMDList.size(); }
  596. bool named_metadata_empty() const { return NamedMDList.empty(); }
  597. iterator_range<named_metadata_iterator> named_metadata() {
  598. return make_range(named_metadata_begin(), named_metadata_end());
  599. }
  600. iterator_range<const_named_metadata_iterator> named_metadata() const {
  601. return make_range(named_metadata_begin(), named_metadata_end());
  602. }
  603. /// An iterator for DICompileUnits that skips those marked NoDebug.
  604. class debug_compile_units_iterator {
  605. NamedMDNode *CUs;
  606. unsigned Idx;
  607. void SkipNoDebugCUs();
  608. public:
  609. using iterator_category = std::input_iterator_tag;
  610. using value_type = DICompileUnit *;
  611. using difference_type = std::ptrdiff_t;
  612. using pointer = value_type *;
  613. using reference = value_type &;
  614. explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
  615. : CUs(CUs), Idx(Idx) {
  616. SkipNoDebugCUs();
  617. }
  618. debug_compile_units_iterator &operator++() {
  619. ++Idx;
  620. SkipNoDebugCUs();
  621. return *this;
  622. }
  623. debug_compile_units_iterator operator++(int) {
  624. debug_compile_units_iterator T(*this);
  625. ++Idx;
  626. return T;
  627. }
  628. bool operator==(const debug_compile_units_iterator &I) const {
  629. return Idx == I.Idx;
  630. }
  631. bool operator!=(const debug_compile_units_iterator &I) const {
  632. return Idx != I.Idx;
  633. }
  634. DICompileUnit *operator*() const;
  635. DICompileUnit *operator->() const;
  636. };
  637. debug_compile_units_iterator debug_compile_units_begin() const {
  638. auto *CUs = getNamedMetadata("llvm.dbg.cu");
  639. return debug_compile_units_iterator(CUs, 0);
  640. }
  641. debug_compile_units_iterator debug_compile_units_end() const {
  642. auto *CUs = getNamedMetadata("llvm.dbg.cu");
  643. return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
  644. }
  645. /// Return an iterator for all DICompileUnits listed in this Module's
  646. /// llvm.dbg.cu named metadata node and aren't explicitly marked as
  647. /// NoDebug.
  648. iterator_range<debug_compile_units_iterator> debug_compile_units() const {
  649. auto *CUs = getNamedMetadata("llvm.dbg.cu");
  650. return make_range(
  651. debug_compile_units_iterator(CUs, 0),
  652. debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
  653. }
  654. /// @}
  655. /// Destroy ConstantArrays in LLVMContext if they are not used.
  656. /// ConstantArrays constructed during linking can cause quadratic memory
  657. /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
  658. /// slowdown for a large application.
  659. ///
  660. /// NOTE: Constants are currently owned by LLVMContext. This can then only
  661. /// be called where all uses of the LLVMContext are understood.
  662. void dropTriviallyDeadConstantArrays();
  663. /// @name Utility functions for printing and dumping Module objects
  664. /// @{
  665. /// Print the module to an output stream with an optional
  666. /// AssemblyAnnotationWriter. If \c ShouldPreserveUseListOrder, then include
  667. /// uselistorder directives so that use-lists can be recreated when reading
  668. /// the assembly.
  669. void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
  670. bool ShouldPreserveUseListOrder = false,
  671. bool IsForDebug = false) const;
  672. /// Dump the module to stderr (for debugging).
  673. void dump() const;
  674. /// This function causes all the subinstructions to "let go" of all references
  675. /// that they are maintaining. This allows one to 'delete' a whole class at
  676. /// a time, even though there may be circular references... first all
  677. /// references are dropped, and all use counts go to zero. Then everything
  678. /// is delete'd for real. Note that no operations are valid on an object
  679. /// that has "dropped all references", except operator delete.
  680. void dropAllReferences();
  681. /// @}
  682. /// @name Utility functions for querying Debug information.
  683. /// @{
  684. /// Returns the Number of Register ParametersDwarf Version by checking
  685. /// module flags.
  686. unsigned getNumberRegisterParameters() const;
  687. /// Returns the Dwarf Version by checking module flags.
  688. unsigned getDwarfVersion() const;
  689. /// Returns the DWARF format by checking module flags.
  690. bool isDwarf64() const;
  691. /// Returns the CodeView Version by checking module flags.
  692. /// Returns zero if not present in module.
  693. unsigned getCodeViewFlag() const;
  694. /// @}
  695. /// @name Utility functions for querying and setting PIC level
  696. /// @{
  697. /// Returns the PIC level (small or large model)
  698. PICLevel::Level getPICLevel() const;
  699. /// Set the PIC level (small or large model)
  700. void setPICLevel(PICLevel::Level PL);
  701. /// @}
  702. /// @}
  703. /// @name Utility functions for querying and setting PIE level
  704. /// @{
  705. /// Returns the PIE level (small or large model)
  706. PIELevel::Level getPIELevel() const;
  707. /// Set the PIE level (small or large model)
  708. void setPIELevel(PIELevel::Level PL);
  709. /// @}
  710. /// @}
  711. /// @name Utility function for querying and setting code model
  712. /// @{
  713. /// Returns the code model (tiny, small, kernel, medium or large model)
  714. Optional<CodeModel::Model> getCodeModel() const;
  715. /// Set the code model (tiny, small, kernel, medium or large)
  716. void setCodeModel(CodeModel::Model CL);
  717. /// @}
  718. /// @name Utility functions for querying and setting PGO summary
  719. /// @{
  720. /// Attach profile summary metadata to this module.
  721. void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind);
  722. /// Returns profile summary metadata. When IsCS is true, use the context
  723. /// sensitive profile summary.
  724. Metadata *getProfileSummary(bool IsCS) const;
  725. /// @}
  726. /// Returns whether semantic interposition is to be respected.
  727. bool getSemanticInterposition() const;
  728. /// Set whether semantic interposition is to be respected.
  729. void setSemanticInterposition(bool);
  730. /// Returns true if PLT should be avoided for RTLib calls.
  731. bool getRtLibUseGOT() const;
  732. /// Set that PLT should be avoid for RTLib calls.
  733. void setRtLibUseGOT();
  734. /// Get/set whether synthesized functions should get the uwtable attribute.
  735. bool getUwtable() const;
  736. void setUwtable();
  737. /// Get/set whether synthesized functions should get the "frame-pointer"
  738. /// attribute.
  739. FramePointerKind getFramePointer() const;
  740. void setFramePointer(FramePointerKind Kind);
  741. /// Get/set what kind of stack protector guard to use.
  742. StringRef getStackProtectorGuard() const;
  743. void setStackProtectorGuard(StringRef Kind);
  744. /// Get/set which register to use as the stack protector guard register. The
  745. /// empty string is equivalent to "global". Other values may be "tls" or
  746. /// "sysreg".
  747. StringRef getStackProtectorGuardReg() const;
  748. void setStackProtectorGuardReg(StringRef Reg);
  749. /// Get/set what offset from the stack protector to use.
  750. int getStackProtectorGuardOffset() const;
  751. void setStackProtectorGuardOffset(int Offset);
  752. /// Get/set the stack alignment overridden from the default.
  753. unsigned getOverrideStackAlignment() const;
  754. void setOverrideStackAlignment(unsigned Align);
  755. /// @name Utility functions for querying and setting the build SDK version
  756. /// @{
  757. /// Attach a build SDK version metadata to this module.
  758. void setSDKVersion(const VersionTuple &V);
  759. /// Get the build SDK version metadata.
  760. ///
  761. /// An empty version is returned if no such metadata is attached.
  762. VersionTuple getSDKVersion() const;
  763. /// @}
  764. /// Take ownership of the given memory buffer.
  765. void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
  766. /// Set the partial sample profile ratio in the profile summary module flag,
  767. /// if applicable.
  768. void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index);
  769. /// Get the target variant triple which is a string describing a variant of
  770. /// the target host platform. For example, Mac Catalyst can be a variant
  771. /// target triple for a macOS target.
  772. /// @returns a string containing the target variant triple.
  773. StringRef getDarwinTargetVariantTriple() const;
  774. /// Get the target variant version build SDK version metadata.
  775. ///
  776. /// An empty version is returned if no such metadata is attached.
  777. VersionTuple getDarwinTargetVariantSDKVersion() const;
  778. };
  779. /// Given "llvm.used" or "llvm.compiler.used" as a global name, collect the
  780. /// initializer elements of that global in a SmallVector and return the global
  781. /// itself.
  782. GlobalVariable *collectUsedGlobalVariables(const Module &M,
  783. SmallVectorImpl<GlobalValue *> &Vec,
  784. bool CompilerUsed);
  785. /// An raw_ostream inserter for modules.
  786. inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
  787. M.print(O, nullptr);
  788. return O;
  789. }
  790. // Create wrappers for C Binding types (see CBindingWrapping.h).
  791. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
  792. /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
  793. * Module.
  794. */
  795. inline Module *unwrap(LLVMModuleProviderRef MP) {
  796. return reinterpret_cast<Module*>(MP);
  797. }
  798. } // end namespace llvm
  799. #endif // LLVM_IR_MODULE_H
  800. #ifdef __GNUC__
  801. #pragma GCC diagnostic pop
  802. #endif