1 //===-- Module.cpp - Implement the Module class ------------------*- C++ -*--=//
3 // This file implements the Module class for the VMCore library.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Module.h"
8 #include "llvm/InstrTypes.h"
9 #include "llvm/Constants.h"
10 #include "llvm/DerivedTypes.h"
11 #include "Support/STLExtras.h"
12 #include "Support/LeakDetector.h"
13 #include "SymbolTableListTraitsImpl.h"
18 Function *ilist_traits<Function>::createNode() {
20 FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
21 Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
22 // This should not be garbage monitored.
23 LeakDetector::removeGarbageObject(Ret);
26 GlobalVariable *ilist_traits<GlobalVariable>::createNode() {
27 GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
28 GlobalValue::ExternalLinkage);
29 // This should not be garbage monitored.
30 LeakDetector::removeGarbageObject(Ret);
34 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
35 return M->getFunctionList();
37 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
38 return M->getGlobalList();
41 // Explicit instantiations of SymbolTableListTraits since some of the methods
42 // are not in the public header file...
43 template SymbolTableListTraits<GlobalVariable, Module, Module>;
44 template SymbolTableListTraits<Function, Module, Module>;
46 // Define the GlobalValueRefMap as a struct that wraps a map so that we don't
47 // have Module.h depend on <map>
49 struct GlobalValueRefMap {
50 typedef std::map<GlobalValue*, ConstantPointerRef*> MapTy;
51 typedef MapTy::iterator iterator;
52 std::map<GlobalValue*, ConstantPointerRef*> Map;
56 Module::Module(const std::string &MID)
57 : ModuleID(MID), Endian(AnyEndianness), PtrSize(AnyPointerSize) {
58 FunctionList.setItemParent(this);
59 FunctionList.setParent(this);
60 GlobalList.setItemParent(this);
61 GlobalList.setParent(this);
63 SymTab = new SymbolTable();
69 GlobalList.setParent(0);
71 FunctionList.setParent(0);
75 // Module::dump() - Allow printing from debugger
76 void Module::dump() const {
80 // getOrInsertFunction - Look up the specified function in the module symbol
81 // table. If it does not exist, add a prototype for the function and return
82 // it. This is nice because it allows most passes to get away with not handling
83 // the symbol table directly for this common task.
85 Function *Module::getOrInsertFunction(const std::string &Name,
86 const FunctionType *Ty) {
87 SymbolTable &SymTab = getSymbolTable();
89 // See if we have a definitions for the specified function already...
90 if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
91 return cast<Function>(V); // Yup, got it
92 } else { // Nope, add one
93 Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
94 FunctionList.push_back(New);
95 return New; // Return the new prototype...
99 // getOrInsertFunction - Look up the specified function in the module symbol
100 // table. If it does not exist, add a prototype for the function and return it.
101 // This version of the method takes a null terminated list of function
102 // arguments, which makes it easier for clients to use.
104 Function *Module::getOrInsertFunction(const std::string &Name,
105 const Type *RetTy, ...) {
107 va_start(Args, RetTy);
109 // Build the list of argument types...
110 std::vector<const Type*> ArgTys;
111 while (const Type *ArgTy = va_arg(Args, const Type*))
112 ArgTys.push_back(ArgTy);
116 // Build the function type and chain to the other getOrInsertFunction...
117 return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
122 // getFunction - Look up the specified function in the module symbol table.
123 // If it does not exist, return null.
125 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
126 SymbolTable &SymTab = getSymbolTable();
127 return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
130 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
131 // there is already an entry for this name, true is returned and the symbol
132 // table is not modified.
134 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
135 SymbolTable &ST = getSymbolTable();
137 if (ST.lookup(Type::TypeTy, Name)) return true; // Already in symtab...
139 // Not in symbol table? Set the name with the Symtab as an argument so the
140 // type knows what to update...
141 ((Value*)Ty)->setName(Name, &ST);
146 /// getMainFunction - This function looks up main efficiently. This is such a
147 /// common case, that it is a method in Module. If main cannot be found, a
148 /// null pointer is returned.
150 Function *Module::getMainFunction() {
151 std::vector<const Type*> Params;
154 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
158 // void main(void)...
159 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
163 Params.push_back(Type::IntTy);
165 // int main(int argc)...
166 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
170 // void main(int argc)...
171 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
175 for (unsigned i = 0; i != 2; ++i) { // Check argv and envp
176 Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
178 // int main(int argc, char **argv)...
179 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
183 // void main(int argc, char **argv)...
184 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
189 // Ok, try to find main the hard way...
190 return getNamedFunction("main");
193 /// getNamedFunction - Return the first function in the module with the
194 /// specified name, of arbitrary type. This method returns null if a function
195 /// with the specified name is not found.
197 Function *Module::getNamedFunction(const std::string &Name) {
198 // Loop over all of the functions, looking for the function desired
200 for (iterator I = begin(), E = end(); I != E; ++I)
201 if (I->getName() == Name)
206 return Found; // Non-external function not found...
211 // getTypeName - If there is at least one entry in the symbol table for the
212 // specified type, return it.
214 std::string Module::getTypeName(const Type *Ty) {
215 const SymbolTable &ST = getSymbolTable();
216 if (ST.find(Type::TypeTy) == ST.end())
217 return ""; // No names for types...
219 SymbolTable::type_const_iterator TI = ST.type_begin(Type::TypeTy);
220 SymbolTable::type_const_iterator TE = ST.type_end(Type::TypeTy);
222 while (TI != TE && TI->second != (const Value*)Ty)
225 if (TI != TE) // Must have found an entry!
227 return ""; // Must not have found anything...
231 // dropAllReferences() - This function causes all the subelementss to "let go"
232 // of all references that they are maintaining. This allows one to 'delete' a
233 // whole module at a time, even though there may be circular references... first
234 // all references are dropped, and all use counts go to zero. Then everything
235 // is delete'd for real. Note that no operations are valid on an object that
236 // has "dropped all references", except operator delete.
238 void Module::dropAllReferences() {
239 for(Module::iterator I = begin(), E = end(); I != E; ++I)
240 I->dropAllReferences();
242 for(Module::giterator I = gbegin(), E = gend(); I != E; ++I)
243 I->dropAllReferences();
245 // If there are any GlobalVariable references still out there, nuke them now.
246 // Since all references are hereby dropped, nothing could possibly reference
247 // them still. Note that destroying all of the constant pointer refs will
248 // eventually cause the GVRefMap field to be set to null (by
249 // destroyConstantPointerRef, below).
252 // Delete the ConstantPointerRef node...
253 GVRefMap->Map.begin()->second->destroyConstant();
256 // Accessor for the underlying GlobalValRefMap...
257 ConstantPointerRef *Module::getConstantPointerRef(GlobalValue *V){
258 // Create ref map lazily on demand...
259 if (GVRefMap == 0) GVRefMap = new GlobalValueRefMap();
261 GlobalValueRefMap::iterator I = GVRefMap->Map.find(V);
262 if (I != GVRefMap->Map.end()) return I->second;
264 ConstantPointerRef *Ref = new ConstantPointerRef(V);
265 GVRefMap->Map[V] = Ref;
269 void Module::destroyConstantPointerRef(ConstantPointerRef *CPR) {
270 assert(GVRefMap && "No map allocated, but we have a CPR?");
271 if (!GVRefMap->Map.erase(CPR->getValue())) // Remove it from the map...
272 assert(0 && "ConstantPointerRef not found in module CPR map!");
274 if (GVRefMap->Map.empty()) { // If the map is empty, delete it.
280 void Module::mutateConstantPointerRef(GlobalValue *OldGV, GlobalValue *NewGV) {
281 assert(OldGV != NewGV && "Cannot mutate to the same global!");
282 GlobalValueRefMap::iterator I = GVRefMap->Map.find(OldGV);
283 assert(I != GVRefMap->Map.end() &&
284 "mutateConstantPointerRef; OldGV not in table!");
285 ConstantPointerRef *Ref = I->second;
287 // Remove the old entry...
288 GVRefMap->Map.erase(I);
290 // Check to see if a CPR already exists for NewGV
291 I = GVRefMap->Map.lower_bound(NewGV);
293 if (I == GVRefMap->Map.end() || I->first != NewGV) {
294 // Insert the new entry...
295 GVRefMap->Map.insert(I, std::make_pair(NewGV, Ref));
297 // Otherwise, an entry already exists for the current global value.
298 // Completely replace the old CPR with the existing one...
299 Ref->replaceAllUsesWith(I->second);