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