xref: /llvm-project/llvm/lib/IR/Module.cpp (revision e2dcf7c3a12d5e623048d6e77d5b320dfb553ace)
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/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/RandomNumberGenerator.h"
31 #include <algorithm>
32 #include <cstdarg>
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,
123                                       FunctionType *Ty,
124                                       AttributeSet AttributeList) {
125   // See if we have a definition for the specified function already.
126   GlobalValue *F = getNamedValue(Name);
127   if (!F) {
128     // Nope, add it
129     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
130     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
131       New->setAttributes(AttributeList);
132     FunctionList.push_back(New);
133     return New;                    // Return the new prototype.
134   }
135 
136   // If the function exists but has the wrong type, return a bitcast to the
137   // right type.
138   if (F->getType() != PointerType::getUnqual(Ty))
139     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
140 
141   // Otherwise, we just found the existing function or a prototype.
142   return F;
143 }
144 
145 Constant *Module::getOrInsertFunction(StringRef Name,
146                                       FunctionType *Ty) {
147   return getOrInsertFunction(Name, Ty, AttributeSet());
148 }
149 
150 // getOrInsertFunction - Look up the specified function in the module symbol
151 // table.  If it does not exist, add a prototype for the function and return it.
152 // This version of the method takes a null terminated list of function
153 // arguments, which makes it easier for clients to use.
154 //
155 Constant *Module::getOrInsertFunction(StringRef Name,
156                                       AttributeSet AttributeList,
157                                       Type *RetTy, ...) {
158   va_list Args;
159   va_start(Args, RetTy);
160 
161   // Build the list of argument types...
162   std::vector<Type*> ArgTys;
163   while (Type *ArgTy = va_arg(Args, Type*))
164     ArgTys.push_back(ArgTy);
165 
166   va_end(Args);
167 
168   // Build the function type and chain to the other getOrInsertFunction...
169   return getOrInsertFunction(Name,
170                              FunctionType::get(RetTy, ArgTys, false),
171                              AttributeList);
172 }
173 
174 Constant *Module::getOrInsertFunction(StringRef Name,
175                                       Type *RetTy, ...) {
176   va_list Args;
177   va_start(Args, RetTy);
178 
179   // Build the list of argument types...
180   std::vector<Type*> ArgTys;
181   while (Type *ArgTy = va_arg(Args, Type*))
182     ArgTys.push_back(ArgTy);
183 
184   va_end(Args);
185 
186   // Build the function type and chain to the other getOrInsertFunction...
187   return getOrInsertFunction(Name,
188                              FunctionType::get(RetTy, ArgTys, false),
189                              AttributeSet());
190 }
191 
192 // getFunction - Look up the specified function in the module symbol table.
193 // If it does not exist, return null.
194 //
195 Function *Module::getFunction(StringRef Name) const {
196   return dyn_cast_or_null<Function>(getNamedValue(Name));
197 }
198 
199 //===----------------------------------------------------------------------===//
200 // Methods for easy access to the global variables in the module.
201 //
202 
203 /// getGlobalVariable - Look up the specified global variable in the module
204 /// symbol table.  If it does not exist, return null.  The type argument
205 /// should be the underlying type of the global, i.e., it should not have
206 /// the top-level PointerType, which represents the address of the global.
207 /// If AllowLocal is set to true, this function will return types that
208 /// have an local. By default, these types are not returned.
209 ///
210 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
211   if (GlobalVariable *Result =
212       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
213     if (AllowLocal || !Result->hasLocalLinkage())
214       return Result;
215   return nullptr;
216 }
217 
218 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
219 ///   1. If it does not exist, add a declaration of the global and return it.
220 ///   2. Else, the global exists but has the wrong type: return the function
221 ///      with a constantexpr cast to the right type.
222 ///   3. Finally, if the existing global is the correct declaration, return the
223 ///      existing global.
224 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
225   // See if we have a definition for the specified global already.
226   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
227   if (!GV) {
228     // Nope, add it
229     GlobalVariable *New =
230       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
231                          nullptr, Name);
232      return New;                    // Return the new declaration.
233   }
234 
235   // If the variable exists but has the wrong type, return a bitcast to the
236   // right type.
237   Type *GVTy = GV->getType();
238   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
239   if (GVTy != PTy)
240     return ConstantExpr::getBitCast(GV, PTy);
241 
242   // Otherwise, we just found the existing function or a prototype.
243   return GV;
244 }
245 
246 //===----------------------------------------------------------------------===//
247 // Methods for easy access to the global variables in the module.
248 //
249 
250 // getNamedAlias - Look up the specified global in the module symbol table.
251 // If it does not exist, return null.
252 //
253 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
254   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
255 }
256 
257 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
258   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
259 }
260 
261 /// getNamedMetadata - Return the first NamedMDNode in the module with the
262 /// specified name. This method returns null if a NamedMDNode with the
263 /// specified name is not found.
264 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
265   SmallString<256> NameData;
266   StringRef NameRef = Name.toStringRef(NameData);
267   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
268 }
269 
270 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
271 /// with the specified name. This method returns a new NamedMDNode if a
272 /// NamedMDNode with the specified name is not found.
273 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
274   NamedMDNode *&NMD =
275     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
276   if (!NMD) {
277     NMD = new NamedMDNode(Name);
278     NMD->setParent(this);
279     NamedMDList.push_back(NMD);
280   }
281   return NMD;
282 }
283 
284 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
285 /// delete it.
286 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
287   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
288   NamedMDList.erase(NMD->getIterator());
289 }
290 
291 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
292   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
293     uint64_t Val = Behavior->getLimitedValue();
294     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
295       MFB = static_cast<ModFlagBehavior>(Val);
296       return true;
297     }
298   }
299   return false;
300 }
301 
302 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
303 void Module::
304 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
305   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
306   if (!ModFlags) return;
307 
308   for (const MDNode *Flag : ModFlags->operands()) {
309     ModFlagBehavior MFB;
310     if (Flag->getNumOperands() >= 3 &&
311         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
312         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
313       // Check the operands of the MDNode before accessing the operands.
314       // The verifier will actually catch these failures.
315       MDString *Key = cast<MDString>(Flag->getOperand(1));
316       Metadata *Val = Flag->getOperand(2);
317       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
318     }
319   }
320 }
321 
322 /// Return the corresponding value if Key appears in module flags, otherwise
323 /// return null.
324 Metadata *Module::getModuleFlag(StringRef Key) const {
325   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
326   getModuleFlagsMetadata(ModuleFlags);
327   for (const ModuleFlagEntry &MFE : ModuleFlags) {
328     if (Key == MFE.Key->getString())
329       return MFE.Val;
330   }
331   return nullptr;
332 }
333 
334 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
335 /// represents module-level flags. This method returns null if there are no
336 /// module-level flags.
337 NamedMDNode *Module::getModuleFlagsMetadata() const {
338   return getNamedMetadata("llvm.module.flags");
339 }
340 
341 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
342 /// represents module-level flags. If module-level flags aren't found, it
343 /// creates the named metadata that contains them.
344 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
345   return getOrInsertNamedMetadata("llvm.module.flags");
346 }
347 
348 /// addModuleFlag - Add a module-level flag to the module-level flags
349 /// metadata. It will create the module-level flags named metadata if it doesn't
350 /// already exist.
351 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
352                            Metadata *Val) {
353   Type *Int32Ty = Type::getInt32Ty(Context);
354   Metadata *Ops[3] = {
355       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
356       MDString::get(Context, Key), Val};
357   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
358 }
359 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
360                            Constant *Val) {
361   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
362 }
363 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
364                            uint32_t Val) {
365   Type *Int32Ty = Type::getInt32Ty(Context);
366   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
367 }
368 void Module::addModuleFlag(MDNode *Node) {
369   assert(Node->getNumOperands() == 3 &&
370          "Invalid number of operands for module flag!");
371   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
372          isa<MDString>(Node->getOperand(1)) &&
373          "Invalid operand types for module flag!");
374   getOrInsertModuleFlagsMetadata()->addOperand(Node);
375 }
376 
377 void Module::setDataLayout(StringRef Desc) {
378   DL.reset(Desc);
379 }
380 
381 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
382 
383 const DataLayout &Module::getDataLayout() const { return DL; }
384 
385 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
386   return cast<DICompileUnit>(CUs->getOperand(Idx));
387 }
388 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
389   return cast<DICompileUnit>(CUs->getOperand(Idx));
390 }
391 
392 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
393   while (CUs && (Idx < CUs->getNumOperands()) &&
394          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
395     ++Idx;
396 }
397 
398 //===----------------------------------------------------------------------===//
399 // Methods to control the materialization of GlobalValues in the Module.
400 //
401 void Module::setMaterializer(GVMaterializer *GVM) {
402   assert(!Materializer &&
403          "Module already has a GVMaterializer.  Call materializeAll"
404          " to clear it out before setting another one.");
405   Materializer.reset(GVM);
406 }
407 
408 std::error_code Module::materialize(GlobalValue *GV) {
409   if (!Materializer)
410     return std::error_code();
411 
412   return Materializer->materialize(GV);
413 }
414 
415 std::error_code Module::materializeAll() {
416   if (!Materializer)
417     return std::error_code();
418   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
419   return M->materializeModule();
420 }
421 
422 std::error_code Module::materializeMetadata() {
423   if (!Materializer)
424     return std::error_code();
425   return Materializer->materializeMetadata();
426 }
427 
428 //===----------------------------------------------------------------------===//
429 // Other module related stuff.
430 //
431 
432 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
433   // If we have a materializer, it is possible that some unread function
434   // uses a type that is currently not visible to a TypeFinder, so ask
435   // the materializer which types it created.
436   if (Materializer)
437     return Materializer->getIdentifiedStructTypes();
438 
439   std::vector<StructType *> Ret;
440   TypeFinder SrcStructTypes;
441   SrcStructTypes.run(*this, true);
442   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
443   return Ret;
444 }
445 
446 // dropAllReferences() - This function causes all the subelements to "let go"
447 // of all references that they are maintaining.  This allows one to 'delete' a
448 // whole module at a time, even though there may be circular references... first
449 // all references are dropped, and all use counts go to zero.  Then everything
450 // is deleted for real.  Note that no operations are valid on an object that
451 // has "dropped all references", except operator delete.
452 //
453 void Module::dropAllReferences() {
454   for (Function &F : *this)
455     F.dropAllReferences();
456 
457   for (GlobalVariable &GV : globals())
458     GV.dropAllReferences();
459 
460   for (GlobalAlias &GA : aliases())
461     GA.dropAllReferences();
462 
463   for (GlobalIFunc &GIF : ifuncs())
464     GIF.dropAllReferences();
465 }
466 
467 unsigned Module::getDwarfVersion() const {
468   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
469   if (!Val)
470     return 0;
471   return cast<ConstantInt>(Val->getValue())->getZExtValue();
472 }
473 
474 unsigned Module::getCodeViewFlag() const {
475   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
476   if (!Val)
477     return 0;
478   return cast<ConstantInt>(Val->getValue())->getZExtValue();
479 }
480 
481 Comdat *Module::getOrInsertComdat(StringRef Name) {
482   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
483   Entry.second.Name = &Entry;
484   return &Entry.second;
485 }
486 
487 PICLevel::Level Module::getPICLevel() const {
488   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
489 
490   if (!Val)
491     return PICLevel::NotPIC;
492 
493   return static_cast<PICLevel::Level>(
494       cast<ConstantInt>(Val->getValue())->getZExtValue());
495 }
496 
497 void Module::setPICLevel(PICLevel::Level PL) {
498   addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
499 }
500 
501 PIELevel::Level Module::getPIELevel() const {
502   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
503 
504   if (!Val)
505     return PIELevel::Default;
506 
507   return static_cast<PIELevel::Level>(
508       cast<ConstantInt>(Val->getValue())->getZExtValue());
509 }
510 
511 void Module::setPIELevel(PIELevel::Level PL) {
512   addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
513 }
514 
515 void Module::setProfileSummary(Metadata *M) {
516   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
517 }
518 
519 Metadata *Module::getProfileSummary() {
520   return getModuleFlag("ProfileSummary");
521 }
522 
523 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
524   OwnedMemoryBuffer = std::move(MB);
525 }
526 
527 GlobalVariable *llvm::collectUsedGlobalVariables(
528     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
529   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
530   GlobalVariable *GV = M.getGlobalVariable(Name);
531   if (!GV || !GV->hasInitializer())
532     return GV;
533 
534   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
535   for (Value *Op : Init->operands()) {
536     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
537     Set.insert(G);
538   }
539   return GV;
540 }
541