Switch ValueSymbolTable to use StringMap<Value*> instead of std::map<std::string...
[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 slots
11 // values in a program will land in (keeping track of per plane information).
12 //
13 // This is used when writing a file to disk, either in bytecode or assembly.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "SlotCalculator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/Type.h"
26 #include "llvm/ValueSymbolTable.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include <algorithm>
29 #include <functional>
30 using namespace llvm;
31
32 #ifndef NDEBUG
33 #include "llvm/Support/Streams.h"
34 #include "llvm/Support/CommandLine.h"
35 static cl::opt<bool> SlotCalculatorDebugOption("scdebug",cl::init(false), 
36     cl::desc("Enable SlotCalculator debug output"), cl::Hidden);
37 #define SC_DEBUG(X) if (SlotCalculatorDebugOption) cerr << X
38 #else
39 #define SC_DEBUG(X)
40 #endif
41
42 void SlotCalculator::insertPrimitives() {
43   // Preload the table with the built-in types. These built-in types are
44   // inserted first to ensure that they have low integer indices which helps to
45   // keep bytecode sizes small. Note that the first group of indices must match
46   // the Type::TypeIDs for the primitive types. After that the integer types are
47   // added, but the order and value is not critical. What is critical is that 
48   // the indices of these "well known" slot numbers be properly maintained in
49   // Reader.h which uses them directly to extract values of these types.
50   SC_DEBUG("Inserting primitive types:\n");
51                                     // See WellKnownTypeSlots in Reader.h
52   getOrCreateTypeSlot(Type::VoidTy  ); // 0: VoidTySlot
53   getOrCreateTypeSlot(Type::FloatTy ); // 1: FloatTySlot
54   getOrCreateTypeSlot(Type::DoubleTy); // 2: DoubleTySlot
55   getOrCreateTypeSlot(Type::LabelTy ); // 3: LabelTySlot
56   assert(TypeMap.size() == Type::FirstDerivedTyID &&"Invalid primitive insert");
57   // Above here *must* correspond 1:1 with the primitive types.
58   getOrCreateTypeSlot(Type::Int1Ty  ); // 4: Int1TySlot
59   getOrCreateTypeSlot(Type::Int8Ty  ); // 5: Int8TySlot
60   getOrCreateTypeSlot(Type::Int16Ty ); // 6: Int16TySlot
61   getOrCreateTypeSlot(Type::Int32Ty ); // 7: Int32TySlot
62   getOrCreateTypeSlot(Type::Int64Ty ); // 8: Int64TySlot
63 }
64
65 SlotCalculator::SlotCalculator(const Module *M) {
66   assert(M);
67   TheModule = M;
68
69   insertPrimitives();
70   processModule();
71 }
72
73 // processModule - Process all of the module level function declarations and
74 // types that are available.
75 //
76 void SlotCalculator::processModule() {
77   SC_DEBUG("begin processModule!\n");
78
79   // Add all of the global variables to the value table...
80   //
81   for (Module::const_global_iterator I = TheModule->global_begin(),
82          E = TheModule->global_end(); I != E; ++I)
83     CreateSlotIfNeeded(I);
84
85   // Scavenge the types out of the functions, then add the functions themselves
86   // to the value table...
87   //
88   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
89        I != E; ++I)
90     CreateSlotIfNeeded(I);
91
92   // Add all of the module level constants used as initializers
93   //
94   for (Module::const_global_iterator I = TheModule->global_begin(),
95          E = TheModule->global_end(); I != E; ++I)
96     if (I->hasInitializer())
97       CreateSlotIfNeeded(I->getInitializer());
98
99   // Now that all global constants have been added, rearrange constant planes
100   // that contain constant strings so that the strings occur at the start of the
101   // plane, not somewhere in the middle.
102   //
103   for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
104     if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
105       if (AT->getElementType() == Type::Int8Ty) {
106         TypePlane &Plane = Table[plane];
107         unsigned FirstNonStringID = 0;
108         for (unsigned i = 0, e = Plane.size(); i != e; ++i)
109           if (isa<ConstantAggregateZero>(Plane[i]) ||
110               (isa<ConstantArray>(Plane[i]) &&
111                cast<ConstantArray>(Plane[i])->isString())) {
112             // Check to see if we have to shuffle this string around.  If not,
113             // don't do anything.
114             if (i != FirstNonStringID) {
115               // Swap the plane entries....
116               std::swap(Plane[i], Plane[FirstNonStringID]);
117
118               // Keep the NodeMap up to date.
119               NodeMap[Plane[i]] = i;
120               NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
121             }
122             ++FirstNonStringID;
123           }
124       }
125   }
126
127   // Scan all of the functions for their constants, which allows us to emit
128   // more compact modules.
129   SC_DEBUG("Inserting function constants:\n");
130   for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
131        F != E; ++F) {
132     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
133       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
134         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
135              OI != E; ++OI) {
136           if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
137               isa<InlineAsm>(*OI))
138             CreateSlotIfNeeded(*OI);
139         }
140         getOrCreateTypeSlot(I->getType());
141       }
142   }
143
144   // Insert constants that are named at module level into the slot pool so that
145   // the module symbol table can refer to them...
146   SC_DEBUG("Inserting SymbolTable values:\n");
147   processTypeSymbolTable(&TheModule->getTypeSymbolTable());
148   processValueSymbolTable(&TheModule->getValueSymbolTable());
149
150   // Now that we have collected together all of the information relevant to the
151   // module, compactify the type table if it is particularly big and outputting
152   // a bytecode file.  The basic problem we run into is that some programs have
153   // a large number of types, which causes the type field to overflow its size,
154   // which causes instructions to explode in size (particularly call
155   // instructions).  To avoid this behavior, we "sort" the type table so that
156   // all non-value types are pushed to the end of the type table, giving nice
157   // low numbers to the types that can be used by instructions, thus reducing
158   // the amount of explodage we suffer.
159   if (Types.size() >= 64) {
160     unsigned FirstNonValueTypeID = 0;
161     for (unsigned i = 0, e = Types.size(); i != e; ++i)
162       if (Types[i]->isFirstClassType() || Types[i]->isPrimitiveType()) {
163         // Check to see if we have to shuffle this type around.  If not, don't
164         // do anything.
165         if (i != FirstNonValueTypeID) {
166           // Swap the type ID's.
167           std::swap(Types[i], Types[FirstNonValueTypeID]);
168
169           // Keep the TypeMap up to date.
170           TypeMap[Types[i]] = i;
171           TypeMap[Types[FirstNonValueTypeID]] = FirstNonValueTypeID;
172
173           // When we move a type, make sure to move its value plane as needed.
174           if (Table.size() > FirstNonValueTypeID) {
175             if (Table.size() <= i) Table.resize(i+1);
176             std::swap(Table[i], Table[FirstNonValueTypeID]);
177           }
178         }
179         ++FirstNonValueTypeID;
180       }
181   }
182     
183   NumModuleTypes = getNumPlanes();
184
185   SC_DEBUG("end processModule!\n");
186 }
187
188 // processTypeSymbolTable - Insert all of the type sin the specified symbol
189 // table.
190 void SlotCalculator::processTypeSymbolTable(const TypeSymbolTable *TST) {
191   for (TypeSymbolTable::const_iterator TI = TST->begin(), TE = TST->end(); 
192        TI != TE; ++TI )
193     getOrCreateTypeSlot(TI->second);
194 }
195
196 // processSymbolTable - Insert all of the values in the specified symbol table
197 // into the values table...
198 //
199 void SlotCalculator::processValueSymbolTable(const ValueSymbolTable *VST) {
200   for (ValueSymbolTable::const_iterator VI = VST->begin(), VE = VST->end(); 
201        VI != VE; ++VI)
202     CreateSlotIfNeeded(VI->getValue());
203 }
204
205 void SlotCalculator::CreateSlotIfNeeded(const Value *V) {
206   // Check to see if it's already in!
207   if (NodeMap.count(V)) return;
208
209   const Type *Ty = V->getType();
210   assert(Ty != Type::VoidTy && "Can't insert void values!");
211   
212   if (const Constant *C = dyn_cast<Constant>(V)) {
213     if (isa<GlobalValue>(C)) {
214       // Initializers for globals are handled explicitly elsewhere.
215     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
216       // Do not index the characters that make up constant strings.  We emit
217       // constant strings as special entities that don't require their
218       // individual characters to be emitted.
219       if (!C->isNullValue())
220         ConstantStrings.push_back(cast<ConstantArray>(C));
221     } else {
222       // This makes sure that if a constant has uses (for example an array of
223       // const ints), that they are inserted also.
224       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
225            I != E; ++I)
226         CreateSlotIfNeeded(*I);
227     }
228   }
229
230   unsigned TyPlane = getOrCreateTypeSlot(Ty);
231   if (Table.size() <= TyPlane)    // Make sure we have the type plane allocated.
232     Table.resize(TyPlane+1, TypePlane());
233   
234   // If this is the first value to get inserted into the type plane, make sure
235   // to insert the implicit null value.
236   if (Table[TyPlane].empty()) {
237     // Label's and opaque types can't have a null value.
238     if (Ty != Type::LabelTy && !isa<OpaqueType>(Ty)) {
239       Value *ZeroInitializer = Constant::getNullValue(Ty);
240       
241       // If we are pushing zeroinit, it will be handled below.
242       if (V != ZeroInitializer) {
243         Table[TyPlane].push_back(ZeroInitializer);
244         NodeMap[ZeroInitializer] = 0;
245       }
246     }
247   }
248   
249   // Insert node into table and NodeMap...
250   NodeMap[V] = Table[TyPlane].size();
251   Table[TyPlane].push_back(V);
252   
253   SC_DEBUG("  Inserting value [" << TyPlane << "] = " << *V << " slot=" <<
254            NodeMap[V] << "\n");
255 }
256
257
258 unsigned SlotCalculator::getOrCreateTypeSlot(const Type *Ty) {
259   TypeMapType::iterator TyIt = TypeMap.find(Ty);
260   if (TyIt != TypeMap.end()) return TyIt->second;
261
262   // Insert into TypeMap.
263   unsigned ResultSlot = TypeMap[Ty] = Types.size();
264   Types.push_back(Ty);
265   SC_DEBUG("  Inserting type [" << ResultSlot << "] = " << *Ty << "\n" );
266   
267   // Loop over any contained types in the definition, ensuring they are also
268   // inserted.
269   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
270        I != E; ++I)
271     getOrCreateTypeSlot(*I);
272
273   return ResultSlot;
274 }
275
276
277
278 void SlotCalculator::incorporateFunction(const Function *F) {
279   SC_DEBUG("begin processFunction!\n");
280   
281   // Iterate over function arguments, adding them to the value table...
282   for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
283       I != E; ++I)
284     CreateFunctionValueSlot(I);
285   
286   SC_DEBUG("Inserting Instructions:\n");
287   
288   // Add all of the instructions to the type planes...
289   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
290     CreateFunctionValueSlot(BB);
291     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
292       if (I->getType() != Type::VoidTy)
293         CreateFunctionValueSlot(I);
294     }
295   }
296   
297   SC_DEBUG("end processFunction!\n");
298 }
299
300 void SlotCalculator::purgeFunction() {
301   SC_DEBUG("begin purgeFunction!\n");
302   
303   // Next, remove values from existing type planes
304   for (DenseMap<unsigned,unsigned,
305           ModuleLevelDenseMapKeyInfo>::iterator I = ModuleLevel.begin(),
306        E = ModuleLevel.end(); I != E; ++I) {
307     unsigned PlaneNo = I->first;
308     unsigned ModuleLev = I->second;
309     
310     // Pop all function-local values in this type-plane off of Table.
311     TypePlane &Plane = getPlane(PlaneNo);
312     assert(ModuleLev < Plane.size() && "module levels higher than elements?");
313     for (unsigned i = ModuleLev, e = Plane.size(); i != e; ++i) {
314       NodeMap.erase(Plane.back());       // Erase from nodemap
315       Plane.pop_back();                  // Shrink plane
316     }
317   }
318
319   ModuleLevel.clear();
320
321   // Finally, remove any type planes defined by the function...
322   while (Table.size() > NumModuleTypes) {
323     TypePlane &Plane = Table.back();
324     SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
325              << Plane.size() << "\n");
326     for (unsigned i = 0, e = Plane.size(); i != e; ++i)
327       NodeMap.erase(Plane[i]);   // Erase from nodemap
328     
329     Table.pop_back();                // Nuke the plane, we don't like it.
330   }
331   
332   SC_DEBUG("end purgeFunction!\n");
333 }
334
335 void SlotCalculator::CreateFunctionValueSlot(const Value *V) {
336   assert(!NodeMap.count(V) && "Function-local value can't be inserted!");
337   
338   const Type *Ty = V->getType();
339   assert(Ty != Type::VoidTy && "Can't insert void values!");
340   assert(!isa<Constant>(V) && "Not a function-local value!");
341   
342   unsigned TyPlane = getOrCreateTypeSlot(Ty);
343   if (Table.size() <= TyPlane)    // Make sure we have the type plane allocated.
344     Table.resize(TyPlane+1, TypePlane());
345   
346   // If this is the first value noticed of this type within this function,
347   // remember the module level for this type plane in ModuleLevel.  This reminds
348   // us to remove the values in purgeFunction and tells us how many to remove.
349   if (TyPlane < NumModuleTypes)
350     ModuleLevel.insert(std::make_pair(TyPlane, Table[TyPlane].size()));
351   
352   // If this is the first value to get inserted into the type plane, make sure
353   // to insert the implicit null value.
354   if (Table[TyPlane].empty()) {
355     // Label's and opaque types can't have a null value.
356     if (Ty != Type::LabelTy && !isa<OpaqueType>(Ty)) {
357       Value *ZeroInitializer = Constant::getNullValue(Ty);
358       
359       // If we are pushing zeroinit, it will be handled below.
360       if (V != ZeroInitializer) {
361         Table[TyPlane].push_back(ZeroInitializer);
362         NodeMap[ZeroInitializer] = 0;
363       }
364     }
365   }
366   
367   // Insert node into table and NodeMap...
368   NodeMap[V] = Table[TyPlane].size();
369   Table[TyPlane].push_back(V);
370   
371   SC_DEBUG("  Inserting value [" << TyPlane << "] = " << *V << " slot=" <<
372            NodeMap[V] << "\n");
373 }  
374