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