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