xref: /llvm-project-15.0.7/llvm/lib/IR/Module.cpp (revision e14625fa)
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 
91*e14625faSSerge 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 
106*e14625faSSerge 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
148ef860a24SChandler Carruth     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
149ef860a24SChandler Carruth     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
150ef860a24SChandler Carruth       New->setAttributes(AttributeList);
151ef860a24SChandler Carruth     FunctionList.push_back(New);
152ef860a24SChandler Carruth     return New;                    // Return the new prototype.
153ef860a24SChandler Carruth   }
154ef860a24SChandler Carruth 
155ef860a24SChandler Carruth   // If the function exists but has the wrong type, return a bitcast to the
156ef860a24SChandler Carruth   // right type.
157ef860a24SChandler Carruth   if (F->getType() != PointerType::getUnqual(Ty))
158ef860a24SChandler Carruth     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
159ef860a24SChandler Carruth 
160ef860a24SChandler Carruth   // Otherwise, we just found the existing function or a prototype.
161ef860a24SChandler Carruth   return F;
162ef860a24SChandler Carruth }
163ef860a24SChandler Carruth 
164ef860a24SChandler Carruth Constant *Module::getOrInsertFunction(StringRef Name,
165ef860a24SChandler Carruth                                       FunctionType *Ty) {
166b518054bSReid Kleckner   return getOrInsertFunction(Name, Ty, AttributeList());
167ef860a24SChandler Carruth }
168ef860a24SChandler Carruth 
169ef860a24SChandler Carruth // getFunction - Look up the specified function in the module symbol table.
170ef860a24SChandler Carruth // If it does not exist, return null.
171ef860a24SChandler Carruth //
172ef860a24SChandler Carruth Function *Module::getFunction(StringRef Name) const {
173ef860a24SChandler Carruth   return dyn_cast_or_null<Function>(getNamedValue(Name));
174ef860a24SChandler Carruth }
175ef860a24SChandler Carruth 
176ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
177ef860a24SChandler Carruth // Methods for easy access to the global variables in the module.
178ef860a24SChandler Carruth //
179ef860a24SChandler Carruth 
180ef860a24SChandler Carruth /// getGlobalVariable - Look up the specified global variable in the module
181ef860a24SChandler Carruth /// symbol table.  If it does not exist, return null.  The type argument
182ef860a24SChandler Carruth /// should be the underlying type of the global, i.e., it should not have
183ef860a24SChandler Carruth /// the top-level PointerType, which represents the address of the global.
184ef860a24SChandler Carruth /// If AllowLocal is set to true, this function will return types that
185ef860a24SChandler Carruth /// have an local. By default, these types are not returned.
186ef860a24SChandler Carruth ///
1871dd20e65SCraig Topper GlobalVariable *Module::getGlobalVariable(StringRef Name,
1881dd20e65SCraig Topper                                           bool AllowLocal) const {
189ef860a24SChandler Carruth   if (GlobalVariable *Result =
190ef860a24SChandler Carruth       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
191ef860a24SChandler Carruth     if (AllowLocal || !Result->hasLocalLinkage())
192ef860a24SChandler Carruth       return Result;
193c620761cSCraig Topper   return nullptr;
194ef860a24SChandler Carruth }
195ef860a24SChandler Carruth 
196ef860a24SChandler Carruth /// getOrInsertGlobal - Look up the specified global in the module symbol table.
197ef860a24SChandler Carruth ///   1. If it does not exist, add a declaration of the global and return it.
198ef860a24SChandler Carruth ///   2. Else, the global exists but has the wrong type: return the function
199ef860a24SChandler Carruth ///      with a constantexpr cast to the right type.
2005200fdf0SMatt Arsenault ///   3. Finally, if the existing global is the correct declaration, return the
201ef860a24SChandler Carruth ///      existing global.
202ef860a24SChandler Carruth Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
203ef860a24SChandler Carruth   // See if we have a definition for the specified global already.
204ef860a24SChandler Carruth   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
205c620761cSCraig Topper   if (!GV) {
206ef860a24SChandler Carruth     // Nope, add it
207ef860a24SChandler Carruth     GlobalVariable *New =
208ef860a24SChandler Carruth       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
209c620761cSCraig Topper                          nullptr, Name);
210ef860a24SChandler Carruth      return New;                    // Return the new declaration.
211ef860a24SChandler Carruth   }
212ef860a24SChandler Carruth 
213ef860a24SChandler Carruth   // If the variable exists but has the wrong type, return a bitcast to the
214ef860a24SChandler Carruth   // right type.
21527e783e9SMatt Arsenault   Type *GVTy = GV->getType();
21627e783e9SMatt Arsenault   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
217a90a340fSMatt Arsenault   if (GVTy != PTy)
21827e783e9SMatt Arsenault     return ConstantExpr::getBitCast(GV, PTy);
219ef860a24SChandler Carruth 
220ef860a24SChandler Carruth   // Otherwise, we just found the existing function or a prototype.
221ef860a24SChandler Carruth   return GV;
222ef860a24SChandler Carruth }
223ef860a24SChandler Carruth 
224ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
225ef860a24SChandler Carruth // Methods for easy access to the global variables in the module.
226ef860a24SChandler Carruth //
227ef860a24SChandler Carruth 
228ef860a24SChandler Carruth // getNamedAlias - Look up the specified global in the module symbol table.
229ef860a24SChandler Carruth // If it does not exist, return null.
230ef860a24SChandler Carruth //
231ef860a24SChandler Carruth GlobalAlias *Module::getNamedAlias(StringRef Name) const {
232ef860a24SChandler Carruth   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
233ef860a24SChandler Carruth }
234ef860a24SChandler Carruth 
235a1feff70SDmitry Polukhin GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
236a1feff70SDmitry Polukhin   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
237a1feff70SDmitry Polukhin }
238a1feff70SDmitry Polukhin 
239ef860a24SChandler Carruth /// getNamedMetadata - Return the first NamedMDNode in the module with the
240ef860a24SChandler Carruth /// specified name. This method returns null if a NamedMDNode with the
241ef860a24SChandler Carruth /// specified name is not found.
242ef860a24SChandler Carruth NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
243ef860a24SChandler Carruth   SmallString<256> NameData;
244ef860a24SChandler Carruth   StringRef NameRef = Name.toStringRef(NameData);
245ef860a24SChandler Carruth   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
246ef860a24SChandler Carruth }
247ef860a24SChandler Carruth 
248ef860a24SChandler Carruth /// getOrInsertNamedMetadata - Return the first named MDNode in the module
249ef860a24SChandler Carruth /// with the specified name. This method returns a new NamedMDNode if a
250ef860a24SChandler Carruth /// NamedMDNode with the specified name is not found.
251ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
252ef860a24SChandler Carruth   NamedMDNode *&NMD =
253ef860a24SChandler Carruth     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
254ef860a24SChandler Carruth   if (!NMD) {
255ef860a24SChandler Carruth     NMD = new NamedMDNode(Name);
256ef860a24SChandler Carruth     NMD->setParent(this);
257ef860a24SChandler Carruth     NamedMDList.push_back(NMD);
258ef860a24SChandler Carruth   }
259ef860a24SChandler Carruth   return NMD;
260ef860a24SChandler Carruth }
261ef860a24SChandler Carruth 
262ef860a24SChandler Carruth /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
263ef860a24SChandler Carruth /// delete it.
264ef860a24SChandler Carruth void Module::eraseNamedMetadata(NamedMDNode *NMD) {
265ef860a24SChandler Carruth   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
26652888a67SDuncan P. N. Exon Smith   NamedMDList.erase(NMD->getIterator());
267ef860a24SChandler Carruth }
268ef860a24SChandler Carruth 
2695bf8fef5SDuncan P. N. Exon Smith bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
270d7677e7aSDavid Majnemer   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
271af023adbSAlexey Samsonov     uint64_t Val = Behavior->getLimitedValue();
272af023adbSAlexey Samsonov     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
273af023adbSAlexey Samsonov       MFB = static_cast<ModFlagBehavior>(Val);
274af023adbSAlexey Samsonov       return true;
275af023adbSAlexey Samsonov     }
276af023adbSAlexey Samsonov   }
277af023adbSAlexey Samsonov   return false;
278af023adbSAlexey Samsonov }
279af023adbSAlexey Samsonov 
280ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
281ef860a24SChandler Carruth void Module::
282ef860a24SChandler Carruth getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
283ef860a24SChandler Carruth   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
284ef860a24SChandler Carruth   if (!ModFlags) return;
285ef860a24SChandler Carruth 
286de36e804SDuncan P. N. Exon Smith   for (const MDNode *Flag : ModFlags->operands()) {
287af023adbSAlexey Samsonov     ModFlagBehavior MFB;
288af023adbSAlexey Samsonov     if (Flag->getNumOperands() >= 3 &&
289af023adbSAlexey Samsonov         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
290d7677e7aSDavid Majnemer         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
2918b4306ceSManman Ren       // Check the operands of the MDNode before accessing the operands.
2928b4306ceSManman Ren       // The verifier will actually catch these failures.
293ef860a24SChandler Carruth       MDString *Key = cast<MDString>(Flag->getOperand(1));
2945bf8fef5SDuncan P. N. Exon Smith       Metadata *Val = Flag->getOperand(2);
295af023adbSAlexey Samsonov       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
296ef860a24SChandler Carruth     }
297ef860a24SChandler Carruth   }
2988b4306ceSManman Ren }
299ef860a24SChandler Carruth 
3008bfde891SManman Ren /// Return the corresponding value if Key appears in module flags, otherwise
3018bfde891SManman Ren /// return null.
3025bf8fef5SDuncan P. N. Exon Smith Metadata *Module::getModuleFlag(StringRef Key) const {
3038bfde891SManman Ren   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
3048bfde891SManman Ren   getModuleFlagsMetadata(ModuleFlags);
3053ad5c962SBenjamin Kramer   for (const ModuleFlagEntry &MFE : ModuleFlags) {
3068bfde891SManman Ren     if (Key == MFE.Key->getString())
3078bfde891SManman Ren       return MFE.Val;
3088bfde891SManman Ren   }
309c620761cSCraig Topper   return nullptr;
3108bfde891SManman Ren }
3118bfde891SManman Ren 
312ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
313ef860a24SChandler Carruth /// represents module-level flags. This method returns null if there are no
314ef860a24SChandler Carruth /// module-level flags.
315ef860a24SChandler Carruth NamedMDNode *Module::getModuleFlagsMetadata() const {
316ef860a24SChandler Carruth   return getNamedMetadata("llvm.module.flags");
317ef860a24SChandler Carruth }
318ef860a24SChandler Carruth 
319ef860a24SChandler Carruth /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
320ef860a24SChandler Carruth /// represents module-level flags. If module-level flags aren't found, it
321ef860a24SChandler Carruth /// creates the named metadata that contains them.
322ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
323ef860a24SChandler Carruth   return getOrInsertNamedMetadata("llvm.module.flags");
324ef860a24SChandler Carruth }
325ef860a24SChandler Carruth 
326ef860a24SChandler Carruth /// addModuleFlag - Add a module-level flag to the module-level flags
327ef860a24SChandler Carruth /// metadata. It will create the module-level flags named metadata if it doesn't
328ef860a24SChandler Carruth /// already exist.
329ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3305bf8fef5SDuncan P. N. Exon Smith                            Metadata *Val) {
331ef860a24SChandler Carruth   Type *Int32Ty = Type::getInt32Ty(Context);
3325bf8fef5SDuncan P. N. Exon Smith   Metadata *Ops[3] = {
3335bf8fef5SDuncan P. N. Exon Smith       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
3345bf8fef5SDuncan P. N. Exon Smith       MDString::get(Context, Key), Val};
335ef860a24SChandler Carruth   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
336ef860a24SChandler Carruth }
337ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3385bf8fef5SDuncan P. N. Exon Smith                            Constant *Val) {
3395bf8fef5SDuncan P. N. Exon Smith   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
3405bf8fef5SDuncan P. N. Exon Smith }
3415bf8fef5SDuncan P. N. Exon Smith void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
342ef860a24SChandler Carruth                            uint32_t Val) {
343ef860a24SChandler Carruth   Type *Int32Ty = Type::getInt32Ty(Context);
344ef860a24SChandler Carruth   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
345ef860a24SChandler Carruth }
346ef860a24SChandler Carruth void Module::addModuleFlag(MDNode *Node) {
347ef860a24SChandler Carruth   assert(Node->getNumOperands() == 3 &&
348ef860a24SChandler Carruth          "Invalid number of operands for module flag!");
3495bf8fef5SDuncan P. N. Exon Smith   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
350ef860a24SChandler Carruth          isa<MDString>(Node->getOperand(1)) &&
351ef860a24SChandler Carruth          "Invalid operand types for module flag!");
352ef860a24SChandler Carruth   getOrInsertModuleFlagsMetadata()->addOperand(Node);
353ef860a24SChandler Carruth }
354ef860a24SChandler Carruth 
355f863ee29SRafael Espindola void Module::setDataLayout(StringRef Desc) {
356248ac139SRafael Espindola   DL.reset(Desc);
357f863ee29SRafael Espindola }
358f863ee29SRafael Espindola 
35946a43556SMehdi Amini void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
360f863ee29SRafael Espindola 
36146a43556SMehdi Amini const DataLayout &Module::getDataLayout() const { return DL; }
362f863ee29SRafael Espindola 
3635992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
3645992a72bSAdrian Prantl   return cast<DICompileUnit>(CUs->getOperand(Idx));
3655992a72bSAdrian Prantl }
3665992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
3675992a72bSAdrian Prantl   return cast<DICompileUnit>(CUs->getOperand(Idx));
3685992a72bSAdrian Prantl }
3695992a72bSAdrian Prantl 
3705992a72bSAdrian Prantl void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
3715992a72bSAdrian Prantl   while (CUs && (Idx < CUs->getNumOperands()) &&
3725992a72bSAdrian Prantl          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
3735992a72bSAdrian Prantl     ++Idx;
3745992a72bSAdrian Prantl }
3755992a72bSAdrian Prantl 
376ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
377ef860a24SChandler Carruth // Methods to control the materialization of GlobalValues in the Module.
378ef860a24SChandler Carruth //
379ef860a24SChandler Carruth void Module::setMaterializer(GVMaterializer *GVM) {
380ef860a24SChandler Carruth   assert(!Materializer &&
381c4a03483SRafael Espindola          "Module already has a GVMaterializer.  Call materializeAll"
382ef860a24SChandler Carruth          " to clear it out before setting another one.");
383ef860a24SChandler Carruth   Materializer.reset(GVM);
384ef860a24SChandler Carruth }
385ef860a24SChandler Carruth 
3867f00d0a1SPeter Collingbourne Error Module::materialize(GlobalValue *GV) {
3872b11ad4fSRafael Espindola   if (!Materializer)
3887f00d0a1SPeter Collingbourne     return Error::success();
3892b11ad4fSRafael Espindola 
3905a52e6dcSRafael Espindola   return Materializer->materialize(GV);
391ef860a24SChandler Carruth }
392ef860a24SChandler Carruth 
3937f00d0a1SPeter Collingbourne Error Module::materializeAll() {
394ef860a24SChandler Carruth   if (!Materializer)
3957f00d0a1SPeter Collingbourne     return Error::success();
396257a3536SRafael Espindola   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
397257a3536SRafael Espindola   return M->materializeModule();
398ef860a24SChandler Carruth }
399ef860a24SChandler Carruth 
4007f00d0a1SPeter Collingbourne Error Module::materializeMetadata() {
401cba833a0SRafael Espindola   if (!Materializer)
4027f00d0a1SPeter Collingbourne     return Error::success();
403cba833a0SRafael Espindola   return Materializer->materializeMetadata();
404cba833a0SRafael Espindola }
405cba833a0SRafael Espindola 
406ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
407ef860a24SChandler Carruth // Other module related stuff.
408ef860a24SChandler Carruth //
409ef860a24SChandler Carruth 
4102fa1e43aSRafael Espindola std::vector<StructType *> Module::getIdentifiedStructTypes() const {
4112fa1e43aSRafael Espindola   // If we have a materializer, it is possible that some unread function
4122fa1e43aSRafael Espindola   // uses a type that is currently not visible to a TypeFinder, so ask
4132fa1e43aSRafael Espindola   // the materializer which types it created.
4142fa1e43aSRafael Espindola   if (Materializer)
4152fa1e43aSRafael Espindola     return Materializer->getIdentifiedStructTypes();
4162fa1e43aSRafael Espindola 
4172fa1e43aSRafael Espindola   std::vector<StructType *> Ret;
4182fa1e43aSRafael Espindola   TypeFinder SrcStructTypes;
4192fa1e43aSRafael Espindola   SrcStructTypes.run(*this, true);
4202fa1e43aSRafael Espindola   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
4212fa1e43aSRafael Espindola   return Ret;
4222fa1e43aSRafael Espindola }
423ef860a24SChandler Carruth 
424ef860a24SChandler Carruth // dropAllReferences() - This function causes all the subelements to "let go"
425ef860a24SChandler Carruth // of all references that they are maintaining.  This allows one to 'delete' a
426ef860a24SChandler Carruth // whole module at a time, even though there may be circular references... first
427ef860a24SChandler Carruth // all references are dropped, and all use counts go to zero.  Then everything
428ef860a24SChandler Carruth // is deleted for real.  Note that no operations are valid on an object that
429ef860a24SChandler Carruth // has "dropped all references", except operator delete.
430ef860a24SChandler Carruth //
431ef860a24SChandler Carruth void Module::dropAllReferences() {
4323374910fSDavid Majnemer   for (Function &F : *this)
4333374910fSDavid Majnemer     F.dropAllReferences();
434ef860a24SChandler Carruth 
4353374910fSDavid Majnemer   for (GlobalVariable &GV : globals())
4363374910fSDavid Majnemer     GV.dropAllReferences();
437ef860a24SChandler Carruth 
4383374910fSDavid Majnemer   for (GlobalAlias &GA : aliases())
4393374910fSDavid Majnemer     GA.dropAllReferences();
440a1feff70SDmitry Polukhin 
441a1feff70SDmitry Polukhin   for (GlobalIFunc &GIF : ifuncs())
442a1feff70SDmitry Polukhin     GIF.dropAllReferences();
443ef860a24SChandler Carruth }
4440915c047SDiego Novillo 
445ac6081cbSNirav Dave unsigned Module::getNumberRegisterParameters() const {
446ac6081cbSNirav Dave   auto *Val =
447ac6081cbSNirav Dave       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
448ac6081cbSNirav Dave   if (!Val)
449ac6081cbSNirav Dave     return 0;
450ac6081cbSNirav Dave   return cast<ConstantInt>(Val->getValue())->getZExtValue();
451ac6081cbSNirav Dave }
452ac6081cbSNirav Dave 
4530915c047SDiego Novillo unsigned Module::getDwarfVersion() const {
4545bf8fef5SDuncan P. N. Exon Smith   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
4550915c047SDiego Novillo   if (!Val)
45612d2c120SReid Kleckner     return 0;
45712d2c120SReid Kleckner   return cast<ConstantInt>(Val->getValue())->getZExtValue();
45812d2c120SReid Kleckner }
45912d2c120SReid Kleckner 
46012d2c120SReid Kleckner unsigned Module::getCodeViewFlag() const {
46112d2c120SReid Kleckner   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
46212d2c120SReid Kleckner   if (!Val)
46312d2c120SReid Kleckner     return 0;
4645bf8fef5SDuncan P. N. Exon Smith   return cast<ConstantInt>(Val->getValue())->getZExtValue();
4650915c047SDiego Novillo }
466dad0a645SDavid Majnemer 
467dad0a645SDavid Majnemer Comdat *Module::getOrInsertComdat(StringRef Name) {
4685106ce78SDavid Blaikie   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
469dad0a645SDavid Majnemer   Entry.second.Name = &Entry;
470dad0a645SDavid Majnemer   return &Entry.second;
471dad0a645SDavid Majnemer }
472771c132eSJustin Hibbits 
473771c132eSJustin Hibbits PICLevel::Level Module::getPICLevel() const {
4745bf8fef5SDuncan P. N. Exon Smith   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
475771c132eSJustin Hibbits 
476083ca9bbSHans Wennborg   if (!Val)
4774cccc488SDavide Italiano     return PICLevel::NotPIC;
478771c132eSJustin Hibbits 
4795bf8fef5SDuncan P. N. Exon Smith   return static_cast<PICLevel::Level>(
4805bf8fef5SDuncan P. N. Exon Smith       cast<ConstantInt>(Val->getValue())->getZExtValue());
481771c132eSJustin Hibbits }
482771c132eSJustin Hibbits 
483771c132eSJustin Hibbits void Module::setPICLevel(PICLevel::Level PL) {
4842db1369cSTeresa Johnson   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
485771c132eSJustin Hibbits }
486ecb05e51SEaswaran Raman 
48746d47b8cSSriraman Tallam PIELevel::Level Module::getPIELevel() const {
48846d47b8cSSriraman Tallam   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
48946d47b8cSSriraman Tallam 
49046d47b8cSSriraman Tallam   if (!Val)
49146d47b8cSSriraman Tallam     return PIELevel::Default;
49246d47b8cSSriraman Tallam 
49346d47b8cSSriraman Tallam   return static_cast<PIELevel::Level>(
49446d47b8cSSriraman Tallam       cast<ConstantInt>(Val->getValue())->getZExtValue());
49546d47b8cSSriraman Tallam }
49646d47b8cSSriraman Tallam 
49746d47b8cSSriraman Tallam void Module::setPIELevel(PIELevel::Level PL) {
4982db1369cSTeresa Johnson   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
49946d47b8cSSriraman Tallam }
50046d47b8cSSriraman Tallam 
50126628d30SEaswaran Raman void Module::setProfileSummary(Metadata *M) {
50226628d30SEaswaran Raman   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
50326628d30SEaswaran Raman }
50426628d30SEaswaran Raman 
50526628d30SEaswaran Raman Metadata *Module::getProfileSummary() {
50626628d30SEaswaran Raman   return getModuleFlag("ProfileSummary");
50726628d30SEaswaran Raman }
508b35cc691STeresa Johnson 
509e2dcf7c3SPeter Collingbourne void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
510e2dcf7c3SPeter Collingbourne   OwnedMemoryBuffer = std::move(MB);
511e2dcf7c3SPeter Collingbourne }
512e2dcf7c3SPeter Collingbourne 
513b35cc691STeresa Johnson GlobalVariable *llvm::collectUsedGlobalVariables(
514b35cc691STeresa Johnson     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
515b35cc691STeresa Johnson   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
516b35cc691STeresa Johnson   GlobalVariable *GV = M.getGlobalVariable(Name);
517b35cc691STeresa Johnson   if (!GV || !GV->hasInitializer())
518b35cc691STeresa Johnson     return GV;
519b35cc691STeresa Johnson 
520b35cc691STeresa Johnson   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
521b35cc691STeresa Johnson   for (Value *Op : Init->operands()) {
522b35cc691STeresa Johnson     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
523b35cc691STeresa Johnson     Set.insert(G);
524b35cc691STeresa Johnson   }
525b35cc691STeresa Johnson   return GV;
526b35cc691STeresa Johnson }
527