1 //===-- Module.cpp - Implement the Module class ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/TypeSymbolTable.h"
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
33 Function *ilist_traits<Function>::createSentinel() {
35 FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false,
36 std::vector<FunctionType::ParameterAttributes>() );
37 Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
38 // This should not be garbage monitored.
39 LeakDetector::removeGarbageObject(Ret);
42 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
43 GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
44 GlobalValue::ExternalLinkage);
45 // This should not be garbage monitored.
46 LeakDetector::removeGarbageObject(Ret);
50 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
51 return M->getFunctionList();
53 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
54 return M->getGlobalList();
57 // Explicit instantiations of SymbolTableListTraits since some of the methods
58 // are not in the public header file.
59 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
60 template class SymbolTableListTraits<Function, Module, Module>;
62 //===----------------------------------------------------------------------===//
63 // Primitive Module methods.
66 Module::Module(const std::string &MID)
67 : ModuleID(MID), DataLayout("") {
68 FunctionList.setItemParent(this);
69 FunctionList.setParent(this);
70 GlobalList.setItemParent(this);
71 GlobalList.setParent(this);
72 ValSymTab = new SymbolTable();
73 TypeSymTab = new TypeSymbolTable();
79 GlobalList.setParent(0);
81 FunctionList.setParent(0);
87 // Module::dump() - Allow printing from debugger
88 void Module::dump() const {
89 print(*cerr.stream());
92 /// Target endian information...
93 Module::Endianness Module::getEndianness() const {
94 std::string temp = DataLayout;
95 Module::Endianness ret = AnyEndianness;
97 while (!temp.empty()) {
98 std::string token = getToken(temp, "-");
100 if (token[0] == 'e') {
102 } else if (token[0] == 'E') {
110 /// Target Pointer Size information...
111 Module::PointerSize Module::getPointerSize() const {
112 std::string temp = DataLayout;
113 Module::PointerSize ret = AnyPointerSize;
115 while (!temp.empty()) {
116 std::string token = getToken(temp, "-");
117 char signal = getToken(token, ":")[0];
120 int size = atoi(getToken(token, ":").c_str());
131 //===----------------------------------------------------------------------===//
132 // Methods for easy access to the functions in the module.
135 Constant *Module::getOrInsertFunction(const std::string &Name,
136 const FunctionType *Ty) {
137 SymbolTable &SymTab = getValueSymbolTable();
139 // See if we have a definitions for the specified function already.
141 dyn_cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
144 Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
145 FunctionList.push_back(New);
146 return New; // Return the new prototype.
149 // Okay, the function exists. Does it have externally visible linkage?
150 if (F->hasInternalLinkage()) {
151 // Rename the function.
152 F->setName(SymTab.getUniqueName(F->getType(), F->getName()));
153 // Retry, now there won't be a conflict.
154 return getOrInsertFunction(Name, Ty);
157 // If the function exists but has the wrong type, return a bitcast to the
159 if (F->getFunctionType() != Ty)
160 return ConstantExpr::getBitCast(F, PointerType::get(Ty));
162 // Otherwise, we just found the existing function or a prototype.
166 // getOrInsertFunction - Look up the specified function in the module symbol
167 // table. If it does not exist, add a prototype for the function and return it.
168 // This version of the method takes a null terminated list of function
169 // arguments, which makes it easier for clients to use.
171 Constant *Module::getOrInsertFunction(const std::string &Name,
172 const Type *RetTy, ...) {
174 va_start(Args, RetTy);
176 // Build the list of argument types...
177 std::vector<const Type*> ArgTys;
178 while (const Type *ArgTy = va_arg(Args, const Type*))
179 ArgTys.push_back(ArgTy);
183 // Build the function type and chain to the other getOrInsertFunction...
184 return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
188 // getFunction - Look up the specified function in the module symbol table.
189 // If it does not exist, return null.
191 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
192 SymbolTable &SymTab = getValueSymbolTable();
193 return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
197 /// getMainFunction - This function looks up main efficiently. This is such a
198 /// common case, that it is a method in Module. If main cannot be found, a
199 /// null pointer is returned.
201 Function *Module::getMainFunction() {
202 std::vector<const Type*> Params;
205 if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
209 // void main(void)...
210 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
214 Params.push_back(Type::Int32Ty);
216 // int main(int argc)...
217 if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
221 // void main(int argc)...
222 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
226 for (unsigned i = 0; i != 2; ++i) { // Check argv and envp
227 Params.push_back(PointerType::get(PointerType::get(Type::Int8Ty)));
229 // int main(int argc, char **argv)...
230 if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
234 // void main(int argc, char **argv)...
235 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
240 // Ok, try to find main the hard way...
241 return getNamedFunction("main");
244 /// getNamedFunction - Return the first function in the module with the
245 /// specified name, of arbitrary type. This method returns null if a function
246 /// with the specified name is not found.
248 Function *Module::getNamedFunction(const std::string &Name) const {
249 // Loop over all of the functions, looking for the function desired
250 const Function *Found = 0;
251 for (const_iterator I = begin(), E = end(); I != E; ++I)
252 if (I->getName() == Name)
256 return const_cast<Function*>(&(*I));
257 return const_cast<Function*>(Found); // Non-external function not found...
260 //===----------------------------------------------------------------------===//
261 // Methods for easy access to the global variables in the module.
264 /// getGlobalVariable - Look up the specified global variable in the module
265 /// symbol table. If it does not exist, return null. The type argument
266 /// should be the underlying type of the global, i.e., it should not have
267 /// the top-level PointerType, which represents the address of the global.
268 /// If AllowInternal is set to true, this function will return types that
269 /// have InternalLinkage. By default, these types are not returned.
271 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
272 const Type *Ty, bool AllowInternal) {
273 if (Value *V = getValueSymbolTable().lookup(PointerType::get(Ty), Name)) {
274 GlobalVariable *Result = cast<GlobalVariable>(V);
275 if (AllowInternal || !Result->hasInternalLinkage())
281 /// getNamedGlobal - Return the first global variable in the module with the
282 /// specified name, of arbitrary type. This method returns null if a global
283 /// with the specified name is not found.
285 GlobalVariable *Module::getNamedGlobal(const std::string &Name) const {
286 // FIXME: This would be much faster with a symbol table that doesn't
287 // discriminate based on type!
288 for (const_global_iterator I = global_begin(), E = global_end();
290 if (I->getName() == Name)
291 return const_cast<GlobalVariable*>(&(*I));
297 //===----------------------------------------------------------------------===//
298 // Methods for easy access to the types in the module.
302 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
303 // there is already an entry for this name, true is returned and the symbol
304 // table is not modified.
306 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
307 TypeSymbolTable &ST = getTypeSymbolTable();
309 if (ST.lookup(Name)) return true; // Already in symtab...
311 // Not in symbol table? Set the name with the Symtab as an argument so the
312 // type knows what to update...
318 /// getTypeByName - Return the type with the specified name in this module, or
319 /// null if there is none by that name.
320 const Type *Module::getTypeByName(const std::string &Name) const {
321 const TypeSymbolTable &ST = getTypeSymbolTable();
322 return cast_or_null<Type>(ST.lookup(Name));
325 // getTypeName - If there is at least one entry in the symbol table for the
326 // specified type, return it.
328 std::string Module::getTypeName(const Type *Ty) const {
329 const TypeSymbolTable &ST = getTypeSymbolTable();
331 TypeSymbolTable::const_iterator TI = ST.begin();
332 TypeSymbolTable::const_iterator TE = ST.end();
333 if ( TI == TE ) return ""; // No names for types
335 while (TI != TE && TI->second != Ty)
338 if (TI != TE) // Must have found an entry!
340 return ""; // Must not have found anything...
343 //===----------------------------------------------------------------------===//
344 // Other module related stuff.
348 // dropAllReferences() - This function causes all the subelementss to "let go"
349 // of all references that they are maintaining. This allows one to 'delete' a
350 // whole module at a time, even though there may be circular references... first
351 // all references are dropped, and all use counts go to zero. Then everything
352 // is deleted for real. Note that no operations are valid on an object that
353 // has "dropped all references", except operator delete.
355 void Module::dropAllReferences() {
356 for(Module::iterator I = begin(), E = end(); I != E; ++I)
357 I->dropAllReferences();
359 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
360 I->dropAllReferences();