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