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