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 //===----------------------------------------------------------------------===//
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/Metadata.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/Support/DataTypes.h"
32 template<typename T> struct DenseMapInfo;
33 template<typename KeyT, typename ValueT,
34 typename KeyInfoT, typename ValueInfoT> class DenseMap;
36 template<> struct ilist_traits<Function>
37 : public SymbolTableListTraits<Function, Module> {
39 // createSentinel is used to get hold of the node that marks the end of the
40 // list... (same trick used here as in ilist_traits<Instruction>)
41 Function *createSentinel() const {
42 return static_cast<Function*>(&Sentinel);
44 static void destroySentinel(Function*) {}
46 Function *provideInitialHead() const { return createSentinel(); }
47 Function *ensureHead(Function*) const { return createSentinel(); }
48 static void noteHead(Function*, Function*) {}
51 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 static GlobalVariable *createSentinel();
57 static void destroySentinel(GlobalVariable *GV) { delete GV; }
59 template<> struct ilist_traits<GlobalAlias>
60 : public SymbolTableListTraits<GlobalAlias, Module> {
61 // createSentinel is used to create a node that marks the end of the list.
62 static GlobalAlias *createSentinel();
63 static void destroySentinel(GlobalAlias *GA) { delete GA; }
66 template<> struct ilist_traits<NamedMDNode>
67 : public ilist_default_traits<NamedMDNode> {
68 // createSentinel is used to get hold of a node that marks the end of
70 NamedMDNode *createSentinel() const {
71 return static_cast<NamedMDNode*>(&Sentinel);
73 static void destroySentinel(NamedMDNode*) {}
75 NamedMDNode *provideInitialHead() const { return createSentinel(); }
76 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
77 static void noteHead(NamedMDNode*, NamedMDNode*) {}
78 void addNodeToList(NamedMDNode *) {}
79 void removeNodeFromList(NamedMDNode *) {}
81 mutable ilist_node<NamedMDNode> Sentinel;
84 /// A Module instance is used to store all the information related to an
85 /// LLVM module. Modules are the top level container of all other LLVM
86 /// Intermediate Representation (IR) objects. Each module directly contains a
87 /// list of globals variables, a list of functions, a list of libraries (or
88 /// other modules) this module depends on, a symbol table, and various data
89 /// about the target's characteristics.
91 /// A module maintains a GlobalValRefMap object that is used to hold all
92 /// constant references to global variables in the module. When a global
93 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
94 /// @brief The main container class for the LLVM Intermediate Representation.
96 /// @name Types And Enumerations
99 /// The type for the list of global variables.
100 typedef iplist<GlobalVariable> GlobalListType;
101 /// The type for the list of functions.
102 typedef iplist<Function> FunctionListType;
103 /// The type for the list of aliases.
104 typedef iplist<GlobalAlias> AliasListType;
105 /// The type for the list of named metadata.
106 typedef ilist<NamedMDNode> NamedMDListType;
108 /// The type for the list of dependent libraries.
109 typedef std::vector<std::string> LibraryListType;
111 /// The Global Variable iterator.
112 typedef GlobalListType::iterator global_iterator;
113 /// The Global Variable constant iterator.
114 typedef GlobalListType::const_iterator const_global_iterator;
116 /// The Function iterators.
117 typedef FunctionListType::iterator iterator;
118 /// The Function constant iterator
119 typedef FunctionListType::const_iterator const_iterator;
121 /// The Global Alias iterators.
122 typedef AliasListType::iterator alias_iterator;
123 /// The Global Alias constant iterator
124 typedef AliasListType::const_iterator const_alias_iterator;
126 /// The named metadata iterators.
127 typedef NamedMDListType::iterator named_metadata_iterator;
128 /// The named metadata constant interators.
129 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
130 /// The Library list iterator.
131 typedef LibraryListType::const_iterator lib_iterator;
133 /// An enumeration for describing the endianess of the target machine.
134 enum Endianness { AnyEndianness, LittleEndian, BigEndian };
136 /// An enumeration for describing the size of a pointer on the target machine.
137 enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
140 /// @name Member Variables
143 LLVMContext &Context; ///< The LLVMContext from which types and
144 ///< constants are allocated.
145 GlobalListType GlobalList; ///< The Global Variables in the module
146 FunctionListType FunctionList; ///< The Functions in the module
147 AliasListType AliasList; ///< The Aliases in the module
148 LibraryListType LibraryList; ///< The Libraries needed by the module
149 NamedMDListType NamedMDList; ///< The named metadata in the module
150 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
151 ValueSymbolTable *ValSymTab; ///< Symbol table for values
152 OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
153 std::string ModuleID; ///< Human readable identifier for the module
154 std::string TargetTriple; ///< Platform target triple Module compiled on
155 std::string DataLayout; ///< Target data description
156 void *NamedMDSymTab; ///< NamedMDNode names.
158 friend class Constant;
161 /// @name Constructors
164 /// The Module constructor. Note that there is no default constructor. You
165 /// must provide a name for the module upon construction.
166 explicit Module(StringRef ModuleID, LLVMContext& C);
167 /// The module destructor. This will dropAllReferences.
171 /// @name Module Level Accessors
174 /// Get the module identifier which is, essentially, the name of the module.
175 /// @returns the module identifier as a string
176 const std::string &getModuleIdentifier() const { return ModuleID; }
178 /// Get the data layout string for the module's target platform. This encodes
179 /// the type sizes and alignments expected by this module.
180 /// @returns the data layout as a string
181 const std::string &getDataLayout() const { return DataLayout; }
183 /// Get the target triple which is a string describing the target host.
184 /// @returns a string containing the target triple.
185 const std::string &getTargetTriple() const { return TargetTriple; }
187 /// Get the target endian information.
188 /// @returns Endianess - an enumeration for the endianess of the target
189 Endianness getEndianness() const;
191 /// Get the target pointer size.
192 /// @returns PointerSize - an enumeration for the size of the target's pointer
193 PointerSize getPointerSize() const;
195 /// Get the global data context.
196 /// @returns LLVMContext - a container for LLVM's global information
197 LLVMContext &getContext() const { return Context; }
199 /// Get any module-scope inline assembly blocks.
200 /// @returns a string containing the module-scope inline assembly blocks.
201 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
204 /// @name Module Level Mutators
207 /// Set the module identifier.
208 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
210 /// Set the data layout
211 void setDataLayout(StringRef DL) { DataLayout = DL; }
213 /// Set the target triple.
214 void setTargetTriple(StringRef T) { TargetTriple = T; }
216 /// Set the module-scope inline assembly blocks.
217 void setModuleInlineAsm(StringRef Asm) {
218 GlobalScopeAsm = Asm;
219 if (!GlobalScopeAsm.empty() &&
220 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
221 GlobalScopeAsm += '\n';
224 /// Append to the module-scope inline assembly blocks, automatically inserting
225 /// a separating newline if necessary.
226 void appendModuleInlineAsm(StringRef Asm) {
227 GlobalScopeAsm += Asm;
228 if (!GlobalScopeAsm.empty() &&
229 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
230 GlobalScopeAsm += '\n';
234 /// @name Generic Value Accessors
237 /// getNamedValue - Return the global value in the module with
238 /// the specified name, of arbitrary type. This method returns null
239 /// if a global with the specified name is not found.
240 GlobalValue *getNamedValue(StringRef Name) const;
242 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
243 /// This ID is uniqued across modules in the current LLVMContext.
244 unsigned getMDKindID(StringRef Name) const;
246 /// getMDKindNames - Populate client supplied SmallVector with the name for
247 /// custom metadata IDs registered in this LLVMContext.
248 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
251 typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*>,
252 DenseMapInfo<unsigned> > NumeredTypesMapTy;
254 /// findUsedStructTypes - Walk the entire module and find all of the
255 /// struct types that are in use, returning them in a vector.
256 void findUsedStructTypes(std::vector<StructType*> &StructTypes) const;
258 /// getTypeByName - Return the type with the specified name, or null if there
259 /// is none by that name.
260 StructType *getTypeByName(StringRef Name) const;
263 /// @name Function Accessors
266 /// getOrInsertFunction - Look up the specified function in the module symbol
267 /// table. Four possibilities:
268 /// 1. If it does not exist, add a prototype for the function and return it.
269 /// 2. If it exists, and has a local linkage, the existing function is
270 /// renamed and a new one is inserted.
271 /// 3. Otherwise, if the existing function has the correct prototype, return
272 /// the existing function.
273 /// 4. Finally, the function exists but has the wrong prototype: return the
274 /// function with a constantexpr cast to the right prototype.
275 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
276 AttrListPtr AttributeList);
278 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
280 /// getOrInsertFunction - Look up the specified function in the module symbol
281 /// table. If it does not exist, add a prototype for the function and return
282 /// it. This function guarantees to return a constant of pointer to the
283 /// specified function type or a ConstantExpr BitCast of that type if the
284 /// named function has a different type. This version of the method takes a
285 /// null terminated list of function arguments, which makes it easier for
287 Constant *getOrInsertFunction(StringRef Name,
288 AttrListPtr AttributeList,
289 Type *RetTy, ...) END_WITH_NULL;
291 /// getOrInsertFunction - Same as above, but without the attributes.
292 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
295 Constant *getOrInsertTargetIntrinsic(StringRef Name,
297 AttrListPtr AttributeList);
299 /// getFunction - Look up the specified function in the module symbol table.
300 /// If it does not exist, return null.
301 Function *getFunction(StringRef Name) const;
304 /// @name Global Variable Accessors
307 /// getGlobalVariable - Look up the specified global variable in the module
308 /// symbol table. If it does not exist, return null. If AllowInternal is set
309 /// to true, this function will return types that have InternalLinkage. By
310 /// default, these types are not returned.
311 GlobalVariable *getGlobalVariable(StringRef Name,
312 bool AllowInternal = false) const;
314 /// getNamedGlobal - Return the global variable in the module with the
315 /// specified name, of arbitrary type. This method returns null if a global
316 /// with the specified name is not found.
317 GlobalVariable *getNamedGlobal(StringRef Name) const {
318 return getGlobalVariable(Name, true);
321 /// getOrInsertGlobal - Look up the specified global in the module symbol
323 /// 1. If it does not exist, add a declaration of the global and return it.
324 /// 2. Else, the global exists but has the wrong type: return the function
325 /// with a constantexpr cast to the right type.
326 /// 3. Finally, if the existing global is the correct declaration, return
327 /// the existing global.
328 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
331 /// @name Global Alias Accessors
334 /// getNamedAlias - Return the global alias in the module with the
335 /// specified name, of arbitrary type. This method returns null if a global
336 /// with the specified name is not found.
337 GlobalAlias *getNamedAlias(StringRef Name) const;
340 /// @name Named Metadata Accessors
343 /// getNamedMetadata - Return the NamedMDNode in the module with the
344 /// specified name. This method returns null if a NamedMDNode with the
345 /// specified name is not found.
346 NamedMDNode *getNamedMetadata(const Twine &Name) const;
348 /// getOrInsertNamedMetadata - Return the named MDNode in the module
349 /// with the specified name. This method returns a new NamedMDNode if a
350 /// NamedMDNode with the specified name is not found.
351 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
353 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
355 void eraseNamedMetadata(NamedMDNode *NMD);
358 /// @name Materialization
361 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
362 /// yet have a Materializer. To reset the materializer for a module that
363 /// already has one, call MaterializeAllPermanently first. Destroying this
364 /// module will destroy its materializer without materializing any more
365 /// GlobalValues. Without destroying the Module, there is no way to detach or
366 /// destroy a materializer without materializing all the GVs it controls, to
367 /// avoid leaving orphan unmaterialized GVs.
368 void setMaterializer(GVMaterializer *GVM);
369 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
370 GVMaterializer *getMaterializer() const { return Materializer.get(); }
372 /// isMaterializable - True if the definition of GV has yet to be materialized
373 /// from the GVMaterializer.
374 bool isMaterializable(const GlobalValue *GV) const;
375 /// isDematerializable - Returns true if this GV was loaded from this Module's
376 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
377 bool isDematerializable(const GlobalValue *GV) const;
379 /// Materialize - Make sure the GlobalValue is fully read. If the module is
380 /// corrupt, this returns true and fills in the optional string with
381 /// information about the problem. If successful, this returns false.
382 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
383 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
384 /// supports it, release the memory for the function, and set it up to be
385 /// materialized lazily. If !isDematerializable(), this method is a noop.
386 void Dematerialize(GlobalValue *GV);
388 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
389 /// If the module is corrupt, this returns true and fills in the optional
390 /// string with information about the problem. If successful, this returns
392 bool MaterializeAll(std::string *ErrInfo = 0);
394 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
395 /// fully read and clear the Materializer. If the module is corrupt, this
396 /// returns true, fills in the optional string with information about the
397 /// problem, and DOES NOT clear the old Materializer. If successful, this
399 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
402 /// @name Direct access to the globals list, functions list, and symbol table
405 /// Get the Module's list of global variables (constant).
406 const GlobalListType &getGlobalList() const { return GlobalList; }
407 /// Get the Module's list of global variables.
408 GlobalListType &getGlobalList() { return GlobalList; }
409 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
410 return &Module::GlobalList;
412 /// Get the Module's list of functions (constant).
413 const FunctionListType &getFunctionList() const { return FunctionList; }
414 /// Get the Module's list of functions.
415 FunctionListType &getFunctionList() { return FunctionList; }
416 static iplist<Function> Module::*getSublistAccess(Function*) {
417 return &Module::FunctionList;
419 /// Get the Module's list of aliases (constant).
420 const AliasListType &getAliasList() const { return AliasList; }
421 /// Get the Module's list of aliases.
422 AliasListType &getAliasList() { return AliasList; }
423 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
424 return &Module::AliasList;
426 /// Get the symbol table of global variable and function identifiers
427 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
428 /// Get the Module's symbol table of global variable and function identifiers.
429 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
432 /// @name Global Variable Iteration
435 global_iterator global_begin() { return GlobalList.begin(); }
436 const_global_iterator global_begin() const { return GlobalList.begin(); }
437 global_iterator global_end () { return GlobalList.end(); }
438 const_global_iterator global_end () const { return GlobalList.end(); }
439 bool global_empty() const { return GlobalList.empty(); }
442 /// @name Function Iteration
445 iterator begin() { return FunctionList.begin(); }
446 const_iterator begin() const { return FunctionList.begin(); }
447 iterator end () { return FunctionList.end(); }
448 const_iterator end () const { return FunctionList.end(); }
449 size_t size() const { return FunctionList.size(); }
450 bool empty() const { return FunctionList.empty(); }
453 /// @name Dependent Library Iteration
456 /// @brief Get a constant iterator to beginning of dependent library list.
457 inline lib_iterator lib_begin() const { return LibraryList.begin(); }
458 /// @brief Get a constant iterator to end of dependent library list.
459 inline lib_iterator lib_end() const { return LibraryList.end(); }
460 /// @brief Returns the number of items in the list of libraries.
461 inline size_t lib_size() const { return LibraryList.size(); }
462 /// @brief Add a library to the list of dependent libraries
463 void addLibrary(StringRef Lib);
464 /// @brief Remove a library from the list of dependent libraries
465 void removeLibrary(StringRef Lib);
466 /// @brief Get all the libraries
467 inline const LibraryListType& getLibraries() const { return LibraryList; }
470 /// @name Alias Iteration
473 alias_iterator alias_begin() { return AliasList.begin(); }
474 const_alias_iterator alias_begin() const { return AliasList.begin(); }
475 alias_iterator alias_end () { return AliasList.end(); }
476 const_alias_iterator alias_end () const { return AliasList.end(); }
477 size_t alias_size () const { return AliasList.size(); }
478 bool alias_empty() const { return AliasList.empty(); }
482 /// @name Named Metadata Iteration
485 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
486 const_named_metadata_iterator named_metadata_begin() const {
487 return NamedMDList.begin();
490 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
491 const_named_metadata_iterator named_metadata_end() const {
492 return NamedMDList.end();
495 size_t named_metadata_size() const { return NamedMDList.size(); }
496 bool named_metadata_empty() const { return NamedMDList.empty(); }
500 /// @name Utility functions for printing and dumping Module objects
503 /// Print the module to an output stream with an optional
504 /// AssemblyAnnotationWriter.
505 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
507 /// Dump the module to stderr (for debugging).
510 /// This function causes all the subinstructions to "let go" of all references
511 /// that they are maintaining. This allows one to 'delete' a whole class at
512 /// a time, even though there may be circular references... first all
513 /// references are dropped, and all use counts go to zero. Then everything
514 /// is delete'd for real. Note that no operations are valid on an object
515 /// that has "dropped all references", except operator delete.
516 void dropAllReferences();
520 /// An raw_ostream inserter for modules.
521 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
526 } // End llvm namespace