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/LLVMContext.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "SymbolTableListTraitsImpl.h"
23 #include "llvm/TypeSymbolTable.h"
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
31 // NOTE: It is ok to allocate the globals used for these methods from the
32 // global context, because all we ever do is use them to compare for equality.
35 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
36 GlobalVariable *Ret = new GlobalVariable(getGlobalContext(),
38 GlobalValue::ExternalLinkage);
39 // This should not be garbage monitored.
40 LeakDetector::removeGarbageObject(Ret);
43 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
44 GlobalAlias *Ret = new GlobalAlias(Type::Int32Ty,
45 GlobalValue::ExternalLinkage);
46 // This should not be garbage monitored.
47 LeakDetector::removeGarbageObject(Ret);
51 // Explicit instantiations of SymbolTableListTraits since some of the methods
52 // are not in the public header file.
53 template class SymbolTableListTraits<GlobalVariable, Module>;
54 template class SymbolTableListTraits<Function, Module>;
55 template class SymbolTableListTraits<GlobalAlias, Module>;
57 //===----------------------------------------------------------------------===//
58 // Primitive Module methods.
61 Module::Module(const std::string &MID, LLVMContext& C)
62 : Context(C), ModuleID(MID), DataLayout("") {
63 ValSymTab = new ValueSymbolTable();
64 TypeSymTab = new TypeSymbolTable();
77 /// Target endian information...
78 Module::Endianness Module::getEndianness() const {
79 std::string temp = DataLayout;
80 Module::Endianness ret = AnyEndianness;
82 while (!temp.empty()) {
83 std::string token = getToken(temp, "-");
85 if (token[0] == 'e') {
87 } else if (token[0] == 'E') {
95 /// Target Pointer Size information...
96 Module::PointerSize Module::getPointerSize() const {
97 std::string temp = DataLayout;
98 Module::PointerSize ret = AnyPointerSize;
100 while (!temp.empty()) {
101 std::string token = getToken(temp, "-");
102 char signal = getToken(token, ":")[0];
105 int size = atoi(getToken(token, ":").c_str());
116 /// getNamedValue - Return the first global value in the module with
117 /// the specified name, of arbitrary type. This method returns null
118 /// if a global with the specified name is not found.
119 GlobalValue *Module::getNamedValue(const std::string &Name) const {
120 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
123 GlobalValue *Module::getNamedValue(const char *Name) const {
124 llvm::Value *V = getValueSymbolTable().lookup(Name, Name+strlen(Name));
125 return cast_or_null<GlobalValue>(V);
128 //===----------------------------------------------------------------------===//
129 // Methods for easy access to the functions in the module.
132 // getOrInsertFunction - Look up the specified function in the module symbol
133 // table. If it does not exist, add a prototype for the function and return
134 // it. This is nice because it allows most passes to get away with not handling
135 // the symbol table directly for this common task.
137 Constant *Module::getOrInsertFunction(const std::string &Name,
138 const FunctionType *Ty,
139 AttrListPtr AttributeList) {
140 // See if we have a definition for the specified function already.
141 GlobalValue *F = getNamedValue(Name);
144 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
145 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
146 New->setAttributes(AttributeList);
147 FunctionList.push_back(New);
148 return New; // Return the new prototype.
151 // Okay, the function exists. Does it have externally visible linkage?
152 if (F->hasLocalLinkage()) {
153 // Clear the function's name.
155 // Retry, now there won't be a conflict.
156 Constant *NewF = getOrInsertFunction(Name, Ty);
157 F->setName(&Name[0], Name.size());
161 // If the function exists but has the wrong type, return a bitcast to the
163 if (F->getType() != PointerType::getUnqual(Ty))
164 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
166 // Otherwise, we just found the existing function or a prototype.
170 Constant *Module::getOrInsertTargetIntrinsic(const std::string &Name,
171 const FunctionType *Ty,
172 AttrListPtr AttributeList) {
173 // See if we have a definition for the specified function already.
174 GlobalValue *F = getNamedValue(Name);
177 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
178 New->setAttributes(AttributeList);
179 FunctionList.push_back(New);
180 return New; // Return the new prototype.
183 // Otherwise, we just found the existing function or a prototype.
187 Constant *Module::getOrInsertFunction(const std::string &Name,
188 const FunctionType *Ty) {
189 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
190 return getOrInsertFunction(Name, Ty, AttributeList);
193 // getOrInsertFunction - Look up the specified function in the module symbol
194 // table. If it does not exist, add a prototype for the function and return it.
195 // This version of the method takes a null terminated list of function
196 // arguments, which makes it easier for clients to use.
198 Constant *Module::getOrInsertFunction(const std::string &Name,
199 AttrListPtr AttributeList,
200 const Type *RetTy, ...) {
202 va_start(Args, RetTy);
204 // Build the list of argument types...
205 std::vector<const Type*> ArgTys;
206 while (const Type *ArgTy = va_arg(Args, const Type*))
207 ArgTys.push_back(ArgTy);
211 // Build the function type and chain to the other getOrInsertFunction...
212 return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false),
216 Constant *Module::getOrInsertFunction(const std::string &Name,
217 const Type *RetTy, ...) {
219 va_start(Args, RetTy);
221 // Build the list of argument types...
222 std::vector<const Type*> ArgTys;
223 while (const Type *ArgTy = va_arg(Args, const Type*))
224 ArgTys.push_back(ArgTy);
228 // Build the function type and chain to the other getOrInsertFunction...
229 return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false),
230 AttrListPtr::get((AttributeWithIndex *)0, 0));
233 // getFunction - Look up the specified function in the module symbol table.
234 // If it does not exist, return null.
236 Function *Module::getFunction(const std::string &Name) const {
237 return dyn_cast_or_null<Function>(getNamedValue(Name));
240 Function *Module::getFunction(const char *Name) const {
241 return dyn_cast_or_null<Function>(getNamedValue(Name));
244 //===----------------------------------------------------------------------===//
245 // Methods for easy access to the global variables in the module.
248 /// getGlobalVariable - Look up the specified global variable in the module
249 /// symbol table. If it does not exist, return null. The type argument
250 /// should be the underlying type of the global, i.e., it should not have
251 /// the top-level PointerType, which represents the address of the global.
252 /// If AllowLocal is set to true, this function will return types that
253 /// have an local. By default, these types are not returned.
255 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
256 bool AllowLocal) const {
257 if (GlobalVariable *Result =
258 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
259 if (AllowLocal || !Result->hasLocalLinkage())
264 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
265 /// 1. If it does not exist, add a declaration of the global and return it.
266 /// 2. Else, the global exists but has the wrong type: return the function
267 /// with a constantexpr cast to the right type.
268 /// 3. Finally, if the existing global is the correct delclaration, return the
270 Constant *Module::getOrInsertGlobal(const std::string &Name, const Type *Ty) {
271 // See if we have a definition for the specified global already.
272 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
275 GlobalVariable *New =
276 new GlobalVariable(getContext(), Ty, false,
277 GlobalVariable::ExternalLinkage, 0, Name);
278 GlobalList.push_back(New);
279 return New; // Return the new declaration.
282 // If the variable exists but has the wrong type, return a bitcast to the
284 if (GV->getType() != PointerType::getUnqual(Ty))
285 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
287 // Otherwise, we just found the existing function or a prototype.
291 //===----------------------------------------------------------------------===//
292 // Methods for easy access to the global variables in the module.
295 // getNamedAlias - Look up the specified global in the module symbol table.
296 // If it does not exist, return null.
298 GlobalAlias *Module::getNamedAlias(const std::string &Name) const {
299 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
302 //===----------------------------------------------------------------------===//
303 // Methods for easy access to the types in the module.
307 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
308 // there is already an entry for this name, true is returned and the symbol
309 // table is not modified.
311 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
312 TypeSymbolTable &ST = getTypeSymbolTable();
314 if (ST.lookup(Name)) return true; // Already in symtab...
316 // Not in symbol table? Set the name with the Symtab as an argument so the
317 // type knows what to update...
323 /// getTypeByName - Return the type with the specified name in this module, or
324 /// null if there is none by that name.
325 const Type *Module::getTypeByName(const std::string &Name) const {
326 const TypeSymbolTable &ST = getTypeSymbolTable();
327 return cast_or_null<Type>(ST.lookup(Name));
330 // getTypeName - If there is at least one entry in the symbol table for the
331 // specified type, return it.
333 std::string Module::getTypeName(const Type *Ty) const {
334 const TypeSymbolTable &ST = getTypeSymbolTable();
336 TypeSymbolTable::const_iterator TI = ST.begin();
337 TypeSymbolTable::const_iterator TE = ST.end();
338 if ( TI == TE ) return ""; // No names for types
340 while (TI != TE && TI->second != Ty)
343 if (TI != TE) // Must have found an entry!
345 return ""; // Must not have found anything...
348 //===----------------------------------------------------------------------===//
349 // Other module related stuff.
353 // dropAllReferences() - This function causes all the subelementss to "let go"
354 // of all references that they are maintaining. This allows one to 'delete' a
355 // whole module at a time, even though there may be circular references... first
356 // all references are dropped, and all use counts go to zero. Then everything
357 // is deleted for real. Note that no operations are valid on an object that
358 // has "dropped all references", except operator delete.
360 void Module::dropAllReferences() {
361 for(Module::iterator I = begin(), E = end(); I != E; ++I)
362 I->dropAllReferences();
364 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
365 I->dropAllReferences();
367 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
368 I->dropAllReferences();
371 void Module::addLibrary(const std::string& Lib) {
372 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
375 LibraryList.push_back(Lib);
378 void Module::removeLibrary(const std::string& Lib) {
379 LibraryListType::iterator I = LibraryList.begin();
380 LibraryListType::iterator E = LibraryList.end();
383 LibraryList.erase(I);