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