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