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