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