1 //===- llvm/Module.h - C++ class to represent a VM module -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Module.h This file contains the declarations for the Module class.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_MODULE_H
16 #define LLVM_IR_MODULE_H
18 #include "llvm-c/Types.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalAlias.h"
29 #include "llvm/IR/GlobalIFunc.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/SymbolTableListTraits.h"
33 #include "llvm/Support/CBindingWrapping.h"
34 #include "llvm/Support/CodeGen.h"
49 class RandomNumberGenerator;
50 template <class PtrType> class SmallPtrSetImpl;
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.
61 /// A module maintains a GlobalValRefMap 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 GlobalValueRefMap.
64 /// The main container class for the LLVM Intermediate Representation.
66 /// @name Types And Enumerations
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>;
82 /// The Global Variable iterator.
83 using global_iterator = GlobalListType::iterator;
84 /// The Global Variable constant iterator.
85 using const_global_iterator = GlobalListType::const_iterator;
87 /// The Function iterators.
88 using iterator = FunctionListType::iterator;
89 /// The Function constant iterator
90 using const_iterator = FunctionListType::const_iterator;
92 /// The Function reverse iterator.
93 using reverse_iterator = FunctionListType::reverse_iterator;
94 /// The Function constant reverse iterator.
95 using const_reverse_iterator = FunctionListType::const_reverse_iterator;
97 /// The Global Alias iterators.
98 using alias_iterator = AliasListType::iterator;
99 /// The Global Alias constant iterator
100 using const_alias_iterator = AliasListType::const_iterator;
102 /// The Global IFunc iterators.
103 using ifunc_iterator = IFuncListType::iterator;
104 /// The Global IFunc constant iterator
105 using const_ifunc_iterator = IFuncListType::const_iterator;
107 /// The named metadata iterators.
108 using named_metadata_iterator = NamedMDListType::iterator;
109 /// The named metadata constant iterators.
110 using const_named_metadata_iterator = NamedMDListType::const_iterator;
112 /// This enumeration defines the supported behaviors of module flags.
113 enum ModFlagBehavior {
114 /// Emits an error if two values disagree, otherwise the resulting value is
115 /// that of the operands.
118 /// Emits a warning if two values disagree. The result value will be the
119 /// operand for the flag from the first module being linked.
122 /// Adds a requirement that another module flag be present and have a
123 /// specified value after linking is performed. The value must be a metadata
124 /// pair, where the first element of the pair is the ID of the module flag
125 /// to be restricted, and the second element of the pair is the value the
126 /// module flag should be restricted to. This behavior can be used to
127 /// restrict the allowable results (via triggering of an error) of linking
128 /// IDs with the **Override** behavior.
131 /// Uses the specified value, regardless of the behavior or value of the
132 /// other module. If both modules specify **Override**, but the values
133 /// differ, an error will be emitted.
136 /// Appends the two values, which are required to be metadata nodes.
139 /// Appends the two values, which are required to be metadata
140 /// nodes. However, duplicate entries in the second list are dropped
141 /// during the append operation.
144 /// Takes the max of the two values, which are required to be integers.
148 ModFlagBehaviorFirstVal = Error,
149 ModFlagBehaviorLastVal = Max
152 /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
153 /// converted result in MFB.
154 static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
156 struct ModuleFlagEntry {
157 ModFlagBehavior Behavior;
161 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
162 : Behavior(B), Key(K), Val(V) {}
166 /// @name Member Variables
169 LLVMContext &Context; ///< The LLVMContext from which types and
170 ///< constants are allocated.
171 GlobalListType GlobalList; ///< The Global Variables in the module
172 FunctionListType FunctionList; ///< The Functions in the module
173 AliasListType AliasList; ///< The Aliases in the module
174 IFuncListType IFuncList; ///< The IFuncs in the module
175 NamedMDListType NamedMDList; ///< The named metadata in the module
176 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
177 ValueSymbolTable *ValSymTab; ///< Symbol table for values
178 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
179 std::unique_ptr<MemoryBuffer>
180 OwnedMemoryBuffer; ///< Memory buffer directly owned by this
181 ///< module, for legacy clients only.
182 std::unique_ptr<GVMaterializer>
183 Materializer; ///< Used to materialize GlobalValues
184 std::string ModuleID; ///< Human readable identifier for the module
185 std::string SourceFileName; ///< Original source file name for module,
186 ///< recorded in bitcode.
187 std::string TargetTriple; ///< Platform target triple Module compiled on
188 ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
189 void *NamedMDSymTab; ///< NamedMDNode names.
190 DataLayout DL; ///< DataLayout associated with the module
192 friend class Constant;
195 /// @name Constructors
198 /// The Module constructor. Note that there is no default constructor. You
199 /// must provide a name for the module upon construction.
200 explicit Module(StringRef ModuleID, LLVMContext& C);
201 /// The module destructor. This will dropAllReferences.
205 /// @name Module Level Accessors
208 /// Get the module identifier which is, essentially, the name of the module.
209 /// @returns the module identifier as a string
210 const std::string &getModuleIdentifier() const { return ModuleID; }
212 /// Returns the number of non-debug IR instructions in the module.
213 /// This is equivalent to the sum of the IR instruction counts of each
214 /// function contained in the module.
215 unsigned getInstructionCount();
217 /// Get the module's original source file name. When compiling from
218 /// bitcode, this is taken from a bitcode record where it was recorded.
219 /// For other compiles it is the same as the ModuleID, which would
220 /// contain the source file name.
221 const std::string &getSourceFileName() const { return SourceFileName; }
223 /// Get a short "name" for the module.
225 /// This is useful for debugging or logging. It is essentially a convenience
226 /// wrapper around getModuleIdentifier().
227 StringRef getName() const { return ModuleID; }
229 /// Get the data layout string for the module's target platform. This is
230 /// equivalent to getDataLayout()->getStringRepresentation().
231 const std::string &getDataLayoutStr() const {
232 return DL.getStringRepresentation();
235 /// Get the data layout for the module's target platform.
236 const DataLayout &getDataLayout() const;
238 /// Get the target triple which is a string describing the target host.
239 /// @returns a string containing the target triple.
240 const std::string &getTargetTriple() const { return TargetTriple; }
242 /// Get the global data context.
243 /// @returns LLVMContext - a container for LLVM's global information
244 LLVMContext &getContext() const { return Context; }
246 /// Get any module-scope inline assembly blocks.
247 /// @returns a string containing the module-scope inline assembly blocks.
248 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
250 /// Get a RandomNumberGenerator salted for use with this module. The
251 /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
252 /// ModuleID and the provided pass salt. The returned RNG should not
253 /// be shared across threads or passes.
255 /// A unique RNG per pass ensures a reproducible random stream even
256 /// when other randomness consuming passes are added or removed. In
257 /// addition, the random stream will be reproducible across LLVM
258 /// versions when the pass does not change.
259 std::unique_ptr<RandomNumberGenerator> createRNG(const Pass* P) const;
261 /// Return true if size-info optimization remark is enabled, false
263 bool shouldEmitInstrCountChangedRemark() {
264 return getContext().getDiagHandlerPtr()->isAnalysisRemarkEnabled(
269 /// @name Module Level Mutators
272 /// Set the module identifier.
273 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
275 /// Set the module's original source file name.
276 void setSourceFileName(StringRef Name) { SourceFileName = Name; }
278 /// Set the data layout
279 void setDataLayout(StringRef Desc);
280 void setDataLayout(const DataLayout &Other);
282 /// Set the target triple.
283 void setTargetTriple(StringRef T) { TargetTriple = T; }
285 /// Set the module-scope inline assembly blocks.
286 /// A trailing newline is added if the input doesn't have one.
287 void setModuleInlineAsm(StringRef Asm) {
288 GlobalScopeAsm = Asm;
289 if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
290 GlobalScopeAsm += '\n';
293 /// Append to the module-scope inline assembly blocks.
294 /// A trailing newline is added if the input doesn't have one.
295 void appendModuleInlineAsm(StringRef Asm) {
296 GlobalScopeAsm += Asm;
297 if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
298 GlobalScopeAsm += '\n';
302 /// @name Generic Value Accessors
305 /// Return the global value in the module with the specified name, of
306 /// arbitrary type. This method returns null if a global with the specified
307 /// name is not found.
308 GlobalValue *getNamedValue(StringRef Name) const;
310 /// Return a unique non-zero ID for the specified metadata kind. This ID is
311 /// uniqued across modules in the current LLVMContext.
312 unsigned getMDKindID(StringRef Name) const;
314 /// Populate client supplied SmallVector with the name for custom metadata IDs
315 /// registered in this LLVMContext.
316 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
318 /// Populate client supplied SmallVector with the bundle tags registered in
319 /// this LLVMContext. The bundle tags are ordered by increasing bundle IDs.
320 /// \see LLVMContext::getOperandBundleTagID
321 void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
323 /// Return the type with the specified name, or null if there is none by that
325 StructType *getTypeByName(StringRef Name) const;
327 std::vector<StructType *> getIdentifiedStructTypes() const;
330 /// @name Function Accessors
333 /// Look up the specified function in the module symbol table. Four
335 /// 1. If it does not exist, add a prototype for the function and return it.
336 /// 2. If it exists, and has a local linkage, the existing function is
337 /// renamed and a new one is inserted.
338 /// 3. Otherwise, if the existing function has the correct prototype, return
339 /// the existing function.
340 /// 4. Finally, the function exists but has the wrong prototype: return the
341 /// function with a constantexpr cast to the right prototype.
342 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
343 AttributeList AttributeList);
345 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
347 /// Look up the specified function in the module symbol table. If it does not
348 /// exist, add a prototype for the function and return it. This function
349 /// guarantees to return a constant of pointer to the specified function type
350 /// or a ConstantExpr BitCast of that type if the named function has a
351 /// different type. This version of the method takes a list of
352 /// function arguments, which makes it easier for clients to use.
353 template<typename... ArgsTy>
354 Constant *getOrInsertFunction(StringRef Name,
355 AttributeList AttributeList,
356 Type *RetTy, ArgsTy... Args)
358 SmallVector<Type*, sizeof...(ArgsTy)> ArgTys{Args...};
359 return getOrInsertFunction(Name,
360 FunctionType::get(RetTy, ArgTys, false),
364 /// Same as above, but without the attributes.
365 template<typename... ArgsTy>
366 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ArgsTy... Args) {
367 return getOrInsertFunction(Name, AttributeList{}, RetTy, Args...);
370 // Avoid an incorrect ordering that'd otherwise compile incorrectly.
371 template <typename... ArgsTy>
372 Constant *getOrInsertFunction(StringRef Name, AttributeList AttributeList,
373 FunctionType *Invalid, ArgsTy... Args) = delete;
375 /// Look up the specified function in the module symbol table. If it does not
376 /// exist, return null.
377 Function *getFunction(StringRef Name) const;
380 /// @name Global Variable Accessors
383 /// Look up the specified global variable in the module symbol table. If it
384 /// does not exist, return null. If AllowInternal is set to true, this
385 /// function will return types that have InternalLinkage. By default, these
386 /// types are not returned.
387 GlobalVariable *getGlobalVariable(StringRef Name) const {
388 return getGlobalVariable(Name, false);
391 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const;
393 GlobalVariable *getGlobalVariable(StringRef Name,
394 bool AllowInternal = false) {
395 return static_cast<const Module *>(this)->getGlobalVariable(Name,
399 /// Return the global variable in the module with the specified name, of
400 /// arbitrary type. This method returns null if a global with the specified
401 /// name is not found.
402 const GlobalVariable *getNamedGlobal(StringRef Name) const {
403 return getGlobalVariable(Name, true);
405 GlobalVariable *getNamedGlobal(StringRef Name) {
406 return const_cast<GlobalVariable *>(
407 static_cast<const Module *>(this)->getNamedGlobal(Name));
410 /// Look up the specified global in the module symbol table.
411 /// If it does not exist, invoke a callback to create a declaration of the
412 /// global and return it. The global is constantexpr casted to the expected
413 /// type if necessary.
415 getOrInsertGlobal(StringRef Name, Type *Ty,
416 function_ref<GlobalVariable *()> CreateGlobalCallback);
418 /// Look up the specified global in the module symbol table. If required, this
419 /// overload constructs the global variable using its constructor's defaults.
420 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
423 /// @name Global Alias Accessors
426 /// Return the global alias in the module with the specified name, of
427 /// arbitrary type. This method returns null if a global with the specified
428 /// name is not found.
429 GlobalAlias *getNamedAlias(StringRef Name) const;
432 /// @name Global IFunc Accessors
435 /// Return the global ifunc in the module with the specified name, of
436 /// arbitrary type. This method returns null if a global with the specified
437 /// name is not found.
438 GlobalIFunc *getNamedIFunc(StringRef Name) const;
441 /// @name Named Metadata Accessors
444 /// Return the first NamedMDNode in the module with the specified name. This
445 /// method returns null if a NamedMDNode with the specified name is not found.
446 NamedMDNode *getNamedMetadata(const Twine &Name) const;
448 /// Return the named MDNode in the module with the specified name. This method
449 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
451 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
453 /// Remove the given NamedMDNode from this module and delete it.
454 void eraseNamedMetadata(NamedMDNode *NMD);
457 /// @name Comdat Accessors
460 /// Return the Comdat in the module with the specified name. It is created
461 /// if it didn't already exist.
462 Comdat *getOrInsertComdat(StringRef Name);
465 /// @name Module Flags Accessors
468 /// Returns the module flags in the provided vector.
469 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
471 /// Return the corresponding value if Key appears in module flags, otherwise
473 Metadata *getModuleFlag(StringRef Key) const;
475 /// Returns the NamedMDNode in the module that represents module-level flags.
476 /// This method returns null if there are no module-level flags.
477 NamedMDNode *getModuleFlagsMetadata() const;
479 /// Returns the NamedMDNode in the module that represents module-level flags.
480 /// If module-level flags aren't found, it creates the named metadata that
482 NamedMDNode *getOrInsertModuleFlagsMetadata();
484 /// Add a module-level flag to the module-level flags metadata. It will create
485 /// the module-level flags named metadata if it doesn't already exist.
486 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
487 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
488 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
489 void addModuleFlag(MDNode *Node);
492 /// @name Materialization
495 /// Sets the GVMaterializer to GVM. This module must not yet have a
496 /// Materializer. To reset the materializer for a module that already has one,
497 /// call materializeAll first. Destroying this module will destroy
498 /// its materializer without materializing any more GlobalValues. Without
499 /// destroying the Module, there is no way to detach or destroy a materializer
500 /// without materializing all the GVs it controls, to avoid leaving orphan
501 /// unmaterialized GVs.
502 void setMaterializer(GVMaterializer *GVM);
503 /// Retrieves the GVMaterializer, if any, for this Module.
504 GVMaterializer *getMaterializer() const { return Materializer.get(); }
505 bool isMaterialized() const { return !getMaterializer(); }
507 /// Make sure the GlobalValue is fully read.
508 llvm::Error materialize(GlobalValue *GV);
510 /// Make sure all GlobalValues in this Module are fully read and clear the
512 llvm::Error materializeAll();
514 llvm::Error materializeMetadata();
517 /// @name Direct access to the globals list, functions list, and symbol table
520 /// Get the Module's list of global variables (constant).
521 const GlobalListType &getGlobalList() const { return GlobalList; }
522 /// Get the Module's list of global variables.
523 GlobalListType &getGlobalList() { return GlobalList; }
525 static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
526 return &Module::GlobalList;
529 /// Get the Module's list of functions (constant).
530 const FunctionListType &getFunctionList() const { return FunctionList; }
531 /// Get the Module's list of functions.
532 FunctionListType &getFunctionList() { return FunctionList; }
533 static FunctionListType Module::*getSublistAccess(Function*) {
534 return &Module::FunctionList;
537 /// Get the Module's list of aliases (constant).
538 const AliasListType &getAliasList() const { return AliasList; }
539 /// Get the Module's list of aliases.
540 AliasListType &getAliasList() { return AliasList; }
542 static AliasListType Module::*getSublistAccess(GlobalAlias*) {
543 return &Module::AliasList;
546 /// Get the Module's list of ifuncs (constant).
547 const IFuncListType &getIFuncList() const { return IFuncList; }
548 /// Get the Module's list of ifuncs.
549 IFuncListType &getIFuncList() { return IFuncList; }
551 static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
552 return &Module::IFuncList;
555 /// Get the Module's list of named metadata (constant).
556 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
557 /// Get the Module's list of named metadata.
558 NamedMDListType &getNamedMDList() { return NamedMDList; }
560 static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
561 return &Module::NamedMDList;
564 /// Get the symbol table of global variable and function identifiers
565 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
566 /// Get the Module's symbol table of global variable and function identifiers.
567 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
569 /// Get the Module's symbol table for COMDATs (constant).
570 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
571 /// Get the Module's symbol table for COMDATs.
572 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
575 /// @name Global Variable Iteration
578 global_iterator global_begin() { return GlobalList.begin(); }
579 const_global_iterator global_begin() const { return GlobalList.begin(); }
580 global_iterator global_end () { return GlobalList.end(); }
581 const_global_iterator global_end () const { return GlobalList.end(); }
582 bool global_empty() const { return GlobalList.empty(); }
584 iterator_range<global_iterator> globals() {
585 return make_range(global_begin(), global_end());
587 iterator_range<const_global_iterator> globals() const {
588 return make_range(global_begin(), global_end());
592 /// @name Function Iteration
595 iterator begin() { return FunctionList.begin(); }
596 const_iterator begin() const { return FunctionList.begin(); }
597 iterator end () { return FunctionList.end(); }
598 const_iterator end () const { return FunctionList.end(); }
599 reverse_iterator rbegin() { return FunctionList.rbegin(); }
600 const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
601 reverse_iterator rend() { return FunctionList.rend(); }
602 const_reverse_iterator rend() const { return FunctionList.rend(); }
603 size_t size() const { return FunctionList.size(); }
604 bool empty() const { return FunctionList.empty(); }
606 iterator_range<iterator> functions() {
607 return make_range(begin(), end());
609 iterator_range<const_iterator> functions() const {
610 return make_range(begin(), end());
614 /// @name Alias Iteration
617 alias_iterator alias_begin() { return AliasList.begin(); }
618 const_alias_iterator alias_begin() const { return AliasList.begin(); }
619 alias_iterator alias_end () { return AliasList.end(); }
620 const_alias_iterator alias_end () const { return AliasList.end(); }
621 size_t alias_size () const { return AliasList.size(); }
622 bool alias_empty() const { return AliasList.empty(); }
624 iterator_range<alias_iterator> aliases() {
625 return make_range(alias_begin(), alias_end());
627 iterator_range<const_alias_iterator> aliases() const {
628 return make_range(alias_begin(), alias_end());
632 /// @name IFunc Iteration
635 ifunc_iterator ifunc_begin() { return IFuncList.begin(); }
636 const_ifunc_iterator ifunc_begin() const { return IFuncList.begin(); }
637 ifunc_iterator ifunc_end () { return IFuncList.end(); }
638 const_ifunc_iterator ifunc_end () const { return IFuncList.end(); }
639 size_t ifunc_size () const { return IFuncList.size(); }
640 bool ifunc_empty() const { return IFuncList.empty(); }
642 iterator_range<ifunc_iterator> ifuncs() {
643 return make_range(ifunc_begin(), ifunc_end());
645 iterator_range<const_ifunc_iterator> ifuncs() const {
646 return make_range(ifunc_begin(), ifunc_end());
650 /// @name Convenience iterators
653 using global_object_iterator =
654 concat_iterator<GlobalObject, iterator, global_iterator>;
655 using const_global_object_iterator =
656 concat_iterator<const GlobalObject, const_iterator,
657 const_global_iterator>;
659 iterator_range<global_object_iterator> global_objects() {
660 return concat<GlobalObject>(functions(), globals());
662 iterator_range<const_global_object_iterator> global_objects() const {
663 return concat<const GlobalObject>(functions(), globals());
666 global_object_iterator global_object_begin() {
667 return global_objects().begin();
669 global_object_iterator global_object_end() { return global_objects().end(); }
671 const_global_object_iterator global_object_begin() const {
672 return global_objects().begin();
674 const_global_object_iterator global_object_end() const {
675 return global_objects().end();
678 using global_value_iterator =
679 concat_iterator<GlobalValue, iterator, global_iterator, alias_iterator,
681 using const_global_value_iterator =
682 concat_iterator<const GlobalValue, const_iterator, const_global_iterator,
683 const_alias_iterator, const_ifunc_iterator>;
685 iterator_range<global_value_iterator> global_values() {
686 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
688 iterator_range<const_global_value_iterator> global_values() const {
689 return concat<const GlobalValue>(functions(), globals(), aliases(),
693 global_value_iterator global_value_begin() { return global_values().begin(); }
694 global_value_iterator global_value_end() { return global_values().end(); }
696 const_global_value_iterator global_value_begin() const {
697 return global_values().begin();
699 const_global_value_iterator global_value_end() const {
700 return global_values().end();
704 /// @name Named Metadata Iteration
707 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
708 const_named_metadata_iterator named_metadata_begin() const {
709 return NamedMDList.begin();
712 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
713 const_named_metadata_iterator named_metadata_end() const {
714 return NamedMDList.end();
717 size_t named_metadata_size() const { return NamedMDList.size(); }
718 bool named_metadata_empty() const { return NamedMDList.empty(); }
720 iterator_range<named_metadata_iterator> named_metadata() {
721 return make_range(named_metadata_begin(), named_metadata_end());
723 iterator_range<const_named_metadata_iterator> named_metadata() const {
724 return make_range(named_metadata_begin(), named_metadata_end());
727 /// An iterator for DICompileUnits that skips those marked NoDebug.
728 class debug_compile_units_iterator
729 : public std::iterator<std::input_iterator_tag, DICompileUnit *> {
733 void SkipNoDebugCUs();
736 explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
737 : CUs(CUs), Idx(Idx) {
741 debug_compile_units_iterator &operator++() {
747 debug_compile_units_iterator operator++(int) {
748 debug_compile_units_iterator T(*this);
753 bool operator==(const debug_compile_units_iterator &I) const {
757 bool operator!=(const debug_compile_units_iterator &I) const {
761 DICompileUnit *operator*() const;
762 DICompileUnit *operator->() const;
765 debug_compile_units_iterator debug_compile_units_begin() const {
766 auto *CUs = getNamedMetadata("llvm.dbg.cu");
767 return debug_compile_units_iterator(CUs, 0);
770 debug_compile_units_iterator debug_compile_units_end() const {
771 auto *CUs = getNamedMetadata("llvm.dbg.cu");
772 return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
775 /// Return an iterator for all DICompileUnits listed in this Module's
776 /// llvm.dbg.cu named metadata node and aren't explicitly marked as
778 iterator_range<debug_compile_units_iterator> debug_compile_units() const {
779 auto *CUs = getNamedMetadata("llvm.dbg.cu");
781 debug_compile_units_iterator(CUs, 0),
782 debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
786 /// Destroy ConstantArrays in LLVMContext if they are not used.
787 /// ConstantArrays constructed during linking can cause quadratic memory
788 /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
789 /// slowdown for a large application.
791 /// NOTE: Constants are currently owned by LLVMContext. This can then only
792 /// be called where all uses of the LLVMContext are understood.
793 void dropTriviallyDeadConstantArrays();
795 /// @name Utility functions for printing and dumping Module objects
798 /// Print the module to an output stream with an optional
799 /// AssemblyAnnotationWriter. If \c ShouldPreserveUseListOrder, then include
800 /// uselistorder directives so that use-lists can be recreated when reading
802 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
803 bool ShouldPreserveUseListOrder = false,
804 bool IsForDebug = false) const;
806 /// Dump the module to stderr (for debugging).
809 /// This function causes all the subinstructions to "let go" of all references
810 /// that they are maintaining. This allows one to 'delete' a whole class at
811 /// a time, even though there may be circular references... first all
812 /// references are dropped, and all use counts go to zero. Then everything
813 /// is delete'd for real. Note that no operations are valid on an object
814 /// that has "dropped all references", except operator delete.
815 void dropAllReferences();
818 /// @name Utility functions for querying Debug information.
821 /// Returns the Number of Register ParametersDwarf Version by checking
823 unsigned getNumberRegisterParameters() const;
825 /// Returns the Dwarf Version by checking module flags.
826 unsigned getDwarfVersion() const;
828 /// Returns the CodeView Version by checking module flags.
829 /// Returns zero if not present in module.
830 unsigned getCodeViewFlag() const;
833 /// @name Utility functions for querying and setting PIC level
836 /// Returns the PIC level (small or large model)
837 PICLevel::Level getPICLevel() const;
839 /// Set the PIC level (small or large model)
840 void setPICLevel(PICLevel::Level PL);
844 /// @name Utility functions for querying and setting PIE level
847 /// Returns the PIE level (small or large model)
848 PIELevel::Level getPIELevel() const;
850 /// Set the PIE level (small or large model)
851 void setPIELevel(PIELevel::Level PL);
855 /// @name Utility function for querying and setting code model
858 /// Returns the code model (tiny, small, kernel, medium or large model)
859 Optional<CodeModel::Model> getCodeModel() const;
861 /// Set the code model (tiny, small, kernel, medium or large)
862 void setCodeModel(CodeModel::Model CL);
865 /// @name Utility functions for querying and setting PGO summary
868 /// Attach profile summary metadata to this module.
869 void setProfileSummary(Metadata *M);
871 /// Returns profile summary metadata
872 Metadata *getProfileSummary();
875 /// Returns true if PLT should be avoided for RTLib calls.
876 bool getRtLibUseGOT() const;
878 /// Set that PLT should be avoid for RTLib calls.
879 void setRtLibUseGOT();
881 /// @name Utility functions for querying and setting the build SDK version
884 /// Attach a build SDK version metadata to this module.
885 void setSDKVersion(const VersionTuple &V);
887 /// Get the build SDK version metadata.
889 /// An empty version is returned if no such metadata is attached.
890 VersionTuple getSDKVersion() const;
893 /// Take ownership of the given memory buffer.
894 void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
897 /// Given "llvm.used" or "llvm.compiler.used" as a global name, collect
898 /// the initializer elements of that global in Set and return the global itself.
899 GlobalVariable *collectUsedGlobalVariables(const Module &M,
900 SmallPtrSetImpl<GlobalValue *> &Set,
903 /// An raw_ostream inserter for modules.
904 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
909 // Create wrappers for C Binding types (see CBindingWrapping.h).
910 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
912 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
915 inline Module *unwrap(LLVMModuleProviderRef MP) {
916 return reinterpret_cast<Module*>(MP);
919 } // end namespace llvm
921 #endif // LLVM_IR_MODULE_H