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