xref: /llvm-project/llvm/lib/IR/Module.cpp (revision a1feff7024b552b579f302fea0030aaaa14624b3)
1 //===-- Module.cpp - Implement the Module class ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Module class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/Module.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/TypeFinder.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/RandomNumberGenerator.h"
29 #include <algorithm>
30 #include <cstdarg>
31 #include <cstdlib>
32 
33 using namespace llvm;
34 
35 //===----------------------------------------------------------------------===//
36 // Methods to implement the globals and functions lists.
37 //
38 
39 // Explicit instantiations of SymbolTableListTraits since some of the methods
40 // are not in the public header file.
41 template class llvm::SymbolTableListTraits<Function>;
42 template class llvm::SymbolTableListTraits<GlobalVariable>;
43 template class llvm::SymbolTableListTraits<GlobalAlias>;
44 template class llvm::SymbolTableListTraits<GlobalIFunc>;
45 
46 //===----------------------------------------------------------------------===//
47 // Primitive Module methods.
48 //
49 
50 Module::Module(StringRef MID, LLVMContext &C)
51     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
52   ValSymTab = new ValueSymbolTable();
53   NamedMDSymTab = new StringMap<NamedMDNode *>();
54   Context.addModule(this);
55 }
56 
57 Module::~Module() {
58   Context.removeModule(this);
59   dropAllReferences();
60   GlobalList.clear();
61   FunctionList.clear();
62   AliasList.clear();
63   IFuncList.clear();
64   NamedMDList.clear();
65   delete ValSymTab;
66   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
67 }
68 
69 RandomNumberGenerator *Module::createRNG(const Pass* P) const {
70   SmallString<32> Salt(P->getPassName());
71 
72   // This RNG is guaranteed to produce the same random stream only
73   // when the Module ID and thus the input filename is the same. This
74   // might be problematic if the input filename extension changes
75   // (e.g. from .c to .bc or .ll).
76   //
77   // We could store this salt in NamedMetadata, but this would make
78   // the parameter non-const. This would unfortunately make this
79   // interface unusable by any Machine passes, since they only have a
80   // const reference to their IR Module. Alternatively we can always
81   // store salt metadata from the Module constructor.
82   Salt += sys::path::filename(getModuleIdentifier());
83 
84   return new RandomNumberGenerator(Salt);
85 }
86 
87 /// getNamedValue - Return the first global value in the module with
88 /// the specified name, of arbitrary type.  This method returns null
89 /// if a global with the specified name is not found.
90 GlobalValue *Module::getNamedValue(StringRef Name) const {
91   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
92 }
93 
94 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
95 /// This ID is uniqued across modules in the current LLVMContext.
96 unsigned Module::getMDKindID(StringRef Name) const {
97   return Context.getMDKindID(Name);
98 }
99 
100 /// getMDKindNames - Populate client supplied SmallVector with the name for
101 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
102 /// so it is filled in as an empty string.
103 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
104   return Context.getMDKindNames(Result);
105 }
106 
107 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
108   return Context.getOperandBundleTags(Result);
109 }
110 
111 //===----------------------------------------------------------------------===//
112 // Methods for easy access to the functions in the module.
113 //
114 
115 // getOrInsertFunction - Look up the specified function in the module symbol
116 // table.  If it does not exist, add a prototype for the function and return
117 // it.  This is nice because it allows most passes to get away with not handling
118 // the symbol table directly for this common task.
119 //
120 Constant *Module::getOrInsertFunction(StringRef Name,
121                                       FunctionType *Ty,
122                                       AttributeSet AttributeList) {
123   // See if we have a definition for the specified function already.
124   GlobalValue *F = getNamedValue(Name);
125   if (!F) {
126     // Nope, add it
127     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
128     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
129       New->setAttributes(AttributeList);
130     FunctionList.push_back(New);
131     return New;                    // Return the new prototype.
132   }
133 
134   // If the function exists but has the wrong type, return a bitcast to the
135   // right type.
136   if (F->getType() != PointerType::getUnqual(Ty))
137     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
138 
139   // Otherwise, we just found the existing function or a prototype.
140   return F;
141 }
142 
143 Constant *Module::getOrInsertFunction(StringRef Name,
144                                       FunctionType *Ty) {
145   return getOrInsertFunction(Name, Ty, AttributeSet());
146 }
147 
148 // getOrInsertFunction - Look up the specified function in the module symbol
149 // table.  If it does not exist, add a prototype for the function and return it.
150 // This version of the method takes a null terminated list of function
151 // arguments, which makes it easier for clients to use.
152 //
153 Constant *Module::getOrInsertFunction(StringRef Name,
154                                       AttributeSet AttributeList,
155                                       Type *RetTy, ...) {
156   va_list Args;
157   va_start(Args, RetTy);
158 
159   // Build the list of argument types...
160   std::vector<Type*> ArgTys;
161   while (Type *ArgTy = va_arg(Args, Type*))
162     ArgTys.push_back(ArgTy);
163 
164   va_end(Args);
165 
166   // Build the function type and chain to the other getOrInsertFunction...
167   return getOrInsertFunction(Name,
168                              FunctionType::get(RetTy, ArgTys, false),
169                              AttributeList);
170 }
171 
172 Constant *Module::getOrInsertFunction(StringRef Name,
173                                       Type *RetTy, ...) {
174   va_list Args;
175   va_start(Args, RetTy);
176 
177   // Build the list of argument types...
178   std::vector<Type*> ArgTys;
179   while (Type *ArgTy = va_arg(Args, Type*))
180     ArgTys.push_back(ArgTy);
181 
182   va_end(Args);
183 
184   // Build the function type and chain to the other getOrInsertFunction...
185   return getOrInsertFunction(Name,
186                              FunctionType::get(RetTy, ArgTys, false),
187                              AttributeSet());
188 }
189 
190 // getFunction - Look up the specified function in the module symbol table.
191 // If it does not exist, return null.
192 //
193 Function *Module::getFunction(StringRef Name) const {
194   return dyn_cast_or_null<Function>(getNamedValue(Name));
195 }
196 
197 //===----------------------------------------------------------------------===//
198 // Methods for easy access to the global variables in the module.
199 //
200 
201 /// getGlobalVariable - Look up the specified global variable in the module
202 /// symbol table.  If it does not exist, return null.  The type argument
203 /// should be the underlying type of the global, i.e., it should not have
204 /// the top-level PointerType, which represents the address of the global.
205 /// If AllowLocal is set to true, this function will return types that
206 /// have an local. By default, these types are not returned.
207 ///
208 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
209   if (GlobalVariable *Result =
210       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
211     if (AllowLocal || !Result->hasLocalLinkage())
212       return Result;
213   return nullptr;
214 }
215 
216 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
217 ///   1. If it does not exist, add a declaration of the global and return it.
218 ///   2. Else, the global exists but has the wrong type: return the function
219 ///      with a constantexpr cast to the right type.
220 ///   3. Finally, if the existing global is the correct declaration, return the
221 ///      existing global.
222 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
223   // See if we have a definition for the specified global already.
224   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
225   if (!GV) {
226     // Nope, add it
227     GlobalVariable *New =
228       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
229                          nullptr, Name);
230      return New;                    // Return the new declaration.
231   }
232 
233   // If the variable exists but has the wrong type, return a bitcast to the
234   // right type.
235   Type *GVTy = GV->getType();
236   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
237   if (GVTy != PTy)
238     return ConstantExpr::getBitCast(GV, PTy);
239 
240   // Otherwise, we just found the existing function or a prototype.
241   return GV;
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // Methods for easy access to the global variables in the module.
246 //
247 
248 // getNamedAlias - Look up the specified global in the module symbol table.
249 // If it does not exist, return null.
250 //
251 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
252   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
253 }
254 
255 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
256   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
257 }
258 
259 /// getNamedMetadata - Return the first NamedMDNode in the module with the
260 /// specified name. This method returns null if a NamedMDNode with the
261 /// specified name is not found.
262 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
263   SmallString<256> NameData;
264   StringRef NameRef = Name.toStringRef(NameData);
265   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
266 }
267 
268 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
269 /// with the specified name. This method returns a new NamedMDNode if a
270 /// NamedMDNode with the specified name is not found.
271 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
272   NamedMDNode *&NMD =
273     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
274   if (!NMD) {
275     NMD = new NamedMDNode(Name);
276     NMD->setParent(this);
277     NamedMDList.push_back(NMD);
278   }
279   return NMD;
280 }
281 
282 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
283 /// delete it.
284 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
285   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
286   NamedMDList.erase(NMD->getIterator());
287 }
288 
289 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
290   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
291     uint64_t Val = Behavior->getLimitedValue();
292     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
293       MFB = static_cast<ModFlagBehavior>(Val);
294       return true;
295     }
296   }
297   return false;
298 }
299 
300 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
301 void Module::
302 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
303   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
304   if (!ModFlags) return;
305 
306   for (const MDNode *Flag : ModFlags->operands()) {
307     ModFlagBehavior MFB;
308     if (Flag->getNumOperands() >= 3 &&
309         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
310         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
311       // Check the operands of the MDNode before accessing the operands.
312       // The verifier will actually catch these failures.
313       MDString *Key = cast<MDString>(Flag->getOperand(1));
314       Metadata *Val = Flag->getOperand(2);
315       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
316     }
317   }
318 }
319 
320 /// Return the corresponding value if Key appears in module flags, otherwise
321 /// return null.
322 Metadata *Module::getModuleFlag(StringRef Key) const {
323   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
324   getModuleFlagsMetadata(ModuleFlags);
325   for (const ModuleFlagEntry &MFE : ModuleFlags) {
326     if (Key == MFE.Key->getString())
327       return MFE.Val;
328   }
329   return nullptr;
330 }
331 
332 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
333 /// represents module-level flags. This method returns null if there are no
334 /// module-level flags.
335 NamedMDNode *Module::getModuleFlagsMetadata() const {
336   return getNamedMetadata("llvm.module.flags");
337 }
338 
339 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
340 /// represents module-level flags. If module-level flags aren't found, it
341 /// creates the named metadata that contains them.
342 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
343   return getOrInsertNamedMetadata("llvm.module.flags");
344 }
345 
346 /// addModuleFlag - Add a module-level flag to the module-level flags
347 /// metadata. It will create the module-level flags named metadata if it doesn't
348 /// already exist.
349 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
350                            Metadata *Val) {
351   Type *Int32Ty = Type::getInt32Ty(Context);
352   Metadata *Ops[3] = {
353       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
354       MDString::get(Context, Key), Val};
355   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
356 }
357 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
358                            Constant *Val) {
359   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
360 }
361 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
362                            uint32_t Val) {
363   Type *Int32Ty = Type::getInt32Ty(Context);
364   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
365 }
366 void Module::addModuleFlag(MDNode *Node) {
367   assert(Node->getNumOperands() == 3 &&
368          "Invalid number of operands for module flag!");
369   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
370          isa<MDString>(Node->getOperand(1)) &&
371          "Invalid operand types for module flag!");
372   getOrInsertModuleFlagsMetadata()->addOperand(Node);
373 }
374 
375 void Module::setDataLayout(StringRef Desc) {
376   DL.reset(Desc);
377 }
378 
379 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
380 
381 const DataLayout &Module::getDataLayout() const { return DL; }
382 
383 //===----------------------------------------------------------------------===//
384 // Methods to control the materialization of GlobalValues in the Module.
385 //
386 void Module::setMaterializer(GVMaterializer *GVM) {
387   assert(!Materializer &&
388          "Module already has a GVMaterializer.  Call materializeAll"
389          " to clear it out before setting another one.");
390   Materializer.reset(GVM);
391 }
392 
393 std::error_code Module::materialize(GlobalValue *GV) {
394   if (!Materializer)
395     return std::error_code();
396 
397   return Materializer->materialize(GV);
398 }
399 
400 std::error_code Module::materializeAll() {
401   if (!Materializer)
402     return std::error_code();
403   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
404   return M->materializeModule();
405 }
406 
407 std::error_code Module::materializeMetadata() {
408   if (!Materializer)
409     return std::error_code();
410   return Materializer->materializeMetadata();
411 }
412 
413 //===----------------------------------------------------------------------===//
414 // Other module related stuff.
415 //
416 
417 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
418   // If we have a materializer, it is possible that some unread function
419   // uses a type that is currently not visible to a TypeFinder, so ask
420   // the materializer which types it created.
421   if (Materializer)
422     return Materializer->getIdentifiedStructTypes();
423 
424   std::vector<StructType *> Ret;
425   TypeFinder SrcStructTypes;
426   SrcStructTypes.run(*this, true);
427   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
428   return Ret;
429 }
430 
431 // dropAllReferences() - This function causes all the subelements to "let go"
432 // of all references that they are maintaining.  This allows one to 'delete' a
433 // whole module at a time, even though there may be circular references... first
434 // all references are dropped, and all use counts go to zero.  Then everything
435 // is deleted for real.  Note that no operations are valid on an object that
436 // has "dropped all references", except operator delete.
437 //
438 void Module::dropAllReferences() {
439   for (Function &F : *this)
440     F.dropAllReferences();
441 
442   for (GlobalVariable &GV : globals())
443     GV.dropAllReferences();
444 
445   for (GlobalAlias &GA : aliases())
446     GA.dropAllReferences();
447 
448   for (GlobalIFunc &GIF : ifuncs())
449     GIF.dropAllReferences();
450 }
451 
452 unsigned Module::getDwarfVersion() const {
453   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
454   if (!Val)
455     return 0;
456   return cast<ConstantInt>(Val->getValue())->getZExtValue();
457 }
458 
459 unsigned Module::getCodeViewFlag() const {
460   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
461   if (!Val)
462     return 0;
463   return cast<ConstantInt>(Val->getValue())->getZExtValue();
464 }
465 
466 Comdat *Module::getOrInsertComdat(StringRef Name) {
467   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
468   Entry.second.Name = &Entry;
469   return &Entry.second;
470 }
471 
472 PICLevel::Level Module::getPICLevel() const {
473   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
474 
475   if (!Val)
476     return PICLevel::Default;
477 
478   return static_cast<PICLevel::Level>(
479       cast<ConstantInt>(Val->getValue())->getZExtValue());
480 }
481 
482 void Module::setPICLevel(PICLevel::Level PL) {
483   addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
484 }
485 
486 void Module::setMaximumFunctionCount(uint64_t Count) {
487   addModuleFlag(ModFlagBehavior::Error, "MaxFunctionCount", Count);
488 }
489 
490 Optional<uint64_t> Module::getMaximumFunctionCount() {
491   auto *Val =
492       cast_or_null<ConstantAsMetadata>(getModuleFlag("MaxFunctionCount"));
493   if (!Val)
494     return None;
495   return cast<ConstantInt>(Val->getValue())->getZExtValue();
496 }
497 
498 void Module::setProfileSummary(Metadata *M) {
499   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
500 }
501 
502 Metadata *Module::getProfileSummary() {
503   return getModuleFlag("ProfileSummary");
504 }
505