45247ec31c5e8a059ff829c337343f9a3dd2ae34
[oota-llvm.git] / include / llvm / Module.h
1 //===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// @file
11 /// Module.h This file contains the declarations for the Module class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_MODULE_H
16 #define LLVM_MODULE_H
17
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/System/DataTypes.h"
24 #include <vector>
25
26 namespace llvm {
27
28 class FunctionType;
29 class GVMaterializer;
30 class LLVMContext;
31
32 template<> struct ilist_traits<Function>
33   : public SymbolTableListTraits<Function, Module> {
34
35   // createSentinel is used to get hold of the node that marks the end of the
36   // list... (same trick used here as in ilist_traits<Instruction>)
37   Function *createSentinel() const {
38     return static_cast<Function*>(&Sentinel);
39   }
40   static void destroySentinel(Function*) {}
41
42   Function *provideInitialHead() const { return createSentinel(); }
43   Function *ensureHead(Function*) const { return createSentinel(); }
44   static void noteHead(Function*, Function*) {}
45
46 private:
47   mutable ilist_node<Function> Sentinel;
48 };
49 template<> struct ilist_traits<GlobalVariable>
50   : public SymbolTableListTraits<GlobalVariable, Module> {
51   // createSentinel is used to create a node that marks the end of the list.
52   static GlobalVariable *createSentinel();
53   static void destroySentinel(GlobalVariable *GV) { delete GV; }
54 };
55 template<> struct ilist_traits<GlobalAlias>
56   : public SymbolTableListTraits<GlobalAlias, Module> {
57   // createSentinel is used to create a node that marks the end of the list.
58   static GlobalAlias *createSentinel();
59   static void destroySentinel(GlobalAlias *GA) { delete GA; }
60 };
61
62 template<> struct ilist_traits<NamedMDNode>
63   : public ilist_default_traits<NamedMDNode> {
64   // createSentinel is used to get hold of a node that marks the end of
65   // the list...
66   NamedMDNode *createSentinel() const {
67     return static_cast<NamedMDNode*>(&Sentinel);
68   }
69   static void destroySentinel(NamedMDNode*) {}
70
71   NamedMDNode *provideInitialHead() const { return createSentinel(); }
72   NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
73   static void noteHead(NamedMDNode*, NamedMDNode*) {}
74   void addNodeToList(NamedMDNode *N) {}
75   void removeNodeFromList(NamedMDNode *N) {}
76 private:
77   mutable ilist_node<NamedMDNode> Sentinel;
78 };
79
80 /// A Module instance is used to store all the information related to an
81 /// LLVM module. Modules are the top level container of all other LLVM
82 /// Intermediate Representation (IR) objects. Each module directly contains a
83 /// list of globals variables, a list of functions, a list of libraries (or
84 /// other modules) this module depends on, a symbol table, and various data
85 /// about the target's characteristics.
86 ///
87 /// A module maintains a GlobalValRefMap object that is used to hold all
88 /// constant references to global variables in the module.  When a global
89 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
90 /// @brief The main container class for the LLVM Intermediate Representation.
91 class Module {
92 /// @name Types And Enumerations
93 /// @{
94 public:
95   /// The type for the list of global variables.
96   typedef iplist<GlobalVariable> GlobalListType;
97   /// The type for the list of functions.
98   typedef iplist<Function> FunctionListType;
99   /// The type for the list of aliases.
100   typedef iplist<GlobalAlias> AliasListType;
101   /// The type for the list of named metadata.
102   typedef ilist<NamedMDNode> NamedMDListType;
103
104   /// The type for the list of dependent libraries.
105   typedef std::vector<std::string> LibraryListType;
106
107   /// The Global Variable iterator.
108   typedef GlobalListType::iterator                      global_iterator;
109   /// The Global Variable constant iterator.
110   typedef GlobalListType::const_iterator          const_global_iterator;
111
112   /// The Function iterators.
113   typedef FunctionListType::iterator                           iterator;
114   /// The Function constant iterator
115   typedef FunctionListType::const_iterator               const_iterator;
116
117   /// The Global Alias iterators.
118   typedef AliasListType::iterator                        alias_iterator;
119   /// The Global Alias constant iterator
120   typedef AliasListType::const_iterator            const_alias_iterator;
121
122   /// The named metadata iterators.
123   typedef NamedMDListType::iterator             named_metadata_iterator;
124   /// The named metadata constant interators.
125   typedef NamedMDListType::const_iterator const_named_metadata_iterator;
126   /// The Library list iterator.
127   typedef LibraryListType::const_iterator lib_iterator;
128
129   /// An enumeration for describing the endianess of the target machine.
130   enum Endianness  { AnyEndianness, LittleEndian, BigEndian };
131
132   /// An enumeration for describing the size of a pointer on the target machine.
133   enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
134
135 /// @}
136 /// @name Member Variables
137 /// @{
138 private:
139   LLVMContext &Context;           ///< The LLVMContext from which types and
140                                   ///< constants are allocated.
141   GlobalListType GlobalList;      ///< The Global Variables in the module
142   FunctionListType FunctionList;  ///< The Functions in the module
143   AliasListType AliasList;        ///< The Aliases in the module
144   LibraryListType LibraryList;    ///< The Libraries needed by the module
145   NamedMDListType NamedMDList;    ///< The named metadata in the module
146   std::string GlobalScopeAsm;     ///< Inline Asm at global scope.
147   ValueSymbolTable *ValSymTab;    ///< Symbol table for values
148   TypeSymbolTable *TypeSymTab;    ///< Symbol table for types
149   OwningPtr<GVMaterializer> Materializer;  ///< Used to materialize GlobalValues
150   std::string ModuleID;           ///< Human readable identifier for the module
151   std::string TargetTriple;       ///< Platform target triple Module compiled on
152   std::string DataLayout;         ///< Target data description
153   void *NamedMDSymTab;            ///< NamedMDNode names.
154
155   friend class Constant;
156
157 /// @}
158 /// @name Constructors
159 /// @{
160 public:
161   /// The Module constructor. Note that there is no default constructor. You
162   /// must provide a name for the module upon construction.
163   explicit Module(StringRef ModuleID, LLVMContext& C);
164   /// The module destructor. This will dropAllReferences.
165   ~Module();
166
167 /// @}
168 /// @name Module Level Accessors
169 /// @{
170
171   /// Get the module identifier which is, essentially, the name of the module.
172   /// @returns the module identifier as a string
173   const std::string &getModuleIdentifier() const { return ModuleID; }
174
175   /// Get the data layout string for the module's target platform.  This encodes
176   /// the type sizes and alignments expected by this module.
177   /// @returns the data layout as a string
178   const std::string &getDataLayout() const { return DataLayout; }
179
180   /// Get the target triple which is a string describing the target host.
181   /// @returns a string containing the target triple.
182   const std::string &getTargetTriple() const { return TargetTriple; }
183
184   /// Get the target endian information.
185   /// @returns Endianess - an enumeration for the endianess of the target
186   Endianness getEndianness() const;
187
188   /// Get the target pointer size.
189   /// @returns PointerSize - an enumeration for the size of the target's pointer
190   PointerSize getPointerSize() const;
191
192   /// Get the global data context.
193   /// @returns LLVMContext - a container for LLVM's global information
194   LLVMContext &getContext() const { return Context; }
195
196   /// Get any module-scope inline assembly blocks.
197   /// @returns a string containing the module-scope inline assembly blocks.
198   const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
199
200 /// @}
201 /// @name Module Level Mutators
202 /// @{
203
204   /// Set the module identifier.
205   void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
206
207   /// Set the data layout
208   void setDataLayout(StringRef DL) { DataLayout = DL; }
209
210   /// Set the target triple.
211   void setTargetTriple(StringRef T) { TargetTriple = T; }
212
213   /// Set the module-scope inline assembly blocks.
214   void setModuleInlineAsm(StringRef Asm) { GlobalScopeAsm = Asm; }
215
216   /// Append to the module-scope inline assembly blocks, automatically inserting
217   /// a separating newline if necessary.
218   void appendModuleInlineAsm(StringRef Asm) {
219     if (!GlobalScopeAsm.empty() &&
220         GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
221       GlobalScopeAsm += '\n';
222     GlobalScopeAsm += Asm;
223   }
224
225 /// @}
226 /// @name Generic Value Accessors
227 /// @{
228
229   /// getNamedValue - Return the first global value in the module with
230   /// the specified name, of arbitrary type.  This method returns null
231   /// if a global with the specified name is not found.
232   GlobalValue *getNamedValue(StringRef Name) const;
233
234   /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
235   /// This ID is uniqued across modules in the current LLVMContext.
236   unsigned getMDKindID(StringRef Name) const;
237
238   /// getMDKindNames - Populate client supplied SmallVector with the name for
239   /// custom metadata IDs registered in this LLVMContext.
240   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
241
242 /// @}
243 /// @name Function Accessors
244 /// @{
245
246   /// getOrInsertFunction - Look up the specified function in the module symbol
247   /// table.  Four possibilities:
248   ///   1. If it does not exist, add a prototype for the function and return it.
249   ///   2. If it exists, and has a local linkage, the existing function is
250   ///      renamed and a new one is inserted.
251   ///   3. Otherwise, if the existing function has the correct prototype, return
252   ///      the existing function.
253   ///   4. Finally, the function exists but has the wrong prototype: return the
254   ///      function with a constantexpr cast to the right prototype.
255   Constant *getOrInsertFunction(StringRef Name, const FunctionType *T,
256                                 AttrListPtr AttributeList);
257
258   Constant *getOrInsertFunction(StringRef Name, const FunctionType *T);
259
260   /// getOrInsertFunction - Look up the specified function in the module symbol
261   /// table.  If it does not exist, add a prototype for the function and return
262   /// it.  This function guarantees to return a constant of pointer to the
263   /// specified function type or a ConstantExpr BitCast of that type if the
264   /// named function has a different type.  This version of the method takes a
265   /// null terminated list of function arguments, which makes it easier for
266   /// clients to use.
267   Constant *getOrInsertFunction(StringRef Name,
268                                 AttrListPtr AttributeList,
269                                 const Type *RetTy, ...)  END_WITH_NULL;
270
271   /// getOrInsertFunction - Same as above, but without the attributes.
272   Constant *getOrInsertFunction(StringRef Name, const Type *RetTy, ...)
273     END_WITH_NULL;
274
275   Constant *getOrInsertTargetIntrinsic(StringRef Name,
276                                        const FunctionType *Ty,
277                                        AttrListPtr AttributeList);
278
279   /// getFunction - Look up the specified function in the module symbol table.
280   /// If it does not exist, return null.
281   Function *getFunction(StringRef Name) const;
282
283 /// @}
284 /// @name Global Variable Accessors
285 /// @{
286
287   /// getGlobalVariable - Look up the specified global variable in the module
288   /// symbol table.  If it does not exist, return null. If AllowInternal is set
289   /// to true, this function will return types that have InternalLinkage. By
290   /// default, these types are not returned.
291   GlobalVariable *getGlobalVariable(StringRef Name,
292                                     bool AllowInternal = false) const;
293
294   /// getNamedGlobal - Return the first global variable in the module with the
295   /// specified name, of arbitrary type.  This method returns null if a global
296   /// with the specified name is not found.
297   GlobalVariable *getNamedGlobal(StringRef Name) const {
298     return getGlobalVariable(Name, true);
299   }
300
301   /// getOrInsertGlobal - Look up the specified global in the module symbol
302   /// table.
303   ///   1. If it does not exist, add a declaration of the global and return it.
304   ///   2. Else, the global exists but has the wrong type: return the function
305   ///      with a constantexpr cast to the right type.
306   ///   3. Finally, if the existing global is the correct delclaration, return
307   ///      the existing global.
308   Constant *getOrInsertGlobal(StringRef Name, const Type *Ty);
309
310 /// @}
311 /// @name Global Alias Accessors
312 /// @{
313
314   /// getNamedAlias - Return the first global alias 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   GlobalAlias *getNamedAlias(StringRef Name) const;
318
319 /// @}
320 /// @name Named Metadata Accessors
321 /// @{
322
323   /// getNamedMetadata - Return the first NamedMDNode in the module with the
324   /// specified name. This method returns null if a NamedMDNode with the
325   /// specified name is not found.
326   NamedMDNode *getNamedMetadata(const Twine &Name) const;
327
328   /// getOrInsertNamedMetadata - Return the first named MDNode in the module
329   /// with the specified name. This method returns a new NamedMDNode if a
330   /// NamedMDNode with the specified name is not found.
331   NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
332
333   /// eraseNamedMetadata - Remove the given NamedMDNode from this module
334   /// and delete it.
335   void eraseNamedMetadata(NamedMDNode *NMD);
336
337 /// @}
338 /// @name Type Accessors
339 /// @{
340
341   /// addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
342   /// there is already an entry for this name, true is returned and the symbol
343   /// table is not modified.
344   bool addTypeName(StringRef Name, const Type *Ty);
345
346   /// getTypeName - If there is at least one entry in the symbol table for the
347   /// specified type, return it.
348   std::string getTypeName(const Type *Ty) const;
349
350   /// getTypeByName - Return the type with the specified name in this module, or
351   /// null if there is none by that name.
352   const Type *getTypeByName(StringRef Name) const;
353
354 /// @}
355 /// @name Materialization
356 /// @{
357
358   /// setMaterializer - Sets the GVMaterializer to GVM.  This module must not
359   /// yet have a Materializer.  To reset the materializer for a module that
360   /// already has one, call MaterializeAllPermanently first.  Destroying this
361   /// module will destroy its materializer without materializing any more
362   /// GlobalValues.  Without destroying the Module, there is no way to detach or
363   /// destroy a materializer without materializing all the GVs it controls, to
364   /// avoid leaving orphan unmaterialized GVs.
365   void setMaterializer(GVMaterializer *GVM);
366   /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
367   GVMaterializer *getMaterializer() const { return Materializer.get(); }
368
369   /// isMaterializable - True if the definition of GV has yet to be materialized
370   /// from the GVMaterializer.
371   bool isMaterializable(const GlobalValue *GV) const;
372   /// isDematerializable - Returns true if this GV was loaded from this Module's
373   /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
374   bool isDematerializable(const GlobalValue *GV) const;
375
376   /// Materialize - Make sure the GlobalValue is fully read.  If the module is
377   /// corrupt, this returns true and fills in the optional string with
378   /// information about the problem.  If successful, this returns false.
379   bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
380   /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
381   /// supports it, release the memory for the function, and set it up to be
382   /// materialized lazily.  If !isDematerializable(), this method is a noop.
383   void Dematerialize(GlobalValue *GV);
384
385   /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
386   /// If the module is corrupt, this returns true and fills in the optional
387   /// string with information about the problem.  If successful, this returns
388   /// false.
389   bool MaterializeAll(std::string *ErrInfo = 0);
390
391   /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
392   /// fully read and clear the Materializer.  If the module is corrupt, this
393   /// returns true, fills in the optional string with information about the
394   /// problem, and DOES NOT clear the old Materializer.  If successful, this
395   /// returns false.
396   bool MaterializeAllPermanently(std::string *ErrInfo = 0);
397
398 /// @}
399 /// @name Direct access to the globals list, functions list, and symbol table
400 /// @{
401
402   /// Get the Module's list of global variables (constant).
403   const GlobalListType   &getGlobalList() const       { return GlobalList; }
404   /// Get the Module's list of global variables.
405   GlobalListType         &getGlobalList()             { return GlobalList; }
406   static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
407     return &Module::GlobalList;
408   }
409   /// Get the Module's list of functions (constant).
410   const FunctionListType &getFunctionList() const     { return FunctionList; }
411   /// Get the Module's list of functions.
412   FunctionListType       &getFunctionList()           { return FunctionList; }
413   static iplist<Function> Module::*getSublistAccess(Function*) {
414     return &Module::FunctionList;
415   }
416   /// Get the Module's list of aliases (constant).
417   const AliasListType    &getAliasList() const        { return AliasList; }
418   /// Get the Module's list of aliases.
419   AliasListType          &getAliasList()              { return AliasList; }
420   static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
421     return &Module::AliasList;
422   }
423   /// Get the symbol table of global variable and function identifiers
424   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
425   /// Get the Module's symbol table of global variable and function identifiers.
426   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
427   /// Get the symbol table of types
428   const TypeSymbolTable  &getTypeSymbolTable() const  { return *TypeSymTab; }
429   /// Get the Module's symbol table of types
430   TypeSymbolTable        &getTypeSymbolTable()        { return *TypeSymTab; }
431
432 /// @}
433 /// @name Global Variable Iteration
434 /// @{
435
436   /// Get an iterator to the first global variable
437   global_iterator       global_begin()       { return GlobalList.begin(); }
438   /// Get a constant iterator to the first global variable
439   const_global_iterator global_begin() const { return GlobalList.begin(); }
440   /// Get an iterator to the last global variable
441   global_iterator       global_end  ()       { return GlobalList.end(); }
442   /// Get a constant iterator to the last global variable
443   const_global_iterator global_end  () const { return GlobalList.end(); }
444   /// Determine if the list of globals is empty.
445   bool                  global_empty() const { return GlobalList.empty(); }
446
447 /// @}
448 /// @name Function Iteration
449 /// @{
450
451   /// Get an iterator to the first function.
452   iterator                begin()       { return FunctionList.begin(); }
453   /// Get a constant iterator to the first function.
454   const_iterator          begin() const { return FunctionList.begin(); }
455   /// Get an iterator to the last function.
456   iterator                end  ()       { return FunctionList.end();   }
457   /// Get a constant iterator to the last function.
458   const_iterator          end  () const { return FunctionList.end();   }
459   /// Determine how many functions are in the Module's list of functions.
460   size_t                  size() const  { return FunctionList.size(); }
461   /// Determine if the list of functions is empty.
462   bool                    empty() const { return FunctionList.empty(); }
463
464 /// @}
465 /// @name Dependent Library Iteration
466 /// @{
467
468   /// @brief Get a constant iterator to beginning of dependent library list.
469   inline lib_iterator lib_begin() const { return LibraryList.begin(); }
470   /// @brief Get a constant iterator to end of dependent library list.
471   inline lib_iterator lib_end()   const { return LibraryList.end();   }
472   /// @brief Returns the number of items in the list of libraries.
473   inline size_t       lib_size()  const { return LibraryList.size();  }
474   /// @brief Add a library to the list of dependent libraries
475   void addLibrary(StringRef Lib);
476   /// @brief Remove a library from the list of dependent libraries
477   void removeLibrary(StringRef Lib);
478   /// @brief Get all the libraries
479   inline const LibraryListType& getLibraries() const { return LibraryList; }
480
481 /// @}
482 /// @name Alias Iteration
483 /// @{
484
485   /// Get an iterator to the first alias.
486   alias_iterator       alias_begin()            { return AliasList.begin(); }
487   /// Get a constant iterator to the first alias.
488   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
489   /// Get an iterator to the last alias.
490   alias_iterator       alias_end  ()            { return AliasList.end();   }
491   /// Get a constant iterator to the last alias.
492   const_alias_iterator alias_end  () const      { return AliasList.end();   }
493   /// Determine how many aliases are in the Module's list of aliases.
494   size_t               alias_size () const      { return AliasList.size();  }
495   /// Determine if the list of aliases is empty.
496   bool                 alias_empty() const      { return AliasList.empty(); }
497
498
499 /// @}
500 /// @name Named Metadata Iteration
501 /// @{
502
503   /// Get an iterator to the first named metadata.
504   named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
505   /// Get a constant iterator to the first named metadata.
506   const_named_metadata_iterator named_metadata_begin() const {
507     return NamedMDList.begin();
508   }
509
510   /// Get an iterator to the last named metadata.
511   named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
512   /// Get a constant iterator to the last named metadata.
513   const_named_metadata_iterator named_metadata_end() const {
514     return NamedMDList.end();
515   }
516
517   /// Determine how many NamedMDNodes are in the Module's list of named
518   /// metadata.
519   size_t named_metadata_size() const { return NamedMDList.size();  }
520   /// Determine if the list of named metadata is empty.
521   bool named_metadata_empty() const { return NamedMDList.empty(); }
522
523
524 /// @}
525 /// @name Utility functions for printing and dumping Module objects
526 /// @{
527
528   /// Print the module to an output stream with AssemblyAnnotationWriter.
529   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
530
531   /// Dump the module to stderr (for debugging).
532   void dump() const;
533   /// This function causes all the subinstructions to "let go" of all references
534   /// that they are maintaining.  This allows one to 'delete' a whole class at
535   /// a time, even though there may be circular references... first all
536   /// references are dropped, and all use counts go to zero.  Then everything
537   /// is delete'd for real.  Note that no operations are valid on an object
538   /// that has "dropped all references", except operator delete.
539   void dropAllReferences();
540 /// @}
541 };
542
543 /// An raw_ostream inserter for modules.
544 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
545   M.print(O, 0);
546   return O;
547 }
548
549 } // End llvm namespace
550
551 #endif