Removing even more <iostream> includes.
[oota-llvm.git] / lib / VMCore / Module.cpp
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.
11 //
12 //===----------------------------------------------------------------------===//
13
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 <map>
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 // Methods to implement the globals and functions lists.
30 //
31
32 Function *ilist_traits<Function>::createSentinel() {
33   FunctionType *FTy =
34     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
35   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
36   // This should not be garbage monitored.
37   LeakDetector::removeGarbageObject(Ret);
38   return Ret;
39 }
40 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
41   GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
42                                            GlobalValue::ExternalLinkage);
43   // This should not be garbage monitored.
44   LeakDetector::removeGarbageObject(Ret);
45   return Ret;
46 }
47
48 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
49   return M->getFunctionList();
50 }
51 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
52   return M->getGlobalList();
53 }
54
55 // Explicit instantiations of SymbolTableListTraits since some of the methods
56 // are not in the public header file.
57 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
58 template class SymbolTableListTraits<Function, Module, Module>;
59
60 //===----------------------------------------------------------------------===//
61 // Primitive Module methods.
62 //
63
64 Module::Module(const std::string &MID)
65   : ModuleID(MID), DataLayout("") {
66   FunctionList.setItemParent(this);
67   FunctionList.setParent(this);
68   GlobalList.setItemParent(this);
69   GlobalList.setParent(this);
70   SymTab = new SymbolTable();
71 }
72
73 Module::~Module() {
74   dropAllReferences();
75   GlobalList.clear();
76   GlobalList.setParent(0);
77   FunctionList.clear();
78   FunctionList.setParent(0);
79   LibraryList.clear();
80   delete SymTab;
81 }
82
83 // Module::dump() - Allow printing from debugger
84 void Module::dump() const {
85   print(*cerr.stream());
86 }
87
88 /// Target endian information...
89 Module::Endianness Module::getEndianness() const {
90   std::string temp = DataLayout;
91   Module::Endianness ret = AnyEndianness;
92   
93   while (!temp.empty()) {
94     std::string token = getToken(temp, "-");
95     
96     if (token[0] == 'e') {
97       ret = LittleEndian;
98     } else if (token[0] == 'E') {
99       ret = BigEndian;
100     }
101   }
102   
103   return ret;
104 }
105
106 void Module::setEndianness(Endianness E) {
107   if (!DataLayout.empty() && E != AnyEndianness)
108     DataLayout += "-";
109   
110   if (E == LittleEndian)
111     DataLayout += "e";
112   else if (E == BigEndian)
113     DataLayout += "E";
114 }
115
116 /// Target Pointer Size information...
117 Module::PointerSize Module::getPointerSize() const {
118   std::string temp = DataLayout;
119   Module::PointerSize ret = AnyPointerSize;
120   
121   while (!temp.empty()) {
122     std::string token = getToken(temp, "-");
123     char signal = getToken(token, ":")[0];
124     
125     if (signal == 'p') {
126       int size = atoi(getToken(token, ":").c_str());
127       if (size == 32)
128         ret = Pointer32;
129       else if (size == 64)
130         ret = Pointer64;
131     }
132   }
133   
134   return ret;
135 }
136
137 void Module::setPointerSize(PointerSize PS) {
138   if (!DataLayout.empty() && PS != AnyPointerSize)
139     DataLayout += "-";
140   
141   if (PS == Pointer32)
142     DataLayout += "p:32:32";
143   else if (PS == Pointer64)
144     DataLayout += "p:64:64";
145 }
146
147 //===----------------------------------------------------------------------===//
148 // Methods for easy access to the functions in the module.
149 //
150
151 // getOrInsertFunction - Look up the specified function in the module symbol
152 // table.  If it does not exist, add a prototype for the function and return
153 // it.  This is nice because it allows most passes to get away with not handling
154 // the symbol table directly for this common task.
155 //
156 Function *Module::getOrInsertFunction(const std::string &Name,
157                                       const FunctionType *Ty) {
158   SymbolTable &SymTab = getSymbolTable();
159
160   // See if we have a definitions for the specified function already...
161   if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
162     return cast<Function>(V);      // Yup, got it
163   } else {                         // Nope, add one
164     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
165     FunctionList.push_back(New);
166     return New;                    // Return the new prototype...
167   }
168 }
169
170 // getOrInsertFunction - Look up the specified function in the module symbol
171 // table.  If it does not exist, add a prototype for the function and return it.
172 // This version of the method takes a null terminated list of function
173 // arguments, which makes it easier for clients to use.
174 //
175 Function *Module::getOrInsertFunction(const std::string &Name,
176                                       const Type *RetTy, ...) {
177   va_list Args;
178   va_start(Args, RetTy);
179
180   // Build the list of argument types...
181   std::vector<const Type*> ArgTys;
182   while (const Type *ArgTy = va_arg(Args, const Type*))
183     ArgTys.push_back(ArgTy);
184
185   va_end(Args);
186
187   // Build the function type and chain to the other getOrInsertFunction...
188   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
189 }
190
191
192 // getFunction - Look up the specified function in the module symbol table.
193 // If it does not exist, return null.
194 //
195 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
196   SymbolTable &SymTab = getSymbolTable();
197   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
198 }
199
200
201 /// getMainFunction - This function looks up main efficiently.  This is such a
202 /// common case, that it is a method in Module.  If main cannot be found, a
203 /// null pointer is returned.
204 ///
205 Function *Module::getMainFunction() {
206   std::vector<const Type*> Params;
207
208   // int main(void)...
209   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
210                                                           Params, false)))
211     return F;
212
213   // void main(void)...
214   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
215                                                           Params, false)))
216     return F;
217
218   Params.push_back(Type::IntTy);
219
220   // int main(int argc)...
221   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
222                                                           Params, false)))
223     return F;
224
225   // void main(int argc)...
226   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
227                                                           Params, false)))
228     return F;
229
230   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
231     Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
232
233     // int main(int argc, char **argv)...
234     if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
235                                                             Params, false)))
236       return F;
237
238     // void main(int argc, char **argv)...
239     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
240                                                             Params, false)))
241       return F;
242   }
243
244   // Ok, try to find main the hard way...
245   return getNamedFunction("main");
246 }
247
248 /// getNamedFunction - Return the first function in the module with the
249 /// specified name, of arbitrary type.  This method returns null if a function
250 /// with the specified name is not found.
251 ///
252 Function *Module::getNamedFunction(const std::string &Name) const {
253   // Loop over all of the functions, looking for the function desired
254   const Function *Found = 0;
255   for (const_iterator I = begin(), E = end(); I != E; ++I)
256     if (I->getName() == Name)
257       if (I->isExternal())
258         Found = I;
259       else
260         return const_cast<Function*>(&(*I));
261   return const_cast<Function*>(Found); // Non-external function not found...
262 }
263
264 //===----------------------------------------------------------------------===//
265 // Methods for easy access to the global variables in the module.
266 //
267
268 /// getGlobalVariable - Look up the specified global variable in the module
269 /// symbol table.  If it does not exist, return null.  The type argument
270 /// should be the underlying type of the global, i.e., it should not have
271 /// the top-level PointerType, which represents the address of the global.
272 /// If AllowInternal is set to true, this function will return types that
273 /// have InternalLinkage. By default, these types are not returned.
274 ///
275 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
276                                           const Type *Ty, bool AllowInternal) {
277   if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
278     GlobalVariable *Result = cast<GlobalVariable>(V);
279     if (AllowInternal || !Result->hasInternalLinkage())
280       return Result;
281   }
282   return 0;
283 }
284
285 /// getNamedGlobal - Return the first global variable in the module with the
286 /// specified name, of arbitrary type.  This method returns null if a global
287 /// with the specified name is not found.
288 ///
289 GlobalVariable *Module::getNamedGlobal(const std::string &Name) const {
290   // FIXME: This would be much faster with a symbol table that doesn't
291   // discriminate based on type!
292   for (const_global_iterator I = global_begin(), E = global_end();
293        I != E; ++I)
294     if (I->getName() == Name) 
295       return const_cast<GlobalVariable*>(&(*I));
296   return 0;
297 }
298
299
300
301 //===----------------------------------------------------------------------===//
302 // Methods for easy access to the types in the module.
303 //
304
305
306 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
307 // there is already an entry for this name, true is returned and the symbol
308 // table is not modified.
309 //
310 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
311   SymbolTable &ST = getSymbolTable();
312
313   if (ST.lookupType(Name)) return true;  // Already in symtab...
314
315   // Not in symbol table?  Set the name with the Symtab as an argument so the
316   // type knows what to update...
317   ST.insert(Name, Ty);
318
319   return false;
320 }
321
322 /// getTypeByName - Return the type with the specified name in this module, or
323 /// null if there is none by that name.
324 const Type *Module::getTypeByName(const std::string &Name) const {
325   const SymbolTable &ST = getSymbolTable();
326   return cast_or_null<Type>(ST.lookupType(Name));
327 }
328
329 // getTypeName - If there is at least one entry in the symbol table for the
330 // specified type, return it.
331 //
332 std::string Module::getTypeName(const Type *Ty) const {
333   const SymbolTable &ST = getSymbolTable();
334
335   SymbolTable::type_const_iterator TI = ST.type_begin();
336   SymbolTable::type_const_iterator TE = ST.type_end();
337   if ( TI == TE ) return ""; // No names for types
338
339   while (TI != TE && TI->second != Ty)
340     ++TI;
341
342   if (TI != TE)  // Must have found an entry!
343     return TI->first;
344   return "";     // Must not have found anything...
345 }
346
347 //===----------------------------------------------------------------------===//
348 // Other module related stuff.
349 //
350
351
352 // dropAllReferences() - This function causes all the subelementss to "let go"
353 // of all references that they are maintaining.  This allows one to 'delete' a
354 // whole module at a time, even though there may be circular references... first
355 // all references are dropped, and all use counts go to zero.  Then everything
356 // is deleted for real.  Note that no operations are valid on an object that
357 // has "dropped all references", except operator delete.
358 //
359 void Module::dropAllReferences() {
360   for(Module::iterator I = begin(), E = end(); I != E; ++I)
361     I->dropAllReferences();
362
363   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
364     I->dropAllReferences();
365 }
366