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