1 //===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Module.h This file contains the declarations for the Module class.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_MODULE_H
16 #define LLVM_IR_MODULE_H
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/Comdat.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GlobalAlias.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/Support/CBindingWrapping.h"
26 #include "llvm/Support/DataTypes.h"
27 #include <system_error>
33 class RandomNumberGenerator;
35 template<typename T> struct DenseMapInfo;
36 template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
38 template<> struct ilist_traits<Function>
39 : public SymbolTableListTraits<Function, Module> {
41 // createSentinel is used to get hold of the node that marks the end of the
42 // list... (same trick used here as in ilist_traits<Instruction>)
43 Function *createSentinel() const {
44 return static_cast<Function*>(&Sentinel);
46 static void destroySentinel(Function*) {}
48 Function *provideInitialHead() const { return createSentinel(); }
49 Function *ensureHead(Function*) const { return createSentinel(); }
50 static void noteHead(Function*, Function*) {}
53 mutable ilist_node<Function> Sentinel;
56 template<> struct ilist_traits<GlobalVariable>
57 : public SymbolTableListTraits<GlobalVariable, Module> {
58 // createSentinel is used to create a node that marks the end of the list.
59 GlobalVariable *createSentinel() const {
60 return static_cast<GlobalVariable*>(&Sentinel);
62 static void destroySentinel(GlobalVariable*) {}
64 GlobalVariable *provideInitialHead() const { return createSentinel(); }
65 GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
66 static void noteHead(GlobalVariable*, GlobalVariable*) {}
68 mutable ilist_node<GlobalVariable> Sentinel;
71 template<> struct ilist_traits<GlobalAlias>
72 : public SymbolTableListTraits<GlobalAlias, Module> {
73 // createSentinel is used to create a node that marks the end of the list.
74 GlobalAlias *createSentinel() const {
75 return static_cast<GlobalAlias*>(&Sentinel);
77 static void destroySentinel(GlobalAlias*) {}
79 GlobalAlias *provideInitialHead() const { return createSentinel(); }
80 GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
81 static void noteHead(GlobalAlias*, GlobalAlias*) {}
83 mutable ilist_node<GlobalAlias> Sentinel;
86 template<> struct ilist_traits<NamedMDNode>
87 : public ilist_default_traits<NamedMDNode> {
88 // createSentinel is used to get hold of a node that marks the end of
90 NamedMDNode *createSentinel() const {
91 return static_cast<NamedMDNode*>(&Sentinel);
93 static void destroySentinel(NamedMDNode*) {}
95 NamedMDNode *provideInitialHead() const { return createSentinel(); }
96 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
97 static void noteHead(NamedMDNode*, NamedMDNode*) {}
98 void addNodeToList(NamedMDNode *) {}
99 void removeNodeFromList(NamedMDNode *) {}
101 mutable ilist_node<NamedMDNode> Sentinel;
104 /// A Module instance is used to store all the information related to an
105 /// LLVM module. Modules are the top level container of all other LLVM
106 /// Intermediate Representation (IR) objects. Each module directly contains a
107 /// list of globals variables, a list of functions, a list of libraries (or
108 /// other modules) this module depends on, a symbol table, and various data
109 /// about the target's characteristics.
111 /// A module maintains a GlobalValRefMap object that is used to hold all
112 /// constant references to global variables in the module. When a global
113 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
114 /// @brief The main container class for the LLVM Intermediate Representation.
116 /// @name Types And Enumerations
119 /// The type for the list of global variables.
120 typedef iplist<GlobalVariable> GlobalListType;
121 /// The type for the list of functions.
122 typedef iplist<Function> FunctionListType;
123 /// The type for the list of aliases.
124 typedef iplist<GlobalAlias> AliasListType;
125 /// The type for the list of named metadata.
126 typedef ilist<NamedMDNode> NamedMDListType;
127 /// The type of the comdat "symbol" table.
128 typedef StringMap<Comdat> ComdatSymTabType;
130 /// The Global Variable iterator.
131 typedef GlobalListType::iterator global_iterator;
132 /// The Global Variable constant iterator.
133 typedef GlobalListType::const_iterator const_global_iterator;
135 /// The Function iterators.
136 typedef FunctionListType::iterator iterator;
137 /// The Function constant iterator
138 typedef FunctionListType::const_iterator const_iterator;
140 /// The Global Alias iterators.
141 typedef AliasListType::iterator alias_iterator;
142 /// The Global Alias constant iterator
143 typedef AliasListType::const_iterator const_alias_iterator;
145 /// The named metadata iterators.
146 typedef NamedMDListType::iterator named_metadata_iterator;
147 /// The named metadata constant interators.
148 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
150 /// This enumeration defines the supported behaviors of module flags.
151 enum ModFlagBehavior {
152 /// Emits an error if two values disagree, otherwise the resulting value is
153 /// that of the operands.
156 /// Emits a warning if two values disagree. The result value will be the
157 /// operand for the flag from the first module being linked.
160 /// Adds a requirement that another module flag be present and have a
161 /// specified value after linking is performed. The value must be a metadata
162 /// pair, where the first element of the pair is the ID of the module flag
163 /// to be restricted, and the second element of the pair is the value the
164 /// module flag should be restricted to. This behavior can be used to
165 /// restrict the allowable results (via triggering of an error) of linking
166 /// IDs with the **Override** behavior.
169 /// Uses the specified value, regardless of the behavior or value of the
170 /// other module. If both modules specify **Override**, but the values
171 /// differ, an error will be emitted.
174 /// Appends the two values, which are required to be metadata nodes.
177 /// Appends the two values, which are required to be metadata
178 /// nodes. However, duplicate entries in the second list are dropped
179 /// during the append operation.
183 struct ModuleFlagEntry {
184 ModFlagBehavior Behavior;
187 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
188 : Behavior(B), Key(K), Val(V) {}
192 /// @name Member Variables
195 LLVMContext &Context; ///< The LLVMContext from which types and
196 ///< constants are allocated.
197 GlobalListType GlobalList; ///< The Global Variables in the module
198 FunctionListType FunctionList; ///< The Functions in the module
199 AliasListType AliasList; ///< The Aliases in the module
200 NamedMDListType NamedMDList; ///< The named metadata in the module
201 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
202 ValueSymbolTable *ValSymTab; ///< Symbol table for values
203 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
204 std::unique_ptr<GVMaterializer>
205 Materializer; ///< Used to materialize GlobalValues
206 std::string ModuleID; ///< Human readable identifier for the module
207 std::string TargetTriple; ///< Platform target triple Module compiled on
208 void *NamedMDSymTab; ///< NamedMDNode names.
209 // Allow lazy initialization in const method.
210 mutable RandomNumberGenerator *RNG; ///< The random number generator for this module.
212 // We need to keep the string because the C API expects us to own the string
214 // Since we have it, we also use an empty string to represent a module without
215 // a DataLayout. If it has a DataLayout, these variables are in sync and the
216 // string is just a cache of getDataLayout()->getStringRepresentation().
217 std::string DataLayoutStr;
220 friend class Constant;
223 /// @name Constructors
226 /// The Module constructor. Note that there is no default constructor. You
227 /// must provide a name for the module upon construction.
228 explicit Module(StringRef ModuleID, LLVMContext& C);
229 /// The module destructor. This will dropAllReferences.
233 /// @name Module Level Accessors
236 /// Get the module identifier which is, essentially, the name of the module.
237 /// @returns the module identifier as a string
238 const std::string &getModuleIdentifier() const { return ModuleID; }
240 /// Get the data layout string for the module's target platform. This is
241 /// equivalent to getDataLayout()->getStringRepresentation().
242 const std::string &getDataLayoutStr() const { return DataLayoutStr; }
244 /// Get the data layout for the module's target platform.
245 const DataLayout *getDataLayout() const;
247 /// Get the target triple which is a string describing the target host.
248 /// @returns a string containing the target triple.
249 const std::string &getTargetTriple() const { return TargetTriple; }
251 /// Get the global data context.
252 /// @returns LLVMContext - a container for LLVM's global information
253 LLVMContext &getContext() const { return Context; }
255 /// Get any module-scope inline assembly blocks.
256 /// @returns a string containing the module-scope inline assembly blocks.
257 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
259 /// Get the RandomNumberGenerator for this module. The RNG can be
260 /// seeded via -rng-seed=<uint64> and is salted with the ModuleID.
261 /// The returned RNG should not be shared across threads.
262 RandomNumberGenerator &getRNG() const;
265 /// @name Module Level Mutators
268 /// Set the module identifier.
269 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
271 /// Set the data layout
272 void setDataLayout(StringRef Desc);
273 void setDataLayout(const DataLayout *Other);
275 /// Set the target triple.
276 void setTargetTriple(StringRef T) { TargetTriple = T; }
278 /// Set the module-scope inline assembly blocks.
279 void setModuleInlineAsm(StringRef Asm) {
280 GlobalScopeAsm = Asm;
281 if (!GlobalScopeAsm.empty() &&
282 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
283 GlobalScopeAsm += '\n';
286 /// Append to the module-scope inline assembly blocks, automatically inserting
287 /// a separating newline if necessary.
288 void appendModuleInlineAsm(StringRef Asm) {
289 GlobalScopeAsm += Asm;
290 if (!GlobalScopeAsm.empty() &&
291 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
292 GlobalScopeAsm += '\n';
296 /// @name Generic Value Accessors
299 /// Return the global value in the module with the specified name, of
300 /// arbitrary type. This method returns null if a global with the specified
301 /// name is not found.
302 GlobalValue *getNamedValue(StringRef Name) const;
304 /// Return a unique non-zero ID for the specified metadata kind. This ID is
305 /// uniqued across modules in the current LLVMContext.
306 unsigned getMDKindID(StringRef Name) const;
308 /// Populate client supplied SmallVector with the name for custom metadata IDs
309 /// registered in this LLVMContext.
310 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
312 /// Return the type with the specified name, or null if there is none by that
314 StructType *getTypeByName(StringRef Name) const;
317 /// @name Function Accessors
320 /// Look up the specified function in the module symbol table. Four
322 /// 1. If it does not exist, add a prototype for the function and return it.
323 /// 2. If it exists, and has a local linkage, the existing function is
324 /// renamed and a new one is inserted.
325 /// 3. Otherwise, if the existing function has the correct prototype, return
326 /// the existing function.
327 /// 4. Finally, the function exists but has the wrong prototype: return the
328 /// function with a constantexpr cast to the right prototype.
329 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
330 AttributeSet AttributeList);
332 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
334 /// Look up the specified function in the module symbol table. If it does not
335 /// exist, add a prototype for the function and return it. This function
336 /// guarantees to return a constant of pointer to the specified function type
337 /// or a ConstantExpr BitCast of that type if the named function has a
338 /// different type. This version of the method takes a null terminated list of
339 /// function arguments, which makes it easier for clients to use.
340 Constant *getOrInsertFunction(StringRef Name,
341 AttributeSet AttributeList,
342 Type *RetTy, ...) END_WITH_NULL;
344 /// Same as above, but without the attributes.
345 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
348 /// Look up the specified function in the module symbol table. If it does not
349 /// exist, return null.
350 Function *getFunction(StringRef Name) const;
353 /// @name Global Variable Accessors
356 /// Look up the specified global variable in the module symbol table. If it
357 /// does not exist, return null. If AllowInternal is set to true, this
358 /// function will return types that have InternalLinkage. By default, these
359 /// types are not returned.
360 const GlobalVariable *getGlobalVariable(StringRef Name,
361 bool AllowInternal = false) const {
362 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
365 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
367 /// Return the global variable in the module with the specified name, of
368 /// arbitrary type. This method returns null if a global with the specified
369 /// name is not found.
370 GlobalVariable *getNamedGlobal(StringRef Name) {
371 return getGlobalVariable(Name, true);
373 const GlobalVariable *getNamedGlobal(StringRef Name) const {
374 return const_cast<Module *>(this)->getNamedGlobal(Name);
377 /// Look up the specified global in the module symbol table.
378 /// 1. If it does not exist, add a declaration of the global and return it.
379 /// 2. Else, the global exists but has the wrong type: return the function
380 /// with a constantexpr cast to the right type.
381 /// 3. Finally, if the existing global is the correct declaration, return
382 /// the existing global.
383 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
386 /// @name Global Alias Accessors
389 /// Return the global alias in the module with the specified name, of
390 /// arbitrary type. This method returns null if a global with the specified
391 /// name is not found.
392 GlobalAlias *getNamedAlias(StringRef Name) const;
395 /// @name Named Metadata Accessors
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;
402 /// Return the named MDNode in the module with the specified name. This method
403 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
405 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
407 /// Remove the given NamedMDNode from this module and delete it.
408 void eraseNamedMetadata(NamedMDNode *NMD);
411 /// @name Comdat Accessors
414 /// Return the Comdat in the module with the specified name. It is created
415 /// if it didn't already exist.
416 Comdat *getOrInsertComdat(StringRef Name);
419 /// @name Module Flags Accessors
422 /// Returns the module flags in the provided vector.
423 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
425 /// Return the corresponding value if Key appears in module flags, otherwise
427 Value *getModuleFlag(StringRef Key) const;
429 /// Returns the NamedMDNode in the module that represents module-level flags.
430 /// This method returns null if there are no module-level flags.
431 NamedMDNode *getModuleFlagsMetadata() const;
433 /// Returns the NamedMDNode in the module that represents module-level flags.
434 /// If module-level flags aren't found, it creates the named metadata that
436 NamedMDNode *getOrInsertModuleFlagsMetadata();
438 /// Add a module-level flag to the module-level flags metadata. It will create
439 /// the module-level flags named metadata if it doesn't already exist.
440 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
441 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
442 void addModuleFlag(MDNode *Node);
445 /// @name Materialization
448 /// Sets the GVMaterializer to GVM. This module must not yet have a
449 /// Materializer. To reset the materializer for a module that already has one,
450 /// call MaterializeAllPermanently first. Destroying this module will destroy
451 /// its materializer without materializing any more GlobalValues. Without
452 /// destroying the Module, there is no way to detach or destroy a materializer
453 /// without materializing all the GVs it controls, to avoid leaving orphan
454 /// unmaterialized GVs.
455 void setMaterializer(GVMaterializer *GVM);
456 /// Retrieves the GVMaterializer, if any, for this Module.
457 GVMaterializer *getMaterializer() const { return Materializer.get(); }
459 /// True if the definition of GV has yet to be materializedfrom the
461 bool isMaterializable(const GlobalValue *GV) const;
462 /// Returns true if this GV was loaded from this Module's GVMaterializer and
463 /// the GVMaterializer knows how to dematerialize the GV.
464 bool isDematerializable(const GlobalValue *GV) const;
466 /// Make sure the GlobalValue is fully read. If the module is corrupt, this
467 /// returns true and fills in the optional string with information about the
468 /// problem. If successful, this returns false.
469 bool Materialize(GlobalValue *GV, std::string *ErrInfo = nullptr);
470 /// If the GlobalValue is read in, and if the GVMaterializer supports it,
471 /// release the memory for the function, and set it up to be materialized
472 /// lazily. If !isDematerializable(), this method is a noop.
473 void Dematerialize(GlobalValue *GV);
475 /// Make sure all GlobalValues in this Module are fully read.
476 std::error_code materializeAll();
478 /// Make sure all GlobalValues in this Module are fully read and clear the
479 /// Materializer. If the module is corrupt, this DOES NOT clear the old
481 std::error_code materializeAllPermanently(bool ReleaseBuffer = false);
484 /// @name Direct access to the globals list, functions list, and symbol table
487 /// Get the Module's list of global variables (constant).
488 const GlobalListType &getGlobalList() const { return GlobalList; }
489 /// Get the Module's list of global variables.
490 GlobalListType &getGlobalList() { return GlobalList; }
491 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
492 return &Module::GlobalList;
494 /// Get the Module's list of functions (constant).
495 const FunctionListType &getFunctionList() const { return FunctionList; }
496 /// Get the Module's list of functions.
497 FunctionListType &getFunctionList() { return FunctionList; }
498 static iplist<Function> Module::*getSublistAccess(Function*) {
499 return &Module::FunctionList;
501 /// Get the Module's list of aliases (constant).
502 const AliasListType &getAliasList() const { return AliasList; }
503 /// Get the Module's list of aliases.
504 AliasListType &getAliasList() { return AliasList; }
505 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
506 return &Module::AliasList;
508 /// Get the Module's list of named metadata (constant).
509 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
510 /// Get the Module's list of named metadata.
511 NamedMDListType &getNamedMDList() { return NamedMDList; }
512 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
513 return &Module::NamedMDList;
515 /// Get the symbol table of global variable and function identifiers
516 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
517 /// Get the Module's symbol table of global variable and function identifiers.
518 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
519 /// Get the Module's symbol table for COMDATs (constant).
520 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
521 /// Get the Module's symbol table for COMDATs.
522 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
525 /// @name Global Variable Iteration
528 global_iterator global_begin() { return GlobalList.begin(); }
529 const_global_iterator global_begin() const { return GlobalList.begin(); }
530 global_iterator global_end () { return GlobalList.end(); }
531 const_global_iterator global_end () const { return GlobalList.end(); }
532 bool global_empty() const { return GlobalList.empty(); }
534 iterator_range<global_iterator> globals() {
535 return iterator_range<global_iterator>(global_begin(), global_end());
537 iterator_range<const_global_iterator> globals() const {
538 return iterator_range<const_global_iterator>(global_begin(), global_end());
542 /// @name Function Iteration
545 iterator begin() { return FunctionList.begin(); }
546 const_iterator begin() const { return FunctionList.begin(); }
547 iterator end () { return FunctionList.end(); }
548 const_iterator end () const { return FunctionList.end(); }
549 size_t size() const { return FunctionList.size(); }
550 bool empty() const { return FunctionList.empty(); }
553 /// @name Alias Iteration
556 alias_iterator alias_begin() { return AliasList.begin(); }
557 const_alias_iterator alias_begin() const { return AliasList.begin(); }
558 alias_iterator alias_end () { return AliasList.end(); }
559 const_alias_iterator alias_end () const { return AliasList.end(); }
560 size_t alias_size () const { return AliasList.size(); }
561 bool alias_empty() const { return AliasList.empty(); }
563 iterator_range<alias_iterator> aliases() {
564 return iterator_range<alias_iterator>(alias_begin(), alias_end());
566 iterator_range<const_alias_iterator> aliases() const {
567 return iterator_range<const_alias_iterator>(alias_begin(), alias_end());
571 /// @name Named Metadata Iteration
574 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
575 const_named_metadata_iterator named_metadata_begin() const {
576 return NamedMDList.begin();
579 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
580 const_named_metadata_iterator named_metadata_end() const {
581 return NamedMDList.end();
584 size_t named_metadata_size() const { return NamedMDList.size(); }
585 bool named_metadata_empty() const { return NamedMDList.empty(); }
587 iterator_range<named_metadata_iterator> named_metadata() {
588 return iterator_range<named_metadata_iterator>(named_metadata_begin(),
589 named_metadata_end());
591 iterator_range<const_named_metadata_iterator> named_metadata() const {
592 return iterator_range<const_named_metadata_iterator>(named_metadata_begin(),
593 named_metadata_end());
597 /// @name Utility functions for printing and dumping Module objects
600 /// Print the module to an output stream with an optional
601 /// AssemblyAnnotationWriter.
602 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
604 /// Dump the module to stderr (for debugging).
607 /// This function causes all the subinstructions to "let go" of all references
608 /// that they are maintaining. This allows one to 'delete' a whole class at
609 /// a time, even though there may be circular references... first all
610 /// references are dropped, and all use counts go to zero. Then everything
611 /// is delete'd for real. Note that no operations are valid on an object
612 /// that has "dropped all references", except operator delete.
613 void dropAllReferences();
616 /// @name Utility functions for querying Debug information.
619 /// \brief Returns the Dwarf Version by checking module flags.
620 unsigned getDwarfVersion() const;
625 /// An raw_ostream inserter for modules.
626 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
631 // Create wrappers for C Binding types (see CBindingWrapping.h).
632 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
634 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
637 inline Module *unwrap(LLVMModuleProviderRef MP) {
638 return reinterpret_cast<Module*>(MP);
641 } // End llvm namespace