6ce2f35ffb1ce5a8a3d807e6cf13b2de2ad28096
[oota-llvm.git] / lib / Bytecode / Writer / SlotCalculator.cpp
1 //===-- SlotCalculator.cpp - Calculate what slots values land in ----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a useful analysis step to figure out what numbered 
11 // slots values in a program will land in (keeping track of per plane
12 // information as required.
13 //
14 // This is used primarily for when writing a file to disk, either in bytecode
15 // or source format.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/SlotCalculator.h"
20 #include "llvm/Analysis/ConstantsScanner.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/iOther.h"
24 #include "llvm/Module.h"
25 #include "llvm/SymbolTable.h"
26 #include "Support/PostOrderIterator.h"
27 #include "Support/STLExtras.h"
28 #include <algorithm>
29 using namespace llvm;
30
31 #if 0
32 #define SC_DEBUG(X) std::cerr << X
33 #else
34 #define SC_DEBUG(X)
35 #endif
36
37 SlotCalculator::SlotCalculator(const Module *M, bool buildBytecodeInfo) {
38   BuildBytecodeInfo = buildBytecodeInfo;
39   TheModule = M;
40
41   // Preload table... Make sure that all of the primitive types are in the table
42   // and that their Primitive ID is equal to their slot #
43   //
44   SC_DEBUG("Inserting primitive types:\n");
45   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
46     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
47     insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
48   }
49
50   if (M == 0) return;   // Empty table...
51   processModule();
52 }
53
54 SlotCalculator::SlotCalculator(const Function *M, bool buildBytecodeInfo) {
55   BuildBytecodeInfo = buildBytecodeInfo;
56   TheModule = M ? M->getParent() : 0;
57
58   // Preload table... Make sure that all of the primitive types are in the table
59   // and that their Primitive ID is equal to their slot #
60   //
61   SC_DEBUG("Inserting primitive types:\n");
62   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
63     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
64     insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
65   }
66
67   if (TheModule == 0) return;   // Empty table...
68
69   processModule();              // Process module level stuff
70   incorporateFunction(M);         // Start out in incorporated state
71 }
72
73
74 // processModule - Process all of the module level function declarations and
75 // types that are available.
76 //
77 void SlotCalculator::processModule() {
78   SC_DEBUG("begin processModule!\n");
79
80   // Add all of the global variables to the value table...
81   //
82   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
83        I != E; ++I)
84     getOrCreateSlot(I);
85
86   // Scavenge the types out of the functions, then add the functions themselves
87   // to the value table...
88   //
89   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
90        I != E; ++I)
91     getOrCreateSlot(I);
92
93   // Add all of the module level constants used as initializers
94   //
95   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
96        I != E; ++I)
97     if (I->hasInitializer())
98       getOrCreateSlot(I->getInitializer());
99
100   // Now that all global constants have been added, rearrange constant planes
101   // that contain constant strings so that the strings occur at the start of the
102   // plane, not somewhere in the middle.
103   //
104   if (BuildBytecodeInfo) {
105     TypePlane &Types = Table[Type::TypeTyID];
106     for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
107       if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
108         if (AT->getElementType() == Type::SByteTy ||
109             AT->getElementType() == Type::UByteTy) {
110           TypePlane &Plane = Table[plane];
111           unsigned FirstNonStringID = 0;
112           for (unsigned i = 0, e = Plane.size(); i != e; ++i)
113             if (cast<ConstantArray>(Plane[i])->isString()) {
114               // Check to see if we have to shuffle this string around.  If not,
115               // don't do anything.
116               if (i != FirstNonStringID) {
117                 // Swap the plane entries....
118                 std::swap(Plane[i], Plane[FirstNonStringID]);
119                 
120                 // Keep the NodeMap up to date.
121                 NodeMap[Plane[i]] = i;
122                 NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
123               }
124               ++FirstNonStringID;
125             }
126         }
127     }
128   }
129   
130 #if 0
131   // FIXME: Empirically, this causes the bytecode files to get BIGGER, because
132   // it explodes the operand size numbers to be bigger than can be handled
133   // compactly, which offsets the ~40% savings in constant sizes.  Whoops.
134
135   // If we are emitting a bytecode file, scan all of the functions for their
136   // constants, which allows us to emit more compact modules.  This is optional,
137   // and is just used to compactify the constants used by different functions
138   // together.
139   if (BuildBytecodeInfo) {
140     SC_DEBUG("Inserting function constants:\n");
141     for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
142          F != E; ++F)
143       for_each(constant_begin(F), constant_end(F),
144                bind_obj(this, &SlotCalculator::getOrCreateSlot));
145   }
146 #endif
147
148   // Insert constants that are named at module level into the slot pool so that
149   // the module symbol table can refer to them...
150   //
151   if (BuildBytecodeInfo) {
152     SC_DEBUG("Inserting SymbolTable values:\n");
153     processSymbolTable(&TheModule->getSymbolTable());
154   }
155
156   // Now that we have collected together all of the information relevant to the
157   // module, compactify the type table if it is particularly big and outputting
158   // a bytecode file.  The basic problem we run into is that some programs have
159   // a large number of types, which causes the type field to overflow its size,
160   // which causes instructions to explode in size (particularly call
161   // instructions).  To avoid this behavior, we "sort" the type table so that
162   // all non-value types are pushed to the end of the type table, giving nice
163   // low numbers to the types that can be used by instructions, thus reducing
164   // the amount of explodage we suffer.
165   if (BuildBytecodeInfo && Table[Type::TypeTyID].size() >= 64) {
166     // Scan through the type table moving value types to the start of the table.
167     TypePlane *Types = &Table[Type::TypeTyID];
168     unsigned FirstNonValueTypeID = 0;
169     for (unsigned i = 0, e = Types->size(); i != e; ++i)
170       if (cast<Type>((*Types)[i])->isFirstClassType() ||
171           cast<Type>((*Types)[i])->isPrimitiveType()) {
172         // Check to see if we have to shuffle this type around.  If not, don't
173         // do anything.
174         if (i != FirstNonValueTypeID) {
175           assert(i != Type::TypeTyID && FirstNonValueTypeID != Type::TypeTyID &&
176                  "Cannot move around the type plane!");
177
178           // Swap the type ID's.
179           std::swap((*Types)[i], (*Types)[FirstNonValueTypeID]);
180
181           // Keep the NodeMap up to date.
182           NodeMap[(*Types)[i]] = i;
183           NodeMap[(*Types)[FirstNonValueTypeID]] = FirstNonValueTypeID;
184
185           // When we move a type, make sure to move its value plane as needed.
186           if (Table.size() > FirstNonValueTypeID) {
187             if (Table.size() <= i) Table.resize(i+1);
188             std::swap(Table[i], Table[FirstNonValueTypeID]);
189             Types = &Table[Type::TypeTyID];
190           }
191         }
192         ++FirstNonValueTypeID;
193       }
194   }
195
196   SC_DEBUG("end processModule!\n");
197 }
198
199 // processSymbolTable - Insert all of the values in the specified symbol table
200 // into the values table...
201 //
202 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
203   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
204     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
205            TE = I->second.end(); TI != TE; ++TI)
206       getOrCreateSlot(TI->second);
207 }
208
209 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
210   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
211     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
212            TE = I->second.end(); TI != TE; ++TI)
213       if (isa<Constant>(TI->second))
214         getOrCreateSlot(TI->second);
215 }
216
217
218 void SlotCalculator::incorporateFunction(const Function *F) {
219   assert(ModuleLevel.size() == 0 && "Module already incorporated!");
220
221   SC_DEBUG("begin processFunction!\n");
222
223   // Save the Table state before we process the function...
224   for (unsigned i = 0; i < Table.size(); ++i)
225     ModuleLevel.push_back(Table[i].size());
226
227   SC_DEBUG("Inserting function arguments\n");
228
229   // Iterate over function arguments, adding them to the value table...
230   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
231     getOrCreateSlot(I);
232
233   // Iterate over all of the instructions in the function, looking for constant
234   // values that are referenced.  Add these to the value pools before any
235   // nonconstant values.  This will be turned into the constant pool for the
236   // bytecode writer.
237   //
238   if (BuildBytecodeInfo) {                // Assembly writer does not need this!
239     SC_DEBUG("Inserting function constants:\n";
240              for (constant_iterator I = constant_begin(F), E = constant_end(F);
241                   I != E; ++I) {
242                std::cerr << "  " << *I->getType() << " " << *I << "\n";
243              });
244
245     // Emit all of the constants that are being used by the instructions in the
246     // function...
247     for_each(constant_begin(F), constant_end(F),
248              bind_obj(this, &SlotCalculator::getOrCreateSlot));
249
250     // If there is a symbol table, it is possible that the user has names for
251     // constants that are not being used.  In this case, we will have problems
252     // if we don't emit the constants now, because otherwise we will get 
253     // symbol table references to constants not in the output.  Scan for these
254     // constants now.
255     //
256     processSymbolTableConstants(&F->getSymbolTable());
257   }
258
259   SC_DEBUG("Inserting Labels:\n");
260
261   // Iterate over basic blocks, adding them to the value table...
262   for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
263     getOrCreateSlot(I);
264
265   SC_DEBUG("Inserting Instructions:\n");
266
267   // Add all of the instructions to the type planes...
268   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
269     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
270       getOrCreateSlot(I);
271       if (const VANextInst *VAN = dyn_cast<VANextInst>(I))
272         getOrCreateSlot(VAN->getArgType());
273     }
274
275   if (BuildBytecodeInfo) {
276     SC_DEBUG("Inserting SymbolTable values:\n");
277     processSymbolTable(&F->getSymbolTable());
278   }
279
280   SC_DEBUG("end processFunction!\n");
281 }
282
283 void SlotCalculator::purgeFunction() {
284   assert(ModuleLevel.size() != 0 && "Module not incorporated!");
285   unsigned NumModuleTypes = ModuleLevel.size();
286
287   SC_DEBUG("begin purgeFunction!\n");
288
289   // First, remove values from existing type planes
290   for (unsigned i = 0; i < NumModuleTypes; ++i) {
291     unsigned ModuleSize = ModuleLevel[i];  // Size of plane before function came
292     TypePlane &CurPlane = Table[i];
293     //SC_DEBUG("Processing Plane " <<i<< " of size " << CurPlane.size() <<"\n");
294              
295     while (CurPlane.size() != ModuleSize) {
296       //SC_DEBUG("  Removing [" << i << "] Value=" << CurPlane.back() << "\n");
297       std::map<const Value *, unsigned>::iterator NI =
298         NodeMap.find(CurPlane.back());
299       assert(NI != NodeMap.end() && "Node not in nodemap?");
300       NodeMap.erase(NI);   // Erase from nodemap
301       CurPlane.pop_back();                            // Shrink plane
302     }
303   }
304
305   // We don't need this state anymore, free it up.
306   ModuleLevel.clear();
307
308   // Next, remove any type planes defined by the function...
309   while (NumModuleTypes != Table.size()) {
310     TypePlane &Plane = Table.back();
311     SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
312              << Plane.size() << "\n");
313     while (Plane.size()) {
314       NodeMap.erase(NodeMap.find(Plane.back()));   // Erase from nodemap
315       Plane.pop_back();                            // Shrink plane
316     }
317
318     Table.pop_back();                      // Nuke the plane, we don't like it.
319   }
320
321   SC_DEBUG("end purgeFunction!\n");
322 }
323
324 int SlotCalculator::getSlot(const Value *V) const {
325   std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
326   if (I != NodeMap.end())
327     return (int)I->second;
328
329   // Do not number ConstantPointerRef's at all.  They are an abomination.
330   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
331     return getSlot(CPR->getValue());
332
333   return -1;
334 }
335
336
337 int SlotCalculator::getOrCreateSlot(const Value *V) {
338   int SlotNo = getSlot(V);        // Check to see if it's already in!
339   if (SlotNo != -1) return SlotNo;
340
341   // Do not number ConstantPointerRef's at all.  They are an abomination.
342   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
343     return getOrCreateSlot(CPR->getValue());
344
345   if (!isa<GlobalValue>(V))
346     if (const Constant *C = dyn_cast<Constant>(V)) {
347       // If we are emitting a bytecode file, do not index the characters that
348       // make up constant strings.  We emit constant strings as special
349       // entities that don't require their individual characters to be emitted.
350       if (!BuildBytecodeInfo || !isa<ConstantArray>(C) ||
351           !cast<ConstantArray>(C)->isString()) {
352         // This makes sure that if a constant has uses (for example an array of
353         // const ints), that they are inserted also.
354         //
355         for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
356              I != E; ++I)
357           getOrCreateSlot(*I);
358       } else {
359         assert(ModuleLevel.empty() &&
360                "How can a constant string be directly accessed in a function?");
361         // Otherwise, if we are emitting a bytecode file and this IS a string,
362         // remember it.
363         if (!C->isNullValue())
364           ConstantStrings.push_back(cast<ConstantArray>(C));
365       }
366     }
367
368   return insertValue(V);
369 }
370
371
372 int SlotCalculator::insertValue(const Value *D, bool dontIgnore) {
373   assert(D && "Can't insert a null value!");
374   assert(getSlot(D) == -1 && "Value is already in the table!");
375
376   // If this node does not contribute to a plane, or if the node has a 
377   // name and we don't want names, then ignore the silly node... Note that types
378   // do need slot numbers so that we can keep track of where other values land.
379   //
380   if (!dontIgnore)                               // Don't ignore nonignorables!
381     if (D->getType() == Type::VoidTy ||          // Ignore void type nodes
382         (!BuildBytecodeInfo &&                   // Ignore named and constants
383          (D->hasName() || isa<Constant>(D)) && !isa<Type>(D))) {
384       SC_DEBUG("ignored value " << *D << "\n");
385       return -1;                  // We do need types unconditionally though
386     }
387
388   // If it's a type, make sure that all subtypes of the type are included...
389   if (const Type *TheTy = dyn_cast<Type>(D)) {
390
391     // Insert the current type before any subtypes.  This is important because
392     // recursive types elements are inserted in a bottom up order.  Changing
393     // this here can break things.  For example:
394     //
395     //    global { \2 * } { { \2 }* null }
396     //
397     int ResultSlot = doInsertValue(TheTy);
398     SC_DEBUG("  Inserted type: " << TheTy->getDescription() << " slot=" <<
399              ResultSlot << "\n");
400
401     // Loop over any contained types in the definition... in post
402     // order.
403     //
404     for (po_iterator<const Type*> I = po_begin(TheTy), E = po_end(TheTy);
405          I != E; ++I) {
406       if (*I != TheTy) {
407         const Type *SubTy = *I;
408         // If we haven't seen this sub type before, add it to our type table!
409         if (getSlot(SubTy) == -1) {
410           SC_DEBUG("  Inserting subtype: " << SubTy->getDescription() << "\n");
411           int Slot = doInsertValue(SubTy);
412           SC_DEBUG("  Inserted subtype: " << SubTy->getDescription() << 
413                    " slot=" << Slot << "\n");
414         }
415       }
416     }
417     return ResultSlot;
418   }
419
420   // Okay, everything is happy, actually insert the silly value now...
421   return doInsertValue(D);
422 }
423
424
425 // doInsertValue - This is a small helper function to be called only
426 // be insertValue.
427 //
428 int SlotCalculator::doInsertValue(const Value *D) {
429   const Type *Typ = D->getType();
430   unsigned Ty;
431
432   // Used for debugging DefSlot=-1 assertion...
433   //if (Typ == Type::TypeTy)
434   //  cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
435
436   if (Typ->isDerivedType()) {
437     int ValSlot = getSlot(Typ);
438     if (ValSlot == -1) {                // Have we already entered this type?
439       // Nope, this is the first we have seen the type, process it.
440       ValSlot = insertValue(Typ, true);
441       assert(ValSlot != -1 && "ProcessType returned -1 for a type?");
442     }
443     Ty = (unsigned)ValSlot;
444   } else {
445     Ty = Typ->getPrimitiveID();
446   }
447   
448   if (Table.size() <= Ty)    // Make sure we have the type plane allocated...
449     Table.resize(Ty+1, TypePlane());
450
451   // If this is the first value to get inserted into the type plane, make sure
452   // to insert the implicit null value...
453   if (Table[Ty].empty() && Ty >= Type::FirstDerivedTyID && BuildBytecodeInfo) {
454     Value *ZeroInitializer = Constant::getNullValue(Typ);
455
456     // If we are pushing zeroinit, it will be handled below.
457     if (D != ZeroInitializer) {
458       Table[Ty].push_back(ZeroInitializer);
459       NodeMap[ZeroInitializer] = 0;
460     }
461   }
462
463   // Insert node into table and NodeMap...
464   unsigned DestSlot = NodeMap[D] = Table[Ty].size();
465   Table[Ty].push_back(D);
466
467   SC_DEBUG("  Inserting value [" << Ty << "] = " << D << " slot=" << 
468            DestSlot << " [");
469   // G = Global, C = Constant, T = Type, F = Function, o = other
470   SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" : 
471            (isa<Type>(D) ? "T" : (isa<Function>(D) ? "F" : "o")))));
472   SC_DEBUG("]\n");
473   return (int)DestSlot;
474 }