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