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