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