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