Module.cpp revision 1c7b907325e9cf3a0713ceab5029fef04d9e498c
1//===-- Module.cpp - Implement the Module class ---------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/Support/LeakDetector.h"
20#include "SymbolTableListTraitsImpl.h"
21#include <algorithm>
22#include <cstdarg>
23#include <iostream>
24#include <map>
25using namespace llvm;
26
27//===----------------------------------------------------------------------===//
28// Methods to implement the globals and functions lists.
29//
30
31Function *ilist_traits<Function>::createNode() {
32  FunctionType *FTy =
33    FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
34  Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
35  // This should not be garbage monitored.
36  LeakDetector::removeGarbageObject(Ret);
37  return Ret;
38}
39GlobalVariable *ilist_traits<GlobalVariable>::createNode() {
40  GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
41                                           GlobalValue::ExternalLinkage);
42  // This should not be garbage monitored.
43  LeakDetector::removeGarbageObject(Ret);
44  return Ret;
45}
46
47iplist<Function> &ilist_traits<Function>::getList(Module *M) {
48  return M->getFunctionList();
49}
50iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
51  return M->getGlobalList();
52}
53
54// Explicit instantiations of SymbolTableListTraits since some of the methods
55// are not in the public header file...
56template class SymbolTableListTraits<GlobalVariable, Module, Module>;
57template class SymbolTableListTraits<Function, Module, Module>;
58
59//===----------------------------------------------------------------------===//
60// Primitive Module methods.
61//
62
63Module::Module(const std::string &MID)
64  : ModuleID(MID), Endian(AnyEndianness), PtrSize(AnyPointerSize) {
65  FunctionList.setItemParent(this);
66  FunctionList.setParent(this);
67  GlobalList.setItemParent(this);
68  GlobalList.setParent(this);
69  SymTab = new SymbolTable();
70}
71
72Module::~Module() {
73  dropAllReferences();
74  GlobalList.clear();
75  GlobalList.setParent(0);
76  FunctionList.clear();
77  FunctionList.setParent(0);
78  LibraryList.clear();
79  delete SymTab;
80}
81
82// Module::dump() - Allow printing from debugger
83void Module::dump() const {
84  print(std::cerr);
85}
86
87//===----------------------------------------------------------------------===//
88// Methods for easy access to the functions in the module.
89//
90
91// getOrInsertFunction - Look up the specified function in the module symbol
92// table.  If it does not exist, add a prototype for the function and return
93// it.  This is nice because it allows most passes to get away with not handling
94// the symbol table directly for this common task.
95//
96Function *Module::getOrInsertFunction(const std::string &Name,
97                                      const FunctionType *Ty) {
98  SymbolTable &SymTab = getSymbolTable();
99
100  // See if we have a definitions for the specified function already...
101  if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
102    return cast<Function>(V);      // Yup, got it
103  } else {                         // Nope, add one
104    Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
105    FunctionList.push_back(New);
106    return New;                    // Return the new prototype...
107  }
108}
109
110// getOrInsertFunction - Look up the specified function in the module symbol
111// table.  If it does not exist, add a prototype for the function and return it.
112// This version of the method takes a null terminated list of function
113// arguments, which makes it easier for clients to use.
114//
115Function *Module::getOrInsertFunction(const std::string &Name,
116                                      const Type *RetTy, ...) {
117  va_list Args;
118  va_start(Args, RetTy);
119
120  // Build the list of argument types...
121  std::vector<const Type*> ArgTys;
122  while (const Type *ArgTy = va_arg(Args, const Type*))
123    ArgTys.push_back(ArgTy);
124
125  va_end(Args);
126
127  // Build the function type and chain to the other getOrInsertFunction...
128  return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
129}
130
131
132// getFunction - Look up the specified function in the module symbol table.
133// If it does not exist, return null.
134//
135Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
136  SymbolTable &SymTab = getSymbolTable();
137  return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
138}
139
140
141/// getMainFunction - This function looks up main efficiently.  This is such a
142/// common case, that it is a method in Module.  If main cannot be found, a
143/// null pointer is returned.
144///
145Function *Module::getMainFunction() {
146  std::vector<const Type*> Params;
147
148  // int main(void)...
149  if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
150                                                          Params, false)))
151    return F;
152
153  // void main(void)...
154  if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
155                                                          Params, false)))
156    return F;
157
158  Params.push_back(Type::IntTy);
159
160  // int main(int argc)...
161  if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
162                                                          Params, false)))
163    return F;
164
165  // void main(int argc)...
166  if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
167                                                          Params, false)))
168    return F;
169
170  for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
171    Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
172
173    // int main(int argc, char **argv)...
174    if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
175                                                            Params, false)))
176      return F;
177
178    // void main(int argc, char **argv)...
179    if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
180                                                            Params, false)))
181      return F;
182  }
183
184  // Ok, try to find main the hard way...
185  return getNamedFunction("main");
186}
187
188/// getNamedFunction - Return the first function in the module with the
189/// specified name, of arbitrary type.  This method returns null if a function
190/// with the specified name is not found.
191///
192Function *Module::getNamedFunction(const std::string &Name) {
193  // Loop over all of the functions, looking for the function desired
194  Function *Found = 0;
195  for (iterator I = begin(), E = end(); I != E; ++I)
196    if (I->getName() == Name)
197      if (I->isExternal())
198        Found = I;
199      else
200        return I;
201  return Found; // Non-external function not found...
202}
203
204//===----------------------------------------------------------------------===//
205// Methods for easy access to the global variables in the module.
206//
207
208/// getGlobalVariable - Look up the specified global variable in the module
209/// symbol table.  If it does not exist, return null.  Note that this only
210/// returns a global variable if it does not have internal linkage.  The type
211/// argument should be the underlying type of the global, ie, it should not
212/// have the top-level PointerType, which represents the address of the
213/// global.
214///
215GlobalVariable *Module::getGlobalVariable(const std::string &Name,
216                                          const Type *Ty) {
217  if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
218    GlobalVariable *Result = cast<GlobalVariable>(V);
219    if (!Result->hasInternalLinkage())
220      return Result;
221  }
222  return 0;
223}
224
225
226
227//===----------------------------------------------------------------------===//
228// Methods for easy access to the types in the module.
229//
230
231
232// addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
233// there is already an entry for this name, true is returned and the symbol
234// table is not modified.
235//
236bool Module::addTypeName(const std::string &Name, const Type *Ty) {
237  SymbolTable &ST = getSymbolTable();
238
239  if (ST.lookupType(Name)) return true;  // Already in symtab...
240
241  // Not in symbol table?  Set the name with the Symtab as an argument so the
242  // type knows what to update...
243  ST.insert(Name, Ty);
244
245  return false;
246}
247
248/// getTypeByName - Return the type with the specified name in this module, or
249/// null if there is none by that name.
250const Type *Module::getTypeByName(const std::string &Name) const {
251  const SymbolTable &ST = getSymbolTable();
252  return cast_or_null<Type>(ST.lookupType(Name));
253}
254
255// getTypeName - If there is at least one entry in the symbol table for the
256// specified type, return it.
257//
258std::string Module::getTypeName(const Type *Ty) const {
259  const SymbolTable &ST = getSymbolTable();
260
261  SymbolTable::type_const_iterator TI = ST.type_begin();
262  SymbolTable::type_const_iterator TE = ST.type_end();
263  if ( TI == TE ) return ""; // No names for types
264
265  while (TI != TE && TI->second != Ty)
266    ++TI;
267
268  if (TI != TE)  // Must have found an entry!
269    return TI->first;
270  return "";     // Must not have found anything...
271}
272
273//===----------------------------------------------------------------------===//
274// Other module related stuff.
275//
276
277
278// dropAllReferences() - This function causes all the subelementss to "let go"
279// of all references that they are maintaining.  This allows one to 'delete' a
280// whole module at a time, even though there may be circular references... first
281// all references are dropped, and all use counts go to zero.  Then everything
282// is deleted for real.  Note that no operations are valid on an object that
283// has "dropped all references", except operator delete.
284//
285void Module::dropAllReferences() {
286  for(Module::iterator I = begin(), E = end(); I != E; ++I)
287    I->dropAllReferences();
288
289  for(Module::giterator I = gbegin(), E = gend(); I != E; ++I)
290    I->dropAllReferences();
291}
292
293