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