xref: /llvm-project-15.0.7/llvm/lib/IR/Module.cpp (revision e2dcf7c3)
1ef860a24SChandler Carruth //===-- 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 
149fb823bbSChandler Carruth #include "llvm/IR/Module.h"
15ef860a24SChandler Carruth #include "SymbolTableListTraitsImpl.h"
16ef860a24SChandler Carruth #include "llvm/ADT/STLExtras.h"
17b35cc691STeresa Johnson #include "llvm/ADT/SmallPtrSet.h"
18ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h"
19ef860a24SChandler Carruth #include "llvm/ADT/StringExtras.h"
209fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
219fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
225992a72bSAdrian Prantl #include "llvm/IR/DebugInfoMetadata.h"
23d1163aa5SChandler Carruth #include "llvm/IR/GVMaterializer.h"
249fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
259fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h"
262fa1e43aSRafael Espindola #include "llvm/IR/TypeFinder.h"
270915c047SDiego Novillo #include "llvm/Support/Dwarf.h"
28*e2dcf7c3SPeter Collingbourne #include "llvm/Support/MemoryBuffer.h"
29144829d3SJF Bastien #include "llvm/Support/Path.h"
30144829d3SJF Bastien #include "llvm/Support/RandomNumberGenerator.h"
31ef860a24SChandler Carruth #include <algorithm>
32ef860a24SChandler Carruth #include <cstdarg>
33ef860a24SChandler Carruth #include <cstdlib>
34083ca9bbSHans Wennborg 
35ef860a24SChandler Carruth using namespace llvm;
36ef860a24SChandler Carruth 
37ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
38ef860a24SChandler Carruth // Methods to implement the globals and functions lists.
39ef860a24SChandler Carruth //
40ef860a24SChandler Carruth 
41ef860a24SChandler Carruth // Explicit instantiations of SymbolTableListTraits since some of the methods
42ef860a24SChandler Carruth // are not in the public header file.
4337bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<Function>;
4437bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalVariable>;
4537bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalAlias>;
46a1feff70SDmitry Polukhin template class llvm::SymbolTableListTraits<GlobalIFunc>;
47ef860a24SChandler Carruth 
48ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
49ef860a24SChandler Carruth // Primitive Module methods.
50ef860a24SChandler Carruth //
51ef860a24SChandler Carruth 
52ef860a24SChandler Carruth Module::Module(StringRef MID, LLVMContext &C)
53e1164de5STeresa Johnson     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
54ef860a24SChandler Carruth   ValSymTab = new ValueSymbolTable();
55ef860a24SChandler Carruth   NamedMDSymTab = new StringMap<NamedMDNode *>();
56ef860a24SChandler Carruth   Context.addModule(this);
57ef860a24SChandler Carruth }
58ef860a24SChandler Carruth 
59ef860a24SChandler Carruth Module::~Module() {
60ef860a24SChandler Carruth   Context.removeModule(this);
61ef860a24SChandler Carruth   dropAllReferences();
62ef860a24SChandler Carruth   GlobalList.clear();
63ef860a24SChandler Carruth   FunctionList.clear();
64ef860a24SChandler Carruth   AliasList.clear();
65a1feff70SDmitry Polukhin   IFuncList.clear();
66ef860a24SChandler Carruth   NamedMDList.clear();
67ef860a24SChandler Carruth   delete ValSymTab;
68ef860a24SChandler Carruth   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
69ef860a24SChandler Carruth }
70ef860a24SChandler Carruth 
71e6acbdc4SJF Bastien RandomNumberGenerator *Module::createRNG(const Pass* P) const {
72e6acbdc4SJF Bastien   SmallString<32> Salt(P->getPassName());
73e6acbdc4SJF Bastien 
74e6acbdc4SJF Bastien   // This RNG is guaranteed to produce the same random stream only
75e6acbdc4SJF Bastien   // when the Module ID and thus the input filename is the same. This
76e6acbdc4SJF Bastien   // might be problematic if the input filename extension changes
77e6acbdc4SJF Bastien   // (e.g. from .c to .bc or .ll).
78e6acbdc4SJF Bastien   //
79e6acbdc4SJF Bastien   // We could store this salt in NamedMetadata, but this would make
80e6acbdc4SJF Bastien   // the parameter non-const. This would unfortunately make this
81e6acbdc4SJF Bastien   // interface unusable by any Machine passes, since they only have a
82e6acbdc4SJF Bastien   // const reference to their IR Module. Alternatively we can always
83e6acbdc4SJF Bastien   // store salt metadata from the Module constructor.
84e6acbdc4SJF Bastien   Salt += sys::path::filename(getModuleIdentifier());
85e6acbdc4SJF Bastien 
86e6acbdc4SJF Bastien   return new RandomNumberGenerator(Salt);
87e6acbdc4SJF Bastien }
88e6acbdc4SJF Bastien 
89ef860a24SChandler Carruth /// getNamedValue - Return the first global value in the module with
90ef860a24SChandler Carruth /// the specified name, of arbitrary type.  This method returns null
91ef860a24SChandler Carruth /// if a global with the specified name is not found.
92ef860a24SChandler Carruth GlobalValue *Module::getNamedValue(StringRef Name) const {
93ef860a24SChandler Carruth   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
94ef860a24SChandler Carruth }
95ef860a24SChandler Carruth 
96ef860a24SChandler Carruth /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
97ef860a24SChandler Carruth /// This ID is uniqued across modules in the current LLVMContext.
98ef860a24SChandler Carruth unsigned Module::getMDKindID(StringRef Name) const {
99ef860a24SChandler Carruth   return Context.getMDKindID(Name);
100ef860a24SChandler Carruth }
101ef860a24SChandler Carruth 
102ef860a24SChandler Carruth /// getMDKindNames - Populate client supplied SmallVector with the name for
103ef860a24SChandler Carruth /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
104ef860a24SChandler Carruth /// so it is filled in as an empty string.
105ef860a24SChandler Carruth void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
106ef860a24SChandler Carruth   return Context.getMDKindNames(Result);
107ef860a24SChandler Carruth }
108ef860a24SChandler Carruth 
1099303c246SSanjoy Das void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
1109303c246SSanjoy Das   return Context.getOperandBundleTags(Result);
1119303c246SSanjoy Das }
112ef860a24SChandler Carruth 
113ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
114ef860a24SChandler Carruth // Methods for easy access to the functions in the module.
115ef860a24SChandler Carruth //
116ef860a24SChandler Carruth 
117ef860a24SChandler Carruth // getOrInsertFunction - Look up the specified function in the module symbol
118ef860a24SChandler Carruth // table.  If it does not exist, add a prototype for the function and return
119ef860a24SChandler Carruth // it.  This is nice because it allows most passes to get away with not handling
120ef860a24SChandler Carruth // the symbol table directly for this common task.
121ef860a24SChandler Carruth //
122ef860a24SChandler Carruth Constant *Module::getOrInsertFunction(StringRef Name,
123ef860a24SChandler Carruth                                       FunctionType *Ty,
124ef860a24SChandler Carruth                                       AttributeSet AttributeList) {
125ef860a24SChandler Carruth   // See if we have a definition for the specified function already.
126ef860a24SChandler Carruth   GlobalValue *F = getNamedValue(Name);
127c620761cSCraig Topper   if (!F) {
128ef860a24SChandler Carruth     // Nope, add it
129ef860a24SChandler Carruth     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
130ef860a24SChandler Carruth     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
131ef860a24SChandler Carruth       New->setAttributes(AttributeList);
132ef860a24SChandler Carruth     FunctionList.push_back(New);
133ef860a24SChandler Carruth     return New;                    // Return the new prototype.
134ef860a24SChandler Carruth   }
135ef860a24SChandler Carruth 
136ef860a24SChandler Carruth   // If the function exists but has the wrong type, return a bitcast to the
137ef860a24SChandler Carruth   // right type.
138ef860a24SChandler Carruth   if (F->getType() != PointerType::getUnqual(Ty))
139ef860a24SChandler Carruth     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
140ef860a24SChandler Carruth 
141ef860a24SChandler Carruth   // Otherwise, we just found the existing function or a prototype.
142ef860a24SChandler Carruth   return F;
143ef860a24SChandler Carruth }
144ef860a24SChandler Carruth 
145ef860a24SChandler Carruth Constant *Module::getOrInsertFunction(StringRef Name,
146ef860a24SChandler Carruth                                       FunctionType *Ty) {
147ef860a24SChandler Carruth   return getOrInsertFunction(Name, Ty, AttributeSet());
148ef860a24SChandler Carruth }
149ef860a24SChandler Carruth 
150ef860a24SChandler Carruth // getOrInsertFunction - Look up the specified function in the module symbol
151ef860a24SChandler Carruth // table.  If it does not exist, add a prototype for the function and return it.
152ef860a24SChandler Carruth // This version of the method takes a null terminated list of function
153ef860a24SChandler Carruth // arguments, which makes it easier for clients to use.
154ef860a24SChandler Carruth //
155ef860a24SChandler Carruth Constant *Module::getOrInsertFunction(StringRef Name,
156ef860a24SChandler Carruth                                       AttributeSet AttributeList,
157ef860a24SChandler Carruth                                       Type *RetTy, ...) {
158ef860a24SChandler Carruth   va_list Args;
159ef860a24SChandler Carruth   va_start(Args, RetTy);
160ef860a24SChandler Carruth 
161ef860a24SChandler Carruth   // Build the list of argument types...
162ef860a24SChandler Carruth   std::vector<Type*> ArgTys;
163ef860a24SChandler Carruth   while (Type *ArgTy = va_arg(Args, Type*))
164ef860a24SChandler Carruth     ArgTys.push_back(ArgTy);
165ef860a24SChandler Carruth 
166ef860a24SChandler Carruth   va_end(Args);
167ef860a24SChandler Carruth 
168ef860a24SChandler Carruth   // Build the function type and chain to the other getOrInsertFunction...
169ef860a24SChandler Carruth   return getOrInsertFunction(Name,
170ef860a24SChandler Carruth                              FunctionType::get(RetTy, ArgTys, false),
171ef860a24SChandler Carruth                              AttributeList);
172ef860a24SChandler Carruth }
173ef860a24SChandler Carruth 
174ef860a24SChandler Carruth Constant *Module::getOrInsertFunction(StringRef Name,
175ef860a24SChandler Carruth                                       Type *RetTy, ...) {
176ef860a24SChandler Carruth   va_list Args;
177ef860a24SChandler Carruth   va_start(Args, RetTy);
178ef860a24SChandler Carruth 
179ef860a24SChandler Carruth   // Build the list of argument types...
180ef860a24SChandler Carruth   std::vector<Type*> ArgTys;
181ef860a24SChandler Carruth   while (Type *ArgTy = va_arg(Args, Type*))
182ef860a24SChandler Carruth     ArgTys.push_back(ArgTy);
183ef860a24SChandler Carruth 
184ef860a24SChandler Carruth   va_end(Args);
185ef860a24SChandler Carruth 
186ef860a24SChandler Carruth   // Build the function type and chain to the other getOrInsertFunction...
187ef860a24SChandler Carruth   return getOrInsertFunction(Name,
188ef860a24SChandler Carruth                              FunctionType::get(RetTy, ArgTys, false),
189ef860a24SChandler Carruth                              AttributeSet());
190ef860a24SChandler Carruth }
191ef860a24SChandler Carruth 
192ef860a24SChandler Carruth // getFunction - Look up the specified function in the module symbol table.
193ef860a24SChandler Carruth // If it does not exist, return null.
194ef860a24SChandler Carruth //
195ef860a24SChandler Carruth Function *Module::getFunction(StringRef Name) const {
196ef860a24SChandler Carruth   return dyn_cast_or_null<Function>(getNamedValue(Name));
197ef860a24SChandler Carruth }
198ef860a24SChandler Carruth 
199ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
200ef860a24SChandler Carruth // Methods for easy access to the global variables in the module.
201ef860a24SChandler Carruth //
202ef860a24SChandler Carruth 
203ef860a24SChandler Carruth /// getGlobalVariable - Look up the specified global variable in the module
204ef860a24SChandler Carruth /// symbol table.  If it does not exist, return null.  The type argument
205ef860a24SChandler Carruth /// should be the underlying type of the global, i.e., it should not have
206ef860a24SChandler Carruth /// the top-level PointerType, which represents the address of the global.
207ef860a24SChandler Carruth /// If AllowLocal is set to true, this function will return types that
208ef860a24SChandler Carruth /// have an local. By default, these types are not returned.
209ef860a24SChandler Carruth ///
210ec2375fbSRafael Espindola GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
211ef860a24SChandler Carruth   if (GlobalVariable *Result =
212ef860a24SChandler Carruth       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
213ef860a24SChandler Carruth     if (AllowLocal || !Result->hasLocalLinkage())
214ef860a24SChandler Carruth       return Result;
215c620761cSCraig Topper   return nullptr;
216ef860a24SChandler Carruth }
217ef860a24SChandler Carruth 
218ef860a24SChandler Carruth /// getOrInsertGlobal - Look up the specified global in the module symbol table.
219ef860a24SChandler Carruth ///   1. If it does not exist, add a declaration of the global and return it.
220ef860a24SChandler Carruth ///   2. Else, the global exists but has the wrong type: return the function
221ef860a24SChandler Carruth ///      with a constantexpr cast to the right type.
2225200fdf0SMatt Arsenault ///   3. Finally, if the existing global is the correct declaration, return the
223ef860a24SChandler Carruth ///      existing global.
224ef860a24SChandler Carruth Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
225ef860a24SChandler Carruth   // See if we have a definition for the specified global already.
226ef860a24SChandler Carruth   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
227c620761cSCraig Topper   if (!GV) {
228ef860a24SChandler Carruth     // Nope, add it
229ef860a24SChandler Carruth     GlobalVariable *New =
230ef860a24SChandler Carruth       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
231c620761cSCraig Topper                          nullptr, Name);
232ef860a24SChandler Carruth      return New;                    // Return the new declaration.
233ef860a24SChandler Carruth   }
234ef860a24SChandler Carruth 
235ef860a24SChandler Carruth   // If the variable exists but has the wrong type, return a bitcast to the
236ef860a24SChandler Carruth   // right type.
23727e783e9SMatt Arsenault   Type *GVTy = GV->getType();
23827e783e9SMatt Arsenault   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
239a90a340fSMatt Arsenault   if (GVTy != PTy)
24027e783e9SMatt Arsenault     return ConstantExpr::getBitCast(GV, PTy);
241ef860a24SChandler Carruth 
242ef860a24SChandler Carruth   // Otherwise, we just found the existing function or a prototype.
243ef860a24SChandler Carruth   return GV;
244ef860a24SChandler Carruth }
245ef860a24SChandler Carruth 
246ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
247ef860a24SChandler Carruth // Methods for easy access to the global variables in the module.
248ef860a24SChandler Carruth //
249ef860a24SChandler Carruth 
250ef860a24SChandler Carruth // getNamedAlias - Look up the specified global in the module symbol table.
251ef860a24SChandler Carruth // If it does not exist, return null.
252ef860a24SChandler Carruth //
253ef860a24SChandler Carruth GlobalAlias *Module::getNamedAlias(StringRef Name) const {
254ef860a24SChandler Carruth   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
255ef860a24SChandler Carruth }
256ef860a24SChandler Carruth 
257a1feff70SDmitry Polukhin GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
258a1feff70SDmitry Polukhin   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
259a1feff70SDmitry Polukhin }
260a1feff70SDmitry Polukhin 
261ef860a24SChandler Carruth /// getNamedMetadata - Return the first NamedMDNode in the module with the
262ef860a24SChandler Carruth /// specified name. This method returns null if a NamedMDNode with the
263ef860a24SChandler Carruth /// specified name is not found.
264ef860a24SChandler Carruth NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
265ef860a24SChandler Carruth   SmallString<256> NameData;
266ef860a24SChandler Carruth   StringRef NameRef = Name.toStringRef(NameData);
267ef860a24SChandler Carruth   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
268ef860a24SChandler Carruth }
269ef860a24SChandler Carruth 
270ef860a24SChandler Carruth /// getOrInsertNamedMetadata - Return the first named MDNode in the module
271ef860a24SChandler Carruth /// with the specified name. This method returns a new NamedMDNode if a
272ef860a24SChandler Carruth /// NamedMDNode with the specified name is not found.
273ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
274ef860a24SChandler Carruth   NamedMDNode *&NMD =
275ef860a24SChandler Carruth     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
276ef860a24SChandler Carruth   if (!NMD) {
277ef860a24SChandler Carruth     NMD = new NamedMDNode(Name);
278ef860a24SChandler Carruth     NMD->setParent(this);
279ef860a24SChandler Carruth     NamedMDList.push_back(NMD);
280ef860a24SChandler Carruth   }
281ef860a24SChandler Carruth   return NMD;
282ef860a24SChandler Carruth }
283ef860a24SChandler Carruth 
284ef860a24SChandler Carruth /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
285ef860a24SChandler Carruth /// delete it.
286ef860a24SChandler Carruth void Module::eraseNamedMetadata(NamedMDNode *NMD) {
287ef860a24SChandler Carruth   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
28852888a67SDuncan P. N. Exon Smith   NamedMDList.erase(NMD->getIterator());
289ef860a24SChandler Carruth }
290ef860a24SChandler Carruth 
2915bf8fef5SDuncan P. N. Exon Smith bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
292d7677e7aSDavid Majnemer   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
293af023adbSAlexey Samsonov     uint64_t Val = Behavior->getLimitedValue();
294af023adbSAlexey Samsonov     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
295af023adbSAlexey Samsonov       MFB = static_cast<ModFlagBehavior>(Val);
296af023adbSAlexey Samsonov       return true;
297af023adbSAlexey Samsonov     }
298af023adbSAlexey Samsonov   }
299af023adbSAlexey Samsonov   return false;
300af023adbSAlexey Samsonov }
301af023adbSAlexey Samsonov 
302ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
303ef860a24SChandler Carruth void Module::
304ef860a24SChandler Carruth getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
305ef860a24SChandler Carruth   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
306ef860a24SChandler Carruth   if (!ModFlags) return;
307ef860a24SChandler Carruth 
308de36e804SDuncan P. N. Exon Smith   for (const MDNode *Flag : ModFlags->operands()) {
309af023adbSAlexey Samsonov     ModFlagBehavior MFB;
310af023adbSAlexey Samsonov     if (Flag->getNumOperands() >= 3 &&
311af023adbSAlexey Samsonov         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
312d7677e7aSDavid Majnemer         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
3138b4306ceSManman Ren       // Check the operands of the MDNode before accessing the operands.
3148b4306ceSManman Ren       // The verifier will actually catch these failures.
315ef860a24SChandler Carruth       MDString *Key = cast<MDString>(Flag->getOperand(1));
3165bf8fef5SDuncan P. N. Exon Smith       Metadata *Val = Flag->getOperand(2);
317af023adbSAlexey Samsonov       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
318ef860a24SChandler Carruth     }
319ef860a24SChandler Carruth   }
3208b4306ceSManman Ren }
321ef860a24SChandler Carruth 
3228bfde891SManman Ren /// Return the corresponding value if Key appears in module flags, otherwise
3238bfde891SManman Ren /// return null.
3245bf8fef5SDuncan P. N. Exon Smith Metadata *Module::getModuleFlag(StringRef Key) const {
3258bfde891SManman Ren   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
3268bfde891SManman Ren   getModuleFlagsMetadata(ModuleFlags);
3273ad5c962SBenjamin Kramer   for (const ModuleFlagEntry &MFE : ModuleFlags) {
3288bfde891SManman Ren     if (Key == MFE.Key->getString())
3298bfde891SManman Ren       return MFE.Val;
3308bfde891SManman Ren   }
331c620761cSCraig Topper   return nullptr;
3328bfde891SManman Ren }
3338bfde891SManman Ren 
334ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
335ef860a24SChandler Carruth /// represents module-level flags. This method returns null if there are no
336ef860a24SChandler Carruth /// module-level flags.
337ef860a24SChandler Carruth NamedMDNode *Module::getModuleFlagsMetadata() const {
338ef860a24SChandler Carruth   return getNamedMetadata("llvm.module.flags");
339ef860a24SChandler Carruth }
340ef860a24SChandler Carruth 
341ef860a24SChandler Carruth /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
342ef860a24SChandler Carruth /// represents module-level flags. If module-level flags aren't found, it
343ef860a24SChandler Carruth /// creates the named metadata that contains them.
344ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
345ef860a24SChandler Carruth   return getOrInsertNamedMetadata("llvm.module.flags");
346ef860a24SChandler Carruth }
347ef860a24SChandler Carruth 
348ef860a24SChandler Carruth /// addModuleFlag - Add a module-level flag to the module-level flags
349ef860a24SChandler Carruth /// metadata. It will create the module-level flags named metadata if it doesn't
350ef860a24SChandler Carruth /// already exist.
351ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3525bf8fef5SDuncan P. N. Exon Smith                            Metadata *Val) {
353ef860a24SChandler Carruth   Type *Int32Ty = Type::getInt32Ty(Context);
3545bf8fef5SDuncan P. N. Exon Smith   Metadata *Ops[3] = {
3555bf8fef5SDuncan P. N. Exon Smith       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
3565bf8fef5SDuncan P. N. Exon Smith       MDString::get(Context, Key), Val};
357ef860a24SChandler Carruth   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
358ef860a24SChandler Carruth }
359ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3605bf8fef5SDuncan P. N. Exon Smith                            Constant *Val) {
3615bf8fef5SDuncan P. N. Exon Smith   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
3625bf8fef5SDuncan P. N. Exon Smith }
3635bf8fef5SDuncan P. N. Exon Smith void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
364ef860a24SChandler Carruth                            uint32_t Val) {
365ef860a24SChandler Carruth   Type *Int32Ty = Type::getInt32Ty(Context);
366ef860a24SChandler Carruth   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
367ef860a24SChandler Carruth }
368ef860a24SChandler Carruth void Module::addModuleFlag(MDNode *Node) {
369ef860a24SChandler Carruth   assert(Node->getNumOperands() == 3 &&
370ef860a24SChandler Carruth          "Invalid number of operands for module flag!");
3715bf8fef5SDuncan P. N. Exon Smith   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
372ef860a24SChandler Carruth          isa<MDString>(Node->getOperand(1)) &&
373ef860a24SChandler Carruth          "Invalid operand types for module flag!");
374ef860a24SChandler Carruth   getOrInsertModuleFlagsMetadata()->addOperand(Node);
375ef860a24SChandler Carruth }
376ef860a24SChandler Carruth 
377f863ee29SRafael Espindola void Module::setDataLayout(StringRef Desc) {
378248ac139SRafael Espindola   DL.reset(Desc);
379f863ee29SRafael Espindola }
380f863ee29SRafael Espindola 
38146a43556SMehdi Amini void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
382f863ee29SRafael Espindola 
38346a43556SMehdi Amini const DataLayout &Module::getDataLayout() const { return DL; }
384f863ee29SRafael Espindola 
3855992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
3865992a72bSAdrian Prantl   return cast<DICompileUnit>(CUs->getOperand(Idx));
3875992a72bSAdrian Prantl }
3885992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
3895992a72bSAdrian Prantl   return cast<DICompileUnit>(CUs->getOperand(Idx));
3905992a72bSAdrian Prantl }
3915992a72bSAdrian Prantl 
3925992a72bSAdrian Prantl void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
3935992a72bSAdrian Prantl   while (CUs && (Idx < CUs->getNumOperands()) &&
3945992a72bSAdrian Prantl          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
3955992a72bSAdrian Prantl     ++Idx;
3965992a72bSAdrian Prantl }
3975992a72bSAdrian Prantl 
398ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
399ef860a24SChandler Carruth // Methods to control the materialization of GlobalValues in the Module.
400ef860a24SChandler Carruth //
401ef860a24SChandler Carruth void Module::setMaterializer(GVMaterializer *GVM) {
402ef860a24SChandler Carruth   assert(!Materializer &&
403c4a03483SRafael Espindola          "Module already has a GVMaterializer.  Call materializeAll"
404ef860a24SChandler Carruth          " to clear it out before setting another one.");
405ef860a24SChandler Carruth   Materializer.reset(GVM);
406ef860a24SChandler Carruth }
407ef860a24SChandler Carruth 
4085a52e6dcSRafael Espindola std::error_code Module::materialize(GlobalValue *GV) {
4092b11ad4fSRafael Espindola   if (!Materializer)
4105a52e6dcSRafael Espindola     return std::error_code();
4112b11ad4fSRafael Espindola 
4125a52e6dcSRafael Espindola   return Materializer->materialize(GV);
413ef860a24SChandler Carruth }
414ef860a24SChandler Carruth 
415db4ed0bdSRafael Espindola std::error_code Module::materializeAll() {
416ef860a24SChandler Carruth   if (!Materializer)
417db4ed0bdSRafael Espindola     return std::error_code();
418257a3536SRafael Espindola   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
419257a3536SRafael Espindola   return M->materializeModule();
420ef860a24SChandler Carruth }
421ef860a24SChandler Carruth 
422cba833a0SRafael Espindola std::error_code Module::materializeMetadata() {
423cba833a0SRafael Espindola   if (!Materializer)
424cba833a0SRafael Espindola     return std::error_code();
425cba833a0SRafael Espindola   return Materializer->materializeMetadata();
426cba833a0SRafael Espindola }
427cba833a0SRafael Espindola 
428ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
429ef860a24SChandler Carruth // Other module related stuff.
430ef860a24SChandler Carruth //
431ef860a24SChandler Carruth 
4322fa1e43aSRafael Espindola std::vector<StructType *> Module::getIdentifiedStructTypes() const {
4332fa1e43aSRafael Espindola   // If we have a materializer, it is possible that some unread function
4342fa1e43aSRafael Espindola   // uses a type that is currently not visible to a TypeFinder, so ask
4352fa1e43aSRafael Espindola   // the materializer which types it created.
4362fa1e43aSRafael Espindola   if (Materializer)
4372fa1e43aSRafael Espindola     return Materializer->getIdentifiedStructTypes();
4382fa1e43aSRafael Espindola 
4392fa1e43aSRafael Espindola   std::vector<StructType *> Ret;
4402fa1e43aSRafael Espindola   TypeFinder SrcStructTypes;
4412fa1e43aSRafael Espindola   SrcStructTypes.run(*this, true);
4422fa1e43aSRafael Espindola   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
4432fa1e43aSRafael Espindola   return Ret;
4442fa1e43aSRafael Espindola }
445ef860a24SChandler Carruth 
446ef860a24SChandler Carruth // dropAllReferences() - This function causes all the subelements to "let go"
447ef860a24SChandler Carruth // of all references that they are maintaining.  This allows one to 'delete' a
448ef860a24SChandler Carruth // whole module at a time, even though there may be circular references... first
449ef860a24SChandler Carruth // all references are dropped, and all use counts go to zero.  Then everything
450ef860a24SChandler Carruth // is deleted for real.  Note that no operations are valid on an object that
451ef860a24SChandler Carruth // has "dropped all references", except operator delete.
452ef860a24SChandler Carruth //
453ef860a24SChandler Carruth void Module::dropAllReferences() {
4543374910fSDavid Majnemer   for (Function &F : *this)
4553374910fSDavid Majnemer     F.dropAllReferences();
456ef860a24SChandler Carruth 
4573374910fSDavid Majnemer   for (GlobalVariable &GV : globals())
4583374910fSDavid Majnemer     GV.dropAllReferences();
459ef860a24SChandler Carruth 
4603374910fSDavid Majnemer   for (GlobalAlias &GA : aliases())
4613374910fSDavid Majnemer     GA.dropAllReferences();
462a1feff70SDmitry Polukhin 
463a1feff70SDmitry Polukhin   for (GlobalIFunc &GIF : ifuncs())
464a1feff70SDmitry Polukhin     GIF.dropAllReferences();
465ef860a24SChandler Carruth }
4660915c047SDiego Novillo 
4670915c047SDiego Novillo unsigned Module::getDwarfVersion() const {
4685bf8fef5SDuncan P. N. Exon Smith   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
4690915c047SDiego Novillo   if (!Val)
47012d2c120SReid Kleckner     return 0;
47112d2c120SReid Kleckner   return cast<ConstantInt>(Val->getValue())->getZExtValue();
47212d2c120SReid Kleckner }
47312d2c120SReid Kleckner 
47412d2c120SReid Kleckner unsigned Module::getCodeViewFlag() const {
47512d2c120SReid Kleckner   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
47612d2c120SReid Kleckner   if (!Val)
47712d2c120SReid Kleckner     return 0;
4785bf8fef5SDuncan P. N. Exon Smith   return cast<ConstantInt>(Val->getValue())->getZExtValue();
4790915c047SDiego Novillo }
480dad0a645SDavid Majnemer 
481dad0a645SDavid Majnemer Comdat *Module::getOrInsertComdat(StringRef Name) {
4825106ce78SDavid Blaikie   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
483dad0a645SDavid Majnemer   Entry.second.Name = &Entry;
484dad0a645SDavid Majnemer   return &Entry.second;
485dad0a645SDavid Majnemer }
486771c132eSJustin Hibbits 
487771c132eSJustin Hibbits PICLevel::Level Module::getPICLevel() const {
4885bf8fef5SDuncan P. N. Exon Smith   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
489771c132eSJustin Hibbits 
490083ca9bbSHans Wennborg   if (!Val)
4914cccc488SDavide Italiano     return PICLevel::NotPIC;
492771c132eSJustin Hibbits 
4935bf8fef5SDuncan P. N. Exon Smith   return static_cast<PICLevel::Level>(
4945bf8fef5SDuncan P. N. Exon Smith       cast<ConstantInt>(Val->getValue())->getZExtValue());
495771c132eSJustin Hibbits }
496771c132eSJustin Hibbits 
497771c132eSJustin Hibbits void Module::setPICLevel(PICLevel::Level PL) {
498771c132eSJustin Hibbits   addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
499771c132eSJustin Hibbits }
500ecb05e51SEaswaran Raman 
50146d47b8cSSriraman Tallam PIELevel::Level Module::getPIELevel() const {
50246d47b8cSSriraman Tallam   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
50346d47b8cSSriraman Tallam 
50446d47b8cSSriraman Tallam   if (!Val)
50546d47b8cSSriraman Tallam     return PIELevel::Default;
50646d47b8cSSriraman Tallam 
50746d47b8cSSriraman Tallam   return static_cast<PIELevel::Level>(
50846d47b8cSSriraman Tallam       cast<ConstantInt>(Val->getValue())->getZExtValue());
50946d47b8cSSriraman Tallam }
51046d47b8cSSriraman Tallam 
51146d47b8cSSriraman Tallam void Module::setPIELevel(PIELevel::Level PL) {
51246d47b8cSSriraman Tallam   addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
51346d47b8cSSriraman Tallam }
51446d47b8cSSriraman Tallam 
51526628d30SEaswaran Raman void Module::setProfileSummary(Metadata *M) {
51626628d30SEaswaran Raman   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
51726628d30SEaswaran Raman }
51826628d30SEaswaran Raman 
51926628d30SEaswaran Raman Metadata *Module::getProfileSummary() {
52026628d30SEaswaran Raman   return getModuleFlag("ProfileSummary");
52126628d30SEaswaran Raman }
522b35cc691STeresa Johnson 
523*e2dcf7c3SPeter Collingbourne void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
524*e2dcf7c3SPeter Collingbourne   OwnedMemoryBuffer = std::move(MB);
525*e2dcf7c3SPeter Collingbourne }
526*e2dcf7c3SPeter Collingbourne 
527b35cc691STeresa Johnson GlobalVariable *llvm::collectUsedGlobalVariables(
528b35cc691STeresa Johnson     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
529b35cc691STeresa Johnson   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
530b35cc691STeresa Johnson   GlobalVariable *GV = M.getGlobalVariable(Name);
531b35cc691STeresa Johnson   if (!GV || !GV->hasInitializer())
532b35cc691STeresa Johnson     return GV;
533b35cc691STeresa Johnson 
534b35cc691STeresa Johnson   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
535b35cc691STeresa Johnson   for (Value *Op : Init->operands()) {
536b35cc691STeresa Johnson     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
537b35cc691STeresa Johnson     Set.insert(G);
538b35cc691STeresa Johnson   }
539b35cc691STeresa Johnson   return GV;
540b35cc691STeresa Johnson }
541