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