For PR1136: Rename GlobalVariable::isExternal as isDeclaration to avoid
[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 /// Target Pointer Size information...
111 Module::PointerSize Module::getPointerSize() const {
112   std::string temp = DataLayout;
113   Module::PointerSize ret = AnyPointerSize;
114   
115   while (!temp.empty()) {
116     std::string token = getToken(temp, "-");
117     char signal = getToken(token, ":")[0];
118     
119     if (signal == 'p') {
120       int size = atoi(getToken(token, ":").c_str());
121       if (size == 32)
122         ret = Pointer32;
123       else if (size == 64)
124         ret = Pointer64;
125     }
126   }
127   
128   return ret;
129 }
130
131 //===----------------------------------------------------------------------===//
132 // Methods for easy access to the functions in the module.
133 //
134
135 Constant *Module::getOrInsertFunction(const std::string &Name,
136                                       const FunctionType *Ty) {
137   SymbolTable &SymTab = getValueSymbolTable();
138
139   // See if we have a definitions for the specified function already.
140   Function *F =
141     dyn_cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
142   if (F == 0) {
143     // Nope, add it.
144     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
145     FunctionList.push_back(New);
146     return New;                    // Return the new prototype.
147   }
148
149   // Okay, the function exists.  Does it have externally visible linkage?
150   if (F->hasInternalLinkage()) {
151     // Rename the function.
152     F->setName(SymTab.getUniqueName(F->getType(), F->getName()));
153     // Retry, now there won't be a conflict.
154     return getOrInsertFunction(Name, Ty);
155   }
156
157   // If the function exists but has the wrong type, return a bitcast to the
158   // right type.
159   if (F->getFunctionType() != Ty)
160     return ConstantExpr::getBitCast(F, PointerType::get(Ty));
161   
162   // Otherwise, we just found the existing function or a prototype.
163   return F;  
164 }
165
166 // getOrInsertFunction - Look up the specified function in the module symbol
167 // table.  If it does not exist, add a prototype for the function and return it.
168 // This version of the method takes a null terminated list of function
169 // arguments, which makes it easier for clients to use.
170 //
171 Constant *Module::getOrInsertFunction(const std::string &Name,
172                                       const Type *RetTy, ...) {
173   va_list Args;
174   va_start(Args, RetTy);
175
176   // Build the list of argument types...
177   std::vector<const Type*> ArgTys;
178   while (const Type *ArgTy = va_arg(Args, const Type*))
179     ArgTys.push_back(ArgTy);
180
181   va_end(Args);
182
183   // Build the function type and chain to the other getOrInsertFunction...
184   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
185 }
186
187
188 // getFunction - Look up the specified function in the module symbol table.
189 // If it does not exist, return null.
190 //
191 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
192   SymbolTable &SymTab = getValueSymbolTable();
193   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
194 }
195
196
197 /// getMainFunction - This function looks up main efficiently.  This is such a
198 /// common case, that it is a method in Module.  If main cannot be found, a
199 /// null pointer is returned.
200 ///
201 Function *Module::getMainFunction() {
202   std::vector<const Type*> Params;
203
204   // int main(void)...
205   if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
206                                                           Params, false)))
207     return F;
208
209   // void main(void)...
210   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
211                                                           Params, false)))
212     return F;
213
214   Params.push_back(Type::Int32Ty);
215
216   // int main(int argc)...
217   if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
218                                                           Params, false)))
219     return F;
220
221   // void main(int argc)...
222   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
223                                                           Params, false)))
224     return F;
225
226   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
227     Params.push_back(PointerType::get(PointerType::get(Type::Int8Ty)));
228
229     // int main(int argc, char **argv)...
230     if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty,
231                                                             Params, false)))
232       return F;
233
234     // void main(int argc, char **argv)...
235     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
236                                                             Params, false)))
237       return F;
238   }
239
240   // Ok, try to find main the hard way...
241   return getNamedFunction("main");
242 }
243
244 /// getNamedFunction - Return the first function in the module with the
245 /// specified name, of arbitrary type.  This method returns null if a function
246 /// with the specified name is not found.
247 ///
248 Function *Module::getNamedFunction(const std::string &Name) const {
249   // Loop over all of the functions, looking for the function desired
250   const Function *Found = 0;
251   for (const_iterator I = begin(), E = end(); I != E; ++I)
252     if (I->getName() == Name)
253       if (I->isDeclaration())
254         Found = I;
255       else
256         return const_cast<Function*>(&(*I));
257   return const_cast<Function*>(Found); // Non-external function not found...
258 }
259
260 //===----------------------------------------------------------------------===//
261 // Methods for easy access to the global variables in the module.
262 //
263
264 /// getGlobalVariable - Look up the specified global variable in the module
265 /// symbol table.  If it does not exist, return null.  The type argument
266 /// should be the underlying type of the global, i.e., it should not have
267 /// the top-level PointerType, which represents the address of the global.
268 /// If AllowInternal is set to true, this function will return types that
269 /// have InternalLinkage. By default, these types are not returned.
270 ///
271 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
272                                           const Type *Ty, bool AllowInternal) {
273   if (Value *V = getValueSymbolTable().lookup(PointerType::get(Ty), Name)) {
274     GlobalVariable *Result = cast<GlobalVariable>(V);
275     if (AllowInternal || !Result->hasInternalLinkage())
276       return Result;
277   }
278   return 0;
279 }
280
281 /// getNamedGlobal - Return the first global variable in the module with the
282 /// specified name, of arbitrary type.  This method returns null if a global
283 /// with the specified name is not found.
284 ///
285 GlobalVariable *Module::getNamedGlobal(const std::string &Name) const {
286   // FIXME: This would be much faster with a symbol table that doesn't
287   // discriminate based on type!
288   for (const_global_iterator I = global_begin(), E = global_end();
289        I != E; ++I)
290     if (I->getName() == Name) 
291       return const_cast<GlobalVariable*>(&(*I));
292   return 0;
293 }
294
295
296
297 //===----------------------------------------------------------------------===//
298 // Methods for easy access to the types in the module.
299 //
300
301
302 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
303 // there is already an entry for this name, true is returned and the symbol
304 // table is not modified.
305 //
306 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
307   TypeSymbolTable &ST = getTypeSymbolTable();
308
309   if (ST.lookup(Name)) return true;  // Already in symtab...
310
311   // Not in symbol table?  Set the name with the Symtab as an argument so the
312   // type knows what to update...
313   ST.insert(Name, Ty);
314
315   return false;
316 }
317
318 /// getTypeByName - Return the type with the specified name in this module, or
319 /// null if there is none by that name.
320 const Type *Module::getTypeByName(const std::string &Name) const {
321   const TypeSymbolTable &ST = getTypeSymbolTable();
322   return cast_or_null<Type>(ST.lookup(Name));
323 }
324
325 // getTypeName - If there is at least one entry in the symbol table for the
326 // specified type, return it.
327 //
328 std::string Module::getTypeName(const Type *Ty) const {
329   const TypeSymbolTable &ST = getTypeSymbolTable();
330
331   TypeSymbolTable::const_iterator TI = ST.begin();
332   TypeSymbolTable::const_iterator TE = ST.end();
333   if ( TI == TE ) return ""; // No names for types
334
335   while (TI != TE && TI->second != Ty)
336     ++TI;
337
338   if (TI != TE)  // Must have found an entry!
339     return TI->first;
340   return "";     // Must not have found anything...
341 }
342
343 //===----------------------------------------------------------------------===//
344 // Other module related stuff.
345 //
346
347
348 // dropAllReferences() - This function causes all the subelementss to "let go"
349 // of all references that they are maintaining.  This allows one to 'delete' a
350 // whole module at a time, even though there may be circular references... first
351 // all references are dropped, and all use counts go to zero.  Then everything
352 // is deleted for real.  Note that no operations are valid on an object that
353 // has "dropped all references", except operator delete.
354 //
355 void Module::dropAllReferences() {
356   for(Module::iterator I = begin(), E = end(); I != E; ++I)
357     I->dropAllReferences();
358
359   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
360     I->dropAllReferences();
361 }
362