1 //===-- Module.cpp - Implement the Module class ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Module class for the IR library.
12 //===----------------------------------------------------------------------===//
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/LeakDetector.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/RandomNumberGenerator.h"
34 //===----------------------------------------------------------------------===//
35 // Methods to implement the globals and functions lists.
38 // Explicit instantiations of SymbolTableListTraits since some of the methods
39 // are not in the public header file.
40 template class llvm::SymbolTableListTraits<Function, Module>;
41 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
42 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
44 //===----------------------------------------------------------------------===//
45 // Primitive Module methods.
48 Module::Module(StringRef MID, LLVMContext &C)
49 : Context(C), Materializer(), ModuleID(MID), RNG(nullptr), DL("") {
50 ValSymTab = new ValueSymbolTable();
51 NamedMDSymTab = new StringMap<NamedMDNode *>();
52 Context.addModule(this);
56 Context.removeModule(this);
63 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
67 /// getNamedValue - Return the first global value in the module with
68 /// the specified name, of arbitrary type. This method returns null
69 /// if a global with the specified name is not found.
70 GlobalValue *Module::getNamedValue(StringRef Name) const {
71 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
74 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
75 /// This ID is uniqued across modules in the current LLVMContext.
76 unsigned Module::getMDKindID(StringRef Name) const {
77 return Context.getMDKindID(Name);
80 /// getMDKindNames - Populate client supplied SmallVector with the name for
81 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
82 /// so it is filled in as an empty string.
83 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
84 return Context.getMDKindNames(Result);
88 //===----------------------------------------------------------------------===//
89 // Methods for easy access to the functions in the module.
92 // getOrInsertFunction - Look up the specified function in the module symbol
93 // table. If it does not exist, add a prototype for the function and return
94 // it. This is nice because it allows most passes to get away with not handling
95 // the symbol table directly for this common task.
97 Constant *Module::getOrInsertFunction(StringRef Name,
99 AttributeSet AttributeList) {
100 // See if we have a definition for the specified function already.
101 GlobalValue *F = getNamedValue(Name);
104 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
105 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
106 New->setAttributes(AttributeList);
107 FunctionList.push_back(New);
108 return New; // Return the new prototype.
111 // If the function exists but has the wrong type, return a bitcast to the
113 if (F->getType() != PointerType::getUnqual(Ty))
114 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
116 // Otherwise, we just found the existing function or a prototype.
120 Constant *Module::getOrInsertFunction(StringRef Name,
122 return getOrInsertFunction(Name, Ty, AttributeSet());
125 // getOrInsertFunction - Look up the specified function in the module symbol
126 // table. If it does not exist, add a prototype for the function and return it.
127 // This version of the method takes a null terminated list of function
128 // arguments, which makes it easier for clients to use.
130 Constant *Module::getOrInsertFunction(StringRef Name,
131 AttributeSet AttributeList,
134 va_start(Args, RetTy);
136 // Build the list of argument types...
137 std::vector<Type*> ArgTys;
138 while (Type *ArgTy = va_arg(Args, Type*))
139 ArgTys.push_back(ArgTy);
143 // Build the function type and chain to the other getOrInsertFunction...
144 return getOrInsertFunction(Name,
145 FunctionType::get(RetTy, ArgTys, false),
149 Constant *Module::getOrInsertFunction(StringRef Name,
152 va_start(Args, RetTy);
154 // Build the list of argument types...
155 std::vector<Type*> ArgTys;
156 while (Type *ArgTy = va_arg(Args, Type*))
157 ArgTys.push_back(ArgTy);
161 // Build the function type and chain to the other getOrInsertFunction...
162 return getOrInsertFunction(Name,
163 FunctionType::get(RetTy, ArgTys, false),
167 // getFunction - Look up the specified function in the module symbol table.
168 // If it does not exist, return null.
170 Function *Module::getFunction(StringRef Name) const {
171 return dyn_cast_or_null<Function>(getNamedValue(Name));
174 //===----------------------------------------------------------------------===//
175 // Methods for easy access to the global variables in the module.
178 /// getGlobalVariable - Look up the specified global variable in the module
179 /// symbol table. If it does not exist, return null. The type argument
180 /// should be the underlying type of the global, i.e., it should not have
181 /// the top-level PointerType, which represents the address of the global.
182 /// If AllowLocal is set to true, this function will return types that
183 /// have an local. By default, these types are not returned.
185 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
186 if (GlobalVariable *Result =
187 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
188 if (AllowLocal || !Result->hasLocalLinkage())
193 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
194 /// 1. If it does not exist, add a declaration of the global and return it.
195 /// 2. Else, the global exists but has the wrong type: return the function
196 /// with a constantexpr cast to the right type.
197 /// 3. Finally, if the existing global is the correct declaration, return the
199 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
200 // See if we have a definition for the specified global already.
201 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
204 GlobalVariable *New =
205 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
207 return New; // Return the new declaration.
210 // If the variable exists but has the wrong type, return a bitcast to the
212 Type *GVTy = GV->getType();
213 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
215 return ConstantExpr::getBitCast(GV, PTy);
217 // Otherwise, we just found the existing function or a prototype.
221 //===----------------------------------------------------------------------===//
222 // Methods for easy access to the global variables in the module.
225 // getNamedAlias - Look up the specified global in the module symbol table.
226 // If it does not exist, return null.
228 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
229 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
232 /// getNamedMetadata - Return the first NamedMDNode in the module with the
233 /// specified name. This method returns null if a NamedMDNode with the
234 /// specified name is not found.
235 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
236 SmallString<256> NameData;
237 StringRef NameRef = Name.toStringRef(NameData);
238 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
241 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
242 /// with the specified name. This method returns a new NamedMDNode if a
243 /// NamedMDNode with the specified name is not found.
244 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
246 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
248 NMD = new NamedMDNode(Name);
249 NMD->setParent(this);
250 NamedMDList.push_back(NMD);
255 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
257 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
258 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
259 NamedMDList.erase(NMD);
262 bool Module::isValidModFlagBehavior(Value *V, ModFlagBehavior &MFB) {
263 if (ConstantInt *Behavior = dyn_cast<ConstantInt>(V)) {
264 uint64_t Val = Behavior->getLimitedValue();
265 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
266 MFB = static_cast<ModFlagBehavior>(Val);
273 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
275 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
276 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
277 if (!ModFlags) return;
279 for (const MDNode *Flag : ModFlags->operands()) {
281 if (Flag->getNumOperands() >= 3 &&
282 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
283 isa<MDString>(Flag->getOperand(1))) {
284 // Check the operands of the MDNode before accessing the operands.
285 // The verifier will actually catch these failures.
286 MDString *Key = cast<MDString>(Flag->getOperand(1));
287 Value *Val = Flag->getOperand(2);
288 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
293 /// Return the corresponding value if Key appears in module flags, otherwise
295 Value *Module::getModuleFlag(StringRef Key) const {
296 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
297 getModuleFlagsMetadata(ModuleFlags);
298 for (const ModuleFlagEntry &MFE : ModuleFlags) {
299 if (Key == MFE.Key->getString())
305 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
306 /// represents module-level flags. This method returns null if there are no
307 /// module-level flags.
308 NamedMDNode *Module::getModuleFlagsMetadata() const {
309 return getNamedMetadata("llvm.module.flags");
312 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
313 /// represents module-level flags. If module-level flags aren't found, it
314 /// creates the named metadata that contains them.
315 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
316 return getOrInsertNamedMetadata("llvm.module.flags");
319 /// addModuleFlag - Add a module-level flag to the module-level flags
320 /// metadata. It will create the module-level flags named metadata if it doesn't
322 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
324 Type *Int32Ty = Type::getInt32Ty(Context);
326 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
328 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
330 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
332 Type *Int32Ty = Type::getInt32Ty(Context);
333 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
335 void Module::addModuleFlag(MDNode *Node) {
336 assert(Node->getNumOperands() == 3 &&
337 "Invalid number of operands for module flag!");
338 assert(isa<ConstantInt>(Node->getOperand(0)) &&
339 isa<MDString>(Node->getOperand(1)) &&
340 "Invalid operand types for module flag!");
341 getOrInsertModuleFlagsMetadata()->addOperand(Node);
344 void Module::setDataLayout(StringRef Desc) {
350 DataLayoutStr = DL.getStringRepresentation();
351 // DataLayoutStr is now equivalent to Desc, but since the representation
352 // is not unique, they may not be identical.
356 void Module::setDataLayout(const DataLayout *Other) {
362 DataLayoutStr = DL.getStringRepresentation();
366 const DataLayout *Module::getDataLayout() const {
367 if (DataLayoutStr.empty())
372 // We want reproducible builds, but ModuleID may be a full path so we just use
373 // the filename to salt the RNG (although it is not guaranteed to be unique).
374 RandomNumberGenerator &Module::getRNG() const {
375 if (RNG == nullptr) {
376 StringRef Salt = sys::path::filename(ModuleID);
377 RNG = new RandomNumberGenerator(Salt);
382 //===----------------------------------------------------------------------===//
383 // Methods to control the materialization of GlobalValues in the Module.
385 void Module::setMaterializer(GVMaterializer *GVM) {
386 assert(!Materializer &&
387 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
388 " to clear it out before setting another one.");
389 Materializer.reset(GVM);
392 bool Module::isDematerializable(const GlobalValue *GV) const {
394 return Materializer->isDematerializable(GV);
398 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
402 std::error_code EC = Materializer->Materialize(GV);
406 *ErrInfo = EC.message();
410 void Module::Dematerialize(GlobalValue *GV) {
412 return Materializer->Dematerialize(GV);
415 std::error_code Module::materializeAll() {
417 return std::error_code();
418 return Materializer->MaterializeModule(this);
421 std::error_code Module::materializeAllPermanently() {
422 if (std::error_code EC = materializeAll())
425 Materializer.reset();
426 return std::error_code();
429 //===----------------------------------------------------------------------===//
430 // Other module related stuff.
434 // dropAllReferences() - This function causes all the subelements to "let go"
435 // of all references that they are maintaining. This allows one to 'delete' a
436 // whole module at a time, even though there may be circular references... first
437 // all references are dropped, and all use counts go to zero. Then everything
438 // is deleted for real. Note that no operations are valid on an object that
439 // has "dropped all references", except operator delete.
441 void Module::dropAllReferences() {
442 for (Function &F : *this)
443 F.dropAllReferences();
445 for (GlobalVariable &GV : globals())
446 GV.dropAllReferences();
448 for (GlobalAlias &GA : aliases())
449 GA.dropAllReferences();
452 unsigned Module::getDwarfVersion() const {
453 Value *Val = getModuleFlag("Dwarf Version");
455 return dwarf::DWARF_VERSION;
456 return cast<ConstantInt>(Val)->getZExtValue();
459 Comdat *Module::getOrInsertComdat(StringRef Name) {
461 StringMapEntry<Comdat> &Entry =
462 ComdatSymTab.GetOrCreateValue(Name, std::move(C));
463 Entry.second.Name = &Entry;
464 return &Entry.second;