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