1 //===-- SlotCalculator.cpp - Calculate what slots values land in ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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).
13 // This is used when writing a file to disk, either in bytecode or assembly.
15 //===----------------------------------------------------------------------===//
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"
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
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
65 SlotCalculator::SlotCalculator(const Module *M) {
73 // processModule - Process all of the module level function declarations and
74 // types that are available.
76 void SlotCalculator::processModule() {
77 SC_DEBUG("begin processModule!\n");
79 // Add all of the global variables to the value table...
81 for (Module::const_global_iterator I = TheModule->global_begin(),
82 E = TheModule->global_end(); I != E; ++I)
83 CreateSlotIfNeeded(I);
85 // Scavenge the types out of the functions, then add the functions themselves
86 // to the value table...
88 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
90 CreateSlotIfNeeded(I);
92 // Add all of the global aliases to the value table...
94 for (Module::const_alias_iterator I = TheModule->alias_begin(),
95 E = TheModule->alias_end(); I != E; ++I)
96 CreateSlotIfNeeded(I);
98 // Add all of the module level constants used as initializers
100 for (Module::const_global_iterator I = TheModule->global_begin(),
101 E = TheModule->global_end(); I != E; ++I)
102 if (I->hasInitializer())
103 CreateSlotIfNeeded(I->getInitializer());
105 // Add all of the module level constants used as aliasees
107 for (Module::const_alias_iterator I = TheModule->alias_begin(),
108 E = TheModule->alias_end(); I != E; ++I)
110 CreateSlotIfNeeded(I->getAliasee());
112 // Now that all global constants have been added, rearrange constant planes
113 // that contain constant strings so that the strings occur at the start of the
114 // plane, not somewhere in the middle.
116 for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
117 if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
118 if (AT->getElementType() == Type::Int8Ty) {
119 TypePlane &Plane = Table[plane];
120 unsigned FirstNonStringID = 0;
121 for (unsigned i = 0, e = Plane.size(); i != e; ++i)
122 if (isa<ConstantAggregateZero>(Plane[i]) ||
123 (isa<ConstantArray>(Plane[i]) &&
124 cast<ConstantArray>(Plane[i])->isString())) {
125 // Check to see if we have to shuffle this string around. If not,
126 // don't do anything.
127 if (i != FirstNonStringID) {
128 // Swap the plane entries....
129 std::swap(Plane[i], Plane[FirstNonStringID]);
131 // Keep the NodeMap up to date.
132 NodeMap[Plane[i]] = i;
133 NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
140 // Scan all of the functions for their constants, which allows us to emit
141 // more compact modules.
142 SC_DEBUG("Inserting function constants:\n");
143 for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
145 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
146 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
147 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
149 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
151 CreateSlotIfNeeded(*OI);
153 getOrCreateTypeSlot(I->getType());
157 // Insert constants that are named at module level into the slot pool so that
158 // the module symbol table can refer to them...
159 SC_DEBUG("Inserting SymbolTable values:\n");
160 processTypeSymbolTable(&TheModule->getTypeSymbolTable());
161 processValueSymbolTable(&TheModule->getValueSymbolTable());
163 // Now that we have collected together all of the information relevant to the
164 // module, compactify the type table if it is particularly big and outputting
165 // a bytecode file. The basic problem we run into is that some programs have
166 // a large number of types, which causes the type field to overflow its size,
167 // which causes instructions to explode in size (particularly call
168 // instructions). To avoid this behavior, we "sort" the type table so that
169 // all non-value types are pushed to the end of the type table, giving nice
170 // low numbers to the types that can be used by instructions, thus reducing
171 // the amount of explodage we suffer.
172 if (Types.size() >= 64) {
173 unsigned FirstNonValueTypeID = 0;
174 for (unsigned i = 0, e = Types.size(); i != e; ++i)
175 if (Types[i]->isFirstClassType() || Types[i]->isPrimitiveType()) {
176 // Check to see if we have to shuffle this type around. If not, don't
178 if (i != FirstNonValueTypeID) {
179 // Swap the type ID's.
180 std::swap(Types[i], Types[FirstNonValueTypeID]);
182 // Keep the TypeMap up to date.
183 TypeMap[Types[i]] = i;
184 TypeMap[Types[FirstNonValueTypeID]] = FirstNonValueTypeID;
186 // When we move a type, make sure to move its value plane as needed.
187 if (Table.size() > FirstNonValueTypeID) {
188 if (Table.size() <= i) Table.resize(i+1);
189 std::swap(Table[i], Table[FirstNonValueTypeID]);
192 ++FirstNonValueTypeID;
196 NumModuleTypes = getNumPlanes();
198 SC_DEBUG("end processModule!\n");
201 // processTypeSymbolTable - Insert all of the type sin the specified symbol
203 void SlotCalculator::processTypeSymbolTable(const TypeSymbolTable *TST) {
204 for (TypeSymbolTable::const_iterator TI = TST->begin(), TE = TST->end();
206 getOrCreateTypeSlot(TI->second);
209 // processSymbolTable - Insert all of the values in the specified symbol table
210 // into the values table...
212 void SlotCalculator::processValueSymbolTable(const ValueSymbolTable *VST) {
213 for (ValueSymbolTable::const_iterator VI = VST->begin(), VE = VST->end();
215 CreateSlotIfNeeded(VI->getValue());
218 void SlotCalculator::CreateSlotIfNeeded(const Value *V) {
219 // Check to see if it's already in!
220 if (NodeMap.count(V)) return;
222 const Type *Ty = V->getType();
223 assert(Ty != Type::VoidTy && "Can't insert void values!");
225 if (const Constant *C = dyn_cast<Constant>(V)) {
226 if (isa<GlobalValue>(C)) {
227 // Initializers for globals are handled explicitly elsewhere.
228 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
229 // Do not index the characters that make up constant strings. We emit
230 // constant strings as special entities that don't require their
231 // individual characters to be emitted.
232 if (!C->isNullValue())
233 ConstantStrings.push_back(cast<ConstantArray>(C));
235 // This makes sure that if a constant has uses (for example an array of
236 // const ints), that they are inserted also.
237 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
239 CreateSlotIfNeeded(*I);
243 unsigned TyPlane = getOrCreateTypeSlot(Ty);
244 if (Table.size() <= TyPlane) // Make sure we have the type plane allocated.
245 Table.resize(TyPlane+1, TypePlane());
247 // If this is the first value to get inserted into the type plane, make sure
248 // to insert the implicit null value.
249 if (Table[TyPlane].empty()) {
250 // Label's and opaque types can't have a null value.
251 if (Ty != Type::LabelTy && !isa<OpaqueType>(Ty)) {
252 Value *ZeroInitializer = Constant::getNullValue(Ty);
254 // If we are pushing zeroinit, it will be handled below.
255 if (V != ZeroInitializer) {
256 Table[TyPlane].push_back(ZeroInitializer);
257 NodeMap[ZeroInitializer] = 0;
262 // Insert node into table and NodeMap...
263 NodeMap[V] = Table[TyPlane].size();
264 Table[TyPlane].push_back(V);
266 SC_DEBUG(" Inserting value [" << TyPlane << "] = " << *V << " slot=" <<
271 unsigned SlotCalculator::getOrCreateTypeSlot(const Type *Ty) {
272 TypeMapType::iterator TyIt = TypeMap.find(Ty);
273 if (TyIt != TypeMap.end()) return TyIt->second;
275 // Insert into TypeMap.
276 unsigned ResultSlot = TypeMap[Ty] = Types.size();
278 SC_DEBUG(" Inserting type [" << ResultSlot << "] = " << *Ty << "\n" );
280 // Loop over any contained types in the definition, ensuring they are also
282 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
284 getOrCreateTypeSlot(*I);
291 void SlotCalculator::incorporateFunction(const Function *F) {
292 SC_DEBUG("begin processFunction!\n");
294 // Iterate over function arguments, adding them to the value table...
295 for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
297 CreateFunctionValueSlot(I);
299 SC_DEBUG("Inserting Instructions:\n");
301 // Add all of the instructions to the type planes...
302 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
303 CreateFunctionValueSlot(BB);
304 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
305 if (I->getType() != Type::VoidTy)
306 CreateFunctionValueSlot(I);
310 SC_DEBUG("end processFunction!\n");
313 void SlotCalculator::purgeFunction() {
314 SC_DEBUG("begin purgeFunction!\n");
316 // Next, remove values from existing type planes
317 for (DenseMap<unsigned,unsigned,
318 ModuleLevelDenseMapKeyInfo>::iterator I = ModuleLevel.begin(),
319 E = ModuleLevel.end(); I != E; ++I) {
320 unsigned PlaneNo = I->first;
321 unsigned ModuleLev = I->second;
323 // Pop all function-local values in this type-plane off of Table.
324 TypePlane &Plane = getPlane(PlaneNo);
325 assert(ModuleLev < Plane.size() && "module levels higher than elements?");
326 for (unsigned i = ModuleLev, e = Plane.size(); i != e; ++i) {
327 NodeMap.erase(Plane.back()); // Erase from nodemap
328 Plane.pop_back(); // Shrink plane
334 // Finally, remove any type planes defined by the function...
335 while (Table.size() > NumModuleTypes) {
336 TypePlane &Plane = Table.back();
337 SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
338 << Plane.size() << "\n");
339 for (unsigned i = 0, e = Plane.size(); i != e; ++i)
340 NodeMap.erase(Plane[i]); // Erase from nodemap
342 Table.pop_back(); // Nuke the plane, we don't like it.
345 SC_DEBUG("end purgeFunction!\n");
348 inline static bool hasImplicitNull(const Type* Ty) {
349 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
352 void SlotCalculator::CreateFunctionValueSlot(const Value *V) {
353 assert(!NodeMap.count(V) && "Function-local value can't be inserted!");
355 const Type *Ty = V->getType();
356 assert(Ty != Type::VoidTy && "Can't insert void values!");
357 assert(!isa<Constant>(V) && "Not a function-local value!");
359 unsigned TyPlane = getOrCreateTypeSlot(Ty);
360 if (Table.size() <= TyPlane) // Make sure we have the type plane allocated.
361 Table.resize(TyPlane+1, TypePlane());
363 // If this is the first value noticed of this type within this function,
364 // remember the module level for this type plane in ModuleLevel. This reminds
365 // us to remove the values in purgeFunction and tells us how many to remove.
366 if (TyPlane < NumModuleTypes)
367 ModuleLevel.insert(std::make_pair(TyPlane, Table[TyPlane].size()));
369 // If this is the first value to get inserted into the type plane, make sure
370 // to insert the implicit null value.
371 if (Table[TyPlane].empty()) {
372 // Label's and opaque types can't have a null value.
373 if (hasImplicitNull(Ty)) {
374 Value *ZeroInitializer = Constant::getNullValue(Ty);
376 // If we are pushing zeroinit, it will be handled below.
377 if (V != ZeroInitializer) {
378 Table[TyPlane].push_back(ZeroInitializer);
379 NodeMap[ZeroInitializer] = 0;
384 // Insert node into table and NodeMap...
385 NodeMap[V] = Table[TyPlane].size();
386 Table[TyPlane].push_back(V);
388 SC_DEBUG(" Inserting value [" << TyPlane << "] = " << *V << " slot=" <<