xref: /llvm-project-15.0.7/llvm/lib/IR/Module.cpp (revision 6bcf2ba2)
1eba7e4ecSEugene Zelenko //===- Module.cpp - Implement the Module class ----------------------------===//
2ef860a24SChandler Carruth //
3ef860a24SChandler Carruth //                     The LLVM Compiler Infrastructure
4ef860a24SChandler Carruth //
5ef860a24SChandler Carruth // This file is distributed under the University of Illinois Open Source
6ef860a24SChandler Carruth // License. See LICENSE.TXT for details.
7ef860a24SChandler Carruth //
8ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
9ef860a24SChandler Carruth //
10ef860a24SChandler Carruth // This file implements the Module class for the IR library.
11ef860a24SChandler Carruth //
12ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
13ef860a24SChandler Carruth 
146bda14b3SChandler Carruth #include "llvm/IR/Module.h"
15ef860a24SChandler Carruth #include "SymbolTableListTraitsImpl.h"
16b35cc691STeresa Johnson #include "llvm/ADT/SmallPtrSet.h"
17ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h"
18eba7e4ecSEugene Zelenko #include "llvm/ADT/SmallVector.h"
19eba7e4ecSEugene Zelenko #include "llvm/ADT/StringMap.h"
20eba7e4ecSEugene Zelenko #include "llvm/ADT/StringRef.h"
21eba7e4ecSEugene Zelenko #include "llvm/ADT/Twine.h"
22eba7e4ecSEugene Zelenko #include "llvm/IR/Attributes.h"
23eba7e4ecSEugene Zelenko #include "llvm/IR/Comdat.h"
249fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
25eba7e4ecSEugene Zelenko #include "llvm/IR/DataLayout.h"
265992a72bSAdrian Prantl #include "llvm/IR/DebugInfoMetadata.h"
276bda14b3SChandler Carruth #include "llvm/IR/DerivedTypes.h"
28eba7e4ecSEugene Zelenko #include "llvm/IR/Function.h"
296bda14b3SChandler Carruth #include "llvm/IR/GVMaterializer.h"
30eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalAlias.h"
31eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalIFunc.h"
32eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalValue.h"
33eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalVariable.h"
349fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h"
35eba7e4ecSEugene Zelenko #include "llvm/IR/Metadata.h"
36eba7e4ecSEugene Zelenko #include "llvm/IR/SymbolTableListTraits.h"
37eba7e4ecSEugene Zelenko #include "llvm/IR/Type.h"
382fa1e43aSRafael Espindola #include "llvm/IR/TypeFinder.h"
39eba7e4ecSEugene Zelenko #include "llvm/IR/Value.h"
40eba7e4ecSEugene Zelenko #include "llvm/IR/ValueSymbolTable.h"
41eba7e4ecSEugene Zelenko #include "llvm/Pass.h"
42eba7e4ecSEugene Zelenko #include "llvm/Support/Casting.h"
43eba7e4ecSEugene Zelenko #include "llvm/Support/CodeGen.h"
447f00d0a1SPeter Collingbourne #include "llvm/Support/Error.h"
45e2dcf7c3SPeter Collingbourne #include "llvm/Support/MemoryBuffer.h"
46144829d3SJF Bastien #include "llvm/Support/Path.h"
47144829d3SJF Bastien #include "llvm/Support/RandomNumberGenerator.h"
48ef860a24SChandler Carruth #include <algorithm>
49eba7e4ecSEugene Zelenko #include <cassert>
50eba7e4ecSEugene Zelenko #include <cstdint>
51eba7e4ecSEugene Zelenko #include <memory>
52eba7e4ecSEugene Zelenko #include <utility>
53eba7e4ecSEugene Zelenko #include <vector>
54083ca9bbSHans Wennborg 
55ef860a24SChandler Carruth using namespace llvm;
56ef860a24SChandler Carruth 
57ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
58ef860a24SChandler Carruth // Methods to implement the globals and functions lists.
59ef860a24SChandler Carruth //
60ef860a24SChandler Carruth 
61ef860a24SChandler Carruth // Explicit instantiations of SymbolTableListTraits since some of the methods
62ef860a24SChandler Carruth // are not in the public header file.
6337bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<Function>;
6437bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalVariable>;
6537bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalAlias>;
66a1feff70SDmitry Polukhin template class llvm::SymbolTableListTraits<GlobalIFunc>;
67ef860a24SChandler Carruth 
68ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
69ef860a24SChandler Carruth // Primitive Module methods.
70ef860a24SChandler Carruth //
71ef860a24SChandler Carruth 
72ef860a24SChandler Carruth Module::Module(StringRef MID, LLVMContext &C)
73e1164de5STeresa Johnson     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
74ef860a24SChandler Carruth   ValSymTab = new ValueSymbolTable();
75ef860a24SChandler Carruth   NamedMDSymTab = new StringMap<NamedMDNode *>();
76ef860a24SChandler Carruth   Context.addModule(this);
77ef860a24SChandler Carruth }
78ef860a24SChandler Carruth 
79ef860a24SChandler Carruth Module::~Module() {
80ef860a24SChandler Carruth   Context.removeModule(this);
81ef860a24SChandler Carruth   dropAllReferences();
82ef860a24SChandler Carruth   GlobalList.clear();
83ef860a24SChandler Carruth   FunctionList.clear();
84ef860a24SChandler Carruth   AliasList.clear();
85a1feff70SDmitry Polukhin   IFuncList.clear();
86ef860a24SChandler Carruth   NamedMDList.clear();
87ef860a24SChandler Carruth   delete ValSymTab;
88ef860a24SChandler Carruth   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
89ef860a24SChandler Carruth }
90ef860a24SChandler Carruth 
91e14625faSSerge Guelton std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
92e6acbdc4SJF Bastien   SmallString<32> Salt(P->getPassName());
93e6acbdc4SJF Bastien 
94e6acbdc4SJF Bastien   // This RNG is guaranteed to produce the same random stream only
95e6acbdc4SJF Bastien   // when the Module ID and thus the input filename is the same. This
96e6acbdc4SJF Bastien   // might be problematic if the input filename extension changes
97e6acbdc4SJF Bastien   // (e.g. from .c to .bc or .ll).
98e6acbdc4SJF Bastien   //
99e6acbdc4SJF Bastien   // We could store this salt in NamedMetadata, but this would make
100e6acbdc4SJF Bastien   // the parameter non-const. This would unfortunately make this
101e6acbdc4SJF Bastien   // interface unusable by any Machine passes, since they only have a
102e6acbdc4SJF Bastien   // const reference to their IR Module. Alternatively we can always
103e6acbdc4SJF Bastien   // store salt metadata from the Module constructor.
104e6acbdc4SJF Bastien   Salt += sys::path::filename(getModuleIdentifier());
105e6acbdc4SJF Bastien 
106ad9bbc20SSerge Guelton   return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
107e6acbdc4SJF Bastien }
108e6acbdc4SJF Bastien 
109ef860a24SChandler Carruth /// getNamedValue - Return the first global value in the module with
110ef860a24SChandler Carruth /// the specified name, of arbitrary type.  This method returns null
111ef860a24SChandler Carruth /// if a global with the specified name is not found.
112ef860a24SChandler Carruth GlobalValue *Module::getNamedValue(StringRef Name) const {
113ef860a24SChandler Carruth   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
114ef860a24SChandler Carruth }
115ef860a24SChandler Carruth 
116ef860a24SChandler Carruth /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
117ef860a24SChandler Carruth /// This ID is uniqued across modules in the current LLVMContext.
118ef860a24SChandler Carruth unsigned Module::getMDKindID(StringRef Name) const {
119ef860a24SChandler Carruth   return Context.getMDKindID(Name);
120ef860a24SChandler Carruth }
121ef860a24SChandler Carruth 
122ef860a24SChandler Carruth /// getMDKindNames - Populate client supplied SmallVector with the name for
123ef860a24SChandler Carruth /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
124ef860a24SChandler Carruth /// so it is filled in as an empty string.
125ef860a24SChandler Carruth void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
126ef860a24SChandler Carruth   return Context.getMDKindNames(Result);
127ef860a24SChandler Carruth }
128ef860a24SChandler Carruth 
1299303c246SSanjoy Das void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
1309303c246SSanjoy Das   return Context.getOperandBundleTags(Result);
1319303c246SSanjoy Das }
132ef860a24SChandler Carruth 
133ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
134ef860a24SChandler Carruth // Methods for easy access to the functions in the module.
135ef860a24SChandler Carruth //
136ef860a24SChandler Carruth 
137ef860a24SChandler Carruth // getOrInsertFunction - Look up the specified function in the module symbol
138ef860a24SChandler Carruth // table.  If it does not exist, add a prototype for the function and return
139ef860a24SChandler Carruth // it.  This is nice because it allows most passes to get away with not handling
140ef860a24SChandler Carruth // the symbol table directly for this common task.
141ef860a24SChandler Carruth //
142b518054bSReid Kleckner Constant *Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
143b518054bSReid Kleckner                                       AttributeList AttributeList) {
144ef860a24SChandler Carruth   // See if we have a definition for the specified function already.
145ef860a24SChandler Carruth   GlobalValue *F = getNamedValue(Name);
146c620761cSCraig Topper   if (!F) {
147ef860a24SChandler Carruth     // Nope, add it
148*6bcf2ba2SAlexander Richardson     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
149*6bcf2ba2SAlexander Richardson                                      DL.getProgramAddressSpace(), Name);
150ef860a24SChandler Carruth     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
151ef860a24SChandler Carruth       New->setAttributes(AttributeList);
152ef860a24SChandler Carruth     FunctionList.push_back(New);
153ef860a24SChandler Carruth     return New;                    // Return the new prototype.
154ef860a24SChandler Carruth   }
155ef860a24SChandler Carruth 
156ef860a24SChandler Carruth   // If the function exists but has the wrong type, return a bitcast to the
157ef860a24SChandler Carruth   // right type.
158*6bcf2ba2SAlexander Richardson   auto *PTy = PointerType::get(Ty, F->getAddressSpace());
159*6bcf2ba2SAlexander Richardson   if (F->getType() != PTy)
160*6bcf2ba2SAlexander Richardson     return ConstantExpr::getBitCast(F, PTy);
161ef860a24SChandler Carruth 
162ef860a24SChandler Carruth   // Otherwise, we just found the existing function or a prototype.
163ef860a24SChandler Carruth   return F;
164ef860a24SChandler Carruth }
165ef860a24SChandler Carruth 
166ef860a24SChandler Carruth Constant *Module::getOrInsertFunction(StringRef Name,
167ef860a24SChandler Carruth                                       FunctionType *Ty) {
168b518054bSReid Kleckner   return getOrInsertFunction(Name, Ty, AttributeList());
169ef860a24SChandler Carruth }
170ef860a24SChandler Carruth 
171ef860a24SChandler Carruth // getFunction - Look up the specified function in the module symbol table.
172ef860a24SChandler Carruth // If it does not exist, return null.
173ef860a24SChandler Carruth //
174ef860a24SChandler Carruth Function *Module::getFunction(StringRef Name) const {
175ef860a24SChandler Carruth   return dyn_cast_or_null<Function>(getNamedValue(Name));
176ef860a24SChandler Carruth }
177ef860a24SChandler Carruth 
178ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
179ef860a24SChandler Carruth // Methods for easy access to the global variables in the module.
180ef860a24SChandler Carruth //
181ef860a24SChandler Carruth 
182ef860a24SChandler Carruth /// getGlobalVariable - Look up the specified global variable in the module
183ef860a24SChandler Carruth /// symbol table.  If it does not exist, return null.  The type argument
184ef860a24SChandler Carruth /// should be the underlying type of the global, i.e., it should not have
185ef860a24SChandler Carruth /// the top-level PointerType, which represents the address of the global.
186ef860a24SChandler Carruth /// If AllowLocal is set to true, this function will return types that
187ef860a24SChandler Carruth /// have an local. By default, these types are not returned.
188ef860a24SChandler Carruth ///
1891dd20e65SCraig Topper GlobalVariable *Module::getGlobalVariable(StringRef Name,
1901dd20e65SCraig Topper                                           bool AllowLocal) const {
191ef860a24SChandler Carruth   if (GlobalVariable *Result =
192ef860a24SChandler Carruth       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
193ef860a24SChandler Carruth     if (AllowLocal || !Result->hasLocalLinkage())
194ef860a24SChandler Carruth       return Result;
195c620761cSCraig Topper   return nullptr;
196ef860a24SChandler Carruth }
197ef860a24SChandler Carruth 
198ef860a24SChandler Carruth /// getOrInsertGlobal - Look up the specified global in the module symbol table.
199ef860a24SChandler Carruth ///   1. If it does not exist, add a declaration of the global and return it.
200ef860a24SChandler Carruth ///   2. Else, the global exists but has the wrong type: return the function
201ef860a24SChandler Carruth ///      with a constantexpr cast to the right type.
2025200fdf0SMatt Arsenault ///   3. Finally, if the existing global is the correct declaration, return the
203ef860a24SChandler Carruth ///      existing global.
204ef860a24SChandler Carruth Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
205ef860a24SChandler Carruth   // See if we have a definition for the specified global already.
206ef860a24SChandler Carruth   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
207c620761cSCraig Topper   if (!GV) {
208ef860a24SChandler Carruth     // Nope, add it
209ef860a24SChandler Carruth     GlobalVariable *New =
210ef860a24SChandler Carruth       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
211c620761cSCraig Topper                          nullptr, Name);
212ef860a24SChandler Carruth      return New;                    // Return the new declaration.
213ef860a24SChandler Carruth   }
214ef860a24SChandler Carruth 
215ef860a24SChandler Carruth   // If the variable exists but has the wrong type, return a bitcast to the
216ef860a24SChandler Carruth   // right type.
21727e783e9SMatt Arsenault   Type *GVTy = GV->getType();
21827e783e9SMatt Arsenault   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
219a90a340fSMatt Arsenault   if (GVTy != PTy)
22027e783e9SMatt Arsenault     return ConstantExpr::getBitCast(GV, PTy);
221ef860a24SChandler Carruth 
222ef860a24SChandler Carruth   // Otherwise, we just found the existing function or a prototype.
223ef860a24SChandler Carruth   return GV;
224ef860a24SChandler Carruth }
225ef860a24SChandler Carruth 
226ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
227ef860a24SChandler Carruth // Methods for easy access to the global variables in the module.
228ef860a24SChandler Carruth //
229ef860a24SChandler Carruth 
230ef860a24SChandler Carruth // getNamedAlias - Look up the specified global in the module symbol table.
231ef860a24SChandler Carruth // If it does not exist, return null.
232ef860a24SChandler Carruth //
233ef860a24SChandler Carruth GlobalAlias *Module::getNamedAlias(StringRef Name) const {
234ef860a24SChandler Carruth   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
235ef860a24SChandler Carruth }
236ef860a24SChandler Carruth 
237a1feff70SDmitry Polukhin GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
238a1feff70SDmitry Polukhin   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
239a1feff70SDmitry Polukhin }
240a1feff70SDmitry Polukhin 
241ef860a24SChandler Carruth /// getNamedMetadata - Return the first NamedMDNode in the module with the
242ef860a24SChandler Carruth /// specified name. This method returns null if a NamedMDNode with the
243ef860a24SChandler Carruth /// specified name is not found.
244ef860a24SChandler Carruth NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
245ef860a24SChandler Carruth   SmallString<256> NameData;
246ef860a24SChandler Carruth   StringRef NameRef = Name.toStringRef(NameData);
247ef860a24SChandler Carruth   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
248ef860a24SChandler Carruth }
249ef860a24SChandler Carruth 
250ef860a24SChandler Carruth /// getOrInsertNamedMetadata - Return the first named MDNode in the module
251ef860a24SChandler Carruth /// with the specified name. This method returns a new NamedMDNode if a
252ef860a24SChandler Carruth /// NamedMDNode with the specified name is not found.
253ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
254ef860a24SChandler Carruth   NamedMDNode *&NMD =
255ef860a24SChandler Carruth     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
256ef860a24SChandler Carruth   if (!NMD) {
257ef860a24SChandler Carruth     NMD = new NamedMDNode(Name);
258ef860a24SChandler Carruth     NMD->setParent(this);
259ef860a24SChandler Carruth     NamedMDList.push_back(NMD);
260ef860a24SChandler Carruth   }
261ef860a24SChandler Carruth   return NMD;
262ef860a24SChandler Carruth }
263ef860a24SChandler Carruth 
264ef860a24SChandler Carruth /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
265ef860a24SChandler Carruth /// delete it.
266ef860a24SChandler Carruth void Module::eraseNamedMetadata(NamedMDNode *NMD) {
267ef860a24SChandler Carruth   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
26852888a67SDuncan P. N. Exon Smith   NamedMDList.erase(NMD->getIterator());
269ef860a24SChandler Carruth }
270ef860a24SChandler Carruth 
2715bf8fef5SDuncan P. N. Exon Smith bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
272d7677e7aSDavid Majnemer   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
273af023adbSAlexey Samsonov     uint64_t Val = Behavior->getLimitedValue();
274af023adbSAlexey Samsonov     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
275af023adbSAlexey Samsonov       MFB = static_cast<ModFlagBehavior>(Val);
276af023adbSAlexey Samsonov       return true;
277af023adbSAlexey Samsonov     }
278af023adbSAlexey Samsonov   }
279af023adbSAlexey Samsonov   return false;
280af023adbSAlexey Samsonov }
281af023adbSAlexey Samsonov 
282ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
283ef860a24SChandler Carruth void Module::
284ef860a24SChandler Carruth getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
285ef860a24SChandler Carruth   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
286ef860a24SChandler Carruth   if (!ModFlags) return;
287ef860a24SChandler Carruth 
288de36e804SDuncan P. N. Exon Smith   for (const MDNode *Flag : ModFlags->operands()) {
289af023adbSAlexey Samsonov     ModFlagBehavior MFB;
290af023adbSAlexey Samsonov     if (Flag->getNumOperands() >= 3 &&
291af023adbSAlexey Samsonov         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
292d7677e7aSDavid Majnemer         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
2938b4306ceSManman Ren       // Check the operands of the MDNode before accessing the operands.
2948b4306ceSManman Ren       // The verifier will actually catch these failures.
295ef860a24SChandler Carruth       MDString *Key = cast<MDString>(Flag->getOperand(1));
2965bf8fef5SDuncan P. N. Exon Smith       Metadata *Val = Flag->getOperand(2);
297af023adbSAlexey Samsonov       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
298ef860a24SChandler Carruth     }
299ef860a24SChandler Carruth   }
3008b4306ceSManman Ren }
301ef860a24SChandler Carruth 
3028bfde891SManman Ren /// Return the corresponding value if Key appears in module flags, otherwise
3038bfde891SManman Ren /// return null.
3045bf8fef5SDuncan P. N. Exon Smith Metadata *Module::getModuleFlag(StringRef Key) const {
3058bfde891SManman Ren   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
3068bfde891SManman Ren   getModuleFlagsMetadata(ModuleFlags);
3073ad5c962SBenjamin Kramer   for (const ModuleFlagEntry &MFE : ModuleFlags) {
3088bfde891SManman Ren     if (Key == MFE.Key->getString())
3098bfde891SManman Ren       return MFE.Val;
3108bfde891SManman Ren   }
311c620761cSCraig Topper   return nullptr;
3128bfde891SManman Ren }
3138bfde891SManman Ren 
314ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
315ef860a24SChandler Carruth /// represents module-level flags. This method returns null if there are no
316ef860a24SChandler Carruth /// module-level flags.
317ef860a24SChandler Carruth NamedMDNode *Module::getModuleFlagsMetadata() const {
318ef860a24SChandler Carruth   return getNamedMetadata("llvm.module.flags");
319ef860a24SChandler Carruth }
320ef860a24SChandler Carruth 
321ef860a24SChandler Carruth /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
322ef860a24SChandler Carruth /// represents module-level flags. If module-level flags aren't found, it
323ef860a24SChandler Carruth /// creates the named metadata that contains them.
324ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
325ef860a24SChandler Carruth   return getOrInsertNamedMetadata("llvm.module.flags");
326ef860a24SChandler Carruth }
327ef860a24SChandler Carruth 
328ef860a24SChandler Carruth /// addModuleFlag - Add a module-level flag to the module-level flags
329ef860a24SChandler Carruth /// metadata. It will create the module-level flags named metadata if it doesn't
330ef860a24SChandler Carruth /// already exist.
331ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3325bf8fef5SDuncan P. N. Exon Smith                            Metadata *Val) {
333ef860a24SChandler Carruth   Type *Int32Ty = Type::getInt32Ty(Context);
3345bf8fef5SDuncan P. N. Exon Smith   Metadata *Ops[3] = {
3355bf8fef5SDuncan P. N. Exon Smith       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
3365bf8fef5SDuncan P. N. Exon Smith       MDString::get(Context, Key), Val};
337ef860a24SChandler Carruth   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
338ef860a24SChandler Carruth }
339ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3405bf8fef5SDuncan P. N. Exon Smith                            Constant *Val) {
3415bf8fef5SDuncan P. N. Exon Smith   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
3425bf8fef5SDuncan P. N. Exon Smith }
3435bf8fef5SDuncan P. N. Exon Smith void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
344ef860a24SChandler Carruth                            uint32_t Val) {
345ef860a24SChandler Carruth   Type *Int32Ty = Type::getInt32Ty(Context);
346ef860a24SChandler Carruth   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
347ef860a24SChandler Carruth }
348ef860a24SChandler Carruth void Module::addModuleFlag(MDNode *Node) {
349ef860a24SChandler Carruth   assert(Node->getNumOperands() == 3 &&
350ef860a24SChandler Carruth          "Invalid number of operands for module flag!");
3515bf8fef5SDuncan P. N. Exon Smith   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
352ef860a24SChandler Carruth          isa<MDString>(Node->getOperand(1)) &&
353ef860a24SChandler Carruth          "Invalid operand types for module flag!");
354ef860a24SChandler Carruth   getOrInsertModuleFlagsMetadata()->addOperand(Node);
355ef860a24SChandler Carruth }
356ef860a24SChandler Carruth 
357f863ee29SRafael Espindola void Module::setDataLayout(StringRef Desc) {
358248ac139SRafael Espindola   DL.reset(Desc);
359f863ee29SRafael Espindola }
360f863ee29SRafael Espindola 
36146a43556SMehdi Amini void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
362f863ee29SRafael Espindola 
36346a43556SMehdi Amini const DataLayout &Module::getDataLayout() const { return DL; }
364f863ee29SRafael Espindola 
3655992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
3665992a72bSAdrian Prantl   return cast<DICompileUnit>(CUs->getOperand(Idx));
3675992a72bSAdrian Prantl }
3685992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
3695992a72bSAdrian Prantl   return cast<DICompileUnit>(CUs->getOperand(Idx));
3705992a72bSAdrian Prantl }
3715992a72bSAdrian Prantl 
3725992a72bSAdrian Prantl void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
3735992a72bSAdrian Prantl   while (CUs && (Idx < CUs->getNumOperands()) &&
3745992a72bSAdrian Prantl          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
3755992a72bSAdrian Prantl     ++Idx;
3765992a72bSAdrian Prantl }
3775992a72bSAdrian Prantl 
378ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
379ef860a24SChandler Carruth // Methods to control the materialization of GlobalValues in the Module.
380ef860a24SChandler Carruth //
381ef860a24SChandler Carruth void Module::setMaterializer(GVMaterializer *GVM) {
382ef860a24SChandler Carruth   assert(!Materializer &&
383c4a03483SRafael Espindola          "Module already has a GVMaterializer.  Call materializeAll"
384ef860a24SChandler Carruth          " to clear it out before setting another one.");
385ef860a24SChandler Carruth   Materializer.reset(GVM);
386ef860a24SChandler Carruth }
387ef860a24SChandler Carruth 
3887f00d0a1SPeter Collingbourne Error Module::materialize(GlobalValue *GV) {
3892b11ad4fSRafael Espindola   if (!Materializer)
3907f00d0a1SPeter Collingbourne     return Error::success();
3912b11ad4fSRafael Espindola 
3925a52e6dcSRafael Espindola   return Materializer->materialize(GV);
393ef860a24SChandler Carruth }
394ef860a24SChandler Carruth 
3957f00d0a1SPeter Collingbourne Error Module::materializeAll() {
396ef860a24SChandler Carruth   if (!Materializer)
3977f00d0a1SPeter Collingbourne     return Error::success();
398257a3536SRafael Espindola   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
399257a3536SRafael Espindola   return M->materializeModule();
400ef860a24SChandler Carruth }
401ef860a24SChandler Carruth 
4027f00d0a1SPeter Collingbourne Error Module::materializeMetadata() {
403cba833a0SRafael Espindola   if (!Materializer)
4047f00d0a1SPeter Collingbourne     return Error::success();
405cba833a0SRafael Espindola   return Materializer->materializeMetadata();
406cba833a0SRafael Espindola }
407cba833a0SRafael Espindola 
408ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
409ef860a24SChandler Carruth // Other module related stuff.
410ef860a24SChandler Carruth //
411ef860a24SChandler Carruth 
4122fa1e43aSRafael Espindola std::vector<StructType *> Module::getIdentifiedStructTypes() const {
4132fa1e43aSRafael Espindola   // If we have a materializer, it is possible that some unread function
4142fa1e43aSRafael Espindola   // uses a type that is currently not visible to a TypeFinder, so ask
4152fa1e43aSRafael Espindola   // the materializer which types it created.
4162fa1e43aSRafael Espindola   if (Materializer)
4172fa1e43aSRafael Espindola     return Materializer->getIdentifiedStructTypes();
4182fa1e43aSRafael Espindola 
4192fa1e43aSRafael Espindola   std::vector<StructType *> Ret;
4202fa1e43aSRafael Espindola   TypeFinder SrcStructTypes;
4212fa1e43aSRafael Espindola   SrcStructTypes.run(*this, true);
4222fa1e43aSRafael Espindola   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
4232fa1e43aSRafael Espindola   return Ret;
4242fa1e43aSRafael Espindola }
425ef860a24SChandler Carruth 
426ef860a24SChandler Carruth // dropAllReferences() - This function causes all the subelements to "let go"
427ef860a24SChandler Carruth // of all references that they are maintaining.  This allows one to 'delete' a
428ef860a24SChandler Carruth // whole module at a time, even though there may be circular references... first
429ef860a24SChandler Carruth // all references are dropped, and all use counts go to zero.  Then everything
430ef860a24SChandler Carruth // is deleted for real.  Note that no operations are valid on an object that
431ef860a24SChandler Carruth // has "dropped all references", except operator delete.
432ef860a24SChandler Carruth //
433ef860a24SChandler Carruth void Module::dropAllReferences() {
4343374910fSDavid Majnemer   for (Function &F : *this)
4353374910fSDavid Majnemer     F.dropAllReferences();
436ef860a24SChandler Carruth 
4373374910fSDavid Majnemer   for (GlobalVariable &GV : globals())
4383374910fSDavid Majnemer     GV.dropAllReferences();
439ef860a24SChandler Carruth 
4403374910fSDavid Majnemer   for (GlobalAlias &GA : aliases())
4413374910fSDavid Majnemer     GA.dropAllReferences();
442a1feff70SDmitry Polukhin 
443a1feff70SDmitry Polukhin   for (GlobalIFunc &GIF : ifuncs())
444a1feff70SDmitry Polukhin     GIF.dropAllReferences();
445ef860a24SChandler Carruth }
4460915c047SDiego Novillo 
447ac6081cbSNirav Dave unsigned Module::getNumberRegisterParameters() const {
448ac6081cbSNirav Dave   auto *Val =
449ac6081cbSNirav Dave       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
450ac6081cbSNirav Dave   if (!Val)
451ac6081cbSNirav Dave     return 0;
452ac6081cbSNirav Dave   return cast<ConstantInt>(Val->getValue())->getZExtValue();
453ac6081cbSNirav Dave }
454ac6081cbSNirav Dave 
4550915c047SDiego Novillo unsigned Module::getDwarfVersion() const {
4565bf8fef5SDuncan P. N. Exon Smith   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
4570915c047SDiego Novillo   if (!Val)
45812d2c120SReid Kleckner     return 0;
45912d2c120SReid Kleckner   return cast<ConstantInt>(Val->getValue())->getZExtValue();
46012d2c120SReid Kleckner }
46112d2c120SReid Kleckner 
46212d2c120SReid Kleckner unsigned Module::getCodeViewFlag() const {
46312d2c120SReid Kleckner   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
46412d2c120SReid Kleckner   if (!Val)
46512d2c120SReid Kleckner     return 0;
4665bf8fef5SDuncan P. N. Exon Smith   return cast<ConstantInt>(Val->getValue())->getZExtValue();
4670915c047SDiego Novillo }
468dad0a645SDavid Majnemer 
469e49374d0SJessica Paquette unsigned Module::getInstructionCount() {
470e49374d0SJessica Paquette   unsigned NumInstrs = 0;
471e49374d0SJessica Paquette   for (Function &F : FunctionList)
472e49374d0SJessica Paquette     NumInstrs += F.getInstructionCount();
473e49374d0SJessica Paquette   return NumInstrs;
474e49374d0SJessica Paquette }
475e49374d0SJessica Paquette 
476dad0a645SDavid Majnemer Comdat *Module::getOrInsertComdat(StringRef Name) {
4775106ce78SDavid Blaikie   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
478dad0a645SDavid Majnemer   Entry.second.Name = &Entry;
479dad0a645SDavid Majnemer   return &Entry.second;
480dad0a645SDavid Majnemer }
481771c132eSJustin Hibbits 
482771c132eSJustin Hibbits PICLevel::Level Module::getPICLevel() const {
4835bf8fef5SDuncan P. N. Exon Smith   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
484771c132eSJustin Hibbits 
485083ca9bbSHans Wennborg   if (!Val)
4864cccc488SDavide Italiano     return PICLevel::NotPIC;
487771c132eSJustin Hibbits 
4885bf8fef5SDuncan P. N. Exon Smith   return static_cast<PICLevel::Level>(
4895bf8fef5SDuncan P. N. Exon Smith       cast<ConstantInt>(Val->getValue())->getZExtValue());
490771c132eSJustin Hibbits }
491771c132eSJustin Hibbits 
492771c132eSJustin Hibbits void Module::setPICLevel(PICLevel::Level PL) {
4932db1369cSTeresa Johnson   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
494771c132eSJustin Hibbits }
495ecb05e51SEaswaran Raman 
49646d47b8cSSriraman Tallam PIELevel::Level Module::getPIELevel() const {
49746d47b8cSSriraman Tallam   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
49846d47b8cSSriraman Tallam 
49946d47b8cSSriraman Tallam   if (!Val)
50046d47b8cSSriraman Tallam     return PIELevel::Default;
50146d47b8cSSriraman Tallam 
50246d47b8cSSriraman Tallam   return static_cast<PIELevel::Level>(
50346d47b8cSSriraman Tallam       cast<ConstantInt>(Val->getValue())->getZExtValue());
50446d47b8cSSriraman Tallam }
50546d47b8cSSriraman Tallam 
50646d47b8cSSriraman Tallam void Module::setPIELevel(PIELevel::Level PL) {
5072db1369cSTeresa Johnson   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
50846d47b8cSSriraman Tallam }
50946d47b8cSSriraman Tallam 
51026628d30SEaswaran Raman void Module::setProfileSummary(Metadata *M) {
51126628d30SEaswaran Raman   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
51226628d30SEaswaran Raman }
51326628d30SEaswaran Raman 
51426628d30SEaswaran Raman Metadata *Module::getProfileSummary() {
51526628d30SEaswaran Raman   return getModuleFlag("ProfileSummary");
51626628d30SEaswaran Raman }
517b35cc691STeresa Johnson 
518e2dcf7c3SPeter Collingbourne void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
519e2dcf7c3SPeter Collingbourne   OwnedMemoryBuffer = std::move(MB);
520e2dcf7c3SPeter Collingbourne }
521e2dcf7c3SPeter Collingbourne 
522609f8c01SSriraman Tallam bool Module::getRtLibUseGOT() const {
523609f8c01SSriraman Tallam   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
524609f8c01SSriraman Tallam   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
525609f8c01SSriraman Tallam }
526609f8c01SSriraman Tallam 
527609f8c01SSriraman Tallam void Module::setRtLibUseGOT() {
528609f8c01SSriraman Tallam   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
529609f8c01SSriraman Tallam }
530609f8c01SSriraman Tallam 
531b35cc691STeresa Johnson GlobalVariable *llvm::collectUsedGlobalVariables(
532b35cc691STeresa Johnson     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
533b35cc691STeresa Johnson   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
534b35cc691STeresa Johnson   GlobalVariable *GV = M.getGlobalVariable(Name);
535b35cc691STeresa Johnson   if (!GV || !GV->hasInitializer())
536b35cc691STeresa Johnson     return GV;
537b35cc691STeresa Johnson 
538b35cc691STeresa Johnson   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
539b35cc691STeresa Johnson   for (Value *Op : Init->operands()) {
540b35cc691STeresa Johnson     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
541b35cc691STeresa Johnson     Set.insert(G);
542b35cc691STeresa Johnson   }
543b35cc691STeresa Johnson   return GV;
544b35cc691STeresa Johnson }
545