Don't ever call materializeAllPermanently during LTO.
[oota-llvm.git] / include / llvm / IR / 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_IR_MODULE_H
16 #define LLVM_IR_MODULE_H
17
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/Comdat.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GlobalAlias.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/Support/CBindingWrapping.h"
26 #include "llvm/Support/DataTypes.h"
27 #include <system_error>
28
29 namespace llvm {
30 class FunctionType;
31 class GVMaterializer;
32 class LLVMContext;
33 class RandomNumberGenerator;
34 class StructType;
35 template<typename T> struct DenseMapInfo;
36 template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
37
38 template<> struct ilist_traits<Function>
39   : public SymbolTableListTraits<Function, Module> {
40
41   // createSentinel is used to get hold of the node that marks the end of the
42   // list... (same trick used here as in ilist_traits<Instruction>)
43   Function *createSentinel() const {
44     return static_cast<Function*>(&Sentinel);
45   }
46   static void destroySentinel(Function*) {}
47
48   Function *provideInitialHead() const { return createSentinel(); }
49   Function *ensureHead(Function*) const { return createSentinel(); }
50   static void noteHead(Function*, Function*) {}
51
52 private:
53   mutable ilist_node<Function> Sentinel;
54 };
55
56 template<> struct ilist_traits<GlobalVariable>
57   : public SymbolTableListTraits<GlobalVariable, Module> {
58   // createSentinel is used to create a node that marks the end of the list.
59   GlobalVariable *createSentinel() const {
60     return static_cast<GlobalVariable*>(&Sentinel);
61   }
62   static void destroySentinel(GlobalVariable*) {}
63
64   GlobalVariable *provideInitialHead() const { return createSentinel(); }
65   GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
66   static void noteHead(GlobalVariable*, GlobalVariable*) {}
67 private:
68   mutable ilist_node<GlobalVariable> Sentinel;
69 };
70
71 template<> struct ilist_traits<GlobalAlias>
72   : public SymbolTableListTraits<GlobalAlias, Module> {
73   // createSentinel is used to create a node that marks the end of the list.
74   GlobalAlias *createSentinel() const {
75     return static_cast<GlobalAlias*>(&Sentinel);
76   }
77   static void destroySentinel(GlobalAlias*) {}
78
79   GlobalAlias *provideInitialHead() const { return createSentinel(); }
80   GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
81   static void noteHead(GlobalAlias*, GlobalAlias*) {}
82 private:
83   mutable ilist_node<GlobalAlias> Sentinel;
84 };
85
86 template<> struct ilist_traits<NamedMDNode>
87   : public ilist_default_traits<NamedMDNode> {
88   // createSentinel is used to get hold of a node that marks the end of
89   // the list...
90   NamedMDNode *createSentinel() const {
91     return static_cast<NamedMDNode*>(&Sentinel);
92   }
93   static void destroySentinel(NamedMDNode*) {}
94
95   NamedMDNode *provideInitialHead() const { return createSentinel(); }
96   NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
97   static void noteHead(NamedMDNode*, NamedMDNode*) {}
98   void addNodeToList(NamedMDNode *) {}
99   void removeNodeFromList(NamedMDNode *) {}
100 private:
101   mutable ilist_node<NamedMDNode> Sentinel;
102 };
103
104 /// A Module instance is used to store all the information related to an
105 /// LLVM module. Modules are the top level container of all other LLVM
106 /// Intermediate Representation (IR) objects. Each module directly contains a
107 /// list of globals variables, a list of functions, a list of libraries (or
108 /// other modules) this module depends on, a symbol table, and various data
109 /// about the target's characteristics.
110 ///
111 /// A module maintains a GlobalValRefMap object that is used to hold all
112 /// constant references to global variables in the module.  When a global
113 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
114 /// @brief The main container class for the LLVM Intermediate Representation.
115 class Module {
116 /// @name Types And Enumerations
117 /// @{
118 public:
119   /// The type for the list of global variables.
120   typedef iplist<GlobalVariable> GlobalListType;
121   /// The type for the list of functions.
122   typedef iplist<Function> FunctionListType;
123   /// The type for the list of aliases.
124   typedef iplist<GlobalAlias> AliasListType;
125   /// The type for the list of named metadata.
126   typedef ilist<NamedMDNode> NamedMDListType;
127   /// The type of the comdat "symbol" table.
128   typedef StringMap<Comdat> ComdatSymTabType;
129
130   /// The Global Variable iterator.
131   typedef GlobalListType::iterator                      global_iterator;
132   /// The Global Variable constant iterator.
133   typedef GlobalListType::const_iterator          const_global_iterator;
134
135   /// The Function iterators.
136   typedef FunctionListType::iterator                           iterator;
137   /// The Function constant iterator
138   typedef FunctionListType::const_iterator               const_iterator;
139
140   /// The Function reverse iterator.
141   typedef FunctionListType::reverse_iterator             reverse_iterator;
142   /// The Function constant reverse iterator.
143   typedef FunctionListType::const_reverse_iterator const_reverse_iterator;
144
145   /// The Global Alias iterators.
146   typedef AliasListType::iterator                        alias_iterator;
147   /// The Global Alias constant iterator
148   typedef AliasListType::const_iterator            const_alias_iterator;
149
150   /// The named metadata iterators.
151   typedef NamedMDListType::iterator             named_metadata_iterator;
152   /// The named metadata constant interators.
153   typedef NamedMDListType::const_iterator const_named_metadata_iterator;
154
155   /// This enumeration defines the supported behaviors of module flags.
156   enum ModFlagBehavior {
157     /// Emits an error if two values disagree, otherwise the resulting value is
158     /// that of the operands.
159     Error = 1,
160
161     /// Emits a warning if two values disagree. The result value will be the
162     /// operand for the flag from the first module being linked.
163     Warning = 2,
164
165     /// Adds a requirement that another module flag be present and have a
166     /// specified value after linking is performed. The value must be a metadata
167     /// pair, where the first element of the pair is the ID of the module flag
168     /// to be restricted, and the second element of the pair is the value the
169     /// module flag should be restricted to. This behavior can be used to
170     /// restrict the allowable results (via triggering of an error) of linking
171     /// IDs with the **Override** behavior.
172     Require = 3,
173
174     /// Uses the specified value, regardless of the behavior or value of the
175     /// other module. If both modules specify **Override**, but the values
176     /// differ, an error will be emitted.
177     Override = 4,
178
179     /// Appends the two values, which are required to be metadata nodes.
180     Append = 5,
181
182     /// Appends the two values, which are required to be metadata
183     /// nodes. However, duplicate entries in the second list are dropped
184     /// during the append operation.
185     AppendUnique = 6,
186
187     // Markers:
188     ModFlagBehaviorFirstVal = Error,
189     ModFlagBehaviorLastVal = AppendUnique
190   };
191
192   /// Checks if Value represents a valid ModFlagBehavior, and stores the
193   /// converted result in MFB.
194   static bool isValidModFlagBehavior(Value *V, ModFlagBehavior &MFB);
195
196   struct ModuleFlagEntry {
197     ModFlagBehavior Behavior;
198     MDString *Key;
199     Value *Val;
200     ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
201       : Behavior(B), Key(K), Val(V) {}
202   };
203
204 /// @}
205 /// @name Member Variables
206 /// @{
207 private:
208   LLVMContext &Context;           ///< The LLVMContext from which types and
209                                   ///< constants are allocated.
210   GlobalListType GlobalList;      ///< The Global Variables in the module
211   FunctionListType FunctionList;  ///< The Functions in the module
212   AliasListType AliasList;        ///< The Aliases in the module
213   NamedMDListType NamedMDList;    ///< The named metadata in the module
214   std::string GlobalScopeAsm;     ///< Inline Asm at global scope.
215   ValueSymbolTable *ValSymTab;    ///< Symbol table for values
216   ComdatSymTabType ComdatSymTab;  ///< Symbol table for COMDATs
217   std::unique_ptr<GVMaterializer>
218   Materializer;                   ///< Used to materialize GlobalValues
219   std::string ModuleID;           ///< Human readable identifier for the module
220   std::string TargetTriple;       ///< Platform target triple Module compiled on
221   void *NamedMDSymTab;            ///< NamedMDNode names.
222   // Allow lazy initialization in const method.
223   mutable RandomNumberGenerator *RNG; ///< The random number generator for this module.
224
225   // We need to keep the string because the C API expects us to own the string
226   // representation.
227   // Since we have it, we also use an empty string to represent a module without
228   // a DataLayout. If it has a DataLayout, these variables are in sync and the
229   // string is just a cache of getDataLayout()->getStringRepresentation().
230   std::string DataLayoutStr;
231   DataLayout DL;
232
233   friend class Constant;
234
235 /// @}
236 /// @name Constructors
237 /// @{
238 public:
239   /// The Module constructor. Note that there is no default constructor. You
240   /// must provide a name for the module upon construction.
241   explicit Module(StringRef ModuleID, LLVMContext& C);
242   /// The module destructor. This will dropAllReferences.
243   ~Module();
244
245 /// @}
246 /// @name Module Level Accessors
247 /// @{
248
249   /// Get the module identifier which is, essentially, the name of the module.
250   /// @returns the module identifier as a string
251   const std::string &getModuleIdentifier() const { return ModuleID; }
252
253   /// Get the data layout string for the module's target platform. This is
254   /// equivalent to getDataLayout()->getStringRepresentation().
255   const std::string &getDataLayoutStr() const { return DataLayoutStr; }
256
257   /// Get the data layout for the module's target platform.
258   const DataLayout *getDataLayout() const;
259
260   /// Get the target triple which is a string describing the target host.
261   /// @returns a string containing the target triple.
262   const std::string &getTargetTriple() const { return TargetTriple; }
263
264   /// Get the global data context.
265   /// @returns LLVMContext - a container for LLVM's global information
266   LLVMContext &getContext() const { return Context; }
267
268   /// Get any module-scope inline assembly blocks.
269   /// @returns a string containing the module-scope inline assembly blocks.
270   const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
271
272   /// Get the RandomNumberGenerator for this module. The RNG can be
273   /// seeded via -rng-seed=<uint64> and is salted with the ModuleID.
274   /// The returned RNG should not be shared across threads.
275   RandomNumberGenerator &getRNG() const;
276
277 /// @}
278 /// @name Module Level Mutators
279 /// @{
280
281   /// Set the module identifier.
282   void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
283
284   /// Set the data layout
285   void setDataLayout(StringRef Desc);
286   void setDataLayout(const DataLayout *Other);
287
288   /// Set the target triple.
289   void setTargetTriple(StringRef T) { TargetTriple = T; }
290
291   /// Set the module-scope inline assembly blocks.
292   void setModuleInlineAsm(StringRef Asm) {
293     GlobalScopeAsm = Asm;
294     if (!GlobalScopeAsm.empty() &&
295         GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
296       GlobalScopeAsm += '\n';
297   }
298
299   /// Append to the module-scope inline assembly blocks, automatically inserting
300   /// a separating newline if necessary.
301   void appendModuleInlineAsm(StringRef Asm) {
302     GlobalScopeAsm += Asm;
303     if (!GlobalScopeAsm.empty() &&
304         GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
305       GlobalScopeAsm += '\n';
306   }
307
308 /// @}
309 /// @name Generic Value Accessors
310 /// @{
311
312   /// Return the global value in the module with the specified name, of
313   /// arbitrary type. This method returns null if a global with the specified
314   /// name is not found.
315   GlobalValue *getNamedValue(StringRef Name) const;
316
317   /// Return a unique non-zero ID for the specified metadata kind. This ID is
318   /// uniqued across modules in the current LLVMContext.
319   unsigned getMDKindID(StringRef Name) const;
320
321   /// Populate client supplied SmallVector with the name for custom metadata IDs
322   /// registered in this LLVMContext.
323   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
324
325   /// Return the type with the specified name, or null if there is none by that
326   /// name.
327   StructType *getTypeByName(StringRef Name) const;
328
329 /// @}
330 /// @name Function Accessors
331 /// @{
332
333   /// Look up the specified function in the module symbol table. Four
334   /// possibilities:
335   ///   1. If it does not exist, add a prototype for the function and return it.
336   ///   2. If it exists, and has a local linkage, the existing function is
337   ///      renamed and a new one is inserted.
338   ///   3. Otherwise, if the existing function has the correct prototype, return
339   ///      the existing function.
340   ///   4. Finally, the function exists but has the wrong prototype: return the
341   ///      function with a constantexpr cast to the right prototype.
342   Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
343                                 AttributeSet AttributeList);
344
345   Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
346
347   /// Look up the specified function in the module symbol table. If it does not
348   /// exist, add a prototype for the function and return it. This function
349   /// guarantees to return a constant of pointer to the specified function type
350   /// or a ConstantExpr BitCast of that type if the named function has a
351   /// different type. This version of the method takes a null terminated list of
352   /// function arguments, which makes it easier for clients to use.
353   Constant *getOrInsertFunction(StringRef Name,
354                                 AttributeSet AttributeList,
355                                 Type *RetTy, ...)  END_WITH_NULL;
356
357   /// Same as above, but without the attributes.
358   Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
359     END_WITH_NULL;
360
361   /// Look up the specified function in the module symbol table. If it does not
362   /// exist, return null.
363   Function *getFunction(StringRef Name) const;
364
365 /// @}
366 /// @name Global Variable Accessors
367 /// @{
368
369   /// Look up the specified global variable in the module symbol table. If it
370   /// does not exist, return null. If AllowInternal is set to true, this
371   /// function will return types that have InternalLinkage. By default, these
372   /// types are not returned.
373   const GlobalVariable *getGlobalVariable(StringRef Name,
374                                           bool AllowInternal = false) const {
375     return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
376   }
377
378   GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
379
380   /// Return the global variable in the module with the specified name, of
381   /// arbitrary type. This method returns null if a global with the specified
382   /// name is not found.
383   GlobalVariable *getNamedGlobal(StringRef Name) {
384     return getGlobalVariable(Name, true);
385   }
386   const GlobalVariable *getNamedGlobal(StringRef Name) const {
387     return const_cast<Module *>(this)->getNamedGlobal(Name);
388   }
389
390   /// Look up the specified global in the module symbol table.
391   ///   1. If it does not exist, add a declaration of the global and return it.
392   ///   2. Else, the global exists but has the wrong type: return the function
393   ///      with a constantexpr cast to the right type.
394   ///   3. Finally, if the existing global is the correct declaration, return
395   ///      the existing global.
396   Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
397
398 /// @}
399 /// @name Global Alias Accessors
400 /// @{
401
402   /// Return the global alias in the module with the specified name, of
403   /// arbitrary type. This method returns null if a global with the specified
404   /// name is not found.
405   GlobalAlias *getNamedAlias(StringRef Name) const;
406
407 /// @}
408 /// @name Named Metadata Accessors
409 /// @{
410
411   /// Return the first NamedMDNode in the module with the specified name. This
412   /// method returns null if a NamedMDNode with the specified name is not found.
413   NamedMDNode *getNamedMetadata(const Twine &Name) const;
414
415   /// Return the named MDNode in the module with the specified name. This method
416   /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
417   /// found.
418   NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
419
420   /// Remove the given NamedMDNode from this module and delete it.
421   void eraseNamedMetadata(NamedMDNode *NMD);
422
423 /// @}
424 /// @name Comdat Accessors
425 /// @{
426
427   /// Return the Comdat in the module with the specified name. It is created
428   /// if it didn't already exist.
429   Comdat *getOrInsertComdat(StringRef Name);
430
431 /// @}
432 /// @name Module Flags Accessors
433 /// @{
434
435   /// Returns the module flags in the provided vector.
436   void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
437
438   /// Return the corresponding value if Key appears in module flags, otherwise
439   /// return null.
440   Value *getModuleFlag(StringRef Key) const;
441
442   /// Returns the NamedMDNode in the module that represents module-level flags.
443   /// This method returns null if there are no module-level flags.
444   NamedMDNode *getModuleFlagsMetadata() const;
445
446   /// Returns the NamedMDNode in the module that represents module-level flags.
447   /// If module-level flags aren't found, it creates the named metadata that
448   /// contains them.
449   NamedMDNode *getOrInsertModuleFlagsMetadata();
450
451   /// Add a module-level flag to the module-level flags metadata. It will create
452   /// the module-level flags named metadata if it doesn't already exist.
453   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
454   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
455   void addModuleFlag(MDNode *Node);
456
457 /// @}
458 /// @name Materialization
459 /// @{
460
461   /// Sets the GVMaterializer to GVM. This module must not yet have a
462   /// Materializer. To reset the materializer for a module that already has one,
463   /// call MaterializeAllPermanently first. Destroying this module will destroy
464   /// its materializer without materializing any more GlobalValues. Without
465   /// destroying the Module, there is no way to detach or destroy a materializer
466   /// without materializing all the GVs it controls, to avoid leaving orphan
467   /// unmaterialized GVs.
468   void setMaterializer(GVMaterializer *GVM);
469   /// Retrieves the GVMaterializer, if any, for this Module.
470   GVMaterializer *getMaterializer() const { return Materializer.get(); }
471
472   /// Returns true if this GV was loaded from this Module's GVMaterializer and
473   /// the GVMaterializer knows how to dematerialize the GV.
474   bool isDematerializable(const GlobalValue *GV) const;
475
476   /// Make sure the GlobalValue is fully read. If the module is corrupt, this
477   /// returns true and fills in the optional string with information about the
478   /// problem. If successful, this returns false.
479   bool Materialize(GlobalValue *GV, std::string *ErrInfo = nullptr);
480   /// If the GlobalValue is read in, and if the GVMaterializer supports it,
481   /// release the memory for the function, and set it up to be materialized
482   /// lazily. If !isDematerializable(), this method is a noop.
483   void Dematerialize(GlobalValue *GV);
484
485   /// Make sure all GlobalValues in this Module are fully read.
486   std::error_code materializeAll();
487
488   /// Make sure all GlobalValues in this Module are fully read and clear the
489   /// Materializer. If the module is corrupt, this DOES NOT clear the old
490   /// Materializer.
491   std::error_code materializeAllPermanently();
492
493 /// @}
494 /// @name Direct access to the globals list, functions list, and symbol table
495 /// @{
496
497   /// Get the Module's list of global variables (constant).
498   const GlobalListType   &getGlobalList() const       { return GlobalList; }
499   /// Get the Module's list of global variables.
500   GlobalListType         &getGlobalList()             { return GlobalList; }
501   static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
502     return &Module::GlobalList;
503   }
504   /// Get the Module's list of functions (constant).
505   const FunctionListType &getFunctionList() const     { return FunctionList; }
506   /// Get the Module's list of functions.
507   FunctionListType       &getFunctionList()           { return FunctionList; }
508   static iplist<Function> Module::*getSublistAccess(Function*) {
509     return &Module::FunctionList;
510   }
511   /// Get the Module's list of aliases (constant).
512   const AliasListType    &getAliasList() const        { return AliasList; }
513   /// Get the Module's list of aliases.
514   AliasListType          &getAliasList()              { return AliasList; }
515   static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
516     return &Module::AliasList;
517   }
518   /// Get the Module's list of named metadata (constant).
519   const NamedMDListType  &getNamedMDList() const      { return NamedMDList; }
520   /// Get the Module's list of named metadata.
521   NamedMDListType        &getNamedMDList()            { return NamedMDList; }
522   static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
523     return &Module::NamedMDList;
524   }
525   /// Get the symbol table of global variable and function identifiers
526   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
527   /// Get the Module's symbol table of global variable and function identifiers.
528   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
529   /// Get the Module's symbol table for COMDATs (constant).
530   const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
531   /// Get the Module's symbol table for COMDATs.
532   ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
533
534 /// @}
535 /// @name Global Variable Iteration
536 /// @{
537
538   global_iterator       global_begin()       { return GlobalList.begin(); }
539   const_global_iterator global_begin() const { return GlobalList.begin(); }
540   global_iterator       global_end  ()       { return GlobalList.end(); }
541   const_global_iterator global_end  () const { return GlobalList.end(); }
542   bool                  global_empty() const { return GlobalList.empty(); }
543
544   iterator_range<global_iterator> globals() {
545     return iterator_range<global_iterator>(global_begin(), global_end());
546   }
547   iterator_range<const_global_iterator> globals() const {
548     return iterator_range<const_global_iterator>(global_begin(), global_end());
549   }
550
551 /// @}
552 /// @name Function Iteration
553 /// @{
554
555   iterator                begin()       { return FunctionList.begin(); }
556   const_iterator          begin() const { return FunctionList.begin(); }
557   iterator                end  ()       { return FunctionList.end();   }
558   const_iterator          end  () const { return FunctionList.end();   }
559   reverse_iterator        rbegin()      { return FunctionList.rbegin(); }
560   const_reverse_iterator  rbegin() const{ return FunctionList.rbegin(); }
561   reverse_iterator        rend()        { return FunctionList.rend(); }
562   const_reverse_iterator  rend() const  { return FunctionList.rend(); }
563   size_t                  size() const  { return FunctionList.size(); }
564   bool                    empty() const { return FunctionList.empty(); }
565
566 /// @}
567 /// @name Alias Iteration
568 /// @{
569
570   alias_iterator       alias_begin()            { return AliasList.begin(); }
571   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
572   alias_iterator       alias_end  ()            { return AliasList.end();   }
573   const_alias_iterator alias_end  () const      { return AliasList.end();   }
574   size_t               alias_size () const      { return AliasList.size();  }
575   bool                 alias_empty() const      { return AliasList.empty(); }
576
577   iterator_range<alias_iterator> aliases() {
578     return iterator_range<alias_iterator>(alias_begin(), alias_end());
579   }
580   iterator_range<const_alias_iterator> aliases() const {
581     return iterator_range<const_alias_iterator>(alias_begin(), alias_end());
582   }
583
584 /// @}
585 /// @name Named Metadata Iteration
586 /// @{
587
588   named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
589   const_named_metadata_iterator named_metadata_begin() const {
590     return NamedMDList.begin();
591   }
592
593   named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
594   const_named_metadata_iterator named_metadata_end() const {
595     return NamedMDList.end();
596   }
597
598   size_t named_metadata_size() const { return NamedMDList.size();  }
599   bool named_metadata_empty() const { return NamedMDList.empty(); }
600
601   iterator_range<named_metadata_iterator> named_metadata() {
602     return iterator_range<named_metadata_iterator>(named_metadata_begin(),
603                                                    named_metadata_end());
604   }
605   iterator_range<const_named_metadata_iterator> named_metadata() const {
606     return iterator_range<const_named_metadata_iterator>(named_metadata_begin(),
607                                                          named_metadata_end());
608   }
609
610 /// @}
611 /// @name Utility functions for printing and dumping Module objects
612 /// @{
613
614   /// Print the module to an output stream with an optional
615   /// AssemblyAnnotationWriter.
616   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
617
618   /// Dump the module to stderr (for debugging).
619   void dump() const;
620   
621   /// This function causes all the subinstructions to "let go" of all references
622   /// that they are maintaining.  This allows one to 'delete' a whole class at
623   /// a time, even though there may be circular references... first all
624   /// references are dropped, and all use counts go to zero.  Then everything
625   /// is delete'd for real.  Note that no operations are valid on an object
626   /// that has "dropped all references", except operator delete.
627   void dropAllReferences();
628
629 /// @}
630 /// @name Utility functions for querying Debug information.
631 /// @{
632
633   /// \brief Returns the Dwarf Version by checking module flags.
634   unsigned getDwarfVersion() const;
635
636 /// @}
637 };
638
639 /// An raw_ostream inserter for modules.
640 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
641   M.print(O, nullptr);
642   return O;
643 }
644
645 // Create wrappers for C Binding types (see CBindingWrapping.h).
646 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
647
648 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
649  * Module.
650  */
651 inline Module *unwrap(LLVMModuleProviderRef MP) {
652   return reinterpret_cast<Module*>(MP);
653 }
654   
655 } // End llvm namespace
656
657 #endif