Remove unused var
[oota-llvm.git] / lib / VMCore / SymbolTable.cpp
1 //===-- SymbolTable.cpp - Implement the SymbolTable class -----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and revised by Reid
6 // Spencer. It is distributed under the University of Illinois Open Source 
7 // License. See LICENSE.TXT for details.
8 // 
9 //===----------------------------------------------------------------------===//
10 //
11 // This file implements the SymbolTable class for the VMCore library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/SymbolTable.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "Support/StringExtras.h"
19 #include <algorithm>
20
21 using namespace llvm;
22
23 #define DEBUG_SYMBOL_TABLE 0
24 #define DEBUG_ABSTYPE 0
25
26 SymbolTable::~SymbolTable() {
27   // Drop all abstract type references in the type plane...
28   for (type_iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
29     if (TI->second->isAbstract())   // If abstract, drop the reference...
30       cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
31   }
32
33  // TODO: FIXME: BIG ONE: This doesn't unreference abstract types for the 
34  // planes that could still have entries!
35
36 #ifndef NDEBUG   // Only do this in -g mode...
37   bool LeftoverValues = true;
38   for (plane_iterator PI = pmap.begin(); PI != pmap.end(); ++PI) {
39     for (value_iterator VI = PI->second.begin(); VI != PI->second.end(); ++VI)
40       if (!isa<Constant>(VI->second) ) {
41         std::cerr << "Value still in symbol table! Type = '"
42                   << PI->first->getDescription() << "' Name = '"
43                   << VI->first << "'\n";
44         LeftoverValues = false;
45       }
46   }
47   
48   assert(LeftoverValues && "Values remain in symbol table!");
49 #endif
50 }
51
52 // getUniqueName - Given a base name, return a string that is either equal to
53 // it (or derived from it) that does not already occur in the symbol table for
54 // the specified type.
55 //
56 std::string SymbolTable::getUniqueName(const Type *Ty,
57                                        const std::string &BaseName) const {
58   // Find the plane
59   plane_const_iterator PI = pmap.find(Ty);
60   if (PI == pmap.end()) return BaseName;
61
62   std::string TryName = BaseName;
63   const ValueMap& vmap = PI->second;
64   value_const_iterator End = vmap.end();
65
66   // See if the name exists
67   while (vmap.find(TryName) != End)            // Loop until we find a free
68     TryName = BaseName + utostr(++LastUnique); // name in the symbol table
69   return TryName;
70 }
71
72
73 // lookup a value - Returns null on failure...
74 Value *SymbolTable::lookup(const Type *Ty, const std::string &Name) const {
75   plane_const_iterator PI = pmap.find(Ty);
76   if (PI != pmap.end()) {                  // We have symbols in that plane...
77     value_const_iterator VI = PI->second.find(Name);
78     if (VI != PI->second.end())            // and the name is in our hash table...
79       return VI->second;
80   }
81   return 0;
82 }
83
84
85 // lookup a type by name - returns null on failure
86 Type* SymbolTable::lookupType( const std::string& Name ) const {
87   type_const_iterator TI = tmap.find( Name );
88   if ( TI != tmap.end() )
89     return TI->second;
90   return 0;
91 }
92
93 // Remove a value
94 void SymbolTable::remove(Value *N) {
95   assert(N->hasName() && "Value doesn't have name!");
96   assert(!isa<Type>(N) && "Can't remove types through this interface.");
97   if (InternallyInconsistent) return;
98
99   plane_iterator PI = pmap.find(N->getType());
100   assert(PI != pmap.end() &&
101          "Trying to remove a value that doesn't have a type plane yet!");
102   removeEntry(PI, PI->second.find(N->getName()));
103 }
104
105
106 // removeEntry - Remove a value from the symbol table...
107 Value *SymbolTable::removeEntry(plane_iterator Plane, value_iterator Entry) {
108   if (InternallyInconsistent) return 0;
109   assert(Plane != pmap.end() &&
110          Entry != Plane->second.end() && "Invalid entry to remove!");
111
112   Value *Result = Entry->second;
113   assert(!isa<Type>(Result) && "Can't remove types through this interface.");
114 #if DEBUG_SYMBOL_TABLE
115   dump();
116   std::cerr << " Removing Value: " << Result->getName() << "\n";
117 #endif
118
119   // Remove the value from the plane...
120   Plane->second.erase(Entry);
121
122   // If the plane is empty, remove it now!
123   if (Plane->second.empty()) {
124     // If the plane represented an abstract type that we were interested in,
125     // unlink ourselves from this plane.
126     //
127     if (Plane->first->isAbstract()) {
128 #if DEBUG_ABSTYPE
129       std::cerr << "Plane Empty: Removing type: "
130                 << Plane->first->getDescription() << "\n";
131 #endif
132       cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this);
133     }
134
135     pmap.erase(Plane);
136   }
137   return Result;
138 }
139
140
141 // remove - Remove a type
142 void SymbolTable::remove(Type* Ty ) {
143   type_iterator TI = this->type_begin();
144   type_iterator TE = this->type_end();
145
146   // Search for the entry
147   while ( TI != TE && TI->second != Ty )
148     ++TI;
149
150   if ( TI != TE )
151     this->removeEntry( TI );
152 }
153
154
155 // removeEntry - Remove a type from the symbol table...
156 Type* SymbolTable::removeEntry(type_iterator Entry) {
157   if (InternallyInconsistent) return 0;
158   assert( Entry != tmap.end() && "Invalid entry to remove!");
159
160   Type* Result = Entry->second;
161
162 #if DEBUG_SYMBOL_TABLE
163   dump();
164   std::cerr << " Removing Value: " << Result->getName() << "\n";
165 #endif
166
167   tmap.erase(Entry);
168
169   // If we are removing an abstract type, remove the symbol table from it's use
170   // list...
171   if (Result->isAbstract()) {
172 #if DEBUG_ABSTYPE
173     std::cerr << "Removing abstract type from symtab" << Result->getDescription()<<"\n";
174 #endif
175     cast<DerivedType>(Result)->removeAbstractTypeUser(this);
176   }
177
178   return Result;
179 }
180
181
182 // insertEntry - Insert a value into the symbol table with the specified name.
183 void SymbolTable::insertEntry(const std::string &Name, const Type *VTy,
184                               Value *V) {
185   assert(!isa<Type>(V) && "Can't insert types through this interface.");
186   // Check to see if there is a naming conflict.  If so, rename this value!
187   if (lookup(VTy, Name)) {
188     std::string UniqueName = getUniqueName(VTy, Name);
189     assert(InternallyInconsistent == false && "Infinite loop inserting value!");
190     InternallyInconsistent = true;
191     V->setName(UniqueName, this);
192     InternallyInconsistent = false;
193     return;
194   }
195
196 #if DEBUG_SYMBOL_TABLE
197   dump();
198   std::cerr << " Inserting definition: " << Name << ": " 
199             << VTy->getDescription() << "\n";
200 #endif
201
202   plane_iterator PI = pmap.find(VTy);
203   if (PI == pmap.end()) {      // Not in collection yet... insert dummy entry
204     // Insert a new empty element.  I points to the new elements.
205     PI = pmap.insert(make_pair(VTy, ValueMap())).first;
206     assert(PI != pmap.end() && "How did insert fail?");
207
208     // Check to see if the type is abstract.  If so, it might be refined in the
209     // future, which would cause the plane of the old type to get merged into
210     // a new type plane.
211     //
212     if (VTy->isAbstract()) {
213       cast<DerivedType>(VTy)->addAbstractTypeUser(this);
214 #if DEBUG_ABSTYPE
215       std::cerr << "Added abstract type value: " << VTy->getDescription()
216                 << "\n";
217 #endif
218     }
219   }
220
221   PI->second.insert(make_pair(Name, V));
222 }
223
224
225 // insertEntry - Insert a value into the symbol table with the specified
226 // name...
227 //
228 void SymbolTable::insertEntry(const std::string& Name, Type* T) {
229
230   // Check to see if there is a naming conflict.  If so, rename this type!
231   std::string UniqueName = Name;
232   if (lookupType(Name))
233     UniqueName = getUniqueName(T, Name);
234
235 #if DEBUG_SYMBOL_TABLE
236   dump();
237   std::cerr << " Inserting type: " << UniqueName << ": " 
238             << T->getDescription() << "\n";
239 #endif
240
241   // Insert the tmap entry
242   tmap.insert(make_pair(UniqueName, T));
243
244   // If we are adding an abstract type, add the symbol table to it's use list.
245   if (T->isAbstract()) {
246     cast<DerivedType>(T)->addAbstractTypeUser(this);
247 #if DEBUG_ABSTYPE
248     std::cerr << "Added abstract type to ST: " << T->getDescription() << "\n";
249 #endif
250   }
251 }
252
253
254 // Determine how many entries for a given type.
255 unsigned SymbolTable::type_size(const Type *Ty) const {
256   plane_const_iterator PI = pmap.find(Ty);
257   if ( PI == pmap.end() ) return 0;
258   return PI->second.size();
259 }
260
261
262 // Get the name of a value
263 std::string SymbolTable::get_name( const Value* V ) const {
264   assert(!isa<Type>(V) && "Can't get name of types through this interface.");
265   value_const_iterator VI = this->value_begin( V->getType() );
266   value_const_iterator VE = this->value_end( V->getType() );
267
268   // Search for the entry
269   while ( VI != VE && VI->second != V )
270     ++VI;
271
272   if ( VI != VE )
273     return VI->first;
274
275   return "";
276 }
277
278
279 // Get the name of a type
280 std::string SymbolTable::get_name( const Type* T ) const {
281   if (tmap.empty()) return ""; // No types at all.
282
283   type_const_iterator TI = tmap.begin();
284   type_const_iterator TE = tmap.end();
285
286   // Search for the entry
287   while (TI != TE && TI->second != T )
288     ++TI;
289
290   if (TI != TE)  // Must have found an entry!
291     return TI->first;
292   return "";     // Must not have found anything...
293 }
294
295
296 // Strip the symbol table of its names.
297 bool SymbolTable::strip( void ) {
298   bool RemovedSymbol = false;
299   for (plane_iterator I = pmap.begin(); I != pmap.end();) {
300     // Removing items from the plane can cause the plane itself to get deleted.
301     // If this happens, make sure we incremented our plane iterator already!
302     ValueMap &Plane = (I++)->second;
303     value_iterator B = Plane.begin(), Bend = Plane.end();
304     while (B != Bend) {   // Found nonempty type plane!
305       Value *V = B->second;
306       if (isa<Constant>(V)) {
307         remove(V);
308         RemovedSymbol = true;
309       } else {
310         if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()){
311           // Set name to "", removing from symbol table!
312           V->setName("", this);
313           RemovedSymbol = true;
314         }
315       }
316       ++B;
317     }
318   }
319
320   for (type_iterator TI = tmap.begin(); TI != tmap.end(); ) {
321     Type* T = (TI++)->second;
322     remove(T);
323     RemovedSymbol = true;
324   }
325  
326   return RemovedSymbol;
327 }
328
329
330 // This function is called when one of the types in the type plane are refined
331 void SymbolTable::refineAbstractType(const DerivedType *OldType,
332                                      const Type *NewType) {
333
334   // Search to see if we have any values of the type Oldtype.  If so, we need to
335   // move them into the newtype plane...
336   plane_iterator PI = pmap.find(OldType);
337   if (PI != pmap.end()) {
338     // Get a handle to the new type plane...
339     plane_iterator NewTypeIt = pmap.find(NewType);
340     if (NewTypeIt == pmap.end()) {      // If no plane exists, add one
341       NewTypeIt = pmap.insert(make_pair(NewType, ValueMap())).first;
342       
343       if (NewType->isAbstract()) {
344         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
345 #if DEBUG_ABSTYPE
346         std::cerr << "[Added] refined to abstype: " << NewType->getDescription()
347                   << "\n";
348 #endif
349       }
350     }
351
352     ValueMap &NewPlane = NewTypeIt->second;
353     ValueMap &OldPlane = PI->second;
354     while (!OldPlane.empty()) {
355       std::pair<const std::string, Value*> V = *OldPlane.begin();
356
357       // Check to see if there is already a value in the symbol table that this
358       // would collide with.
359       value_iterator VI = NewPlane.find(V.first);
360       if (VI != NewPlane.end() && VI->second == V.second) {
361         // No action
362
363       } else if (VI != NewPlane.end()) {
364         // The only thing we are allowing for now is two external global values
365         // folded into one.
366         //
367         GlobalValue *ExistGV = dyn_cast<GlobalValue>(VI->second);
368         GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second);
369
370         if (ExistGV && NewGV) {
371           assert((ExistGV->isExternal() || NewGV->isExternal()) &&
372                  "Two planes folded together with overlapping value names!");
373
374           // Make sure that ExistGV is the one we want to keep!
375           if (!NewGV->isExternal())
376             std::swap(NewGV, ExistGV);
377
378           // Ok we have two external global values.  Make all uses of the new
379           // one use the old one...
380           NewGV->uncheckedReplaceAllUsesWith(ExistGV);
381           
382           // Now we just convert it to an unnamed method... which won't get
383           // added to our symbol table.  The problem is that if we call
384           // setName on the method that it will try to remove itself from
385           // the symbol table and die... because it's not in the symtab
386           // right now.  To fix this, we have an internally consistent flag
387           // that turns remove into a noop.  Thus the name will get null'd
388           // out, but the symbol table won't get upset.
389           //
390           assert(InternallyInconsistent == false &&
391                  "Symbol table already inconsistent!");
392           InternallyInconsistent = true;
393
394           // Remove newM from the symtab
395           NewGV->setName("");
396           InternallyInconsistent = false;
397
398           // Now we can remove this global from the module entirely...
399           Module *M = NewGV->getParent();
400           if (Function *F = dyn_cast<Function>(NewGV))
401             M->getFunctionList().remove(F);
402           else
403             M->getGlobalList().remove(cast<GlobalVariable>(NewGV));
404           delete NewGV;
405         } else {
406           // If they are not global values, they must be just random values who
407           // happen to conflict now that types have been resolved.  If this is
408           // the case, reinsert the value into the new plane, allowing it to get
409           // renamed.
410           assert(V.second->getType() == NewType &&"Type resolution is broken!");
411           insert(V.second);
412         }
413       } else {
414         insertEntry(V.first, NewType, V.second);
415
416       }
417       // Remove the item from the old type plane
418       OldPlane.erase(OldPlane.begin());
419     }
420
421     // Ok, now we are not referencing the type anymore... take me off your user
422     // list please!
423 #if DEBUG_ABSTYPE
424     std::cerr << "Removing type " << OldType->getDescription() << "\n";
425 #endif
426     OldType->removeAbstractTypeUser(this);
427
428     // Remove the plane that is no longer used
429     pmap.erase(PI);
430   }
431
432   // Loop over all of the types in the symbol table, replacing any references
433   // to OldType with references to NewType.  Note that there may be multiple
434   // occurrences, and although we only need to remove one at a time, it's
435   // faster to remove them all in one pass.
436   //
437   for (type_iterator I = type_begin(), E = type_end(); I != E; ++I) {
438     if (I->second == (Type*)OldType) {  // FIXME when Types aren't const.
439 #if DEBUG_ABSTYPE
440       std::cerr << "Removing type " << OldType->getDescription() << "\n";
441 #endif
442       OldType->removeAbstractTypeUser(this);
443         
444       I->second = (Type*)NewType;  // TODO FIXME when types aren't const
445       if (NewType->isAbstract()) {
446 #if DEBUG_ABSTYPE
447         std::cerr << "Added type " << NewType->getDescription() << "\n";
448 #endif
449         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
450       }
451     }
452   }
453 }
454
455
456 // Handle situation where type becomes Concreate from Abstract
457 void SymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
458   plane_iterator PI = pmap.find(AbsTy);
459
460   // If there are any values in the symbol table of this type, then the type
461   // plane is a use of the abstract type which must be dropped.
462   if (PI != pmap.end())
463     AbsTy->removeAbstractTypeUser(this);
464
465   // Loop over all of the types in the symbol table, dropping any abstract
466   // type user entries for AbsTy which occur because there are names for the
467   // type.
468   for (type_iterator TI = type_begin(), TE = type_end(); TI != TE; ++TI)
469     if (TI->second == (Type*)AbsTy)   // FIXME when Types aren't const.
470       AbsTy->removeAbstractTypeUser(this);
471 }
472
473 static void DumpVal(const std::pair<const std::string, Value *> &V) {
474   std::cerr << "  '" << V.first << "' = ";
475   V.second->dump();
476   std::cerr << "\n";
477 }
478
479 static void DumpPlane(const std::pair<const Type *,
480                                       std::map<const std::string, Value *> >&P){
481   P.first->dump();
482   std::cerr << "\n";
483   for_each(P.second.begin(), P.second.end(), DumpVal);
484 }
485
486 static void DumpTypes(const std::pair<const std::string, Type*>& T ) {
487   std::cerr << "  '" << T.first << "' = ";
488   T.second->dump();
489   std::cerr << "\n";
490 }
491
492 void SymbolTable::dump() const {
493   std::cerr << "Symbol table dump:\n  Plane:";
494   for_each(pmap.begin(), pmap.end(), DumpPlane);
495   std::cerr << "  Types: ";
496   for_each(tmap.begin(), tmap.end(), DumpTypes);
497 }
498
499 // vim: sw=2 ai