]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/Module.h
Update lld to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/GlobalIFunc.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/Support/CBindingWrapping.h"
27 #include "llvm/Support/CodeGen.h"
28 #include "llvm/Support/DataTypes.h"
29
30 namespace llvm {
31 template <typename T> class Optional;
32 class Error;
33 class FunctionType;
34 class GVMaterializer;
35 class LLVMContext;
36 class MemoryBuffer;
37 class RandomNumberGenerator;
38 class StructType;
39 template <class PtrType> class SmallPtrSetImpl;
40
41 /// A Module instance is used to store all the information related to an
42 /// LLVM module. Modules are the top level container of all other LLVM
43 /// Intermediate Representation (IR) objects. Each module directly contains a
44 /// list of globals variables, a list of functions, a list of libraries (or
45 /// other modules) this module depends on, a symbol table, and various data
46 /// about the target's characteristics.
47 ///
48 /// A module maintains a GlobalValRefMap object that is used to hold all
49 /// constant references to global variables in the module.  When a global
50 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
51 /// @brief The main container class for the LLVM Intermediate Representation.
52 class Module {
53 /// @name Types And Enumerations
54 /// @{
55 public:
56   /// The type for the list of global variables.
57   typedef SymbolTableList<GlobalVariable> GlobalListType;
58   /// The type for the list of functions.
59   typedef SymbolTableList<Function> FunctionListType;
60   /// The type for the list of aliases.
61   typedef SymbolTableList<GlobalAlias> AliasListType;
62   /// The type for the list of ifuncs.
63   typedef SymbolTableList<GlobalIFunc> IFuncListType;
64   /// The type for the list of named metadata.
65   typedef ilist<NamedMDNode> NamedMDListType;
66   /// The type of the comdat "symbol" table.
67   typedef StringMap<Comdat> ComdatSymTabType;
68
69   /// The Global Variable iterator.
70   typedef GlobalListType::iterator                      global_iterator;
71   /// The Global Variable constant iterator.
72   typedef GlobalListType::const_iterator          const_global_iterator;
73
74   /// The Function iterators.
75   typedef FunctionListType::iterator                           iterator;
76   /// The Function constant iterator
77   typedef FunctionListType::const_iterator               const_iterator;
78
79   /// The Function reverse iterator.
80   typedef FunctionListType::reverse_iterator             reverse_iterator;
81   /// The Function constant reverse iterator.
82   typedef FunctionListType::const_reverse_iterator const_reverse_iterator;
83
84   /// The Global Alias iterators.
85   typedef AliasListType::iterator                        alias_iterator;
86   /// The Global Alias constant iterator
87   typedef AliasListType::const_iterator            const_alias_iterator;
88
89   /// The Global IFunc iterators.
90   typedef IFuncListType::iterator                        ifunc_iterator;
91   /// The Global IFunc constant iterator
92   typedef IFuncListType::const_iterator            const_ifunc_iterator;
93
94   /// The named metadata iterators.
95   typedef NamedMDListType::iterator             named_metadata_iterator;
96   /// The named metadata constant iterators.
97   typedef NamedMDListType::const_iterator const_named_metadata_iterator;
98
99   /// This enumeration defines the supported behaviors of module flags.
100   enum ModFlagBehavior {
101     /// Emits an error if two values disagree, otherwise the resulting value is
102     /// that of the operands.
103     Error = 1,
104
105     /// Emits a warning if two values disagree. The result value will be the
106     /// operand for the flag from the first module being linked.
107     Warning = 2,
108
109     /// Adds a requirement that another module flag be present and have a
110     /// specified value after linking is performed. The value must be a metadata
111     /// pair, where the first element of the pair is the ID of the module flag
112     /// to be restricted, and the second element of the pair is the value the
113     /// module flag should be restricted to. This behavior can be used to
114     /// restrict the allowable results (via triggering of an error) of linking
115     /// IDs with the **Override** behavior.
116     Require = 3,
117
118     /// Uses the specified value, regardless of the behavior or value of the
119     /// other module. If both modules specify **Override**, but the values
120     /// differ, an error will be emitted.
121     Override = 4,
122
123     /// Appends the two values, which are required to be metadata nodes.
124     Append = 5,
125
126     /// Appends the two values, which are required to be metadata
127     /// nodes. However, duplicate entries in the second list are dropped
128     /// during the append operation.
129     AppendUnique = 6,
130
131     // Markers:
132     ModFlagBehaviorFirstVal = Error,
133     ModFlagBehaviorLastVal = AppendUnique
134   };
135
136   /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
137   /// converted result in MFB.
138   static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
139
140   struct ModuleFlagEntry {
141     ModFlagBehavior Behavior;
142     MDString *Key;
143     Metadata *Val;
144     ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
145         : Behavior(B), Key(K), Val(V) {}
146   };
147
148 /// @}
149 /// @name Member Variables
150 /// @{
151 private:
152   LLVMContext &Context;           ///< The LLVMContext from which types and
153                                   ///< constants are allocated.
154   GlobalListType GlobalList;      ///< The Global Variables in the module
155   FunctionListType FunctionList;  ///< The Functions in the module
156   AliasListType AliasList;        ///< The Aliases in the module
157   IFuncListType IFuncList;        ///< The IFuncs in the module
158   NamedMDListType NamedMDList;    ///< The named metadata in the module
159   std::string GlobalScopeAsm;     ///< Inline Asm at global scope.
160   ValueSymbolTable *ValSymTab;    ///< Symbol table for values
161   ComdatSymTabType ComdatSymTab;  ///< Symbol table for COMDATs
162   std::unique_ptr<MemoryBuffer>
163   OwnedMemoryBuffer;              ///< Memory buffer directly owned by this
164                                   ///< module, for legacy clients only.
165   std::unique_ptr<GVMaterializer>
166   Materializer;                   ///< Used to materialize GlobalValues
167   std::string ModuleID;           ///< Human readable identifier for the module
168   std::string SourceFileName;     ///< Original source file name for module,
169                                   ///< recorded in bitcode.
170   std::string TargetTriple;       ///< Platform target triple Module compiled on
171                                   ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
172   void *NamedMDSymTab;            ///< NamedMDNode names.
173   DataLayout DL;                  ///< DataLayout associated with the module
174
175   friend class Constant;
176
177 /// @}
178 /// @name Constructors
179 /// @{
180 public:
181   /// The Module constructor. Note that there is no default constructor. You
182   /// must provide a name for the module upon construction.
183   explicit Module(StringRef ModuleID, LLVMContext& C);
184   /// The module destructor. This will dropAllReferences.
185   ~Module();
186
187 /// @}
188 /// @name Module Level Accessors
189 /// @{
190
191   /// Get the module identifier which is, essentially, the name of the module.
192   /// @returns the module identifier as a string
193   const std::string &getModuleIdentifier() const { return ModuleID; }
194
195   /// Get the module's original source file name. When compiling from
196   /// bitcode, this is taken from a bitcode record where it was recorded.
197   /// For other compiles it is the same as the ModuleID, which would
198   /// contain the source file name.
199   const std::string &getSourceFileName() const { return SourceFileName; }
200
201   /// \brief Get a short "name" for the module.
202   ///
203   /// This is useful for debugging or logging. It is essentially a convenience
204   /// wrapper around getModuleIdentifier().
205   StringRef getName() const { return ModuleID; }
206
207   /// Get the data layout string for the module's target platform. This is
208   /// equivalent to getDataLayout()->getStringRepresentation().
209   const std::string &getDataLayoutStr() const {
210     return DL.getStringRepresentation();
211   }
212
213   /// Get the data layout for the module's target platform.
214   const DataLayout &getDataLayout() const;
215
216   /// Get the target triple which is a string describing the target host.
217   /// @returns a string containing the target triple.
218   const std::string &getTargetTriple() const { return TargetTriple; }
219
220   /// Get the global data context.
221   /// @returns LLVMContext - a container for LLVM's global information
222   LLVMContext &getContext() const { return Context; }
223
224   /// Get any module-scope inline assembly blocks.
225   /// @returns a string containing the module-scope inline assembly blocks.
226   const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
227
228   /// Get a RandomNumberGenerator salted for use with this module. The
229   /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
230   /// ModuleID and the provided pass salt. The returned RNG should not
231   /// be shared across threads or passes.
232   ///
233   /// A unique RNG per pass ensures a reproducible random stream even
234   /// when other randomness consuming passes are added or removed. In
235   /// addition, the random stream will be reproducible across LLVM
236   /// versions when the pass does not change.
237   RandomNumberGenerator *createRNG(const Pass* P) const;
238
239 /// @}
240 /// @name Module Level Mutators
241 /// @{
242
243   /// Set the module identifier.
244   void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
245
246   /// Set the module's original source file name.
247   void setSourceFileName(StringRef Name) { SourceFileName = Name; }
248
249   /// Set the data layout
250   void setDataLayout(StringRef Desc);
251   void setDataLayout(const DataLayout &Other);
252
253   /// Set the target triple.
254   void setTargetTriple(StringRef T) { TargetTriple = T; }
255
256   /// Set the module-scope inline assembly blocks.
257   /// A trailing newline is added if the input doesn't have one.
258   void setModuleInlineAsm(StringRef Asm) {
259     GlobalScopeAsm = Asm;
260     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
261       GlobalScopeAsm += '\n';
262   }
263
264   /// Append to the module-scope inline assembly blocks.
265   /// A trailing newline is added if the input doesn't have one.
266   void appendModuleInlineAsm(StringRef Asm) {
267     GlobalScopeAsm += Asm;
268     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
269       GlobalScopeAsm += '\n';
270   }
271
272 /// @}
273 /// @name Generic Value Accessors
274 /// @{
275
276   /// Return the global value in the module with the specified name, of
277   /// arbitrary type. This method returns null if a global with the specified
278   /// name is not found.
279   GlobalValue *getNamedValue(StringRef Name) const;
280
281   /// Return a unique non-zero ID for the specified metadata kind. This ID is
282   /// uniqued across modules in the current LLVMContext.
283   unsigned getMDKindID(StringRef Name) const;
284
285   /// Populate client supplied SmallVector with the name for custom metadata IDs
286   /// registered in this LLVMContext.
287   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
288
289   /// Populate client supplied SmallVector with the bundle tags registered in
290   /// this LLVMContext.  The bundle tags are ordered by increasing bundle IDs.
291   /// \see LLVMContext::getOperandBundleTagID
292   void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
293
294   /// Return the type with the specified name, or null if there is none by that
295   /// name.
296   StructType *getTypeByName(StringRef Name) const;
297
298   std::vector<StructType *> getIdentifiedStructTypes() const;
299
300 /// @}
301 /// @name Function Accessors
302 /// @{
303
304   /// Look up the specified function in the module symbol table. Four
305   /// possibilities:
306   ///   1. If it does not exist, add a prototype for the function and return it.
307   ///   2. If it exists, and has a local linkage, the existing function is
308   ///      renamed and a new one is inserted.
309   ///   3. Otherwise, if the existing function has the correct prototype, return
310   ///      the existing function.
311   ///   4. Finally, the function exists but has the wrong prototype: return the
312   ///      function with a constantexpr cast to the right prototype.
313   Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
314                                 AttributeSet AttributeList);
315
316   Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
317
318   /// Look up the specified function in the module symbol table. If it does not
319   /// exist, add a prototype for the function and return it. This function
320   /// guarantees to return a constant of pointer to the specified function type
321   /// or a ConstantExpr BitCast of that type if the named function has a
322   /// different type. This version of the method takes a null terminated list of
323   /// function arguments, which makes it easier for clients to use.
324   Constant *getOrInsertFunction(StringRef Name,
325                                 AttributeSet AttributeList,
326                                 Type *RetTy, ...) LLVM_END_WITH_NULL;
327
328   /// Same as above, but without the attributes.
329   Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
330     LLVM_END_WITH_NULL;
331
332   /// Look up the specified function in the module symbol table. If it does not
333   /// exist, return null.
334   Function *getFunction(StringRef Name) const;
335
336 /// @}
337 /// @name Global Variable Accessors
338 /// @{
339
340   /// Look up the specified global variable in the module symbol table. If it
341   /// does not exist, return null. If AllowInternal is set to true, this
342   /// function will return types that have InternalLinkage. By default, these
343   /// types are not returned.
344   GlobalVariable *getGlobalVariable(StringRef Name) const {
345     return getGlobalVariable(Name, false);
346   }
347
348   GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const {
349     return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
350   }
351
352   GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
353
354   /// Return the global variable in the module with the specified name, of
355   /// arbitrary type. This method returns null if a global with the specified
356   /// name is not found.
357   GlobalVariable *getNamedGlobal(StringRef Name) {
358     return getGlobalVariable(Name, true);
359   }
360   const GlobalVariable *getNamedGlobal(StringRef Name) const {
361     return const_cast<Module *>(this)->getNamedGlobal(Name);
362   }
363
364   /// Look up the specified global in the module symbol table.
365   ///   1. If it does not exist, add a declaration of the global and return it.
366   ///   2. Else, the global exists but has the wrong type: return the function
367   ///      with a constantexpr cast to the right type.
368   ///   3. Finally, if the existing global is the correct declaration, return
369   ///      the existing global.
370   Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
371
372 /// @}
373 /// @name Global Alias Accessors
374 /// @{
375
376   /// Return the global alias in the module with the specified name, of
377   /// arbitrary type. This method returns null if a global with the specified
378   /// name is not found.
379   GlobalAlias *getNamedAlias(StringRef Name) const;
380
381 /// @}
382 /// @name Global IFunc Accessors
383 /// @{
384
385   /// Return the global ifunc in the module with the specified name, of
386   /// arbitrary type. This method returns null if a global with the specified
387   /// name is not found.
388   GlobalIFunc *getNamedIFunc(StringRef Name) const;
389
390 /// @}
391 /// @name Named Metadata Accessors
392 /// @{
393
394   /// Return the first NamedMDNode in the module with the specified name. This
395   /// method returns null if a NamedMDNode with the specified name is not found.
396   NamedMDNode *getNamedMetadata(const Twine &Name) const;
397
398   /// Return the named MDNode in the module with the specified name. This method
399   /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
400   /// found.
401   NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
402
403   /// Remove the given NamedMDNode from this module and delete it.
404   void eraseNamedMetadata(NamedMDNode *NMD);
405
406 /// @}
407 /// @name Comdat Accessors
408 /// @{
409
410   /// Return the Comdat in the module with the specified name. It is created
411   /// if it didn't already exist.
412   Comdat *getOrInsertComdat(StringRef Name);
413
414 /// @}
415 /// @name Module Flags Accessors
416 /// @{
417
418   /// Returns the module flags in the provided vector.
419   void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
420
421   /// Return the corresponding value if Key appears in module flags, otherwise
422   /// return null.
423   Metadata *getModuleFlag(StringRef Key) const;
424
425   /// Returns the NamedMDNode in the module that represents module-level flags.
426   /// This method returns null if there are no module-level flags.
427   NamedMDNode *getModuleFlagsMetadata() const;
428
429   /// Returns the NamedMDNode in the module that represents module-level flags.
430   /// If module-level flags aren't found, it creates the named metadata that
431   /// contains them.
432   NamedMDNode *getOrInsertModuleFlagsMetadata();
433
434   /// Add a module-level flag to the module-level flags metadata. It will create
435   /// the module-level flags named metadata if it doesn't already exist.
436   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
437   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
438   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
439   void addModuleFlag(MDNode *Node);
440
441 /// @}
442 /// @name Materialization
443 /// @{
444
445   /// Sets the GVMaterializer to GVM. This module must not yet have a
446   /// Materializer. To reset the materializer for a module that already has one,
447   /// call materializeAll first. Destroying this module will destroy
448   /// its materializer without materializing any more GlobalValues. Without
449   /// destroying the Module, there is no way to detach or destroy a materializer
450   /// without materializing all the GVs it controls, to avoid leaving orphan
451   /// unmaterialized GVs.
452   void setMaterializer(GVMaterializer *GVM);
453   /// Retrieves the GVMaterializer, if any, for this Module.
454   GVMaterializer *getMaterializer() const { return Materializer.get(); }
455   bool isMaterialized() const { return !getMaterializer(); }
456
457   /// Make sure the GlobalValue is fully read.
458   llvm::Error materialize(GlobalValue *GV);
459
460   /// Make sure all GlobalValues in this Module are fully read and clear the
461   /// Materializer.
462   llvm::Error materializeAll();
463
464   llvm::Error materializeMetadata();
465
466 /// @}
467 /// @name Direct access to the globals list, functions list, and symbol table
468 /// @{
469
470   /// Get the Module's list of global variables (constant).
471   const GlobalListType   &getGlobalList() const       { return GlobalList; }
472   /// Get the Module's list of global variables.
473   GlobalListType         &getGlobalList()             { return GlobalList; }
474   static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
475     return &Module::GlobalList;
476   }
477   /// Get the Module's list of functions (constant).
478   const FunctionListType &getFunctionList() const     { return FunctionList; }
479   /// Get the Module's list of functions.
480   FunctionListType       &getFunctionList()           { return FunctionList; }
481   static FunctionListType Module::*getSublistAccess(Function*) {
482     return &Module::FunctionList;
483   }
484   /// Get the Module's list of aliases (constant).
485   const AliasListType    &getAliasList() const        { return AliasList; }
486   /// Get the Module's list of aliases.
487   AliasListType          &getAliasList()              { return AliasList; }
488   static AliasListType Module::*getSublistAccess(GlobalAlias*) {
489     return &Module::AliasList;
490   }
491   /// Get the Module's list of ifuncs (constant).
492   const IFuncListType    &getIFuncList() const        { return IFuncList; }
493   /// Get the Module's list of ifuncs.
494   IFuncListType          &getIFuncList()              { return IFuncList; }
495   static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
496     return &Module::IFuncList;
497   }
498   /// Get the Module's list of named metadata (constant).
499   const NamedMDListType  &getNamedMDList() const      { return NamedMDList; }
500   /// Get the Module's list of named metadata.
501   NamedMDListType        &getNamedMDList()            { return NamedMDList; }
502   static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
503     return &Module::NamedMDList;
504   }
505   /// Get the symbol table of global variable and function identifiers
506   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
507   /// Get the Module's symbol table of global variable and function identifiers.
508   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
509   /// Get the Module's symbol table for COMDATs (constant).
510   const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
511   /// Get the Module's symbol table for COMDATs.
512   ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
513
514 /// @}
515 /// @name Global Variable Iteration
516 /// @{
517
518   global_iterator       global_begin()       { return GlobalList.begin(); }
519   const_global_iterator global_begin() const { return GlobalList.begin(); }
520   global_iterator       global_end  ()       { return GlobalList.end(); }
521   const_global_iterator global_end  () const { return GlobalList.end(); }
522   bool                  global_empty() const { return GlobalList.empty(); }
523
524   iterator_range<global_iterator> globals() {
525     return make_range(global_begin(), global_end());
526   }
527   iterator_range<const_global_iterator> globals() const {
528     return make_range(global_begin(), global_end());
529   }
530
531 /// @}
532 /// @name Function Iteration
533 /// @{
534
535   iterator                begin()       { return FunctionList.begin(); }
536   const_iterator          begin() const { return FunctionList.begin(); }
537   iterator                end  ()       { return FunctionList.end();   }
538   const_iterator          end  () const { return FunctionList.end();   }
539   reverse_iterator        rbegin()      { return FunctionList.rbegin(); }
540   const_reverse_iterator  rbegin() const{ return FunctionList.rbegin(); }
541   reverse_iterator        rend()        { return FunctionList.rend(); }
542   const_reverse_iterator  rend() const  { return FunctionList.rend(); }
543   size_t                  size() const  { return FunctionList.size(); }
544   bool                    empty() const { return FunctionList.empty(); }
545
546   iterator_range<iterator> functions() {
547     return make_range(begin(), end());
548   }
549   iterator_range<const_iterator> functions() const {
550     return make_range(begin(), end());
551   }
552
553 /// @}
554 /// @name Alias Iteration
555 /// @{
556
557   alias_iterator       alias_begin()            { return AliasList.begin(); }
558   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
559   alias_iterator       alias_end  ()            { return AliasList.end();   }
560   const_alias_iterator alias_end  () const      { return AliasList.end();   }
561   size_t               alias_size () const      { return AliasList.size();  }
562   bool                 alias_empty() const      { return AliasList.empty(); }
563
564   iterator_range<alias_iterator> aliases() {
565     return make_range(alias_begin(), alias_end());
566   }
567   iterator_range<const_alias_iterator> aliases() const {
568     return make_range(alias_begin(), alias_end());
569   }
570
571 /// @}
572 /// @name IFunc Iteration
573 /// @{
574
575   ifunc_iterator       ifunc_begin()            { return IFuncList.begin(); }
576   const_ifunc_iterator ifunc_begin() const      { return IFuncList.begin(); }
577   ifunc_iterator       ifunc_end  ()            { return IFuncList.end();   }
578   const_ifunc_iterator ifunc_end  () const      { return IFuncList.end();   }
579   size_t               ifunc_size () const      { return IFuncList.size();  }
580   bool                 ifunc_empty() const      { return IFuncList.empty(); }
581
582   iterator_range<ifunc_iterator> ifuncs() {
583     return make_range(ifunc_begin(), ifunc_end());
584   }
585   iterator_range<const_ifunc_iterator> ifuncs() const {
586     return make_range(ifunc_begin(), ifunc_end());
587   }
588
589   /// @}
590   /// @name Convenience iterators
591   /// @{
592
593   typedef concat_iterator<GlobalObject, iterator, global_iterator>
594       global_object_iterator;
595   typedef concat_iterator<const GlobalObject, const_iterator,
596                           const_global_iterator>
597       const_global_object_iterator;
598
599   iterator_range<global_object_iterator> global_objects() {
600     return concat<GlobalObject>(functions(), globals());
601   }
602   iterator_range<const_global_object_iterator> global_objects() const {
603     return concat<const GlobalObject>(functions(), globals());
604   }
605
606   global_object_iterator global_object_begin() {
607     return global_objects().begin();
608   }
609   global_object_iterator global_object_end() { return global_objects().end(); }
610
611   const_global_object_iterator global_object_begin() const {
612     return global_objects().begin();
613   }
614   const_global_object_iterator global_object_end() const {
615     return global_objects().end();
616   }
617
618   /// @}
619   /// @name Named Metadata Iteration
620   /// @{
621
622   named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
623   const_named_metadata_iterator named_metadata_begin() const {
624     return NamedMDList.begin();
625   }
626
627   named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
628   const_named_metadata_iterator named_metadata_end() const {
629     return NamedMDList.end();
630   }
631
632   size_t named_metadata_size() const { return NamedMDList.size();  }
633   bool named_metadata_empty() const { return NamedMDList.empty(); }
634
635   iterator_range<named_metadata_iterator> named_metadata() {
636     return make_range(named_metadata_begin(), named_metadata_end());
637   }
638   iterator_range<const_named_metadata_iterator> named_metadata() const {
639     return make_range(named_metadata_begin(), named_metadata_end());
640   }
641
642   /// An iterator for DICompileUnits that skips those marked NoDebug.
643   class debug_compile_units_iterator
644       : public std::iterator<std::input_iterator_tag, DICompileUnit *> {
645     NamedMDNode *CUs;
646     unsigned Idx;
647     void SkipNoDebugCUs();
648   public:
649     explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
650         : CUs(CUs), Idx(Idx) {
651       SkipNoDebugCUs();
652     }
653     debug_compile_units_iterator &operator++() {
654       ++Idx;
655       SkipNoDebugCUs();
656       return *this;
657     }
658     debug_compile_units_iterator operator++(int) {
659       debug_compile_units_iterator T(*this);
660       ++Idx;
661       return T;
662     }
663     bool operator==(const debug_compile_units_iterator &I) const {
664       return Idx == I.Idx;
665     }
666     bool operator!=(const debug_compile_units_iterator &I) const {
667       return Idx != I.Idx;
668     }
669     DICompileUnit *operator*() const;
670     DICompileUnit *operator->() const;
671   };
672
673   debug_compile_units_iterator debug_compile_units_begin() const {
674     auto *CUs = getNamedMetadata("llvm.dbg.cu");
675     return debug_compile_units_iterator(CUs, 0);
676   }
677
678   debug_compile_units_iterator debug_compile_units_end() const {
679     auto *CUs = getNamedMetadata("llvm.dbg.cu");
680     return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
681   }
682
683   /// Return an iterator for all DICompileUnits listed in this Module's
684   /// llvm.dbg.cu named metadata node and aren't explicitly marked as
685   /// NoDebug.
686   iterator_range<debug_compile_units_iterator> debug_compile_units() const {
687     auto *CUs = getNamedMetadata("llvm.dbg.cu");
688     return make_range(
689         debug_compile_units_iterator(CUs, 0),
690         debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
691   }
692 /// @}
693
694   /// Destroy ConstantArrays in LLVMContext if they are not used.
695   /// ConstantArrays constructed during linking can cause quadratic memory
696   /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
697   /// slowdown for a large application.
698   ///
699   /// NOTE: Constants are currently owned by LLVMContext. This can then only
700   /// be called where all uses of the LLVMContext are understood.
701   void dropTriviallyDeadConstantArrays();
702
703 /// @name Utility functions for printing and dumping Module objects
704 /// @{
705
706   /// Print the module to an output stream with an optional
707   /// AssemblyAnnotationWriter.  If \c ShouldPreserveUseListOrder, then include
708   /// uselistorder directives so that use-lists can be recreated when reading
709   /// the assembly.
710   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
711              bool ShouldPreserveUseListOrder = false,
712              bool IsForDebug = false) const;
713
714   /// Dump the module to stderr (for debugging).
715   void dump() const;
716
717   /// This function causes all the subinstructions to "let go" of all references
718   /// that they are maintaining.  This allows one to 'delete' a whole class at
719   /// a time, even though there may be circular references... first all
720   /// references are dropped, and all use counts go to zero.  Then everything
721   /// is delete'd for real.  Note that no operations are valid on an object
722   /// that has "dropped all references", except operator delete.
723   void dropAllReferences();
724
725 /// @}
726 /// @name Utility functions for querying Debug information.
727 /// @{
728
729   /// \brief Returns the Dwarf Version by checking module flags.
730   unsigned getDwarfVersion() const;
731
732   /// \brief Returns the CodeView Version by checking module flags.
733   /// Returns zero if not present in module.
734   unsigned getCodeViewFlag() const;
735
736 /// @}
737 /// @name Utility functions for querying and setting PIC level
738 /// @{
739
740   /// \brief Returns the PIC level (small or large model)
741   PICLevel::Level getPICLevel() const;
742
743   /// \brief Set the PIC level (small or large model)
744   void setPICLevel(PICLevel::Level PL);
745 /// @}
746
747 /// @}
748 /// @name Utility functions for querying and setting PIE level
749 /// @{
750
751   /// \brief Returns the PIE level (small or large model)
752   PIELevel::Level getPIELevel() const;
753
754   /// \brief Set the PIE level (small or large model)
755   void setPIELevel(PIELevel::Level PL);
756 /// @}
757
758   /// @name Utility functions for querying and setting PGO summary
759   /// @{
760
761   /// \brief Attach profile summary metadata to this module.
762   void setProfileSummary(Metadata *M);
763
764   /// \brief Returns profile summary metadata
765   Metadata *getProfileSummary();
766   /// @}
767
768   /// Take ownership of the given memory buffer.
769   void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
770 };
771
772 /// \brief Given "llvm.used" or "llvm.compiler.used" as a global name, collect
773 /// the initializer elements of that global in Set and return the global itself.
774 GlobalVariable *collectUsedGlobalVariables(const Module &M,
775                                            SmallPtrSetImpl<GlobalValue *> &Set,
776                                            bool CompilerUsed);
777
778 /// An raw_ostream inserter for modules.
779 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
780   M.print(O, nullptr);
781   return O;
782 }
783
784 // Create wrappers for C Binding types (see CBindingWrapping.h).
785 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
786
787 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
788  * Module.
789  */
790 inline Module *unwrap(LLVMModuleProviderRef MP) {
791   return reinterpret_cast<Module*>(MP);
792 }
793
794 } // End llvm namespace
795
796 #endif