9af5a387e1cfdea08b8762f360b4426503dc2b60
[oota-llvm.git] / lib / VMCore / SlotCalculator.cpp
1 //===-- SlotCalculator.cpp - Calculate what slots values land in ------------=//
2 //
3 // This file implements a useful analysis step to figure out what numbered 
4 // slots values in a program will land in (keeping track of per plane
5 // information as required.
6 //
7 // This is used primarily for when writing a file to disk, either in bytecode
8 // or source format.
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Analysis/SlotCalculator.h"
13 #include "llvm/Analysis/ConstantsScanner.h"
14 #include "llvm/Method.h"
15 #include "llvm/Module.h"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/ConstPoolVals.h"
18 #include "llvm/iOther.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/STLExtras.h"
22 #include "llvm/CFG.h"
23 #include <algorithm>
24
25 #if 0
26 #define SC_DEBUG(X) cerr << X
27 #else
28 #define SC_DEBUG(X)
29 #endif
30
31 SlotCalculator::SlotCalculator(const Module *M, bool IgnoreNamed) {
32   IgnoreNamedNodes = IgnoreNamed;
33   TheModule = M;
34
35   // Preload table... Make sure that all of the primitive types are in the table
36   // and that their Primitive ID is equal to their slot #
37   //
38   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
39     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
40     insertVal(Type::getPrimitiveType((Type::PrimitiveID)i), true);
41   }
42
43   if (M == 0) return;   // Empty table...
44   processModule();
45 }
46
47 SlotCalculator::SlotCalculator(const Method *M, bool IgnoreNamed) {
48   IgnoreNamedNodes = IgnoreNamed;
49   TheModule = M ? M->getParent() : 0;
50
51   // Preload table... Make sure that all of the primitive types are in the table
52   // and that their Primitive ID is equal to their slot #
53   //
54   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
55     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
56     insertVal(Type::getPrimitiveType((Type::PrimitiveID)i), true);
57   }
58
59   if (TheModule == 0) return;   // Empty table...
60
61   processModule();              // Process module level stuff
62   incorporateMethod(M);         // Start out in incorporated state
63 }
64
65
66 // processModule - Process all of the module level method declarations and
67 // types that are available.
68 //
69 void SlotCalculator::processModule() {
70   SC_DEBUG("begin processModule!\n");
71   // Currently, the only module level declarations are methods and method
72   // prototypes.  We simply scavenge the types out of the methods, then add the
73   // methods themselves to the value table...
74   //
75   for_each(TheModule->begin(), TheModule->end(),  // Insert methods...
76            bind_obj(this, &SlotCalculator::insertValue));
77
78   if (TheModule->hasSymbolTable() && !IgnoreNamedNodes) {
79     SC_DEBUG("Inserting SymbolTable values:\n");
80     processSymbolTable(TheModule->getSymbolTable());
81   }
82
83   SC_DEBUG("end processModule!\n");
84 }
85
86 // processSymbolTable - Insert all of the values in the specified symbol table
87 // into the values table...
88 //
89 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
90   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
91     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
92            TE = I->second.end(); TI != TE; ++TI)
93       insertValue(TI->second);
94 }
95
96 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
97   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
98     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
99            TE = I->second.end(); TI != TE; ++TI)
100       if (TI->second->isConstant())
101         insertValue(TI->second);
102 }
103
104
105 void SlotCalculator::incorporateMethod(const Method *M) {
106   assert(ModuleLevel.size() == 0 && "Module already incorporated!");
107
108   SC_DEBUG("begin processMethod!\n");
109
110   // Save the Table state before we process the method...
111   for (unsigned i = 0; i < Table.size(); ++i)
112     ModuleLevel.push_back(Table[i].size());
113
114   SC_DEBUG("Inserting method arguments\n");
115
116   // Iterate over method arguments, adding them to the value table...
117   for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
118            bind_obj(this, &SlotCalculator::insertValue));
119
120   // Iterate over all of the instructions in the method, looking for constant
121   // values that are referenced.  Add these to the value pools before any
122   // nonconstant values.  This will be turned into the constant pool for the
123   // bytecode writer.
124   //
125   if (!IgnoreNamedNodes) {                // Assembly writer does not need this!
126     SC_DEBUG("Inserting method constants:\n";
127              for (constant_iterator I = constant_begin(M), E = constant_end(M);
128                   I != E; ++I) {
129                cerr << "  " << I->getType()->getDescription() 
130                     << " " << I->getStrValue() << endl;
131              });
132
133     // Emit all of the constants that are being used by the instructions in the
134     // method...
135     for_each(constant_begin(M), constant_end(M),
136              bind_obj(this, &SlotCalculator::insertValue));
137
138     // If there is a symbol table, it is possible that the user has names for
139     // constants that are not being used.  In this case, we will have problems
140     // if we don't emit the constants now, because otherwise we will get 
141     // symboltable references to constants not in the output.  Scan for these
142     // constants now.
143     //
144     if (M->hasSymbolTable())
145       processSymbolTableConstants(M->getSymbolTable());
146   }
147
148   SC_DEBUG("Inserting Labels:\n");
149
150   // Iterate over basic blocks, adding them to the value table...
151   for_each(M->begin(), M->end(),
152            bind_obj(this, &SlotCalculator::insertValue));
153
154   SC_DEBUG("Inserting Instructions:\n");
155
156   // Add all of the instructions to the type planes...
157   for_each(M->inst_begin(), M->inst_end(),
158            bind_obj(this, &SlotCalculator::insertValue));
159
160   if (M->hasSymbolTable() && !IgnoreNamedNodes) {
161     SC_DEBUG("Inserting SymbolTable values:\n");
162     processSymbolTable(M->getSymbolTable());
163   }
164
165   SC_DEBUG("end processMethod!\n");
166 }
167
168 void SlotCalculator::purgeMethod() {
169   assert(ModuleLevel.size() != 0 && "Module not incorporated!");
170   unsigned NumModuleTypes = ModuleLevel.size();
171
172   SC_DEBUG("begin purgeMethod!\n");
173
174   // First, remove values from existing type planes
175   for (unsigned i = 0; i < NumModuleTypes; ++i) {
176     unsigned ModuleSize = ModuleLevel[i];  // Size of plane before method came
177     TypePlane &CurPlane = Table[i];
178     SC_DEBUG("Processing Plane " << i << " of size " << CurPlane.size() <<endl);
179              
180     while (CurPlane.size() != ModuleSize) {
181       SC_DEBUG("  Removing [" << i << "] Value=" << CurPlane.back() << "\n");
182       map<const Value *, unsigned>::iterator NI = NodeMap.find(CurPlane.back());
183       assert(NI != NodeMap.end() && "Node not in nodemap?");
184       NodeMap.erase(NI);   // Erase from nodemap
185       CurPlane.pop_back();                            // Shrink plane
186     }
187   }
188
189   // We don't need this state anymore, free it up.
190   ModuleLevel.clear();
191
192   // Next, remove any type planes defined by the method...
193   while (NumModuleTypes != Table.size()) {
194     TypePlane &Plane = Table.back();
195     SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
196              << Plane.size() << endl);
197     while (Plane.size()) {
198       NodeMap.erase(NodeMap.find(Plane.back()));   // Erase from nodemap
199       Plane.pop_back();                            // Shrink plane
200     }
201
202     Table.pop_back();                      // Nuke the plane, we don't like it.
203   }
204
205   SC_DEBUG("end purgeMethod!\n");
206 }
207
208 int SlotCalculator::getValSlot(const Value *D) const {
209   map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
210   if (I == NodeMap.end()) return -1;
211  
212   return (int)I->second;
213 }
214
215
216 int SlotCalculator::insertValue(const Value *D) {
217   if (const ConstPoolVal *CPV = D->castConstant()) {
218     // This makes sure that if a constant has uses (for example an array
219     // of const ints), that they are inserted also.
220     //
221     for_each(CPV->op_begin(), CPV->op_end(), 
222              bind_obj(this, &SlotCalculator::insertValue));
223   }
224
225   int SlotNo = getValSlot(D);        // Check to see if it's already in!
226   if (SlotNo != -1) return SlotNo;
227   return insertVal(D); 
228 }
229
230
231 int SlotCalculator::insertVal(const Value *D, bool dontIgnore = false) {
232   assert(D && "Can't insert a null value!");
233   assert(getValSlot(D) == -1 && "Value is already in the table!");
234
235   // If this node does not contribute to a plane, or if the node has a 
236   // name and we don't want names, then ignore the silly node... Note that types
237   // do need slot numbers so that we can keep track of where other values land.
238   //
239   if (!dontIgnore)                               // Don't ignore nonignorables!
240     if (D->getType() == Type::VoidTy ||          // Ignore void type nodes
241         (IgnoreNamedNodes &&                     // Ignore named and constants
242          (D->hasName() || D->isConstant()) && !D->isType())) {
243       SC_DEBUG("ignored value " << D << endl);
244       return -1;                  // We do need types unconditionally though
245     }
246
247   // If it's a type, make sure that all subtypes of the type are included...
248   if (const Type *TheTy = D->castType()) {
249     SC_DEBUG("  Inserted type: " << TheTy->getDescription() << endl);
250
251     // Loop over any contained types in the definition... in reverse depth first
252     // order.  This assures that all of the leafs of a type are output before
253     // the type itself is. This also assures us that we will not hit infinite
254     // recursion on recursive types...
255     //
256     for (cfg::tdf_iterator I = cfg::tdf_begin(TheTy, true), 
257                            E = cfg::tdf_end(TheTy); I != E; ++I)
258       if (*I != TheTy) {
259         // If we haven't seen this sub type before, add it to our type table!
260         const Type *SubTy = *I;
261         if (getValSlot(SubTy) == -1) {
262           SC_DEBUG("  Inserting subtype: " << SubTy->getDescription() << endl);
263           doInsertVal(SubTy);
264         }
265       }
266   }
267
268   // Okay, everything is happy, actually insert the silly value now...
269   return doInsertVal(D);
270 }
271
272
273 // doInsertVal - This is a small helper function to be called only be insertVal.
274 //
275 int SlotCalculator::doInsertVal(const Value *D) {
276   const Type *Typ = D->getType();
277   unsigned Ty;
278
279   // Used for debugging DefSlot=-1 assertion...
280   //if (Typ == Type::TypeTy)
281   //  cerr << "Inserting type '" << D->castTypeAsserting()->getDescription() << "'!\n";
282
283   if (Typ->isDerivedType()) {
284     int DefSlot = getValSlot(Typ);
285     if (DefSlot == -1) {                // Have we already entered this type?
286       // Nope, this is the first we have seen the type, process it.
287       DefSlot = insertVal(Typ, true);
288       assert(DefSlot != -1 && "ProcessType returned -1 for a type?");
289     }
290     Ty = (unsigned)DefSlot;
291   } else {
292     Ty = Typ->getPrimitiveID();
293   }
294   
295   if (Table.size() <= Ty)    // Make sure we have the type plane allocated...
296     Table.resize(Ty+1, TypePlane());
297   
298   SC_DEBUG("  Inserting value [" << Ty << "] = " << D << endl);
299       
300   // Insert node into table and NodeMap...
301   unsigned DestSlot = NodeMap[D] = Table[Ty].size();
302   Table[Ty].push_back(D);
303
304   return (int)DestSlot;
305 }