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/TypeFinder.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), 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);
66 RandomNumberGenerator *Module::createRNG(const Pass* P) const {
67 SmallString<32> Salt(P->getPassName());
69 // This RNG is guaranteed to produce the same random stream only
70 // when the Module ID and thus the input filename is the same. This
71 // might be problematic if the input filename extension changes
72 // (e.g. from .c to .bc or .ll).
74 // We could store this salt in NamedMetadata, but this would make
75 // the parameter non-const. This would unfortunately make this
76 // interface unusable by any Machine passes, since they only have a
77 // const reference to their IR Module. Alternatively we can always
78 // store salt metadata from the Module constructor.
79 Salt += sys::path::filename(getModuleIdentifier());
81 return new RandomNumberGenerator(Salt);
85 /// getNamedValue - Return the first global value in the module with
86 /// the specified name, of arbitrary type. This method returns null
87 /// if a global with the specified name is not found.
88 GlobalValue *Module::getNamedValue(StringRef Name) const {
89 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
92 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
93 /// This ID is uniqued across modules in the current LLVMContext.
94 unsigned Module::getMDKindID(StringRef Name) const {
95 return Context.getMDKindID(Name);
98 /// getMDKindNames - Populate client supplied SmallVector with the name for
99 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
100 /// so it is filled in as an empty string.
101 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
102 return Context.getMDKindNames(Result);
106 //===----------------------------------------------------------------------===//
107 // Methods for easy access to the functions in the module.
110 // getOrInsertFunction - Look up the specified function in the module symbol
111 // table. If it does not exist, add a prototype for the function and return
112 // it. This is nice because it allows most passes to get away with not handling
113 // the symbol table directly for this common task.
115 Constant *Module::getOrInsertFunction(StringRef Name,
117 AttributeSet AttributeList) {
118 // See if we have a definition for the specified function already.
119 GlobalValue *F = getNamedValue(Name);
122 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
123 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
124 New->setAttributes(AttributeList);
125 FunctionList.push_back(New);
126 return New; // Return the new prototype.
129 // If the function exists but has the wrong type, return a bitcast to the
131 if (F->getType() != PointerType::getUnqual(Ty))
132 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
134 // Otherwise, we just found the existing function or a prototype.
138 Constant *Module::getOrInsertFunction(StringRef Name,
140 return getOrInsertFunction(Name, Ty, AttributeSet());
143 // getOrInsertFunction - Look up the specified function in the module symbol
144 // table. If it does not exist, add a prototype for the function and return it.
145 // This version of the method takes a null terminated list of function
146 // arguments, which makes it easier for clients to use.
148 Constant *Module::getOrInsertFunction(StringRef Name,
149 AttributeSet AttributeList,
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 Constant *Module::getOrInsertFunction(StringRef Name,
170 va_start(Args, RetTy);
172 // Build the list of argument types...
173 std::vector<Type*> ArgTys;
174 while (Type *ArgTy = va_arg(Args, Type*))
175 ArgTys.push_back(ArgTy);
179 // Build the function type and chain to the other getOrInsertFunction...
180 return getOrInsertFunction(Name,
181 FunctionType::get(RetTy, ArgTys, false),
185 // getFunction - Look up the specified function in the module symbol table.
186 // If it does not exist, return null.
188 Function *Module::getFunction(StringRef Name) const {
189 return dyn_cast_or_null<Function>(getNamedValue(Name));
192 //===----------------------------------------------------------------------===//
193 // Methods for easy access to the global variables in the module.
196 /// getGlobalVariable - Look up the specified global variable in the module
197 /// symbol table. If it does not exist, return null. The type argument
198 /// should be the underlying type of the global, i.e., it should not have
199 /// the top-level PointerType, which represents the address of the global.
200 /// If AllowLocal is set to true, this function will return types that
201 /// have an local. By default, these types are not returned.
203 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
204 if (GlobalVariable *Result =
205 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
206 if (AllowLocal || !Result->hasLocalLinkage())
211 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
212 /// 1. If it does not exist, add a declaration of the global and return it.
213 /// 2. Else, the global exists but has the wrong type: return the function
214 /// with a constantexpr cast to the right type.
215 /// 3. Finally, if the existing global is the correct declaration, return the
217 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
218 // See if we have a definition for the specified global already.
219 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
222 GlobalVariable *New =
223 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
225 return New; // Return the new declaration.
228 // If the variable exists but has the wrong type, return a bitcast to the
230 Type *GVTy = GV->getType();
231 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
233 return ConstantExpr::getBitCast(GV, PTy);
235 // Otherwise, we just found the existing function or a prototype.
239 //===----------------------------------------------------------------------===//
240 // Methods for easy access to the global variables in the module.
243 // getNamedAlias - Look up the specified global in the module symbol table.
244 // If it does not exist, return null.
246 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
247 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
250 /// getNamedMetadata - Return the first NamedMDNode in the module with the
251 /// specified name. This method returns null if a NamedMDNode with the
252 /// specified name is not found.
253 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
254 SmallString<256> NameData;
255 StringRef NameRef = Name.toStringRef(NameData);
256 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
259 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
260 /// with the specified name. This method returns a new NamedMDNode if a
261 /// NamedMDNode with the specified name is not found.
262 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
264 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
266 NMD = new NamedMDNode(Name);
267 NMD->setParent(this);
268 NamedMDList.push_back(NMD);
273 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
275 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
276 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
277 NamedMDList.erase(NMD);
280 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
281 if (ConstantInt *Behavior = mdconst::dyn_extract<ConstantInt>(MD)) {
282 uint64_t Val = Behavior->getLimitedValue();
283 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
284 MFB = static_cast<ModFlagBehavior>(Val);
291 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
293 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
294 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
295 if (!ModFlags) return;
297 for (const MDNode *Flag : ModFlags->operands()) {
299 if (Flag->getNumOperands() >= 3 &&
300 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
301 isa<MDString>(Flag->getOperand(1))) {
302 // Check the operands of the MDNode before accessing the operands.
303 // The verifier will actually catch these failures.
304 MDString *Key = cast<MDString>(Flag->getOperand(1));
305 Metadata *Val = Flag->getOperand(2);
306 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
311 /// Return the corresponding value if Key appears in module flags, otherwise
313 Metadata *Module::getModuleFlag(StringRef Key) const {
314 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
315 getModuleFlagsMetadata(ModuleFlags);
316 for (const ModuleFlagEntry &MFE : ModuleFlags) {
317 if (Key == MFE.Key->getString())
323 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
324 /// represents module-level flags. This method returns null if there are no
325 /// module-level flags.
326 NamedMDNode *Module::getModuleFlagsMetadata() const {
327 return getNamedMetadata("llvm.module.flags");
330 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
331 /// represents module-level flags. If module-level flags aren't found, it
332 /// creates the named metadata that contains them.
333 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
334 return getOrInsertNamedMetadata("llvm.module.flags");
337 /// addModuleFlag - Add a module-level flag to the module-level flags
338 /// metadata. It will create the module-level flags named metadata if it doesn't
340 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
342 Type *Int32Ty = Type::getInt32Ty(Context);
344 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
345 MDString::get(Context, Key), Val};
346 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
348 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
350 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
352 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
354 Type *Int32Ty = Type::getInt32Ty(Context);
355 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
357 void Module::addModuleFlag(MDNode *Node) {
358 assert(Node->getNumOperands() == 3 &&
359 "Invalid number of operands for module flag!");
360 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
361 isa<MDString>(Node->getOperand(1)) &&
362 "Invalid operand types for module flag!");
363 getOrInsertModuleFlagsMetadata()->addOperand(Node);
366 void Module::setDataLayout(StringRef Desc) {
372 DataLayoutStr = DL.getStringRepresentation();
373 // DataLayoutStr is now equivalent to Desc, but since the representation
374 // is not unique, they may not be identical.
378 void Module::setDataLayout(const DataLayout *Other) {
384 DataLayoutStr = DL.getStringRepresentation();
388 const DataLayout *Module::getDataLayout() const {
389 if (DataLayoutStr.empty())
394 //===----------------------------------------------------------------------===//
395 // Methods to control the materialization of GlobalValues in the Module.
397 void Module::setMaterializer(GVMaterializer *GVM) {
398 assert(!Materializer &&
399 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
400 " to clear it out before setting another one.");
401 Materializer.reset(GVM);
404 bool Module::isDematerializable(const GlobalValue *GV) const {
406 return Materializer->isDematerializable(GV);
410 std::error_code Module::materialize(GlobalValue *GV) {
412 return std::error_code();
414 return Materializer->materialize(GV);
417 void Module::Dematerialize(GlobalValue *GV) {
419 return Materializer->Dematerialize(GV);
422 std::error_code Module::materializeAll() {
424 return std::error_code();
425 return Materializer->MaterializeModule(this);
428 std::error_code Module::materializeAllPermanently() {
429 if (std::error_code EC = materializeAll())
432 Materializer.reset();
433 return std::error_code();
436 //===----------------------------------------------------------------------===//
437 // Other module related stuff.
440 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
441 // If we have a materializer, it is possible that some unread function
442 // uses a type that is currently not visible to a TypeFinder, so ask
443 // the materializer which types it created.
445 return Materializer->getIdentifiedStructTypes();
447 std::vector<StructType *> Ret;
448 TypeFinder SrcStructTypes;
449 SrcStructTypes.run(*this, true);
450 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
454 // dropAllReferences() - This function causes all the subelements to "let go"
455 // of all references that they are maintaining. This allows one to 'delete' a
456 // whole module at a time, even though there may be circular references... first
457 // all references are dropped, and all use counts go to zero. Then everything
458 // is deleted for real. Note that no operations are valid on an object that
459 // has "dropped all references", except operator delete.
461 void Module::dropAllReferences() {
462 for (Function &F : *this)
463 F.dropAllReferences();
465 for (GlobalVariable &GV : globals())
466 GV.dropAllReferences();
468 for (GlobalAlias &GA : aliases())
469 GA.dropAllReferences();
472 unsigned Module::getDwarfVersion() const {
473 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
475 return dwarf::DWARF_VERSION;
476 return cast<ConstantInt>(Val->getValue())->getZExtValue();
479 Comdat *Module::getOrInsertComdat(StringRef Name) {
480 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
481 Entry.second.Name = &Entry;
482 return &Entry.second;
485 PICLevel::Level Module::getPICLevel() const {
486 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
489 return PICLevel::Default;
491 return static_cast<PICLevel::Level>(
492 cast<ConstantInt>(Val->getValue())->getZExtValue());
495 void Module::setPICLevel(PICLevel::Level PL) {
496 addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);