Remove attribution from file headers, per discussion on llvmdev.
[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 #include <map>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
31 //
32
33 Function *ilist_traits<Function>::createSentinel() {
34   FunctionType *FTy =
35     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
36   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
37   // This should not be garbage monitored.
38   LeakDetector::removeGarbageObject(Ret);
39   return Ret;
40 }
41 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
42   GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
43                                            GlobalValue::ExternalLinkage);
44   // This should not be garbage monitored.
45   LeakDetector::removeGarbageObject(Ret);
46   return Ret;
47 }
48 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
49   GlobalAlias *Ret = new GlobalAlias(Type::Int32Ty, GlobalValue::ExternalLinkage);
50   // This should not be garbage monitored.
51   LeakDetector::removeGarbageObject(Ret);
52   return Ret;
53 }
54
55 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
56   return M->getFunctionList();
57 }
58 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
59   return M->getGlobalList();
60 }
61 iplist<GlobalAlias> &ilist_traits<GlobalAlias>::getList(Module *M) {
62   return M->getAliasList();
63 }
64
65 // Explicit instantiations of SymbolTableListTraits since some of the methods
66 // are not in the public header file.
67 template class SymbolTableListTraits<GlobalVariable, Module>;
68 template class SymbolTableListTraits<Function, Module>;
69 template class SymbolTableListTraits<GlobalAlias, Module>;
70
71 //===----------------------------------------------------------------------===//
72 // Primitive Module methods.
73 //
74
75 Module::Module(const std::string &MID)
76   : ModuleID(MID), DataLayout("") {
77   ValSymTab = new ValueSymbolTable();
78   TypeSymTab = new TypeSymbolTable();
79 }
80
81 Module::~Module() {
82   dropAllReferences();
83   GlobalList.clear();
84   FunctionList.clear();
85   AliasList.clear();
86   LibraryList.clear();
87   delete ValSymTab;
88   delete TypeSymTab;
89 }
90
91 // Module::dump() - Allow printing from debugger
92 void Module::dump() const {
93   print(*cerr.stream());
94 }
95
96 /// Target endian information...
97 Module::Endianness Module::getEndianness() const {
98   std::string temp = DataLayout;
99   Module::Endianness ret = AnyEndianness;
100   
101   while (!temp.empty()) {
102     std::string token = getToken(temp, "-");
103     
104     if (token[0] == 'e') {
105       ret = LittleEndian;
106     } else if (token[0] == 'E') {
107       ret = BigEndian;
108     }
109   }
110   
111   return ret;
112 }
113
114 /// Target Pointer Size information...
115 Module::PointerSize Module::getPointerSize() const {
116   std::string temp = DataLayout;
117   Module::PointerSize ret = AnyPointerSize;
118   
119   while (!temp.empty()) {
120     std::string token = getToken(temp, "-");
121     char signal = getToken(token, ":")[0];
122     
123     if (signal == 'p') {
124       int size = atoi(getToken(token, ":").c_str());
125       if (size == 32)
126         ret = Pointer32;
127       else if (size == 64)
128         ret = Pointer64;
129     }
130   }
131   
132   return ret;
133 }
134
135 //===----------------------------------------------------------------------===//
136 // Methods for easy access to the functions in the module.
137 //
138
139 // getOrInsertFunction - Look up the specified function in the module symbol
140 // table.  If it does not exist, add a prototype for the function and return
141 // it.  This is nice because it allows most passes to get away with not handling
142 // the symbol table directly for this common task.
143 //
144 Constant *Module::getOrInsertFunction(const std::string &Name,
145                                       const FunctionType *Ty) {
146   ValueSymbolTable &SymTab = getValueSymbolTable();
147
148   // See if we have a definition for the specified function already.
149   GlobalValue *F = dyn_cast_or_null<GlobalValue>(SymTab.lookup(Name));
150   if (F == 0) {
151     // Nope, add it
152     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
153     FunctionList.push_back(New);
154     return New;                    // Return the new prototype.
155   }
156
157   // Okay, the function exists.  Does it have externally visible linkage?
158   if (F->hasInternalLinkage()) {
159     // Rename the function.
160     F->setName(SymTab.getUniqueName(F->getName()));
161     // Retry, now there won't be a conflict.
162     return getOrInsertFunction(Name, Ty);
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 // getOrInsertFunction - Look up the specified function in the module symbol
175 // table.  If it does not exist, add a prototype for the function and return it.
176 // This version of the method takes a null terminated list of function
177 // arguments, which makes it easier for clients to use.
178 //
179 Constant *Module::getOrInsertFunction(const std::string &Name,
180                                       const Type *RetTy, ...) {
181   va_list Args;
182   va_start(Args, RetTy);
183
184   // Build the list of argument types...
185   std::vector<const Type*> ArgTys;
186   while (const Type *ArgTy = va_arg(Args, const Type*))
187     ArgTys.push_back(ArgTy);
188
189   va_end(Args);
190
191   // Build the function type and chain to the other getOrInsertFunction...
192   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
193 }
194
195
196 // getFunction - Look up the specified function in the module symbol table.
197 // If it does not exist, return null.
198 //
199 Function *Module::getFunction(const std::string &Name) const {
200   const ValueSymbolTable &SymTab = getValueSymbolTable();
201   return dyn_cast_or_null<Function>(SymTab.lookup(Name));
202 }
203
204 //===----------------------------------------------------------------------===//
205 // Methods for easy access to the global variables in the module.
206 //
207
208 /// getGlobalVariable - Look up the specified global variable in the module
209 /// symbol table.  If it does not exist, return null.  The type argument
210 /// should be the underlying type of the global, i.e., it should not have
211 /// the top-level PointerType, which represents the address of the global.
212 /// If AllowInternal is set to true, this function will return types that
213 /// have InternalLinkage. By default, these types are not returned.
214 ///
215 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
216                                           bool AllowInternal) const {
217   if (Value *V = ValSymTab->lookup(Name)) {
218     GlobalVariable *Result = dyn_cast<GlobalVariable>(V);
219     if (Result && (AllowInternal || !Result->hasInternalLinkage()))
220       return Result;
221   }
222   return 0;
223 }
224
225 //===----------------------------------------------------------------------===//
226 // Methods for easy access to the global variables in the module.
227 //
228
229 // getNamedAlias - Look up the specified global in the module symbol table.
230 // If it does not exist, return null.
231 //
232 GlobalAlias *Module::getNamedAlias(const std::string &Name) const {
233   const ValueSymbolTable &SymTab = getValueSymbolTable();
234   return dyn_cast_or_null<GlobalAlias>(SymTab.lookup(Name));
235 }
236
237 //===----------------------------------------------------------------------===//
238 // Methods for easy access to the types in the module.
239 //
240
241
242 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
243 // there is already an entry for this name, true is returned and the symbol
244 // table is not modified.
245 //
246 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
247   TypeSymbolTable &ST = getTypeSymbolTable();
248
249   if (ST.lookup(Name)) return true;  // Already in symtab...
250
251   // Not in symbol table?  Set the name with the Symtab as an argument so the
252   // type knows what to update...
253   ST.insert(Name, Ty);
254
255   return false;
256 }
257
258 /// getTypeByName - Return the type with the specified name in this module, or
259 /// null if there is none by that name.
260 const Type *Module::getTypeByName(const std::string &Name) const {
261   const TypeSymbolTable &ST = getTypeSymbolTable();
262   return cast_or_null<Type>(ST.lookup(Name));
263 }
264
265 // getTypeName - If there is at least one entry in the symbol table for the
266 // specified type, return it.
267 //
268 std::string Module::getTypeName(const Type *Ty) const {
269   const TypeSymbolTable &ST = getTypeSymbolTable();
270
271   TypeSymbolTable::const_iterator TI = ST.begin();
272   TypeSymbolTable::const_iterator TE = ST.end();
273   if ( TI == TE ) return ""; // No names for types
274
275   while (TI != TE && TI->second != Ty)
276     ++TI;
277
278   if (TI != TE)  // Must have found an entry!
279     return TI->first;
280   return "";     // Must not have found anything...
281 }
282
283 //===----------------------------------------------------------------------===//
284 // Other module related stuff.
285 //
286
287
288 // dropAllReferences() - This function causes all the subelementss to "let go"
289 // of all references that they are maintaining.  This allows one to 'delete' a
290 // whole module at a time, even though there may be circular references... first
291 // all references are dropped, and all use counts go to zero.  Then everything
292 // is deleted for real.  Note that no operations are valid on an object that
293 // has "dropped all references", except operator delete.
294 //
295 void Module::dropAllReferences() {
296   for(Module::iterator I = begin(), E = end(); I != E; ++I)
297     I->dropAllReferences();
298
299   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
300     I->dropAllReferences();
301
302   for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
303     I->dropAllReferences();
304 }
305
306 void Module::addLibrary(const std::string& Lib) {
307   for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
308     if (*I == Lib)
309       return;
310   LibraryList.push_back(Lib);
311 }
312
313 void Module::removeLibrary(const std::string& Lib) {
314   LibraryListType::iterator I = LibraryList.begin();
315   LibraryListType::iterator E = LibraryList.end();
316   for (;I != E; ++I)
317     if (*I == Lib) {
318       LibraryList.erase(I);
319       return;
320     }
321 }
322