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