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