Change the interface to Module::getOrInsertFunction to be easier to use,
[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                       std::vector<FunctionType::ParameterAttributes>() );
37   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
38   // This should not be garbage monitored.
39   LeakDetector::removeGarbageObject(Ret);
40   return Ret;
41 }
42 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
43   GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
44                                            GlobalValue::ExternalLinkage);
45   // This should not be garbage monitored.
46   LeakDetector::removeGarbageObject(Ret);
47   return Ret;
48 }
49
50 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
51   return M->getFunctionList();
52 }
53 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
54   return M->getGlobalList();
55 }
56
57 // Explicit instantiations of SymbolTableListTraits since some of the methods
58 // are not in the public header file.
59 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
60 template class SymbolTableListTraits<Function, Module, Module>;
61
62 //===----------------------------------------------------------------------===//
63 // Primitive Module methods.
64 //
65
66 Module::Module(const std::string &MID)
67   : ModuleID(MID), DataLayout("") {
68   FunctionList.setItemParent(this);
69   FunctionList.setParent(this);
70   GlobalList.setItemParent(this);
71   GlobalList.setParent(this);
72   ValSymTab = new SymbolTable();
73   TypeSymTab = new TypeSymbolTable();
74 }
75
76 Module::~Module() {
77   dropAllReferences();
78   GlobalList.clear();
79   GlobalList.setParent(0);
80   FunctionList.clear();
81   FunctionList.setParent(0);
82   LibraryList.clear();
83   delete ValSymTab;
84   delete TypeSymTab;
85 }
86
87 // Module::dump() - Allow printing from debugger
88 void Module::dump() const {
89   print(*cerr.stream());
90 }
91
92 /// Target endian information...
93 Module::Endianness Module::getEndianness() const {
94   std::string temp = DataLayout;
95   Module::Endianness ret = AnyEndianness;
96   
97   while (!temp.empty()) {
98     std::string token = getToken(temp, "-");
99     
100     if (token[0] == 'e') {
101       ret = LittleEndian;
102     } else if (token[0] == 'E') {
103       ret = BigEndian;
104     }
105   }
106   
107   return ret;
108 }
109
110 void Module::setEndianness(Endianness E) {
111   if (!DataLayout.empty() && E != AnyEndianness)
112     DataLayout += "-";
113   
114   if (E == LittleEndian)
115     DataLayout += "e";
116   else if (E == BigEndian)
117     DataLayout += "E";
118 }
119
120 /// Target Pointer Size information...
121 Module::PointerSize Module::getPointerSize() const {
122   std::string temp = DataLayout;
123   Module::PointerSize ret = AnyPointerSize;
124   
125   while (!temp.empty()) {
126     std::string token = getToken(temp, "-");
127     char signal = getToken(token, ":")[0];
128     
129     if (signal == 'p') {
130       int size = atoi(getToken(token, ":").c_str());
131       if (size == 32)
132         ret = Pointer32;
133       else if (size == 64)
134         ret = Pointer64;
135     }
136   }
137   
138   return ret;
139 }
140
141 void Module::setPointerSize(PointerSize PS) {
142   if (!DataLayout.empty() && PS != AnyPointerSize)
143     DataLayout += "-";
144   
145   if (PS == Pointer32)
146     DataLayout += "p:32:32";
147   else if (PS == Pointer64)
148     DataLayout += "p:64:64";
149 }
150
151 //===----------------------------------------------------------------------===//
152 // Methods for easy access to the functions in the module.
153 //
154
155 Constant *Module::getOrInsertFunction(const std::string &Name,
156                                       const FunctionType *Ty) {
157   SymbolTable &SymTab = getValueSymbolTable();
158
159   // See if we have a definitions for the specified function already.
160   Function *F =
161     dyn_cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
162   if (F == 0) {
163     // Nope, add it.
164     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
165     FunctionList.push_back(New);
166     return New;                    // Return the new prototype.
167   }
168
169   // Okay, the function exists.  Does it have externally visible linkage?
170   if (F->hasInternalLinkage()) {
171     // Rename the function.
172     F->setName(SymTab.getUniqueName(F->getType(), F->getName()));
173     // Retry, now there won't be a conflict.
174     return getOrInsertFunction(Name, Ty);
175   }
176
177   // If the function exists but has the wrong type, return a bitcast to the
178   // right type.
179   if (F->getFunctionType() != Ty)
180     return ConstantExpr::getBitCast(F, PointerType::get(Ty));
181   
182   // Otherwise, we just found the existing function or a prototype.
183   return F;  
184 }
185
186 // getOrInsertFunction - Look up the specified function in the module symbol
187 // table.  If it does not exist, add a prototype for the function and return it.
188 // This version of the method takes a null terminated list of function
189 // arguments, which makes it easier for clients to use.
190 //
191 Constant *Module::getOrInsertFunction(const std::string &Name,
192                                       const Type *RetTy, ...) {
193   va_list Args;
194   va_start(Args, RetTy);
195
196   // Build the list of argument types...
197   std::vector<const Type*> ArgTys;
198   while (const Type *ArgTy = va_arg(Args, const Type*))
199     ArgTys.push_back(ArgTy);
200
201   va_end(Args);
202
203   // Build the function type and chain to the other getOrInsertFunction...
204   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
205 }
206
207
208 // getFunction - Look up the specified function in the module symbol table.
209 // If it does not exist, return null.
210 //
211 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
212   SymbolTable &SymTab = getValueSymbolTable();
213   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
214 }
215
216
217 /// getMainFunction - This function looks up main efficiently.  This is such a
218 /// common case, that it is a method in Module.  If main cannot be found, a
219 /// null pointer is returned.
220 ///
221 Function *Module::getMainFunction() {
222   std::vector<const Type*> Params;
223
224   // int main(void)...
225   if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
226                                                           Params, false)))
227     return F;
228
229   // void main(void)...
230   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
231                                                           Params, false)))
232     return F;
233
234   Params.push_back(Type::Int32Ty);
235
236   // int main(int argc)...
237   if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
238                                                           Params, false)))
239     return F;
240
241   // void main(int argc)...
242   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
243                                                           Params, false)))
244     return F;
245
246   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
247     Params.push_back(PointerType::get(PointerType::get(Type::Int8Ty)));
248
249     // int main(int argc, char **argv)...
250     if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
251                                                             Params, false)))
252       return F;
253
254     // void main(int argc, char **argv)...
255     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
256                                                             Params, false)))
257       return F;
258   }
259
260   // Ok, try to find main the hard way...
261   return getNamedFunction("main");
262 }
263
264 /// getNamedFunction - Return the first function in the module with the
265 /// specified name, of arbitrary type.  This method returns null if a function
266 /// with the specified name is not found.
267 ///
268 Function *Module::getNamedFunction(const std::string &Name) const {
269   // Loop over all of the functions, looking for the function desired
270   const Function *Found = 0;
271   for (const_iterator I = begin(), E = end(); I != E; ++I)
272     if (I->getName() == Name)
273       if (I->isExternal())
274         Found = I;
275       else
276         return const_cast<Function*>(&(*I));
277   return const_cast<Function*>(Found); // Non-external function not found...
278 }
279
280 //===----------------------------------------------------------------------===//
281 // Methods for easy access to the global variables in the module.
282 //
283
284 /// getGlobalVariable - Look up the specified global variable in the module
285 /// symbol table.  If it does not exist, return null.  The type argument
286 /// should be the underlying type of the global, i.e., it should not have
287 /// the top-level PointerType, which represents the address of the global.
288 /// If AllowInternal is set to true, this function will return types that
289 /// have InternalLinkage. By default, these types are not returned.
290 ///
291 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
292                                           const Type *Ty, bool AllowInternal) {
293   if (Value *V = getValueSymbolTable().lookup(PointerType::get(Ty), Name)) {
294     GlobalVariable *Result = cast<GlobalVariable>(V);
295     if (AllowInternal || !Result->hasInternalLinkage())
296       return Result;
297   }
298   return 0;
299 }
300
301 /// getNamedGlobal - Return the first global variable in the module with the
302 /// specified name, of arbitrary type.  This method returns null if a global
303 /// with the specified name is not found.
304 ///
305 GlobalVariable *Module::getNamedGlobal(const std::string &Name) const {
306   // FIXME: This would be much faster with a symbol table that doesn't
307   // discriminate based on type!
308   for (const_global_iterator I = global_begin(), E = global_end();
309        I != E; ++I)
310     if (I->getName() == Name) 
311       return const_cast<GlobalVariable*>(&(*I));
312   return 0;
313 }
314
315
316
317 //===----------------------------------------------------------------------===//
318 // Methods for easy access to the types in the module.
319 //
320
321
322 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
323 // there is already an entry for this name, true is returned and the symbol
324 // table is not modified.
325 //
326 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
327   TypeSymbolTable &ST = getTypeSymbolTable();
328
329   if (ST.lookup(Name)) return true;  // Already in symtab...
330
331   // Not in symbol table?  Set the name with the Symtab as an argument so the
332   // type knows what to update...
333   ST.insert(Name, Ty);
334
335   return false;
336 }
337
338 /// getTypeByName - Return the type with the specified name in this module, or
339 /// null if there is none by that name.
340 const Type *Module::getTypeByName(const std::string &Name) const {
341   const TypeSymbolTable &ST = getTypeSymbolTable();
342   return cast_or_null<Type>(ST.lookup(Name));
343 }
344
345 // getTypeName - If there is at least one entry in the symbol table for the
346 // specified type, return it.
347 //
348 std::string Module::getTypeName(const Type *Ty) const {
349   const TypeSymbolTable &ST = getTypeSymbolTable();
350
351   TypeSymbolTable::const_iterator TI = ST.begin();
352   TypeSymbolTable::const_iterator TE = ST.end();
353   if ( TI == TE ) return ""; // No names for types
354
355   while (TI != TE && TI->second != Ty)
356     ++TI;
357
358   if (TI != TE)  // Must have found an entry!
359     return TI->first;
360   return "";     // Must not have found anything...
361 }
362
363 //===----------------------------------------------------------------------===//
364 // Other module related stuff.
365 //
366
367
368 // dropAllReferences() - This function causes all the subelementss to "let go"
369 // of all references that they are maintaining.  This allows one to 'delete' a
370 // whole module at a time, even though there may be circular references... first
371 // all references are dropped, and all use counts go to zero.  Then everything
372 // is deleted for real.  Note that no operations are valid on an object that
373 // has "dropped all references", except operator delete.
374 //
375 void Module::dropAllReferences() {
376   for(Module::iterator I = begin(), E = end(); I != E; ++I)
377     I->dropAllReferences();
378
379   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
380     I->dropAllReferences();
381 }
382