Simplify printAlias.
[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/DenseSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "SymbolTableListTraitsImpl.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   NamedMDSymTab = new StringMap<NamedMDNode *>();
64   Context.addModule(this);
65 }
66
67 Module::~Module() {
68   Context.removeModule(this);
69   dropAllReferences();
70   GlobalList.clear();
71   FunctionList.clear();
72   AliasList.clear();
73   LibraryList.clear();
74   NamedMDList.clear();
75   delete ValSymTab;
76   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
77 }
78
79 /// Target endian information.
80 Module::Endianness Module::getEndianness() const {
81   StringRef temp = DataLayout;
82   Module::Endianness ret = AnyEndianness;
83   
84   while (!temp.empty()) {
85     std::pair<StringRef, StringRef> P = getToken(temp, "-");
86     
87     StringRef token = P.first;
88     temp = P.second;
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     std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
107     temp = TmpP.second;
108     TmpP = getToken(TmpP.first, ":");
109     StringRef token = TmpP.second, signalToken = TmpP.first;
110     
111     if (signalToken[0] == 'p') {
112       int size = 0;
113       getToken(token, ":").first.getAsInteger(10, size);
114       if (size == 32)
115         ret = Pointer32;
116       else if (size == 64)
117         ret = Pointer64;
118     }
119   }
120   
121   return ret;
122 }
123
124 /// getNamedValue - Return the first global value in the module with
125 /// the specified name, of arbitrary type.  This method returns null
126 /// if a global with the specified name is not found.
127 GlobalValue *Module::getNamedValue(StringRef Name) const {
128   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
129 }
130
131 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
132 /// This ID is uniqued across modules in the current LLVMContext.
133 unsigned Module::getMDKindID(StringRef Name) const {
134   return Context.getMDKindID(Name);
135 }
136
137 /// getMDKindNames - Populate client supplied SmallVector with the name for
138 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
139 /// so it is filled in as an empty string.
140 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
141   return Context.getMDKindNames(Result);
142 }
143
144
145 //===----------------------------------------------------------------------===//
146 // Methods for easy access to the functions in the module.
147 //
148
149 // getOrInsertFunction - Look up the specified function in the module symbol
150 // table.  If it does not exist, add a prototype for the function and return
151 // it.  This is nice because it allows most passes to get away with not handling
152 // the symbol table directly for this common task.
153 //
154 Constant *Module::getOrInsertFunction(StringRef Name,
155                                       FunctionType *Ty,
156                                       AttrListPtr AttributeList) {
157   // See if we have a definition for the specified function already.
158   GlobalValue *F = getNamedValue(Name);
159   if (F == 0) {
160     // Nope, add it
161     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
162     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
163       New->setAttributes(AttributeList);
164     FunctionList.push_back(New);
165     return New;                    // Return the new prototype.
166   }
167
168   // Okay, the function exists.  Does it have externally visible linkage?
169   if (F->hasLocalLinkage()) {
170     // Clear the function's name.
171     F->setName("");
172     // Retry, now there won't be a conflict.
173     Constant *NewF = getOrInsertFunction(Name, Ty);
174     F->setName(Name);
175     return NewF;
176   }
177
178   // If the function exists but has the wrong type, return a bitcast to the
179   // right type.
180   if (F->getType() != PointerType::getUnqual(Ty))
181     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
182   
183   // Otherwise, we just found the existing function or a prototype.
184   return F;  
185 }
186
187 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
188                                              FunctionType *Ty,
189                                              AttrListPtr AttributeList) {
190   // See if we have a definition for the specified function already.
191   GlobalValue *F = getNamedValue(Name);
192   if (F == 0) {
193     // Nope, add it
194     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
195     New->setAttributes(AttributeList);
196     FunctionList.push_back(New);
197     return New; // Return the new prototype.
198   }
199
200   // Otherwise, we just found the existing function or a prototype.
201   return F;  
202 }
203
204 Constant *Module::getOrInsertFunction(StringRef Name,
205                                       FunctionType *Ty) {
206   AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
207   return getOrInsertFunction(Name, Ty, AttributeList);
208 }
209
210 // getOrInsertFunction - Look up the specified function in the module symbol
211 // table.  If it does not exist, add a prototype for the function and return it.
212 // This version of the method takes a null terminated list of function
213 // arguments, which makes it easier for clients to use.
214 //
215 Constant *Module::getOrInsertFunction(StringRef Name,
216                                       AttrListPtr AttributeList,
217                                       Type *RetTy, ...) {
218   va_list Args;
219   va_start(Args, RetTy);
220
221   // Build the list of argument types...
222   std::vector<Type*> ArgTys;
223   while (Type *ArgTy = va_arg(Args, Type*))
224     ArgTys.push_back(ArgTy);
225
226   va_end(Args);
227
228   // Build the function type and chain to the other getOrInsertFunction...
229   return getOrInsertFunction(Name,
230                              FunctionType::get(RetTy, ArgTys, false),
231                              AttributeList);
232 }
233
234 Constant *Module::getOrInsertFunction(StringRef Name,
235                                       Type *RetTy, ...) {
236   va_list Args;
237   va_start(Args, RetTy);
238
239   // Build the list of argument types...
240   std::vector<Type*> ArgTys;
241   while (Type *ArgTy = va_arg(Args, Type*))
242     ArgTys.push_back(ArgTy);
243
244   va_end(Args);
245
246   // Build the function type and chain to the other getOrInsertFunction...
247   return getOrInsertFunction(Name, 
248                              FunctionType::get(RetTy, ArgTys, false),
249                              AttrListPtr::get((AttributeWithIndex *)0, 0));
250 }
251
252 // getFunction - Look up the specified function in the module symbol table.
253 // If it does not exist, return null.
254 //
255 Function *Module::getFunction(StringRef Name) const {
256   return dyn_cast_or_null<Function>(getNamedValue(Name));
257 }
258
259 //===----------------------------------------------------------------------===//
260 // Methods for easy access to the global variables in the module.
261 //
262
263 /// getGlobalVariable - Look up the specified global variable in the module
264 /// symbol table.  If it does not exist, return null.  The type argument
265 /// should be the underlying type of the global, i.e., it should not have
266 /// the top-level PointerType, which represents the address of the global.
267 /// If AllowLocal is set to true, this function will return types that
268 /// have an local. By default, these types are not returned.
269 ///
270 GlobalVariable *Module::getGlobalVariable(StringRef Name,
271                                           bool AllowLocal) const {
272   if (GlobalVariable *Result = 
273       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
274     if (AllowLocal || !Result->hasLocalLinkage())
275       return Result;
276   return 0;
277 }
278
279 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
280 ///   1. If it does not exist, add a declaration of the global and return it.
281 ///   2. Else, the global exists but has the wrong type: return the function
282 ///      with a constantexpr cast to the right type.
283 ///   3. Finally, if the existing global is the correct delclaration, return the
284 ///      existing global.
285 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
286   // See if we have a definition for the specified global already.
287   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
288   if (GV == 0) {
289     // Nope, add it
290     GlobalVariable *New =
291       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
292                          0, Name);
293      return New;                    // Return the new declaration.
294   }
295
296   // If the variable exists but has the wrong type, return a bitcast to the
297   // right type.
298   if (GV->getType() != PointerType::getUnqual(Ty))
299     return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
300   
301   // Otherwise, we just found the existing function or a prototype.
302   return GV;
303 }
304
305 //===----------------------------------------------------------------------===//
306 // Methods for easy access to the global variables in the module.
307 //
308
309 // getNamedAlias - Look up the specified global in the module symbol table.
310 // If it does not exist, return null.
311 //
312 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
313   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
314 }
315
316 /// getNamedMetadata - Return the first NamedMDNode in the module with the
317 /// specified name. This method returns null if a NamedMDNode with the 
318 /// specified name is not found.
319 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
320   SmallString<256> NameData;
321   StringRef NameRef = Name.toStringRef(NameData);
322   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
323 }
324
325 /// getOrInsertNamedMetadata - Return the first named MDNode in the module 
326 /// with the specified name. This method returns a new NamedMDNode if a 
327 /// NamedMDNode with the specified name is not found.
328 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
329   NamedMDNode *&NMD =
330     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
331   if (!NMD) {
332     NMD = new NamedMDNode(Name);
333     NMD->setParent(this);
334     NamedMDList.push_back(NMD);
335   }
336   return NMD;
337 }
338
339 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
340   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
341   NamedMDList.erase(NMD);
342 }
343
344
345 //===----------------------------------------------------------------------===//
346 // Methods to control the materialization of GlobalValues in the Module.
347 //
348 void Module::setMaterializer(GVMaterializer *GVM) {
349   assert(!Materializer &&
350          "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
351          " to clear it out before setting another one.");
352   Materializer.reset(GVM);
353 }
354
355 bool Module::isMaterializable(const GlobalValue *GV) const {
356   if (Materializer)
357     return Materializer->isMaterializable(GV);
358   return false;
359 }
360
361 bool Module::isDematerializable(const GlobalValue *GV) const {
362   if (Materializer)
363     return Materializer->isDematerializable(GV);
364   return false;
365 }
366
367 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
368   if (Materializer)
369     return Materializer->Materialize(GV, ErrInfo);
370   return false;
371 }
372
373 void Module::Dematerialize(GlobalValue *GV) {
374   if (Materializer)
375     return Materializer->Dematerialize(GV);
376 }
377
378 bool Module::MaterializeAll(std::string *ErrInfo) {
379   if (!Materializer)
380     return false;
381   return Materializer->MaterializeModule(this, ErrInfo);
382 }
383
384 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
385   if (MaterializeAll(ErrInfo))
386     return true;
387   Materializer.reset();
388   return false;
389 }
390
391 //===----------------------------------------------------------------------===//
392 // Other module related stuff.
393 //
394
395
396 // dropAllReferences() - This function causes all the subelementss to "let go"
397 // of all references that they are maintaining.  This allows one to 'delete' a
398 // whole module at a time, even though there may be circular references... first
399 // all references are dropped, and all use counts go to zero.  Then everything
400 // is deleted for real.  Note that no operations are valid on an object that
401 // has "dropped all references", except operator delete.
402 //
403 void Module::dropAllReferences() {
404   for(Module::iterator I = begin(), E = end(); I != E; ++I)
405     I->dropAllReferences();
406
407   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
408     I->dropAllReferences();
409
410   for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
411     I->dropAllReferences();
412 }
413
414 void Module::addLibrary(StringRef Lib) {
415   for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
416     if (*I == Lib)
417       return;
418   LibraryList.push_back(Lib);
419 }
420
421 void Module::removeLibrary(StringRef Lib) {
422   LibraryListType::iterator I = LibraryList.begin();
423   LibraryListType::iterator E = LibraryList.end();
424   for (;I != E; ++I)
425     if (*I == Lib) {
426       LibraryList.erase(I);
427       return;
428     }
429 }
430
431 //===----------------------------------------------------------------------===//
432 // Type finding functionality.
433 //===----------------------------------------------------------------------===//
434
435 namespace {
436   /// TypeFinder - Walk over a module, identifying all of the types that are
437   /// used by the module.
438   class TypeFinder {
439     // To avoid walking constant expressions multiple times and other IR
440     // objects, we keep several helper maps.
441     DenseSet<const Value*> VisitedConstants;
442     DenseSet<Type*> VisitedTypes;
443     
444     std::vector<StructType*> &StructTypes;
445   public:
446     TypeFinder(std::vector<StructType*> &structTypes)
447       : StructTypes(structTypes) {}
448     
449     void run(const Module &M) {
450       // Get types from global variables.
451       for (Module::const_global_iterator I = M.global_begin(),
452            E = M.global_end(); I != E; ++I) {
453         incorporateType(I->getType());
454         if (I->hasInitializer())
455           incorporateValue(I->getInitializer());
456       }
457       
458       // Get types from aliases.
459       for (Module::const_alias_iterator I = M.alias_begin(),
460            E = M.alias_end(); I != E; ++I) {
461         incorporateType(I->getType());
462         if (const Value *Aliasee = I->getAliasee())
463           incorporateValue(Aliasee);
464       }
465       
466       SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
467
468       // Get types from functions.
469       for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
470         incorporateType(FI->getType());
471         
472         for (Function::const_iterator BB = FI->begin(), E = FI->end();
473              BB != E;++BB)
474           for (BasicBlock::const_iterator II = BB->begin(),
475                E = BB->end(); II != E; ++II) {
476             const Instruction &I = *II;
477             // Incorporate the type of the instruction and all its operands.
478             incorporateType(I.getType());
479             for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
480                  OI != OE; ++OI)
481               incorporateValue(*OI);
482             
483             // Incorporate types hiding in metadata.
484             I.getAllMetadataOtherThanDebugLoc(MDForInst);
485             for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
486               incorporateMDNode(MDForInst[i].second);
487             MDForInst.clear();
488           }
489       }
490       
491       for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
492            E = M.named_metadata_end(); I != E; ++I) {
493         const NamedMDNode *NMD = I;
494         for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
495           incorporateMDNode(NMD->getOperand(i));
496       }
497     }
498     
499   private:
500     void incorporateType(Type *Ty) {
501       // Check to see if we're already visited this type.
502       if (!VisitedTypes.insert(Ty).second)
503         return;
504       
505       // If this is a structure or opaque type, add a name for the type.
506       if (StructType *STy = dyn_cast<StructType>(Ty))
507         StructTypes.push_back(STy);
508       
509       // Recursively walk all contained types.
510       for (Type::subtype_iterator I = Ty->subtype_begin(),
511            E = Ty->subtype_end(); I != E; ++I)
512         incorporateType(*I);
513     }
514     
515     /// incorporateValue - This method is used to walk operand lists finding
516     /// types hiding in constant expressions and other operands that won't be
517     /// walked in other ways.  GlobalValues, basic blocks, instructions, and
518     /// inst operands are all explicitly enumerated.
519     void incorporateValue(const Value *V) {
520       if (const MDNode *M = dyn_cast<MDNode>(V))
521         return incorporateMDNode(M);
522       if (!isa<Constant>(V) || isa<GlobalValue>(V)) return;
523       
524       // Already visited?
525       if (!VisitedConstants.insert(V).second)
526         return;
527       
528       // Check this type.
529       incorporateType(V->getType());
530       
531       // Look in operands for types.
532       const User *U = cast<User>(V);
533       for (Constant::const_op_iterator I = U->op_begin(),
534            E = U->op_end(); I != E;++I)
535         incorporateValue(*I);
536     }
537     
538     void incorporateMDNode(const MDNode *V) {
539       
540       // Already visited?
541       if (!VisitedConstants.insert(V).second)
542         return;
543       
544       // Look in operands for types.
545       for (unsigned i = 0, e = V->getNumOperands(); i != e; ++i)
546         if (Value *Op = V->getOperand(i))
547           incorporateValue(Op);
548     }
549   };
550 } // end anonymous namespace
551
552 void Module::findUsedStructTypes(std::vector<StructType*> &StructTypes) const {
553   TypeFinder(StructTypes).run(*this);
554 }
555
556