Add new linkage types to support a real frontend
[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() {
56   FunctionList.setItemParent(this);
57   FunctionList.setParent(this);
58   GlobalList.setItemParent(this);
59   GlobalList.setParent(this);
60   GVRefMap = 0;
61   SymTab = new SymbolTable();
62 }
63
64 Module::~Module() {
65   dropAllReferences();
66   GlobalList.clear();
67   GlobalList.setParent(0);
68   FunctionList.clear();
69   FunctionList.setParent(0);
70   delete SymTab;
71 }
72
73 // Module::dump() - Allow printing from debugger
74 void Module::dump() const {
75   print(std::cerr);
76 }
77
78 // getOrInsertFunction - Look up the specified function in the module symbol
79 // table.  If it does not exist, add a prototype for the function and return
80 // it.  This is nice because it allows most passes to get away with not handling
81 // the symbol table directly for this common task.
82 //
83 Function *Module::getOrInsertFunction(const std::string &Name,
84                                       const FunctionType *Ty) {
85   SymbolTable &SymTab = getSymbolTable();
86
87   // See if we have a definitions for the specified function already...
88   if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
89     return cast<Function>(V);      // Yup, got it
90   } else {                         // Nope, add one
91     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
92     FunctionList.push_back(New);
93     return New;                    // Return the new prototype...
94   }
95 }
96
97 // getFunction - Look up the specified function in the module symbol table.
98 // If it does not exist, return null.
99 //
100 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
101   SymbolTable &SymTab = getSymbolTable();
102   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
103 }
104
105 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
106 // there is already an entry for this name, true is returned and the symbol
107 // table is not modified.
108 //
109 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
110   SymbolTable &ST = getSymbolTable();
111
112   if (ST.lookup(Type::TypeTy, Name)) return true;  // Already in symtab...
113   
114   // Not in symbol table?  Set the name with the Symtab as an argument so the
115   // type knows what to update...
116   ((Value*)Ty)->setName(Name, &ST);
117
118   return false;
119 }
120
121 /// getMainFunction - This function looks up main efficiently.  This is such a
122 /// common case, that it is a method in Module.  If main cannot be found, a
123 /// null pointer is returned.
124 ///
125 Function *Module::getMainFunction() {
126   std::vector<const Type*> Params;
127
128   // int main(void)...
129   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
130                                                           Params, false)))
131     return F;
132
133   // void main(void)...
134   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
135                                                           Params, false)))
136     return F;
137
138   Params.push_back(Type::IntTy);
139
140   // int main(int argc)...
141   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
142                                                           Params, false)))
143     return F;
144
145   // void main(int argc)...
146   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
147                                                           Params, false)))
148     return F;
149
150   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
151     Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
152
153     // int main(int argc, char **argv)...
154     if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
155                                                             Params, false)))
156       return F;
157     
158     // void main(int argc, char **argv)...
159     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
160                                                             Params, false)))
161       return F;
162   }
163
164   // Ok, try to find main the hard way...
165   return getNamedFunction("main");
166 }
167
168 /// getNamedFunction - Return the first function in the module with the
169 /// specified name, of arbitrary type.  This method returns null if a function
170 /// with the specified name is not found.
171 ///
172 Function *Module::getNamedFunction(const std::string &Name) {
173   // Loop over all of the functions, looking for the function desired
174   for (iterator I = begin(), E = end(); I != E; ++I)
175     if (I->getName() == Name)
176       return I;
177   return 0; // function not found...
178 }
179
180
181
182 // getTypeName - If there is at least one entry in the symbol table for the
183 // specified type, return it.
184 //
185 std::string Module::getTypeName(const Type *Ty) {
186   const SymbolTable &ST = getSymbolTable();
187   if (ST.find(Type::TypeTy) == ST.end())
188     return ""; // No names for types...
189
190   SymbolTable::type_const_iterator TI = ST.type_begin(Type::TypeTy);
191   SymbolTable::type_const_iterator TE = ST.type_end(Type::TypeTy);
192
193   while (TI != TE && TI->second != (const Value*)Ty)
194     ++TI;
195
196   if (TI != TE)  // Must have found an entry!
197     return TI->first;
198   return "";     // Must not have found anything...
199 }
200
201
202 // dropAllReferences() - This function causes all the subelementss to "let go"
203 // of all references that they are maintaining.  This allows one to 'delete' a
204 // whole module at a time, even though there may be circular references... first
205 // all references are dropped, and all use counts go to zero.  Then everything
206 // is delete'd for real.  Note that no operations are valid on an object that
207 // has "dropped all references", except operator delete.
208 //
209 void Module::dropAllReferences() {
210   for(Module::iterator I = begin(), E = end(); I != E; ++I)
211     I->dropAllReferences();
212
213   for(Module::giterator I = gbegin(), E = gend(); I != E; ++I)
214     I->dropAllReferences();
215
216   // If there are any GlobalVariable references still out there, nuke them now.
217   // Since all references are hereby dropped, nothing could possibly reference
218   // them still.  Note that destroying all of the constant pointer refs will
219   // eventually cause the GVRefMap field to be set to null (by
220   // destroyConstantPointerRef, below).
221   //
222   while (GVRefMap)
223     // Delete the ConstantPointerRef node...  
224     GVRefMap->Map.begin()->second->destroyConstant();
225 }
226
227 // Accessor for the underlying GlobalValRefMap...
228 ConstantPointerRef *Module::getConstantPointerRef(GlobalValue *V){
229   // Create ref map lazily on demand...
230   if (GVRefMap == 0) GVRefMap = new GlobalValueRefMap();
231
232   GlobalValueRefMap::iterator I = GVRefMap->Map.find(V);
233   if (I != GVRefMap->Map.end()) return I->second;
234
235   ConstantPointerRef *Ref = new ConstantPointerRef(V);
236   GVRefMap->Map[V] = Ref;
237   return Ref;
238 }
239
240 void Module::destroyConstantPointerRef(ConstantPointerRef *CPR) {
241   assert(GVRefMap && "No map allocated, but we have a CPR?");
242   if (!GVRefMap->Map.erase(CPR->getValue()))  // Remove it from the map...
243     assert(0 && "ConstantPointerRef not found in module CPR map!");
244   
245   if (GVRefMap->Map.empty()) {   // If the map is empty, delete it.
246     delete GVRefMap;
247     GVRefMap = 0;
248   }
249 }
250
251 void Module::mutateConstantPointerRef(GlobalValue *OldGV, GlobalValue *NewGV) {
252   GlobalValueRefMap::iterator I = GVRefMap->Map.find(OldGV);
253   assert(I != GVRefMap->Map.end() && 
254          "mutateConstantPointerRef; OldGV not in table!");
255   ConstantPointerRef *Ref = I->second;
256
257   // Remove the old entry...
258   GVRefMap->Map.erase(I);
259
260   // Insert the new entry...
261   GVRefMap->Map.insert(std::make_pair(NewGV, Ref));
262 }