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