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"
32 //===----------------------------------------------------------------------===//
33 // Methods to implement the globals and functions lists.
36 // Explicit instantiations of SymbolTableListTraits since some of the methods
37 // are not in the public header file.
38 template class llvm::SymbolTableListTraits<Function, Module>;
39 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
40 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
42 //===----------------------------------------------------------------------===//
43 // Primitive Module methods.
46 Module::Module(StringRef MID, LLVMContext &C)
47 : Context(C), Materializer(), ModuleID(MID), DL("") {
48 ValSymTab = new ValueSymbolTable();
49 NamedMDSymTab = new StringMap<NamedMDNode *>();
50 Context.addModule(this);
54 Context.removeModule(this);
61 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
64 /// getNamedValue - Return the first global value in the module with
65 /// the specified name, of arbitrary type. This method returns null
66 /// if a global with the specified name is not found.
67 GlobalValue *Module::getNamedValue(StringRef Name) const {
68 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
71 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
72 /// This ID is uniqued across modules in the current LLVMContext.
73 unsigned Module::getMDKindID(StringRef Name) const {
74 return Context.getMDKindID(Name);
77 /// getMDKindNames - Populate client supplied SmallVector with the name for
78 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
79 /// so it is filled in as an empty string.
80 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
81 return Context.getMDKindNames(Result);
85 //===----------------------------------------------------------------------===//
86 // Methods for easy access to the functions in the module.
89 // getOrInsertFunction - Look up the specified function in the module symbol
90 // table. If it does not exist, add a prototype for the function and return
91 // it. This is nice because it allows most passes to get away with not handling
92 // the symbol table directly for this common task.
94 Constant *Module::getOrInsertFunction(StringRef Name,
96 AttributeSet AttributeList) {
97 // See if we have a definition for the specified function already.
98 GlobalValue *F = getNamedValue(Name);
101 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
102 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
103 New->setAttributes(AttributeList);
104 FunctionList.push_back(New);
105 return New; // Return the new prototype.
108 // If the function exists but has the wrong type, return a bitcast to the
110 if (F->getType() != PointerType::getUnqual(Ty))
111 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
113 // Otherwise, we just found the existing function or a prototype.
117 Constant *Module::getOrInsertFunction(StringRef Name,
119 return getOrInsertFunction(Name, Ty, AttributeSet());
122 // getOrInsertFunction - Look up the specified function in the module symbol
123 // table. If it does not exist, add a prototype for the function and return it.
124 // This version of the method takes a null terminated list of function
125 // arguments, which makes it easier for clients to use.
127 Constant *Module::getOrInsertFunction(StringRef Name,
128 AttributeSet AttributeList,
131 va_start(Args, RetTy);
133 // Build the list of argument types...
134 std::vector<Type*> ArgTys;
135 while (Type *ArgTy = va_arg(Args, Type*))
136 ArgTys.push_back(ArgTy);
140 // Build the function type and chain to the other getOrInsertFunction...
141 return getOrInsertFunction(Name,
142 FunctionType::get(RetTy, ArgTys, false),
146 Constant *Module::getOrInsertFunction(StringRef Name,
149 va_start(Args, RetTy);
151 // Build the list of argument types...
152 std::vector<Type*> ArgTys;
153 while (Type *ArgTy = va_arg(Args, Type*))
154 ArgTys.push_back(ArgTy);
158 // Build the function type and chain to the other getOrInsertFunction...
159 return getOrInsertFunction(Name,
160 FunctionType::get(RetTy, ArgTys, false),
164 // getFunction - Look up the specified function in the module symbol table.
165 // If it does not exist, return null.
167 Function *Module::getFunction(StringRef Name) const {
168 return dyn_cast_or_null<Function>(getNamedValue(Name));
171 //===----------------------------------------------------------------------===//
172 // Methods for easy access to the global variables in the module.
175 /// getGlobalVariable - Look up the specified global variable in the module
176 /// symbol table. If it does not exist, return null. The type argument
177 /// should be the underlying type of the global, i.e., it should not have
178 /// the top-level PointerType, which represents the address of the global.
179 /// If AllowLocal is set to true, this function will return types that
180 /// have an local. By default, these types are not returned.
182 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
183 if (GlobalVariable *Result =
184 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
185 if (AllowLocal || !Result->hasLocalLinkage())
190 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
191 /// 1. If it does not exist, add a declaration of the global and return it.
192 /// 2. Else, the global exists but has the wrong type: return the function
193 /// with a constantexpr cast to the right type.
194 /// 3. Finally, if the existing global is the correct declaration, return the
196 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
197 // See if we have a definition for the specified global already.
198 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
201 GlobalVariable *New =
202 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
204 return New; // Return the new declaration.
207 // If the variable exists but has the wrong type, return a bitcast to the
209 Type *GVTy = GV->getType();
210 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
212 return ConstantExpr::getBitCast(GV, PTy);
214 // Otherwise, we just found the existing function or a prototype.
218 //===----------------------------------------------------------------------===//
219 // Methods for easy access to the global variables in the module.
222 // getNamedAlias - Look up the specified global in the module symbol table.
223 // If it does not exist, return null.
225 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
226 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
229 /// getNamedMetadata - Return the first NamedMDNode in the module with the
230 /// specified name. This method returns null if a NamedMDNode with the
231 /// specified name is not found.
232 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
233 SmallString<256> NameData;
234 StringRef NameRef = Name.toStringRef(NameData);
235 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
238 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
239 /// with the specified name. This method returns a new NamedMDNode if a
240 /// NamedMDNode with the specified name is not found.
241 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
243 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
245 NMD = new NamedMDNode(Name);
246 NMD->setParent(this);
247 NamedMDList.push_back(NMD);
252 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
254 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
255 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
256 NamedMDList.erase(NMD);
259 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
261 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
262 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
263 if (!ModFlags) return;
265 for (const MDNode *Flag : ModFlags->operands()) {
266 if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
267 isa<MDString>(Flag->getOperand(1))) {
268 // Check the operands of the MDNode before accessing the operands.
269 // The verifier will actually catch these failures.
270 ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
271 MDString *Key = cast<MDString>(Flag->getOperand(1));
272 Value *Val = Flag->getOperand(2);
273 Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
279 /// Return the corresponding value if Key appears in module flags, otherwise
281 Value *Module::getModuleFlag(StringRef Key) const {
282 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
283 getModuleFlagsMetadata(ModuleFlags);
284 for (const ModuleFlagEntry &MFE : ModuleFlags) {
285 if (Key == MFE.Key->getString())
291 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
292 /// represents module-level flags. This method returns null if there are no
293 /// module-level flags.
294 NamedMDNode *Module::getModuleFlagsMetadata() const {
295 return getNamedMetadata("llvm.module.flags");
298 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
299 /// represents module-level flags. If module-level flags aren't found, it
300 /// creates the named metadata that contains them.
301 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
302 return getOrInsertNamedMetadata("llvm.module.flags");
305 /// addModuleFlag - Add a module-level flag to the module-level flags
306 /// metadata. It will create the module-level flags named metadata if it doesn't
308 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
310 Type *Int32Ty = Type::getInt32Ty(Context);
312 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
314 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
316 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
318 Type *Int32Ty = Type::getInt32Ty(Context);
319 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
321 void Module::addModuleFlag(MDNode *Node) {
322 assert(Node->getNumOperands() == 3 &&
323 "Invalid number of operands for module flag!");
324 assert(isa<ConstantInt>(Node->getOperand(0)) &&
325 isa<MDString>(Node->getOperand(1)) &&
326 "Invalid operand types for module flag!");
327 getOrInsertModuleFlagsMetadata()->addOperand(Node);
330 void Module::setDataLayout(StringRef Desc) {
336 DataLayoutStr = DL.getStringRepresentation();
337 // DataLayoutStr is now equivalent to Desc, but since the representation
338 // is not unique, they may not be identical.
342 void Module::setDataLayout(const DataLayout *Other) {
348 DataLayoutStr = DL.getStringRepresentation();
352 const DataLayout *Module::getDataLayout() const {
353 if (DataLayoutStr.empty())
358 //===----------------------------------------------------------------------===//
359 // Methods to control the materialization of GlobalValues in the Module.
361 void Module::setMaterializer(GVMaterializer *GVM) {
362 assert(!Materializer &&
363 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
364 " to clear it out before setting another one.");
365 Materializer.reset(GVM);
368 bool Module::isMaterializable(const GlobalValue *GV) const {
370 return Materializer->isMaterializable(GV);
374 bool Module::isDematerializable(const GlobalValue *GV) const {
376 return Materializer->isDematerializable(GV);
380 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
384 error_code EC = Materializer->Materialize(GV);
388 *ErrInfo = EC.message();
392 void Module::Dematerialize(GlobalValue *GV) {
394 return Materializer->Dematerialize(GV);
397 error_code Module::materializeAll() {
400 return Materializer->MaterializeModule(this);
403 error_code Module::materializeAllPermanently() {
404 if (error_code EC = materializeAll())
407 Materializer.reset();
411 //===----------------------------------------------------------------------===//
412 // Other module related stuff.
416 // dropAllReferences() - This function causes all the subelements to "let go"
417 // of all references that they are maintaining. This allows one to 'delete' a
418 // whole module at a time, even though there may be circular references... first
419 // all references are dropped, and all use counts go to zero. Then everything
420 // is deleted for real. Note that no operations are valid on an object that
421 // has "dropped all references", except operator delete.
423 void Module::dropAllReferences() {
424 for(Module::iterator I = begin(), E = end(); I != E; ++I)
425 I->dropAllReferences();
427 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
428 I->dropAllReferences();
430 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
431 I->dropAllReferences();
434 unsigned Module::getDwarfVersion() const {
435 Value *Val = getModuleFlag("Dwarf Version");
437 return dwarf::DWARF_VERSION;
438 return cast<ConstantInt>(Val)->getZExtValue();