Rename createSimpleX86RegisterAllocator to createSimpleRegisterAllocator.
[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/SlotCalculator.h"
13 #include "llvm/Analysis/ConstantsScanner.h"
14 #include "llvm/Module.h"
15 #include "llvm/iOther.h"
16 #include "llvm/Constant.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/SymbolTable.h"
19 #include "Support/DepthFirstIterator.h"
20 #include "Support/STLExtras.h"
21 #include <algorithm>
22
23 #if 0
24 #define SC_DEBUG(X) cerr << X
25 #else
26 #define SC_DEBUG(X)
27 #endif
28
29 SlotCalculator::SlotCalculator(const Module *M, bool IgnoreNamed) {
30   IgnoreNamedNodes = IgnoreNamed;
31   TheModule = M;
32
33   // Preload table... Make sure that all of the primitive types are in the table
34   // and that their Primitive ID is equal to their slot #
35   //
36   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
37     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
38     insertVal(Type::getPrimitiveType((Type::PrimitiveID)i), true);
39   }
40
41   if (M == 0) return;   // Empty table...
42   processModule();
43 }
44
45 SlotCalculator::SlotCalculator(const Function *M, bool IgnoreNamed) {
46   IgnoreNamedNodes = IgnoreNamed;
47   TheModule = M ? M->getParent() : 0;
48
49   // Preload table... Make sure that all of the primitive types are in the table
50   // and that their Primitive ID is equal to their slot #
51   //
52   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
53     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
54     insertVal(Type::getPrimitiveType((Type::PrimitiveID)i), true);
55   }
56
57   if (TheModule == 0) return;   // Empty table...
58
59   processModule();              // Process module level stuff
60   incorporateFunction(M);         // Start out in incorporated state
61 }
62
63
64 // processModule - Process all of the module level function declarations and
65 // types that are available.
66 //
67 void SlotCalculator::processModule() {
68   SC_DEBUG("begin processModule!\n");
69
70   // Add all of the constants that the global variables might refer to first.
71   //
72   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
73        I != E; ++I)
74     if (I->hasInitializer())
75       insertValue(I->getInitializer());
76
77   // Add all of the global variables to the value table...
78   //
79   for(Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
80       I != E; ++I)
81     insertValue(I);
82
83   // Scavenge the types out of the functions, then add the functions themselves
84   // to the value table...
85   //
86   for(Module::const_iterator I = TheModule->begin(), E = TheModule->end();
87       I != E; ++I)
88     insertValue(I);
89
90   // Insert constants that are named at module level into the slot pool so that
91   // the module symbol table can refer to them...
92   //
93   if (!IgnoreNamedNodes) {
94     SC_DEBUG("Inserting SymbolTable values:\n");
95     processSymbolTable(&TheModule->getSymbolTable());
96   }
97
98   SC_DEBUG("end processModule!\n");
99 }
100
101 // processSymbolTable - Insert all of the values in the specified symbol table
102 // into the values table...
103 //
104 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
105   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
106     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
107            TE = I->second.end(); TI != TE; ++TI)
108       insertValue(TI->second);
109 }
110
111 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
112   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
113     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
114            TE = I->second.end(); TI != TE; ++TI)
115       if (isa<Constant>(TI->second))
116         insertValue(TI->second);
117 }
118
119
120 void SlotCalculator::incorporateFunction(const Function *M) {
121   assert(ModuleLevel.size() == 0 && "Module already incorporated!");
122
123   SC_DEBUG("begin processFunction!\n");
124
125   // Save the Table state before we process the function...
126   for (unsigned i = 0; i < Table.size(); ++i)
127     ModuleLevel.push_back(Table[i].size());
128
129   SC_DEBUG("Inserting function arguments\n");
130
131   // Iterate over function arguments, adding them to the value table...
132   for(Function::const_aiterator I = M->abegin(), E = M->aend(); I != E; ++I)
133     insertValue(I);
134
135   // Iterate over all of the instructions in the function, looking for constant
136   // values that are referenced.  Add these to the value pools before any
137   // nonconstant values.  This will be turned into the constant pool for the
138   // bytecode writer.
139   //
140   if (!IgnoreNamedNodes) {                // Assembly writer does not need this!
141     SC_DEBUG("Inserting function constants:\n";
142              for (constant_iterator I = constant_begin(M), E = constant_end(M);
143                   I != E; ++I) {
144                cerr << "  " << *I->getType()
145                     << " " << *I << "\n";
146              });
147
148     // Emit all of the constants that are being used by the instructions in the
149     // function...
150     for_each(constant_begin(M), constant_end(M),
151              bind_obj(this, &SlotCalculator::insertValue));
152
153     // If there is a symbol table, it is possible that the user has names for
154     // constants that are not being used.  In this case, we will have problems
155     // if we don't emit the constants now, because otherwise we will get 
156     // symboltable references to constants not in the output.  Scan for these
157     // constants now.
158     //
159     processSymbolTableConstants(&M->getSymbolTable());
160   }
161
162   SC_DEBUG("Inserting Labels:\n");
163
164   // Iterate over basic blocks, adding them to the value table...
165   for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
166     insertValue(I);
167   /*  for_each(M->begin(), M->end(),
168       bind_obj(this, &SlotCalculator::insertValue));*/
169
170   SC_DEBUG("Inserting Instructions:\n");
171
172   // Add all of the instructions to the type planes...
173   for_each(inst_begin(M), inst_end(M),
174            bind_obj(this, &SlotCalculator::insertValue));
175
176   if (!IgnoreNamedNodes) {
177     SC_DEBUG("Inserting SymbolTable values:\n");
178     processSymbolTable(&M->getSymbolTable());
179   }
180
181   SC_DEBUG("end processFunction!\n");
182 }
183
184 void SlotCalculator::purgeFunction() {
185   assert(ModuleLevel.size() != 0 && "Module not incorporated!");
186   unsigned NumModuleTypes = ModuleLevel.size();
187
188   SC_DEBUG("begin purgeFunction!\n");
189
190   // First, remove values from existing type planes
191   for (unsigned i = 0; i < NumModuleTypes; ++i) {
192     unsigned ModuleSize = ModuleLevel[i];  // Size of plane before function came
193     TypePlane &CurPlane = Table[i];
194     //SC_DEBUG("Processing Plane " <<i<< " of size " << CurPlane.size() <<"\n");
195              
196     while (CurPlane.size() != ModuleSize) {
197       //SC_DEBUG("  Removing [" << i << "] Value=" << CurPlane.back() << "\n");
198       std::map<const Value *, unsigned>::iterator NI =
199         NodeMap.find(CurPlane.back());
200       assert(NI != NodeMap.end() && "Node not in nodemap?");
201       NodeMap.erase(NI);   // Erase from nodemap
202       CurPlane.pop_back();                            // Shrink plane
203     }
204   }
205
206   // We don't need this state anymore, free it up.
207   ModuleLevel.clear();
208
209   // Next, remove any type planes defined by the function...
210   while (NumModuleTypes != Table.size()) {
211     TypePlane &Plane = Table.back();
212     SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
213              << Plane.size() << "\n");
214     while (Plane.size()) {
215       NodeMap.erase(NodeMap.find(Plane.back()));   // Erase from nodemap
216       Plane.pop_back();                            // Shrink plane
217     }
218
219     Table.pop_back();                      // Nuke the plane, we don't like it.
220   }
221
222   SC_DEBUG("end purgeFunction!\n");
223 }
224
225 int SlotCalculator::getValSlot(const Value *D) const {
226   std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
227   if (I == NodeMap.end()) return -1;
228  
229   return (int)I->second;
230 }
231
232
233 int SlotCalculator::insertValue(const Value *D) {
234   if (isa<Constant>(D) || isa<GlobalVariable>(D)) {
235     const User *U = cast<const User>(D);
236     // This makes sure that if a constant has uses (for example an array
237     // of const ints), that they are inserted also.  Same for global variable
238     // initializers.
239     //
240     for(User::const_op_iterator I = U->op_begin(), E = U->op_end(); I != E; ++I)
241       if (!isa<GlobalValue>(*I))     // Don't chain insert global values
242         insertValue(*I);
243   }
244
245   int SlotNo = getValSlot(D);        // Check to see if it's already in!
246   if (SlotNo != -1) return SlotNo;
247   return insertVal(D); 
248 }
249
250
251 int SlotCalculator::insertVal(const Value *D, bool dontIgnore) {
252   assert(D && "Can't insert a null value!");
253   assert(getValSlot(D) == -1 && "Value is already in the table!");
254
255   // If this node does not contribute to a plane, or if the node has a 
256   // name and we don't want names, then ignore the silly node... Note that types
257   // do need slot numbers so that we can keep track of where other values land.
258   //
259   if (!dontIgnore)                               // Don't ignore nonignorables!
260     if (D->getType() == Type::VoidTy ||          // Ignore void type nodes
261         (IgnoreNamedNodes &&                     // Ignore named and constants
262          (D->hasName() || isa<Constant>(D)) && !isa<Type>(D))) {
263       SC_DEBUG("ignored value " << D << "\n");
264       return -1;                  // We do need types unconditionally though
265     }
266
267   // If it's a type, make sure that all subtypes of the type are included...
268   if (const Type *TheTy = dyn_cast<const Type>(D)) {
269
270     // Insert the current type before any subtypes.  This is important because
271     // recursive types elements are inserted in a bottom up order.  Changing
272     // this here can break things.  For example:
273     //
274     //    global { \2 * } { { \2 }* null }
275     //
276     int ResultSlot;
277     if ((ResultSlot = getValSlot(TheTy)) == -1) {
278       ResultSlot = doInsertVal(TheTy);
279       SC_DEBUG("  Inserted type: " << TheTy->getDescription() << " slot=" <<
280                ResultSlot << "\n");
281     }
282
283     // Loop over any contained types in the definition... in reverse depth first
284     // order.  This assures that all of the leafs of a type are output before
285     // the type itself is. This also assures us that we will not hit infinite
286     // recursion on recursive types...
287     //
288     for (df_iterator<const Type*> I = df_begin(TheTy, true), 
289                                   E = df_end(TheTy); I != E; ++I)
290       if (*I != TheTy) {
291         // If we haven't seen this sub type before, add it to our type table!
292         const Type *SubTy = *I;
293         if (getValSlot(SubTy) == -1) {
294           SC_DEBUG("  Inserting subtype: " << SubTy->getDescription() << "\n");
295           int Slot = doInsertVal(SubTy);
296           SC_DEBUG("  Inserted subtype: " << SubTy->getDescription() << 
297                    " slot=" << Slot << "\n");
298         }
299       }
300     return ResultSlot;
301   }
302
303   // Okay, everything is happy, actually insert the silly value now...
304   return doInsertVal(D);
305 }
306
307
308 // doInsertVal - This is a small helper function to be called only be insertVal.
309 //
310 int SlotCalculator::doInsertVal(const Value *D) {
311   const Type *Typ = D->getType();
312   unsigned Ty;
313
314   // Used for debugging DefSlot=-1 assertion...
315   //if (Typ == Type::TypeTy)
316   //  cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
317
318   if (Typ->isDerivedType()) {
319     int DefSlot = getValSlot(Typ);
320     if (DefSlot == -1) {                // Have we already entered this type?
321       // Nope, this is the first we have seen the type, process it.
322       DefSlot = insertVal(Typ, true);
323       assert(DefSlot != -1 && "ProcessType returned -1 for a type?");
324     }
325     Ty = (unsigned)DefSlot;
326   } else {
327     Ty = Typ->getPrimitiveID();
328   }
329   
330   if (Table.size() <= Ty)    // Make sure we have the type plane allocated...
331     Table.resize(Ty+1, TypePlane());
332   
333   // Insert node into table and NodeMap...
334   unsigned DestSlot = NodeMap[D] = Table[Ty].size();
335   Table[Ty].push_back(D);
336
337   SC_DEBUG("  Inserting value [" << Ty << "] = " << D << " slot=" << 
338            DestSlot << " [");
339   // G = Global, C = Constant, T = Type, F = Function, o = other
340   SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" : 
341            (isa<Type>(D) ? "T" : (isa<Function>(D) ? "F" : "o")))));
342   SC_DEBUG("]\n");
343   return (int)DestSlot;
344 }