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