For PR950:
[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 "llvm/Support/Debug.h"
20 #include <algorithm>
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         DOUT << "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 const_cast<Type*>(TI->second);
90   return 0;
91 }
92
93 /// changeName - Given a value with a non-empty name, remove its existing entry
94 /// from the symbol table and insert a new one for Name.  This is equivalent to
95 /// doing "remove(V), V->Name = Name, insert(V)", but is faster, and will not
96 /// temporarily remove the symbol table plane if V is the last value in the
97 /// symtab with that name (which could invalidate iterators to that plane).
98 void SymbolTable::changeName(Value *V, const std::string &name) {
99   assert(!V->getName().empty() && !name.empty() && V->getName() != name &&
100          "Illegal use of this method!");
101
102   plane_iterator PI = pmap.find(V->getType());
103   assert(PI != pmap.end() && "Value doesn't have an entry in this table?");
104   ValueMap &VM = PI->second;
105
106   value_iterator VI = VM.find(V->getName());
107   assert(VI != VM.end() && "Value does have an entry in this table?");
108
109   // Remove the old entry.
110   VM.erase(VI);
111
112   // See if we can insert the new name.
113   VI = VM.lower_bound(name);
114
115   // Is there a naming conflict?
116   if (VI != VM.end() && VI->first == name) {
117     V->Name = getUniqueName(V->getType(), name);
118     VM.insert(make_pair(V->Name, V));
119   } else {
120     V->Name = name;
121     VM.insert(VI, make_pair(name, V));
122   }
123 }
124
125 // Remove a value
126 void SymbolTable::remove(Value *N) {
127   assert(N->hasName() && "Value doesn't have name!");
128
129   plane_iterator PI = pmap.find(N->getType());
130   assert(PI != pmap.end() &&
131          "Trying to remove a value that doesn't have a type plane yet!");
132   ValueMap &VM = PI->second;
133   value_iterator Entry = VM.find(N->getName());
134   assert(Entry != VM.end() && "Invalid entry to remove!");
135
136 #if DEBUG_SYMBOL_TABLE
137   dump();
138   DOUT << " Removing Value: " << Entry->second->getName() << "\n";
139 #endif
140
141   // Remove the value from the plane...
142   VM.erase(Entry);
143
144   // If the plane is empty, remove it now!
145   if (VM.empty()) {
146     // If the plane represented an abstract type that we were interested in,
147     // unlink ourselves from this plane.
148     //
149     if (N->getType()->isAbstract()) {
150 #if DEBUG_ABSTYPE
151       DOUT << "Plane Empty: Removing type: "
152            << N->getType()->getDescription() << "\n";
153 #endif
154       cast<DerivedType>(N->getType())->removeAbstractTypeUser(this);
155     }
156
157     pmap.erase(PI);
158   }
159 }
160
161 // remove - Remove a type from the symbol table...
162 Type* SymbolTable::remove(type_iterator Entry) {
163   assert(Entry != tmap.end() && "Invalid entry to remove!");
164
165   const Type* Result = Entry->second;
166
167 #if DEBUG_SYMBOL_TABLE
168   dump();
169   DOUT << " Removing type: " << Entry->first << "\n";
170 #endif
171
172   tmap.erase(Entry);
173
174   // If we are removing an abstract type, remove the symbol table from it's use
175   // list...
176   if (Result->isAbstract()) {
177 #if DEBUG_ABSTYPE
178     DOUT  << "Removing abstract type from symtab"
179           << Result->getDescription() << "\n";
180 #endif
181     cast<DerivedType>(Result)->removeAbstractTypeUser(this);
182   }
183
184   return const_cast<Type*>(Result);
185 }
186
187
188 // insertEntry - Insert a value into the symbol table with the specified name.
189 void SymbolTable::insertEntry(const std::string &Name, const Type *VTy,
190                               Value *V) {
191   plane_iterator PI = pmap.find(VTy);   // Plane iterator
192   value_iterator VI;                    // Actual value iterator
193   ValueMap *VM;                         // The plane we care about.
194
195 #if DEBUG_SYMBOL_TABLE
196   dump();
197   DOUT << " Inserting definition: " << Name << ": "
198        << VTy->getDescription() << "\n";
199 #endif
200
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     VM = &pmap.insert(make_pair(VTy, ValueMap())).first->second;
204     VI = VM->end();
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       DOUT << "Added abstract type value: " << VTy->getDescription()
214            << "\n";
215 #endif
216     }
217
218   } else {
219     // Check to see if there is a naming conflict.  If so, rename this value!
220     VM = &PI->second;
221     VI = VM->lower_bound(Name);
222     if (VI != VM->end() && VI->first == Name) {
223       V->Name = getUniqueName(VTy, Name);
224       VM->insert(make_pair(V->Name, V));
225       return;
226     }
227   }
228
229   VM->insert(VI, make_pair(Name, V));
230 }
231
232
233 // insertEntry - Insert a type into the symbol table with the specified
234 // name...
235 //
236 void SymbolTable::insert(const std::string& Name, const Type* T) {
237   assert(T && "Can't insert null type into symbol table!");
238
239   // Check to see if there is a naming conflict.  If so, rename this type!
240   std::string UniqueName = Name;
241   if (lookupType(Name))
242     UniqueName = getUniqueName(T, Name);
243
244 #if DEBUG_SYMBOL_TABLE
245   dump();
246   DOUT << " Inserting type: " << UniqueName << ": "
247        << T->getDescription() << "\n";
248 #endif
249
250   // Insert the tmap entry
251   tmap.insert(make_pair(UniqueName, T));
252
253   // If we are adding an abstract type, add the symbol table to it's use list.
254   if (T->isAbstract()) {
255     cast<DerivedType>(T)->addAbstractTypeUser(this);
256 #if DEBUG_ABSTYPE
257     DOUT << "Added abstract type to ST: " << T->getDescription() << "\n";
258 #endif
259   }
260 }
261
262 // Strip the symbol table of its names.
263 bool SymbolTable::strip() {
264   bool RemovedSymbol = false;
265   for (plane_iterator I = pmap.begin(); I != pmap.end();) {
266     // Removing items from the plane can cause the plane itself to get deleted.
267     // If this happens, make sure we incremented our plane iterator already!
268     ValueMap &Plane = (I++)->second;
269     value_iterator B = Plane.begin(), Bend = Plane.end();
270     while (B != Bend) {   // Found nonempty type plane!
271       Value *V = B->second;
272       ++B;
273       if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) {
274         // Set name to "", removing from symbol table!
275         V->setName("");
276         RemovedSymbol = true;
277       }
278     }
279   }
280
281   for (type_iterator TI = tmap.begin(); TI != tmap.end(); ) {
282     remove(TI++);
283     RemovedSymbol = true;
284   }
285
286   return RemovedSymbol;
287 }
288
289
290 // This function is called when one of the types in the type plane are refined
291 void SymbolTable::refineAbstractType(const DerivedType *OldType,
292                                      const Type *NewType) {
293
294   // Search to see if we have any values of the type Oldtype.  If so, we need to
295   // move them into the newtype plane...
296   plane_iterator PI = pmap.find(OldType);
297   if (PI != pmap.end()) {
298     // Get a handle to the new type plane...
299     plane_iterator NewTypeIt = pmap.find(NewType);
300     if (NewTypeIt == pmap.end()) {      // If no plane exists, add one
301       NewTypeIt = pmap.insert(make_pair(NewType, ValueMap())).first;
302
303       if (NewType->isAbstract()) {
304         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
305 #if DEBUG_ABSTYPE
306         DOUT << "[Added] refined to abstype: " << NewType->getDescription()
307              << "\n";
308 #endif
309       }
310     }
311
312     ValueMap &NewPlane = NewTypeIt->second;
313     ValueMap &OldPlane = PI->second;
314     while (!OldPlane.empty()) {
315       std::pair<const std::string, Value*> V = *OldPlane.begin();
316
317       // Check to see if there is already a value in the symbol table that this
318       // would collide with.
319       value_iterator VI = NewPlane.find(V.first);
320       if (VI != NewPlane.end() && VI->second == V.second) {
321         // No action
322
323       } else if (VI != NewPlane.end()) {
324         // The only thing we are allowing for now is two external global values
325         // folded into one.
326         //
327         GlobalValue *ExistGV = dyn_cast<GlobalValue>(VI->second);
328         GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second);
329
330         if (ExistGV && NewGV) {
331           assert((ExistGV->isExternal() || NewGV->isExternal()) &&
332                  "Two planes folded together with overlapping value names!");
333
334           // Make sure that ExistGV is the one we want to keep!
335           if (!NewGV->isExternal())
336             std::swap(NewGV, ExistGV);
337
338           // Ok we have two external global values.  Make all uses of the new
339           // one use the old one...
340           NewGV->uncheckedReplaceAllUsesWith(ExistGV);
341
342           // Update NewGV's name, we're about the remove it from the symbol
343           // table.
344           NewGV->Name = "";
345
346           // Now we can remove this global from the module entirely...
347           Module *M = NewGV->getParent();
348           if (Function *F = dyn_cast<Function>(NewGV))
349             M->getFunctionList().remove(F);
350           else
351             M->getGlobalList().remove(cast<GlobalVariable>(NewGV));
352           delete NewGV;
353         } else {
354           // If they are not global values, they must be just random values who
355           // happen to conflict now that types have been resolved.  If this is
356           // the case, reinsert the value into the new plane, allowing it to get
357           // renamed.
358           assert(V.second->getType() == NewType &&"Type resolution is broken!");
359           insert(V.second);
360         }
361       } else {
362         insertEntry(V.first, NewType, V.second);
363       }
364       // Remove the item from the old type plane
365       OldPlane.erase(OldPlane.begin());
366     }
367
368     // Ok, now we are not referencing the type anymore... take me off your user
369     // list please!
370 #if DEBUG_ABSTYPE
371     DOUT << "Removing type " << OldType->getDescription() << "\n";
372 #endif
373     OldType->removeAbstractTypeUser(this);
374
375     // Remove the plane that is no longer used
376     pmap.erase(PI);
377   }
378
379   // Loop over all of the types in the symbol table, replacing any references
380   // to OldType with references to NewType.  Note that there may be multiple
381   // occurrences, and although we only need to remove one at a time, it's
382   // faster to remove them all in one pass.
383   //
384   for (type_iterator I = type_begin(), E = type_end(); I != E; ++I) {
385     if (I->second == (Type*)OldType) {  // FIXME when Types aren't const.
386 #if DEBUG_ABSTYPE
387       DOUT << "Removing type " << OldType->getDescription() << "\n";
388 #endif
389       OldType->removeAbstractTypeUser(this);
390
391       I->second = (Type*)NewType;  // TODO FIXME when types aren't const
392       if (NewType->isAbstract()) {
393 #if DEBUG_ABSTYPE
394         DOUT << "Added type " << NewType->getDescription() << "\n";
395 #endif
396         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
397       }
398     }
399   }
400 }
401
402
403 // Handle situation where type becomes Concreate from Abstract
404 void SymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
405   plane_iterator PI = pmap.find(AbsTy);
406
407   // If there are any values in the symbol table of this type, then the type
408   // plane is a use of the abstract type which must be dropped.
409   if (PI != pmap.end())
410     AbsTy->removeAbstractTypeUser(this);
411
412   // Loop over all of the types in the symbol table, dropping any abstract
413   // type user entries for AbsTy which occur because there are names for the
414   // type.
415   for (type_iterator TI = type_begin(), TE = type_end(); TI != TE; ++TI)
416     if (TI->second == (Type*)AbsTy)   // FIXME when Types aren't const.
417       AbsTy->removeAbstractTypeUser(this);
418 }
419
420 static void DumpVal(const std::pair<const std::string, Value *> &V) {
421   DOUT << "  '" << V.first << "' = ";
422   V.second->dump();
423   DOUT << "\n";
424 }
425
426 static void DumpPlane(const std::pair<const Type *,
427                                       std::map<const std::string, Value *> >&P){
428   P.first->dump();
429   DOUT << "\n";
430   for_each(P.second.begin(), P.second.end(), DumpVal);
431 }
432
433 static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
434   DOUT << "  '" << T.first << "' = ";
435   T.second->dump();
436   DOUT << "\n";
437 }
438
439 void SymbolTable::dump() const {
440   DOUT << "Symbol table dump:\n  Plane:";
441   for_each(pmap.begin(), pmap.end(), DumpPlane);
442   DOUT << "  Types: ";
443   for_each(tmap.begin(), tmap.end(), DumpTypes);
444 }
445
446 // vim: sw=2 ai