Reverting back to original 1.8 version so I can manually merge in patch.
[llvm-complete.git] / lib / VMCore / Module.cpp
blob7dcd44ca2e5c526ef59c82b895d4b9041d173310
1 //===-- Module.cpp - Implement the Module class ---------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 <algorithm>
23 #include <cstdarg>
24 #include <cstdlib>
25 #include <iostream>
26 #include <map>
27 using namespace llvm;
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
33 Function *ilist_traits<Function>::createSentinel() {
34 FunctionType *FTy =
35 FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
36 Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
37 // This should not be garbage monitored.
38 LeakDetector::removeGarbageObject(Ret);
39 return Ret;
41 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
42 GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
43 GlobalValue::ExternalLinkage);
44 // This should not be garbage monitored.
45 LeakDetector::removeGarbageObject(Ret);
46 return Ret;
49 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
50 return M->getFunctionList();
52 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
53 return M->getGlobalList();
56 // Explicit instantiations of SymbolTableListTraits since some of the methods
57 // are not in the public header file.
58 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
59 template class SymbolTableListTraits<Function, Module, Module>;
61 //===----------------------------------------------------------------------===//
62 // Primitive Module methods.
65 Module::Module(const std::string &MID)
66 : ModuleID(MID), DataLayout("") {
67 FunctionList.setItemParent(this);
68 FunctionList.setParent(this);
69 GlobalList.setItemParent(this);
70 GlobalList.setParent(this);
71 SymTab = new SymbolTable();
74 Module::~Module() {
75 dropAllReferences();
76 GlobalList.clear();
77 GlobalList.setParent(0);
78 FunctionList.clear();
79 FunctionList.setParent(0);
80 LibraryList.clear();
81 delete SymTab;
84 // Module::dump() - Allow printing from debugger
85 void Module::dump() const {
86 print(std::cerr);
89 /// Target endian information...
90 Module::Endianness Module::getEndianness() const {
91 std::string temp = DataLayout;
92 Module::Endianness ret = AnyEndianness;
94 while (!temp.empty()) {
95 std::string token = getToken(temp, "-");
97 if (token[0] == 'e') {
98 ret = LittleEndian;
99 } else if (token[0] == 'E') {
100 ret = BigEndian;
104 return ret;
107 void Module::setEndianness(Endianness E) {
108 if (!DataLayout.empty() && E != AnyEndianness)
109 DataLayout += "-";
111 if (E == LittleEndian)
112 DataLayout += "e";
113 else if (E == BigEndian)
114 DataLayout += "E";
117 /// Target Pointer Size information...
118 Module::PointerSize Module::getPointerSize() const {
119 std::string temp = DataLayout;
120 Module::PointerSize ret = AnyPointerSize;
122 while (!temp.empty()) {
123 std::string token = getToken(temp, "-");
124 char signal = getToken(token, ":")[0];
126 if (signal == 'p') {
127 int size = atoi(getToken(token, ":").c_str());
128 if (size == 32)
129 ret = Pointer32;
130 else if (size == 64)
131 ret = Pointer64;
135 return ret;
138 void Module::setPointerSize(PointerSize PS) {
139 if (!DataLayout.empty() && PS != AnyPointerSize)
140 DataLayout += "-";
142 if (PS == Pointer32)
143 DataLayout += "p:32:32";
144 else if (PS == Pointer64)
145 DataLayout += "p:64:64";
148 //===----------------------------------------------------------------------===//
149 // Methods for easy access to the functions in the module.
152 // getOrInsertFunction - Look up the specified function in the module symbol
153 // table. If it does not exist, add a prototype for the function and return
154 // it. This is nice because it allows most passes to get away with not handling
155 // the symbol table directly for this common task.
157 Function *Module::getOrInsertFunction(const std::string &Name,
158 const FunctionType *Ty) {
159 SymbolTable &SymTab = getSymbolTable();
161 // See if we have a definitions for the specified function already...
162 if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
163 return cast<Function>(V); // Yup, got it
164 } else { // Nope, add one
165 Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
166 FunctionList.push_back(New);
167 return New; // Return the new prototype...
171 // getOrInsertFunction - Look up the specified function in the module symbol
172 // table. If it does not exist, add a prototype for the function and return it.
173 // This version of the method takes a null terminated list of function
174 // arguments, which makes it easier for clients to use.
176 Function *Module::getOrInsertFunction(const std::string &Name,
177 const Type *RetTy, ...) {
178 va_list Args;
179 va_start(Args, RetTy);
181 // Build the list of argument types...
182 std::vector<const Type*> ArgTys;
183 while (const Type *ArgTy = va_arg(Args, const Type*))
184 ArgTys.push_back(ArgTy);
186 va_end(Args);
188 // Build the function type and chain to the other getOrInsertFunction...
189 return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
193 // getFunction - Look up the specified function in the module symbol table.
194 // If it does not exist, return null.
196 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
197 SymbolTable &SymTab = getSymbolTable();
198 return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
202 /// getMainFunction - This function looks up main efficiently. This is such a
203 /// common case, that it is a method in Module. If main cannot be found, a
204 /// null pointer is returned.
206 Function *Module::getMainFunction() {
207 std::vector<const Type*> Params;
209 // int main(void)...
210 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
211 Params, false)))
212 return F;
214 // void main(void)...
215 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
216 Params, false)))
217 return F;
219 Params.push_back(Type::IntTy);
221 // int main(int argc)...
222 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
223 Params, false)))
224 return F;
226 // void main(int argc)...
227 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
228 Params, false)))
229 return F;
231 for (unsigned i = 0; i != 2; ++i) { // Check argv and envp
232 Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
234 // int main(int argc, char **argv)...
235 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
236 Params, false)))
237 return F;
239 // void main(int argc, char **argv)...
240 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
241 Params, false)))
242 return F;
245 // Ok, try to find main the hard way...
246 return getNamedFunction("main");
249 /// getNamedFunction - Return the first function in the module with the
250 /// specified name, of arbitrary type. This method returns null if a function
251 /// with the specified name is not found.
253 Function *Module::getNamedFunction(const std::string &Name) const {
254 // Loop over all of the functions, looking for the function desired
255 const Function *Found = 0;
256 for (const_iterator I = begin(), E = end(); I != E; ++I)
257 if (I->getName() == Name)
258 if (I->isExternal())
259 Found = I;
260 else
261 return const_cast<Function*>(&(*I));
262 return const_cast<Function*>(Found); // Non-external function not found...
265 //===----------------------------------------------------------------------===//
266 // Methods for easy access to the global variables in the module.
269 /// getGlobalVariable - Look up the specified global variable in the module
270 /// symbol table. If it does not exist, return null. The type argument
271 /// should be the underlying type of the global, i.e., it should not have
272 /// the top-level PointerType, which represents the address of the global.
273 /// If AllowInternal is set to true, this function will return types that
274 /// have InternalLinkage. By default, these types are not returned.
276 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
277 const Type *Ty, bool AllowInternal) {
278 if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
279 GlobalVariable *Result = cast<GlobalVariable>(V);
280 if (AllowInternal || !Result->hasInternalLinkage())
281 return Result;
283 return 0;
286 /// getNamedGlobal - Return the first global variable in the module with the
287 /// specified name, of arbitrary type. This method returns null if a global
288 /// with the specified name is not found.
290 GlobalVariable *Module::getNamedGlobal(const std::string &Name) const {
291 // FIXME: This would be much faster with a symbol table that doesn't
292 // discriminate based on type!
293 for (const_global_iterator I = global_begin(), E = global_end();
294 I != E; ++I)
295 if (I->getName() == Name)
296 return const_cast<GlobalVariable*>(&(*I));
297 return 0;
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 SymbolTable &ST = getSymbolTable();
314 if (ST.lookupType(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...
318 ST.insert(Name, Ty);
320 return false;
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 SymbolTable &ST = getSymbolTable();
327 return cast_or_null<Type>(ST.lookupType(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 SymbolTable &ST = getSymbolTable();
336 SymbolTable::type_const_iterator TI = ST.type_begin();
337 SymbolTable::type_const_iterator TE = ST.type_end();
338 if ( TI == TE ) return ""; // No names for types
340 while (TI != TE && TI->second != Ty)
341 ++TI;
343 if (TI != TE) // Must have found an entry!
344 return TI->first;
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();