Convert to SymbolTable's new lookup and iteration interfaces.
[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 "Support/STLExtras.h"
19 #include "Support/LeakDetector.h"
20 #include "SymbolTableListTraitsImpl.h"
21 #include <algorithm>
22 #include <cstdarg>
23 #include <map>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // Methods to implement the globals and functions lists.
28 //
29
30 Function *ilist_traits<Function>::createNode() {
31   FunctionType *FTy =
32     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
33   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
34   // This should not be garbage monitored.
35   LeakDetector::removeGarbageObject(Ret);
36   return Ret;
37 }
38 GlobalVariable *ilist_traits<GlobalVariable>::createNode() {
39   GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
40                                            GlobalValue::ExternalLinkage);
41   // This should not be garbage monitored.
42   LeakDetector::removeGarbageObject(Ret);
43   return Ret;
44 }
45
46 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
47   return M->getFunctionList();
48 }
49 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
50   return M->getGlobalList();
51 }
52
53 // Explicit instantiations of SymbolTableListTraits since some of the methods
54 // are not in the public header file...
55 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
56 template class SymbolTableListTraits<Function, Module, Module>;
57
58 // Define the GlobalValueRefMap as a struct that wraps a map so that we don't
59 // have Module.h depend on <map>
60 //
61 namespace llvm {
62   struct GlobalValueRefMap {
63     typedef std::map<GlobalValue*, ConstantPointerRef*> MapTy;
64     typedef MapTy::iterator iterator;
65     std::map<GlobalValue*, ConstantPointerRef*> Map;
66   };
67 }
68
69 //===----------------------------------------------------------------------===//
70 // Primitive Module methods.
71 //
72
73 Module::Module(const std::string &MID)
74   : ModuleID(MID), Endian(AnyEndianness), PtrSize(AnyPointerSize) {
75   FunctionList.setItemParent(this);
76   FunctionList.setParent(this);
77   GlobalList.setItemParent(this);
78   GlobalList.setParent(this);
79   GVRefMap = 0;
80   SymTab = new SymbolTable();
81 }
82
83 Module::~Module() {
84   dropAllReferences();
85   GlobalList.clear();
86   GlobalList.setParent(0);
87   FunctionList.clear();
88   FunctionList.setParent(0);
89   delete SymTab;
90 }
91
92 // Module::dump() - Allow printing from debugger
93 void Module::dump() const {
94   print(std::cerr);
95 }
96
97 //===----------------------------------------------------------------------===//
98 // Methods for easy access to the functions in the module.
99 //
100
101 // getOrInsertFunction - Look up the specified function in the module symbol
102 // table.  If it does not exist, add a prototype for the function and return
103 // it.  This is nice because it allows most passes to get away with not handling
104 // the symbol table directly for this common task.
105 //
106 Function *Module::getOrInsertFunction(const std::string &Name,
107                                       const FunctionType *Ty) {
108   SymbolTable &SymTab = getSymbolTable();
109
110   // See if we have a definitions for the specified function already...
111   if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
112     return cast<Function>(V);      // Yup, got it
113   } else {                         // Nope, add one
114     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
115     FunctionList.push_back(New);
116     return New;                    // Return the new prototype...
117   }
118 }
119
120 // getOrInsertFunction - Look up the specified function in the module symbol
121 // table.  If it does not exist, add a prototype for the function and return it.
122 // This version of the method takes a null terminated list of function
123 // arguments, which makes it easier for clients to use.
124 //
125 Function *Module::getOrInsertFunction(const std::string &Name,
126                                       const Type *RetTy, ...) {
127   va_list Args;
128   va_start(Args, RetTy);
129
130   // Build the list of argument types...
131   std::vector<const Type*> ArgTys;
132   while (const Type *ArgTy = va_arg(Args, const Type*))
133     ArgTys.push_back(ArgTy);
134
135   va_end(Args);
136
137   // Build the function type and chain to the other getOrInsertFunction...
138   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
139 }
140
141
142 // getFunction - Look up the specified function in the module symbol table.
143 // If it does not exist, return null.
144 //
145 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
146   SymbolTable &SymTab = getSymbolTable();
147   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
148 }
149
150
151 /// getMainFunction - This function looks up main efficiently.  This is such a
152 /// common case, that it is a method in Module.  If main cannot be found, a
153 /// null pointer is returned.
154 ///
155 Function *Module::getMainFunction() {
156   std::vector<const Type*> Params;
157
158   // int main(void)...
159   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
160                                                           Params, false)))
161     return F;
162
163   // void main(void)...
164   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
165                                                           Params, false)))
166     return F;
167
168   Params.push_back(Type::IntTy);
169
170   // int main(int argc)...
171   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
172                                                           Params, false)))
173     return F;
174
175   // void main(int argc)...
176   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
177                                                           Params, false)))
178     return F;
179
180   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
181     Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
182
183     // int main(int argc, char **argv)...
184     if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
185                                                             Params, false)))
186       return F;
187     
188     // void main(int argc, char **argv)...
189     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
190                                                             Params, false)))
191       return F;
192   }
193
194   // Ok, try to find main the hard way...
195   return getNamedFunction("main");
196 }
197
198 /// getNamedFunction - Return the first function in the module with the
199 /// specified name, of arbitrary type.  This method returns null if a function
200 /// with the specified name is not found.
201 ///
202 Function *Module::getNamedFunction(const std::string &Name) {
203   // Loop over all of the functions, looking for the function desired
204   Function *Found = 0;
205   for (iterator I = begin(), E = end(); I != E; ++I)
206     if (I->getName() == Name)
207       if (I->isExternal())
208         Found = I;
209       else
210         return I;
211   return Found; // Non-external function not found...
212 }
213
214 //===----------------------------------------------------------------------===//
215 // Methods for easy access to the global variables in the module.
216 //
217
218 /// getGlobalVariable - Look up the specified global variable in the module
219 /// symbol table.  If it does not exist, return null.  Note that this only
220 /// returns a global variable if it does not have internal linkage.  The type
221 /// argument should be the underlying type of the global, ie, it should not
222 /// have the top-level PointerType, which represents the address of the
223 /// global.
224 ///
225 GlobalVariable *Module::getGlobalVariable(const std::string &Name, 
226                                           const Type *Ty) {
227   if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
228     GlobalVariable *Result = cast<GlobalVariable>(V);
229     if (!Result->hasInternalLinkage())
230       return Result;
231   }
232   return 0;
233 }
234
235
236
237 //===----------------------------------------------------------------------===//
238 // Methods for easy access to the types in the module.
239 //
240
241
242 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
243 // there is already an entry for this name, true is returned and the symbol
244 // table is not modified.
245 //
246 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
247   SymbolTable &ST = getSymbolTable();
248
249   if (ST.lookupType(Name)) return true;  // Already in symtab...
250   
251   // Not in symbol table?  Set the name with the Symtab as an argument so the
252   // type knows what to update...
253   ((Value*)Ty)->setName(Name, &ST);
254
255   return false;
256 }
257
258 /// getTypeByName - Return the type with the specified name in this module, or
259 /// null if there is none by that name.
260 const Type *Module::getTypeByName(const std::string &Name) const {
261   const SymbolTable &ST = getSymbolTable();
262   return cast_or_null<Type>(ST.lookupType(Name));
263 }
264
265 // getTypeName - If there is at least one entry in the symbol table for the
266 // specified type, return it.
267 //
268 std::string Module::getTypeName(const Type *Ty) const {
269   const SymbolTable &ST = getSymbolTable();
270
271   SymbolTable::type_const_iterator TI = ST.type_begin();
272   SymbolTable::type_const_iterator TE = ST.type_end();
273   if ( TI == TE ) return ""; // No names for types
274
275   while (TI != TE && TI->second != Ty)
276     ++TI;
277
278   if (TI != TE)  // Must have found an entry!
279     return TI->first;
280   return "";     // Must not have found anything...
281 }
282
283
284 //===----------------------------------------------------------------------===//
285 // Other module related stuff.
286 //
287
288
289 // dropAllReferences() - This function causes all the subelementss to "let go"
290 // of all references that they are maintaining.  This allows one to 'delete' a
291 // whole module at a time, even though there may be circular references... first
292 // all references are dropped, and all use counts go to zero.  Then everything
293 // is deleted for real.  Note that no operations are valid on an object that
294 // has "dropped all references", except operator delete.
295 //
296 void Module::dropAllReferences() {
297   for(Module::iterator I = begin(), E = end(); I != E; ++I)
298     I->dropAllReferences();
299
300   for(Module::giterator I = gbegin(), E = gend(); I != E; ++I)
301     I->dropAllReferences();
302
303   // If there are any GlobalVariable references still out there, nuke them now.
304   // Since all references are hereby dropped, nothing could possibly reference
305   // them still.  Note that destroying all of the constant pointer refs will
306   // eventually cause the GVRefMap field to be set to null (by
307   // destroyConstantPointerRef, below).
308   //
309   while (GVRefMap)
310     // Delete the ConstantPointerRef node...  
311     GVRefMap->Map.begin()->second->destroyConstant();
312 }
313
314 // Accessor for the underlying GlobalValRefMap...
315 ConstantPointerRef *Module::getConstantPointerRef(GlobalValue *V){
316   // Create ref map lazily on demand...
317   if (GVRefMap == 0) GVRefMap = new GlobalValueRefMap();
318
319   GlobalValueRefMap::iterator I = GVRefMap->Map.find(V);
320   if (I != GVRefMap->Map.end()) return I->second;
321
322   ConstantPointerRef *Ref = new ConstantPointerRef(V);
323   GVRefMap->Map[V] = Ref;
324   return Ref;
325 }
326
327 void Module::destroyConstantPointerRef(ConstantPointerRef *CPR) {
328   assert(GVRefMap && "No map allocated, but we have a CPR?");
329   if (!GVRefMap->Map.erase(CPR->getValue()))  // Remove it from the map...
330     assert(0 && "ConstantPointerRef not found in module CPR map!");
331   
332   if (GVRefMap->Map.empty()) {   // If the map is empty, delete it.
333     delete GVRefMap;
334     GVRefMap = 0;
335   }
336 }