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