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/OwningPtr.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Metadata.h"
23 #include "llvm/Support/CBindingWrapping.h"
24 #include "llvm/Support/DataTypes.h"
32 template<typename T> struct DenseMapInfo;
33 template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
35 template<> struct ilist_traits<Function>
36 : public SymbolTableListTraits<Function, Module> {
38 // createSentinel is used to get hold of the node that marks the end of the
39 // list... (same trick used here as in ilist_traits<Instruction>)
40 Function *createSentinel() const {
41 return static_cast<Function*>(&Sentinel);
43 static void destroySentinel(Function*) {}
45 Function *provideInitialHead() const { return createSentinel(); }
46 Function *ensureHead(Function*) const { return createSentinel(); }
47 static void noteHead(Function*, Function*) {}
50 mutable ilist_node<Function> Sentinel;
53 template<> struct ilist_traits<GlobalVariable>
54 : public SymbolTableListTraits<GlobalVariable, Module> {
55 // createSentinel is used to create a node that marks the end of the list.
56 GlobalVariable *createSentinel() const {
57 return static_cast<GlobalVariable*>(&Sentinel);
59 static void destroySentinel(GlobalVariable*) {}
61 GlobalVariable *provideInitialHead() const { return createSentinel(); }
62 GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
63 static void noteHead(GlobalVariable*, GlobalVariable*) {}
65 mutable ilist_node<GlobalVariable> Sentinel;
68 template<> struct ilist_traits<GlobalAlias>
69 : public SymbolTableListTraits<GlobalAlias, Module> {
70 // createSentinel is used to create a node that marks the end of the list.
71 GlobalAlias *createSentinel() const {
72 return static_cast<GlobalAlias*>(&Sentinel);
74 static void destroySentinel(GlobalAlias*) {}
76 GlobalAlias *provideInitialHead() const { return createSentinel(); }
77 GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
78 static void noteHead(GlobalAlias*, GlobalAlias*) {}
80 mutable ilist_node<GlobalAlias> Sentinel;
83 template<> struct ilist_traits<NamedMDNode>
84 : public ilist_default_traits<NamedMDNode> {
85 // createSentinel is used to get hold of a node that marks the end of
87 NamedMDNode *createSentinel() const {
88 return static_cast<NamedMDNode*>(&Sentinel);
90 static void destroySentinel(NamedMDNode*) {}
92 NamedMDNode *provideInitialHead() const { return createSentinel(); }
93 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
94 static void noteHead(NamedMDNode*, NamedMDNode*) {}
95 void addNodeToList(NamedMDNode *) {}
96 void removeNodeFromList(NamedMDNode *) {}
98 mutable ilist_node<NamedMDNode> Sentinel;
101 /// A Module instance is used to store all the information related to an
102 /// LLVM module. Modules are the top level container of all other LLVM
103 /// Intermediate Representation (IR) objects. Each module directly contains a
104 /// list of globals variables, a list of functions, a list of libraries (or
105 /// other modules) this module depends on, a symbol table, and various data
106 /// about the target's characteristics.
108 /// A module maintains a GlobalValRefMap object that is used to hold all
109 /// constant references to global variables in the module. When a global
110 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
111 /// @brief The main container class for the LLVM Intermediate Representation.
113 /// @name Types And Enumerations
116 /// The type for the list of global variables.
117 typedef iplist<GlobalVariable> GlobalListType;
118 /// The type for the list of functions.
119 typedef iplist<Function> FunctionListType;
120 /// The type for the list of aliases.
121 typedef iplist<GlobalAlias> AliasListType;
122 /// The type for the list of named metadata.
123 typedef ilist<NamedMDNode> NamedMDListType;
125 /// The Global Variable iterator.
126 typedef GlobalListType::iterator global_iterator;
127 /// The Global Variable constant iterator.
128 typedef GlobalListType::const_iterator const_global_iterator;
130 /// The Function iterators.
131 typedef FunctionListType::iterator iterator;
132 /// The Function constant iterator
133 typedef FunctionListType::const_iterator const_iterator;
135 /// The Global Alias iterators.
136 typedef AliasListType::iterator alias_iterator;
137 /// The Global Alias constant iterator
138 typedef AliasListType::const_iterator const_alias_iterator;
140 /// The named metadata iterators.
141 typedef NamedMDListType::iterator named_metadata_iterator;
142 /// The named metadata constant interators.
143 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
145 /// This enumeration defines the supported behaviors of module flags.
146 enum ModFlagBehavior {
147 /// Emits an error if two values disagree, otherwise the resulting value is
148 /// that of the operands.
151 /// Emits a warning if two values disagree. The result value will be the
152 /// operand for the flag from the first module being linked.
155 /// Adds a requirement that another module flag be present and have a
156 /// specified value after linking is performed. The value must be a metadata
157 /// pair, where the first element of the pair is the ID of the module flag
158 /// to be restricted, and the second element of the pair is the value the
159 /// module flag should be restricted to. This behavior can be used to
160 /// restrict the allowable results (via triggering of an error) of linking
161 /// IDs with the **Override** behavior.
164 /// Uses the specified value, regardless of the behavior or value of the
165 /// other module. If both modules specify **Override**, but the values
166 /// differ, an error will be emitted.
169 /// Appends the two values, which are required to be metadata nodes.
172 /// Appends the two values, which are required to be metadata
173 /// nodes. However, duplicate entries in the second list are dropped
174 /// during the append operation.
178 struct ModuleFlagEntry {
179 ModFlagBehavior Behavior;
182 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
183 : Behavior(B), Key(K), Val(V) {}
187 /// @name Member Variables
190 LLVMContext &Context; ///< The LLVMContext from which types and
191 ///< constants are allocated.
192 GlobalListType GlobalList; ///< The Global Variables in the module
193 FunctionListType FunctionList; ///< The Functions in the module
194 AliasListType AliasList; ///< The Aliases in the module
195 NamedMDListType NamedMDList; ///< The named metadata in the module
196 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
197 ValueSymbolTable *ValSymTab; ///< Symbol table for values
198 OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
199 std::string ModuleID; ///< Human readable identifier for the module
200 std::string TargetTriple; ///< Platform target triple Module compiled on
201 std::string DataLayout; ///< Target data description
202 void *NamedMDSymTab; ///< NamedMDNode names.
204 friend class Constant;
207 /// @name Constructors
210 /// The Module constructor. Note that there is no default constructor. You
211 /// must provide a name for the module upon construction.
212 explicit Module(StringRef ModuleID, LLVMContext& C);
213 /// The module destructor. This will dropAllReferences.
217 /// @name Module Level Accessors
220 /// Get the module identifier which is, essentially, the name of the module.
221 /// @returns the module identifier as a string
222 const std::string &getModuleIdentifier() const { return ModuleID; }
224 /// Get the data layout string for the module's target platform. This encodes
225 /// the type sizes and alignments expected by this module.
226 /// @returns the data layout as a string
227 const std::string &getDataLayout() const { return DataLayout; }
229 /// Get the target triple which is a string describing the target host.
230 /// @returns a string containing the target triple.
231 const std::string &getTargetTriple() const { return TargetTriple; }
233 /// Get the global data context.
234 /// @returns LLVMContext - a container for LLVM's global information
235 LLVMContext &getContext() const { return Context; }
237 /// Get any module-scope inline assembly blocks.
238 /// @returns a string containing the module-scope inline assembly blocks.
239 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
242 /// @name Module Level Mutators
245 /// Set the module identifier.
246 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
248 /// Set the data layout
249 void setDataLayout(StringRef DL) { DataLayout = DL; }
251 /// Set the target triple.
252 void setTargetTriple(StringRef T) { TargetTriple = T; }
254 /// Set the module-scope inline assembly blocks.
255 void setModuleInlineAsm(StringRef Asm) {
256 GlobalScopeAsm = Asm;
257 if (!GlobalScopeAsm.empty() &&
258 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
259 GlobalScopeAsm += '\n';
262 /// Append to the module-scope inline assembly blocks, automatically inserting
263 /// a separating newline if necessary.
264 void appendModuleInlineAsm(StringRef Asm) {
265 GlobalScopeAsm += Asm;
266 if (!GlobalScopeAsm.empty() &&
267 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
268 GlobalScopeAsm += '\n';
272 /// @name Generic Value Accessors
275 /// getNamedValue - Return the global value in the module with
276 /// the specified name, of arbitrary type. This method returns null
277 /// if a global with the specified name is not found.
278 GlobalValue *getNamedValue(StringRef Name) const;
280 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
281 /// This ID is uniqued across modules in the current LLVMContext.
282 unsigned getMDKindID(StringRef Name) const;
284 /// getMDKindNames - Populate client supplied SmallVector with the name for
285 /// custom metadata IDs registered in this LLVMContext.
286 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
289 typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*> >
292 /// getTypeByName - Return the type with the specified name, or null if there
293 /// is none by that name.
294 StructType *getTypeByName(StringRef Name) const;
297 /// @name Function Accessors
300 /// getOrInsertFunction - Look up the specified function in the module symbol
301 /// table. Four possibilities:
302 /// 1. If it does not exist, add a prototype for the function and return it.
303 /// 2. If it exists, and has a local linkage, the existing function is
304 /// renamed and a new one is inserted.
305 /// 3. Otherwise, if the existing function has the correct prototype, return
306 /// the existing function.
307 /// 4. Finally, the function exists but has the wrong prototype: return the
308 /// function with a constantexpr cast to the right prototype.
309 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
310 AttributeSet AttributeList);
312 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
314 /// getOrInsertFunction - Look up the specified function in the module symbol
315 /// table. If it does not exist, add a prototype for the function and return
316 /// it. This function guarantees to return a constant of pointer to the
317 /// specified function type or a ConstantExpr BitCast of that type if the
318 /// named function has a different type. This version of the method takes a
319 /// null terminated list of function arguments, which makes it easier for
321 Constant *getOrInsertFunction(StringRef Name,
322 AttributeSet AttributeList,
323 Type *RetTy, ...) END_WITH_NULL;
325 /// getOrInsertFunction - Same as above, but without the attributes.
326 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
329 /// getFunction - Look up the specified function in the module symbol table.
330 /// If it does not exist, return null.
331 Function *getFunction(StringRef Name) const;
334 /// @name Global Variable Accessors
337 /// getGlobalVariable - Look up the specified global variable in the module
338 /// symbol table. If it does not exist, return null. If AllowInternal is set
339 /// to true, this function will return types that have InternalLinkage. By
340 /// default, these types are not returned.
341 const GlobalVariable *getGlobalVariable(StringRef Name,
342 bool AllowInternal = false) const {
343 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
346 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
348 /// getNamedGlobal - Return the global variable in the module with the
349 /// specified name, of arbitrary type. This method returns null if a global
350 /// with the specified name is not found.
351 GlobalVariable *getNamedGlobal(StringRef Name) {
352 return getGlobalVariable(Name, true);
354 const GlobalVariable *getNamedGlobal(StringRef Name) const {
355 return const_cast<Module *>(this)->getNamedGlobal(Name);
358 /// getOrInsertGlobal - Look up the specified global in the module symbol
360 /// 1. If it does not exist, add a declaration of the global and return it.
361 /// 2. Else, the global exists but has the wrong type: return the function
362 /// with a constantexpr cast to the right type.
363 /// 3. Finally, if the existing global is the correct declaration, return
364 /// the existing global.
365 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
368 /// @name Global Alias Accessors
371 /// getNamedAlias - Return the global alias in the module with the
372 /// specified name, of arbitrary type. This method returns null if a global
373 /// with the specified name is not found.
374 GlobalAlias *getNamedAlias(StringRef Name) const;
377 /// @name Named Metadata Accessors
380 /// getNamedMetadata - Return the first NamedMDNode in the module with the
381 /// specified name. This method returns null if a NamedMDNode with the
382 /// specified name is not found.
383 NamedMDNode *getNamedMetadata(const Twine &Name) const;
385 /// getOrInsertNamedMetadata - Return the named MDNode in the module
386 /// with the specified name. This method returns a new NamedMDNode if a
387 /// NamedMDNode with the specified name is not found.
388 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
390 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
392 void eraseNamedMetadata(NamedMDNode *NMD);
395 /// @name Module Flags Accessors
398 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
399 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
401 /// Return the corresponding value if Key appears in module flags, otherwise
403 Value *getModuleFlag(StringRef Key) const;
405 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
406 /// represents module-level flags. This method returns null if there are no
407 /// module-level flags.
408 NamedMDNode *getModuleFlagsMetadata() const;
410 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
411 /// that represents module-level flags. If module-level flags aren't found,
412 /// it creates the named metadata that contains them.
413 NamedMDNode *getOrInsertModuleFlagsMetadata();
415 /// addModuleFlag - Add a module-level flag to the module-level flags
416 /// metadata. It will create the module-level flags named metadata if it
417 /// doesn't already exist.
418 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
419 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
420 void addModuleFlag(MDNode *Node);
423 /// @name Materialization
426 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
427 /// yet have a Materializer. To reset the materializer for a module that
428 /// already has one, call MaterializeAllPermanently first. Destroying this
429 /// module will destroy its materializer without materializing any more
430 /// GlobalValues. Without destroying the Module, there is no way to detach or
431 /// destroy a materializer without materializing all the GVs it controls, to
432 /// avoid leaving orphan unmaterialized GVs.
433 void setMaterializer(GVMaterializer *GVM);
434 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
435 GVMaterializer *getMaterializer() const { return Materializer.get(); }
437 /// isMaterializable - True if the definition of GV has yet to be materialized
438 /// from the GVMaterializer.
439 bool isMaterializable(const GlobalValue *GV) const;
440 /// isDematerializable - Returns true if this GV was loaded from this Module's
441 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
442 bool isDematerializable(const GlobalValue *GV) const;
444 /// Materialize - Make sure the GlobalValue is fully read. If the module is
445 /// corrupt, this returns true and fills in the optional string with
446 /// information about the problem. If successful, this returns false.
447 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
448 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
449 /// supports it, release the memory for the function, and set it up to be
450 /// materialized lazily. If !isDematerializable(), this method is a noop.
451 void Dematerialize(GlobalValue *GV);
453 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
454 /// If the module is corrupt, this returns true and fills in the optional
455 /// string with information about the problem. If successful, this returns
457 bool MaterializeAll(std::string *ErrInfo = 0);
459 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
460 /// fully read and clear the Materializer. If the module is corrupt, this
461 /// returns true, fills in the optional string with information about the
462 /// problem, and DOES NOT clear the old Materializer. If successful, this
464 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
467 /// @name Direct access to the globals list, functions list, and symbol table
470 /// Get the Module's list of global variables (constant).
471 const GlobalListType &getGlobalList() const { return GlobalList; }
472 /// Get the Module's list of global variables.
473 GlobalListType &getGlobalList() { return GlobalList; }
474 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
475 return &Module::GlobalList;
477 /// Get the Module's list of functions (constant).
478 const FunctionListType &getFunctionList() const { return FunctionList; }
479 /// Get the Module's list of functions.
480 FunctionListType &getFunctionList() { return FunctionList; }
481 static iplist<Function> Module::*getSublistAccess(Function*) {
482 return &Module::FunctionList;
484 /// Get the Module's list of aliases (constant).
485 const AliasListType &getAliasList() const { return AliasList; }
486 /// Get the Module's list of aliases.
487 AliasListType &getAliasList() { return AliasList; }
488 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
489 return &Module::AliasList;
491 /// Get the Module's list of named metadata (constant).
492 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
493 /// Get the Module's list of named metadata.
494 NamedMDListType &getNamedMDList() { return NamedMDList; }
495 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
496 return &Module::NamedMDList;
498 /// Get the symbol table of global variable and function identifiers
499 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
500 /// Get the Module's symbol table of global variable and function identifiers.
501 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
504 /// @name Global Variable Iteration
507 global_iterator global_begin() { return GlobalList.begin(); }
508 const_global_iterator global_begin() const { return GlobalList.begin(); }
509 global_iterator global_end () { return GlobalList.end(); }
510 const_global_iterator global_end () const { return GlobalList.end(); }
511 bool global_empty() const { return GlobalList.empty(); }
514 /// @name Function Iteration
517 iterator begin() { return FunctionList.begin(); }
518 const_iterator begin() const { return FunctionList.begin(); }
519 iterator end () { return FunctionList.end(); }
520 const_iterator end () const { return FunctionList.end(); }
521 size_t size() const { return FunctionList.size(); }
522 bool empty() const { return FunctionList.empty(); }
525 /// @name Alias Iteration
528 alias_iterator alias_begin() { return AliasList.begin(); }
529 const_alias_iterator alias_begin() const { return AliasList.begin(); }
530 alias_iterator alias_end () { return AliasList.end(); }
531 const_alias_iterator alias_end () const { return AliasList.end(); }
532 size_t alias_size () const { return AliasList.size(); }
533 bool alias_empty() const { return AliasList.empty(); }
537 /// @name Named Metadata Iteration
540 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
541 const_named_metadata_iterator named_metadata_begin() const {
542 return NamedMDList.begin();
545 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
546 const_named_metadata_iterator named_metadata_end() const {
547 return NamedMDList.end();
550 size_t named_metadata_size() const { return NamedMDList.size(); }
551 bool named_metadata_empty() const { return NamedMDList.empty(); }
555 /// @name Utility functions for printing and dumping Module objects
558 /// Print the module to an output stream with an optional
559 /// AssemblyAnnotationWriter.
560 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
562 /// Dump the module to stderr (for debugging).
565 /// This function causes all the subinstructions to "let go" of all references
566 /// that they are maintaining. This allows one to 'delete' a whole class at
567 /// a time, even though there may be circular references... first all
568 /// references are dropped, and all use counts go to zero. Then everything
569 /// is delete'd for real. Note that no operations are valid on an object
570 /// that has "dropped all references", except operator delete.
571 void dropAllReferences();
575 /// An raw_ostream inserter for modules.
576 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
581 // Create wrappers for C Binding types (see CBindingWrapping.h).
582 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
584 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
587 inline Module *unwrap(LLVMModuleProviderRef MP) {
588 return reinterpret_cast<Module*>(MP);
591 } // End llvm namespace