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 VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Module.h"
15 #include "llvm/InstrTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GVMaterializer.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/LeakDetector.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include "llvm/TypeSymbolTable.h"
30 //===----------------------------------------------------------------------===//
31 // Methods to implement the globals and functions lists.
34 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
35 GlobalVariable *Ret = new GlobalVariable(Type::getInt32Ty(getGlobalContext()),
36 false, GlobalValue::ExternalLinkage);
37 // This should not be garbage monitored.
38 LeakDetector::removeGarbageObject(Ret);
41 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
42 GlobalAlias *Ret = new GlobalAlias(Type::getInt32Ty(getGlobalContext()),
43 GlobalValue::ExternalLinkage);
44 // This should not be garbage monitored.
45 LeakDetector::removeGarbageObject(Ret);
49 // Explicit instantiations of SymbolTableListTraits since some of the methods
50 // are not in the public header file.
51 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
52 template class llvm::SymbolTableListTraits<Function, Module>;
53 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
55 //===----------------------------------------------------------------------===//
56 // Primitive Module methods.
59 Module::Module(StringRef MID, LLVMContext& C)
60 : Context(C), Materializer(NULL), ModuleID(MID), DataLayout("") {
61 ValSymTab = new ValueSymbolTable();
62 TypeSymTab = new TypeSymbolTable();
63 NamedMDSymTab = new MDSymbolTable();
78 /// Target endian information...
79 Module::Endianness Module::getEndianness() const {
80 StringRef temp = DataLayout;
81 Module::Endianness ret = AnyEndianness;
83 while (!temp.empty()) {
84 StringRef token = DataLayout;
85 tie(token, temp) = getToken(temp, "-");
87 if (token[0] == 'e') {
89 } else if (token[0] == 'E') {
97 /// Target Pointer Size information...
98 Module::PointerSize Module::getPointerSize() const {
99 StringRef temp = DataLayout;
100 Module::PointerSize ret = AnyPointerSize;
102 while (!temp.empty()) {
103 StringRef token, signalToken;
104 tie(token, temp) = getToken(temp, "-");
105 tie(signalToken, token) = getToken(token, ":");
107 if (signalToken[0] == 'p') {
109 getToken(token, ":").first.getAsInteger(10, size);
120 /// getNamedValue - Return the first global value in the module with
121 /// the specified name, of arbitrary type. This method returns null
122 /// if a global with the specified name is not found.
123 GlobalValue *Module::getNamedValue(StringRef Name) const {
124 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
127 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
128 /// This ID is uniqued across modules in the current LLVMContext.
129 unsigned Module::getMDKindID(StringRef Name) const {
130 return Context.getMDKindID(Name);
133 /// getMDKindNames - Populate client supplied SmallVector with the name for
134 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
135 /// so it is filled in as an empty string.
136 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
137 return Context.getMDKindNames(Result);
141 //===----------------------------------------------------------------------===//
142 // Methods for easy access to the functions in the module.
145 // getOrInsertFunction - Look up the specified function in the module symbol
146 // table. If it does not exist, add a prototype for the function and return
147 // it. This is nice because it allows most passes to get away with not handling
148 // the symbol table directly for this common task.
150 Constant *Module::getOrInsertFunction(StringRef Name,
151 const FunctionType *Ty,
152 AttrListPtr AttributeList) {
153 // See if we have a definition for the specified function already.
154 GlobalValue *F = getNamedValue(Name);
157 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
158 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
159 New->setAttributes(AttributeList);
160 FunctionList.push_back(New);
161 return New; // Return the new prototype.
164 // Okay, the function exists. Does it have externally visible linkage?
165 if (F->hasLocalLinkage()) {
166 // Clear the function's name.
168 // Retry, now there won't be a conflict.
169 Constant *NewF = getOrInsertFunction(Name, Ty);
174 // If the function exists but has the wrong type, return a bitcast to the
176 if (F->getType() != PointerType::getUnqual(Ty))
177 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
179 // Otherwise, we just found the existing function or a prototype.
183 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
184 const FunctionType *Ty,
185 AttrListPtr AttributeList) {
186 // See if we have a definition for the specified function already.
187 GlobalValue *F = getNamedValue(Name);
190 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
191 New->setAttributes(AttributeList);
192 FunctionList.push_back(New);
193 return New; // Return the new prototype.
196 // Otherwise, we just found the existing function or a prototype.
200 Constant *Module::getOrInsertFunction(StringRef Name,
201 const FunctionType *Ty) {
202 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
203 return getOrInsertFunction(Name, Ty, AttributeList);
206 // getOrInsertFunction - Look up the specified function in the module symbol
207 // table. If it does not exist, add a prototype for the function and return it.
208 // This version of the method takes a null terminated list of function
209 // arguments, which makes it easier for clients to use.
211 Constant *Module::getOrInsertFunction(StringRef Name,
212 AttrListPtr AttributeList,
213 const Type *RetTy, ...) {
215 va_start(Args, RetTy);
217 // Build the list of argument types...
218 std::vector<const Type*> ArgTys;
219 while (const Type *ArgTy = va_arg(Args, const Type*))
220 ArgTys.push_back(ArgTy);
224 // Build the function type and chain to the other getOrInsertFunction...
225 return getOrInsertFunction(Name,
226 FunctionType::get(RetTy, ArgTys, false),
230 Constant *Module::getOrInsertFunction(StringRef Name,
231 const Type *RetTy, ...) {
233 va_start(Args, RetTy);
235 // Build the list of argument types...
236 std::vector<const Type*> ArgTys;
237 while (const Type *ArgTy = va_arg(Args, const Type*))
238 ArgTys.push_back(ArgTy);
242 // Build the function type and chain to the other getOrInsertFunction...
243 return getOrInsertFunction(Name,
244 FunctionType::get(RetTy, ArgTys, false),
245 AttrListPtr::get((AttributeWithIndex *)0, 0));
248 // getFunction - Look up the specified function in the module symbol table.
249 // If it does not exist, return null.
251 Function *Module::getFunction(StringRef Name) const {
252 return dyn_cast_or_null<Function>(getNamedValue(Name));
255 //===----------------------------------------------------------------------===//
256 // Methods for easy access to the global variables in the module.
259 /// getGlobalVariable - Look up the specified global variable in the module
260 /// symbol table. If it does not exist, return null. The type argument
261 /// should be the underlying type of the global, i.e., it should not have
262 /// the top-level PointerType, which represents the address of the global.
263 /// If AllowLocal is set to true, this function will return types that
264 /// have an local. By default, these types are not returned.
266 GlobalVariable *Module::getGlobalVariable(StringRef Name,
267 bool AllowLocal) const {
268 if (GlobalVariable *Result =
269 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
270 if (AllowLocal || !Result->hasLocalLinkage())
275 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
276 /// 1. If it does not exist, add a declaration of the global and return it.
277 /// 2. Else, the global exists but has the wrong type: return the function
278 /// with a constantexpr cast to the right type.
279 /// 3. Finally, if the existing global is the correct delclaration, return the
281 Constant *Module::getOrInsertGlobal(StringRef Name, const Type *Ty) {
282 // See if we have a definition for the specified global already.
283 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
286 GlobalVariable *New =
287 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
289 return New; // Return the new declaration.
292 // If the variable exists but has the wrong type, return a bitcast to the
294 if (GV->getType() != PointerType::getUnqual(Ty))
295 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
297 // Otherwise, we just found the existing function or a prototype.
301 //===----------------------------------------------------------------------===//
302 // Methods for easy access to the global variables in the module.
305 // getNamedAlias - Look up the specified global in the module symbol table.
306 // If it does not exist, return null.
308 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
309 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
312 /// getNamedMetadata - Return the first NamedMDNode in the module with the
313 /// specified name. This method returns null if a NamedMDNode with the
314 //// specified name is not found.
315 NamedMDNode *Module::getNamedMetadata(StringRef Name) const {
316 return NamedMDSymTab->lookup(Name);
319 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
320 /// with the specified name. This method returns a new NamedMDNode if a
321 /// NamedMDNode with the specified name is not found.
322 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
323 NamedMDNode *NMD = NamedMDSymTab->lookup(Name);
325 NMD = NamedMDNode::Create(getContext(), Name, NULL, 0, this);
329 //===----------------------------------------------------------------------===//
330 // Methods for easy access to the types in the module.
334 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
335 // there is already an entry for this name, true is returned and the symbol
336 // table is not modified.
338 bool Module::addTypeName(StringRef Name, const Type *Ty) {
339 TypeSymbolTable &ST = getTypeSymbolTable();
341 if (ST.lookup(Name)) return true; // Already in symtab...
343 // Not in symbol table? Set the name with the Symtab as an argument so the
344 // type knows what to update...
350 /// getTypeByName - Return the type with the specified name in this module, or
351 /// null if there is none by that name.
352 const Type *Module::getTypeByName(StringRef Name) const {
353 const TypeSymbolTable &ST = getTypeSymbolTable();
354 return cast_or_null<Type>(ST.lookup(Name));
357 // getTypeName - If there is at least one entry in the symbol table for the
358 // specified type, return it.
360 std::string Module::getTypeName(const Type *Ty) const {
361 const TypeSymbolTable &ST = getTypeSymbolTable();
363 TypeSymbolTable::const_iterator TI = ST.begin();
364 TypeSymbolTable::const_iterator TE = ST.end();
365 if ( TI == TE ) return ""; // No names for types
367 while (TI != TE && TI->second != Ty)
370 if (TI != TE) // Must have found an entry!
372 return ""; // Must not have found anything...
375 //===----------------------------------------------------------------------===//
376 // Methods to control the materialization of GlobalValues in the Module.
378 void Module::setMaterializer(GVMaterializer *GVM) {
379 assert(!Materializer &&
380 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
381 " to clear it out before setting another one.");
382 Materializer.reset(GVM);
385 bool Module::isMaterializable(const GlobalValue *GV) const {
387 return Materializer->isMaterializable(GV);
391 bool Module::isDematerializable(const GlobalValue *GV) const {
393 return Materializer->isDematerializable(GV);
397 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
399 return Materializer->Materialize(GV, ErrInfo);
403 void Module::Dematerialize(GlobalValue *GV) {
405 return Materializer->Dematerialize(GV);
408 bool Module::MaterializeAll(std::string *ErrInfo) {
411 return Materializer->MaterializeModule(this, ErrInfo);
414 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
415 if (MaterializeAll(ErrInfo))
417 Materializer.reset();
421 //===----------------------------------------------------------------------===//
422 // Other module related stuff.
426 // dropAllReferences() - This function causes all the subelementss to "let go"
427 // of all references that they are maintaining. This allows one to 'delete' a
428 // whole module at a time, even though there may be circular references... first
429 // all references are dropped, and all use counts go to zero. Then everything
430 // is deleted for real. Note that no operations are valid on an object that
431 // has "dropped all references", except operator delete.
433 void Module::dropAllReferences() {
434 for(Module::iterator I = begin(), E = end(); I != E; ++I)
435 I->dropAllReferences();
437 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
438 I->dropAllReferences();
440 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
441 I->dropAllReferences();
444 void Module::addLibrary(StringRef Lib) {
445 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
448 LibraryList.push_back(Lib);
451 void Module::removeLibrary(StringRef Lib) {
452 LibraryListType::iterator I = LibraryList.begin();
453 LibraryListType::iterator E = LibraryList.end();
456 LibraryList.erase(I);