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