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