Refactor SymbolTableListTraits to only have a single pointer in it, instead
[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 "llvm/TypeSymbolTable.h"
23 #include <algorithm>
24 #include <cstdarg>
25 #include <cstdlib>
26 #include <map>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
31 //
32
33 Function *ilist_traits<Function>::createSentinel() {
34   FunctionType *FTy =
35     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
36   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
37   // This should not be garbage monitored.
38   LeakDetector::removeGarbageObject(Ret);
39   return Ret;
40 }
41 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
42   GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
43                                            GlobalValue::ExternalLinkage);
44   // This should not be garbage monitored.
45   LeakDetector::removeGarbageObject(Ret);
46   return Ret;
47 }
48
49 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
50   return M->getFunctionList();
51 }
52 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
53   return M->getGlobalList();
54 }
55
56 // Explicit instantiations of SymbolTableListTraits since some of the methods
57 // are not in the public header file.
58 template class SymbolTableListTraits<GlobalVariable, Module>;
59 template class SymbolTableListTraits<Function, Module>;
60
61 //===----------------------------------------------------------------------===//
62 // Primitive Module methods.
63 //
64
65 Module::Module(const std::string &MID)
66   : ModuleID(MID), DataLayout("") {
67   FunctionList.setItemParent(this);
68   GlobalList.setItemParent(this);
69   ValSymTab = new ValueSymbolTable();
70   TypeSymTab = new TypeSymbolTable();
71 }
72
73 Module::~Module() {
74   dropAllReferences();
75   GlobalList.clear();
76   FunctionList.clear();
77   LibraryList.clear();
78   delete ValSymTab;
79   delete TypeSymTab;
80 }
81
82 // Module::dump() - Allow printing from debugger
83 void Module::dump() const {
84   print(*cerr.stream());
85 }
86
87 /// Target endian information...
88 Module::Endianness Module::getEndianness() const {
89   std::string temp = DataLayout;
90   Module::Endianness ret = AnyEndianness;
91   
92   while (!temp.empty()) {
93     std::string token = getToken(temp, "-");
94     
95     if (token[0] == 'e') {
96       ret = LittleEndian;
97     } else if (token[0] == 'E') {
98       ret = BigEndian;
99     }
100   }
101   
102   return ret;
103 }
104
105 /// Target Pointer Size information...
106 Module::PointerSize Module::getPointerSize() const {
107   std::string temp = DataLayout;
108   Module::PointerSize ret = AnyPointerSize;
109   
110   while (!temp.empty()) {
111     std::string token = getToken(temp, "-");
112     char signal = getToken(token, ":")[0];
113     
114     if (signal == 'p') {
115       int size = atoi(getToken(token, ":").c_str());
116       if (size == 32)
117         ret = Pointer32;
118       else if (size == 64)
119         ret = Pointer64;
120     }
121   }
122   
123   return ret;
124 }
125
126 //===----------------------------------------------------------------------===//
127 // Methods for easy access to the functions in the module.
128 //
129
130 // getOrInsertFunction - Look up the specified function in the module symbol
131 // table.  If it does not exist, add a prototype for the function and return
132 // it.  This is nice because it allows most passes to get away with not handling
133 // the symbol table directly for this common task.
134 //
135 Constant *Module::getOrInsertFunction(const std::string &Name,
136                                       const FunctionType *Ty) {
137   ValueSymbolTable &SymTab = getValueSymbolTable();
138
139   // See if we have a definition for the specified function already.
140   GlobalValue *F = dyn_cast_or_null<GlobalValue>(SymTab.lookup(Name));
141   if (F == 0) {
142     // Nope, add it
143     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
144     FunctionList.push_back(New);
145     return New;                    // Return the new prototype.
146   }
147
148   // Okay, the function exists.  Does it have externally visible linkage?
149   if (F->hasInternalLinkage()) {
150     // Rename the function.
151     F->setName(SymTab.getUniqueName(F->getName()));
152     // Retry, now there won't be a conflict.
153     return getOrInsertFunction(Name, Ty);
154   }
155
156   // If the function exists but has the wrong type, return a bitcast to the
157   // right type.
158   if (F->getType() != PointerType::get(Ty))
159     return ConstantExpr::getBitCast(F, PointerType::get(Ty));
160   
161   // Otherwise, we just found the existing function or a prototype.
162   return F;  
163 }
164
165 // getOrInsertFunction - Look up the specified function in the module symbol
166 // table.  If it does not exist, add a prototype for the function and return it.
167 // This version of the method takes a null terminated list of function
168 // arguments, which makes it easier for clients to use.
169 //
170 Constant *Module::getOrInsertFunction(const std::string &Name,
171                                       const Type *RetTy, ...) {
172   va_list Args;
173   va_start(Args, RetTy);
174
175   // Build the list of argument types...
176   std::vector<const Type*> ArgTys;
177   while (const Type *ArgTy = va_arg(Args, const Type*))
178     ArgTys.push_back(ArgTy);
179
180   va_end(Args);
181
182   // Build the function type and chain to the other getOrInsertFunction...
183   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
184 }
185
186
187 // getFunction - Look up the specified function in the module symbol table.
188 // If it does not exist, return null.
189 //
190 Function *Module::getFunction(const std::string &Name) const {
191   const ValueSymbolTable &SymTab = getValueSymbolTable();
192   return dyn_cast_or_null<Function>(SymTab.lookup(Name));
193 }
194
195 //===----------------------------------------------------------------------===//
196 // Methods for easy access to the global variables in the module.
197 //
198
199 /// getGlobalVariable - Look up the specified global variable in the module
200 /// symbol table.  If it does not exist, return null.  The type argument
201 /// should be the underlying type of the global, i.e., it should not have
202 /// the top-level PointerType, which represents the address of the global.
203 /// If AllowInternal is set to true, this function will return types that
204 /// have InternalLinkage. By default, these types are not returned.
205 ///
206 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
207                                           bool AllowInternal) const {
208   if (Value *V = ValSymTab->lookup(Name)) {
209     GlobalVariable *Result = dyn_cast<GlobalVariable>(V);
210     if (Result && (AllowInternal || !Result->hasInternalLinkage()))
211       return Result;
212   }
213   return 0;
214 }
215
216 //===----------------------------------------------------------------------===//
217 // Methods for easy access to the types in the module.
218 //
219
220
221 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
222 // there is already an entry for this name, true is returned and the symbol
223 // table is not modified.
224 //
225 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
226   TypeSymbolTable &ST = getTypeSymbolTable();
227
228   if (ST.lookup(Name)) return true;  // Already in symtab...
229
230   // Not in symbol table?  Set the name with the Symtab as an argument so the
231   // type knows what to update...
232   ST.insert(Name, Ty);
233
234   return false;
235 }
236
237 /// getTypeByName - Return the type with the specified name in this module, or
238 /// null if there is none by that name.
239 const Type *Module::getTypeByName(const std::string &Name) const {
240   const TypeSymbolTable &ST = getTypeSymbolTable();
241   return cast_or_null<Type>(ST.lookup(Name));
242 }
243
244 // getTypeName - If there is at least one entry in the symbol table for the
245 // specified type, return it.
246 //
247 std::string Module::getTypeName(const Type *Ty) const {
248   const TypeSymbolTable &ST = getTypeSymbolTable();
249
250   TypeSymbolTable::const_iterator TI = ST.begin();
251   TypeSymbolTable::const_iterator TE = ST.end();
252   if ( TI == TE ) return ""; // No names for types
253
254   while (TI != TE && TI->second != Ty)
255     ++TI;
256
257   if (TI != TE)  // Must have found an entry!
258     return TI->first;
259   return "";     // Must not have found anything...
260 }
261
262 //===----------------------------------------------------------------------===//
263 // Other module related stuff.
264 //
265
266
267 // dropAllReferences() - This function causes all the subelementss to "let go"
268 // of all references that they are maintaining.  This allows one to 'delete' a
269 // whole module at a time, even though there may be circular references... first
270 // all references are dropped, and all use counts go to zero.  Then everything
271 // is deleted for real.  Note that no operations are valid on an object that
272 // has "dropped all references", except operator delete.
273 //
274 void Module::dropAllReferences() {
275   for(Module::iterator I = begin(), E = end(); I != E; ++I)
276     I->dropAllReferences();
277
278   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
279     I->dropAllReferences();
280 }
281
282 void Module::addLibrary(const std::string& Lib) {
283   for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
284     if (*I == Lib)
285       return;
286   LibraryList.push_back(Lib);
287 }
288
289 void Module::removeLibrary(const std::string& Lib) {
290   LibraryListType::iterator I = LibraryList.begin();
291   LibraryListType::iterator E = LibraryList.end();
292   for (;I != E; ++I)
293     if (*I == Lib) {
294       LibraryList.erase(I);
295       return;
296     }
297 }
298