blob: 354905327955bc1f4c2b8ac3fcb4189c28b68300 [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===-- SlotCalculator.cpp - Calculate what slots values land in ----------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattner68e3dbc2004-01-20 00:57:32 +000010// 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).
Chris Lattner00950542001-06-06 20:29:01 +000012//
Chris Lattner68e3dbc2004-01-20 00:57:32 +000013// This is used when writing a file to disk, either in bytecode or assembly.
Chris Lattner00950542001-06-06 20:29:01 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattnerf2d577b2004-01-20 19:50:34 +000017#include "llvm/Analysis/SlotCalculator.h"
Chris Lattnerdcea6302004-01-14 23:34:39 +000018#include "llvm/Constants.h"
Chris Lattner00950542001-06-06 20:29:01 +000019#include "llvm/DerivedTypes.h"
Chris Lattnerdcea6302004-01-14 23:34:39 +000020#include "llvm/iOther.h"
21#include "llvm/Module.h"
Chris Lattner9a297902001-09-07 16:31:52 +000022#include "llvm/SymbolTable.h"
Chris Lattnerf2d577b2004-01-20 19:50:34 +000023#include "llvm/Analysis/ConstantsScanner.h"
Alkis Evlogimenos088eb452003-10-31 03:02:34 +000024#include "Support/PostOrderIterator.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000025#include "Support/STLExtras.h"
Chris Lattner9a297902001-09-07 16:31:52 +000026#include <algorithm>
Chris Lattner31f84992003-11-21 20:23:48 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner9a297902001-09-07 16:31:52 +000029#if 0
Chris Lattner3413d152003-03-19 20:57:22 +000030#define SC_DEBUG(X) std::cerr << X
Chris Lattner9a297902001-09-07 16:31:52 +000031#else
32#define SC_DEBUG(X)
33#endif
Chris Lattner00950542001-06-06 20:29:01 +000034
Chris Lattner8ce75012004-01-14 02:49:34 +000035SlotCalculator::SlotCalculator(const Module *M, bool buildBytecodeInfo) {
36 BuildBytecodeInfo = buildBytecodeInfo;
Chris Lattner614cdcd2004-01-18 21:07:07 +000037 ModuleContainsAllFunctionConstants = false;
Chris Lattner00950542001-06-06 20:29:01 +000038 TheModule = M;
39
40 // Preload table... Make sure that all of the primitive types are in the table
41 // and that their Primitive ID is equal to their slot #
42 //
Alkis Evlogimenos5d1bdcd2003-10-29 03:12:12 +000043 SC_DEBUG("Inserting primitive types:\n");
Chris Lattner00950542001-06-06 20:29:01 +000044 for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
45 assert(Type::getPrimitiveType((Type::PrimitiveID)i));
Alkis Evlogimenos60596382003-10-17 02:02:40 +000046 insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
Chris Lattner00950542001-06-06 20:29:01 +000047 }
48
49 if (M == 0) return; // Empty table...
Chris Lattner9a297902001-09-07 16:31:52 +000050 processModule();
Chris Lattner00950542001-06-06 20:29:01 +000051}
52
Chris Lattner8ce75012004-01-14 02:49:34 +000053SlotCalculator::SlotCalculator(const Function *M, bool buildBytecodeInfo) {
54 BuildBytecodeInfo = buildBytecodeInfo;
Chris Lattner614cdcd2004-01-18 21:07:07 +000055 ModuleContainsAllFunctionConstants = false;
Chris Lattner00950542001-06-06 20:29:01 +000056 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 //
Alkis Evlogimenos5d1bdcd2003-10-29 03:12:12 +000061 SC_DEBUG("Inserting primitive types:\n");
Chris Lattner00950542001-06-06 20:29:01 +000062 for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
63 assert(Type::getPrimitiveType((Type::PrimitiveID)i));
Alkis Evlogimenos60596382003-10-17 02:02:40 +000064 insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
Chris Lattner00950542001-06-06 20:29:01 +000065 }
66
67 if (TheModule == 0) return; // Empty table...
68
Chris Lattner9a297902001-09-07 16:31:52 +000069 processModule(); // Process module level stuff
Chris Lattner68e3dbc2004-01-20 00:57:32 +000070 incorporateFunction(M); // Start out in incorporated state
Chris Lattner00950542001-06-06 20:29:01 +000071}
72
Chris Lattner614cdcd2004-01-18 21:07:07 +000073unsigned SlotCalculator::getGlobalSlot(const Value *V) const {
74 assert(!CompactionTable.empty() &&
75 "This method can only be used when compaction is enabled!");
76 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
77 V = CPR->getValue();
78 std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
Chris Lattner68e3dbc2004-01-20 00:57:32 +000079 assert(I != NodeMap.end() && "Didn't find global slot entry!");
Chris Lattner614cdcd2004-01-18 21:07:07 +000080 return I->second;
81}
82
Chris Lattner68e3dbc2004-01-20 00:57:32 +000083SlotCalculator::TypePlane &SlotCalculator::getPlane(unsigned Plane) {
84 unsigned PIdx = Plane;
85 if (CompactionTable.empty()) { // No compaction table active?
86 // fall out
87 } else if (!CompactionTable[Plane].empty()) { // Compaction table active.
88 assert(Plane < CompactionTable.size());
89 return CompactionTable[Plane];
90 } else {
91 // Final case: compaction table active, but this plane is not
92 // compactified. If the type plane is compactified, unmap back to the
93 // global type plane corresponding to "Plane".
94 if (!CompactionTable[Type::TypeTyID].empty()) {
95 const Type *Ty = cast<Type>(CompactionTable[Type::TypeTyID][Plane]);
96 std::map<const Value*, unsigned>::iterator It = NodeMap.find(Ty);
97 assert(It != NodeMap.end() && "Type not in global constant map?");
98 PIdx = It->second;
99 }
100 }
101
102 // Okay we are just returning an entry out of the main Table. Make sure the
103 // plane exists and return it.
104 if (PIdx >= Table.size())
105 Table.resize(PIdx+1);
106 return Table[PIdx];
107}
Chris Lattner614cdcd2004-01-18 21:07:07 +0000108
Chris Lattner9a297902001-09-07 16:31:52 +0000109
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000110// processModule - Process all of the module level function declarations and
Chris Lattner9a297902001-09-07 16:31:52 +0000111// types that are available.
112//
113void SlotCalculator::processModule() {
114 SC_DEBUG("begin processModule!\n");
Chris Lattner70cc3392001-09-10 07:58:01 +0000115
Chris Lattner3413d152003-03-19 20:57:22 +0000116 // Add all of the global variables to the value table...
Chris Lattnerf1fef652001-10-13 06:35:09 +0000117 //
118 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
Chris Lattner479b54b2002-10-14 00:48:57 +0000119 I != E; ++I)
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000120 getOrCreateSlot(I);
Chris Lattner70cc3392001-09-10 07:58:01 +0000121
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000122 // Scavenge the types out of the functions, then add the functions themselves
123 // to the value table...
Chris Lattner9a297902001-09-07 16:31:52 +0000124 //
Chris Lattner3413d152003-03-19 20:57:22 +0000125 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
126 I != E; ++I)
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000127 getOrCreateSlot(I);
Chris Lattner9a297902001-09-07 16:31:52 +0000128
Chris Lattner3413d152003-03-19 20:57:22 +0000129 // Add all of the module level constants used as initializers
130 //
131 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
132 I != E; ++I)
133 if (I->hasInitializer())
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000134 getOrCreateSlot(I->getInitializer());
Chris Lattner3413d152003-03-19 20:57:22 +0000135
Chris Lattnerdcea6302004-01-14 23:34:39 +0000136 // Now that all global constants have been added, rearrange constant planes
137 // that contain constant strings so that the strings occur at the start of the
138 // plane, not somewhere in the middle.
139 //
140 if (BuildBytecodeInfo) {
141 TypePlane &Types = Table[Type::TypeTyID];
142 for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
143 if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
144 if (AT->getElementType() == Type::SByteTy ||
145 AT->getElementType() == Type::UByteTy) {
146 TypePlane &Plane = Table[plane];
147 unsigned FirstNonStringID = 0;
148 for (unsigned i = 0, e = Plane.size(); i != e; ++i)
Chris Lattnerde512b52004-02-15 05:55:15 +0000149 if (isa<ConstantAggregateZero>(Plane[i]) ||
150 cast<ConstantArray>(Plane[i])->isString()) {
Chris Lattnerdcea6302004-01-14 23:34:39 +0000151 // Check to see if we have to shuffle this string around. If not,
152 // don't do anything.
153 if (i != FirstNonStringID) {
154 // Swap the plane entries....
155 std::swap(Plane[i], Plane[FirstNonStringID]);
156
157 // Keep the NodeMap up to date.
158 NodeMap[Plane[i]] = i;
159 NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
160 }
161 ++FirstNonStringID;
162 }
163 }
164 }
165 }
166
Chris Lattnera14b0d42004-01-10 23:46:13 +0000167 // If we are emitting a bytecode file, scan all of the functions for their
168 // constants, which allows us to emit more compact modules. This is optional,
169 // and is just used to compactify the constants used by different functions
170 // together.
Chris Lattner614cdcd2004-01-18 21:07:07 +0000171 //
172 // This functionality is completely optional for the bytecode writer, but
173 // tends to produce smaller bytecode files. This should not be used in the
174 // future by clients that want to, for example, build and emit functions on
175 // the fly. For now, however, it is unconditionally enabled when building
176 // bytecode information.
177 //
Chris Lattner8ce75012004-01-14 02:49:34 +0000178 if (BuildBytecodeInfo) {
Chris Lattner614cdcd2004-01-18 21:07:07 +0000179 ModuleContainsAllFunctionConstants = true;
180
Chris Lattnera14b0d42004-01-10 23:46:13 +0000181 SC_DEBUG("Inserting function constants:\n");
182 for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
Chris Lattner614cdcd2004-01-18 21:07:07 +0000183 F != E; ++F) {
184 for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I){
185 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
186 if (isa<Constant>(I->getOperand(op)))
187 getOrCreateSlot(I->getOperand(op));
188 getOrCreateSlot(I->getType());
Chris Lattner6ffe5512004-04-27 15:13:33 +0000189 if (const VANextInst *VAN = dyn_cast<VANextInst>(&*I))
Chris Lattner614cdcd2004-01-18 21:07:07 +0000190 getOrCreateSlot(VAN->getArgType());
191 }
192 processSymbolTableConstants(&F->getSymbolTable());
193 }
Chris Lattnera14b0d42004-01-10 23:46:13 +0000194 }
Chris Lattnera14b0d42004-01-10 23:46:13 +0000195
Chris Lattner70cc3392001-09-10 07:58:01 +0000196 // Insert constants that are named at module level into the slot pool so that
197 // the module symbol table can refer to them...
198 //
Chris Lattner8ce75012004-01-14 02:49:34 +0000199 if (BuildBytecodeInfo) {
Chris Lattner9a297902001-09-07 16:31:52 +0000200 SC_DEBUG("Inserting SymbolTable values:\n");
Chris Lattner6e6026b2002-11-20 18:36:02 +0000201 processSymbolTable(&TheModule->getSymbolTable());
Chris Lattner9a297902001-09-07 16:31:52 +0000202 }
203
Chris Lattnera14b0d42004-01-10 23:46:13 +0000204 // Now that we have collected together all of the information relevant to the
205 // module, compactify the type table if it is particularly big and outputting
206 // a bytecode file. The basic problem we run into is that some programs have
207 // a large number of types, which causes the type field to overflow its size,
208 // which causes instructions to explode in size (particularly call
209 // instructions). To avoid this behavior, we "sort" the type table so that
210 // all non-value types are pushed to the end of the type table, giving nice
211 // low numbers to the types that can be used by instructions, thus reducing
212 // the amount of explodage we suffer.
Chris Lattner8ce75012004-01-14 02:49:34 +0000213 if (BuildBytecodeInfo && Table[Type::TypeTyID].size() >= 64) {
Chris Lattnera14b0d42004-01-10 23:46:13 +0000214 // Scan through the type table moving value types to the start of the table.
Chris Lattner93802972004-01-11 23:29:26 +0000215 TypePlane *Types = &Table[Type::TypeTyID];
Chris Lattnera14b0d42004-01-10 23:46:13 +0000216 unsigned FirstNonValueTypeID = 0;
Chris Lattner93802972004-01-11 23:29:26 +0000217 for (unsigned i = 0, e = Types->size(); i != e; ++i)
218 if (cast<Type>((*Types)[i])->isFirstClassType() ||
219 cast<Type>((*Types)[i])->isPrimitiveType()) {
Chris Lattnera14b0d42004-01-10 23:46:13 +0000220 // Check to see if we have to shuffle this type around. If not, don't
221 // do anything.
222 if (i != FirstNonValueTypeID) {
Chris Lattner93802972004-01-11 23:29:26 +0000223 assert(i != Type::TypeTyID && FirstNonValueTypeID != Type::TypeTyID &&
224 "Cannot move around the type plane!");
225
Chris Lattnera14b0d42004-01-10 23:46:13 +0000226 // Swap the type ID's.
Chris Lattner93802972004-01-11 23:29:26 +0000227 std::swap((*Types)[i], (*Types)[FirstNonValueTypeID]);
Chris Lattnera14b0d42004-01-10 23:46:13 +0000228
229 // Keep the NodeMap up to date.
Chris Lattner93802972004-01-11 23:29:26 +0000230 NodeMap[(*Types)[i]] = i;
231 NodeMap[(*Types)[FirstNonValueTypeID]] = FirstNonValueTypeID;
Chris Lattnera14b0d42004-01-10 23:46:13 +0000232
233 // When we move a type, make sure to move its value plane as needed.
Chris Lattner93802972004-01-11 23:29:26 +0000234 if (Table.size() > FirstNonValueTypeID) {
235 if (Table.size() <= i) Table.resize(i+1);
236 std::swap(Table[i], Table[FirstNonValueTypeID]);
237 Types = &Table[Type::TypeTyID];
238 }
Chris Lattnera14b0d42004-01-10 23:46:13 +0000239 }
240 ++FirstNonValueTypeID;
241 }
242 }
243
Chris Lattner9a297902001-09-07 16:31:52 +0000244 SC_DEBUG("end processModule!\n");
245}
246
247// processSymbolTable - Insert all of the values in the specified symbol table
248// into the values table...
249//
250void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
251 for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
252 for (SymbolTable::type_const_iterator TI = I->second.begin(),
253 TE = I->second.end(); TI != TE; ++TI)
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000254 getOrCreateSlot(TI->second);
Chris Lattner9a297902001-09-07 16:31:52 +0000255}
256
257void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
258 for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
259 for (SymbolTable::type_const_iterator TI = I->second.begin(),
260 TE = I->second.end(); TI != TE; ++TI)
Chris Lattnerd5c59d52004-01-15 20:24:09 +0000261 if (isa<Constant>(TI->second) || isa<Type>(TI->second))
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000262 getOrCreateSlot(TI->second);
Chris Lattner9a297902001-09-07 16:31:52 +0000263}
264
265
Chris Lattnerce439b52003-10-20 19:10:06 +0000266void SlotCalculator::incorporateFunction(const Function *F) {
Chris Lattner00950542001-06-06 20:29:01 +0000267 assert(ModuleLevel.size() == 0 && "Module already incorporated!");
268
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000269 SC_DEBUG("begin processFunction!\n");
Chris Lattner9a297902001-09-07 16:31:52 +0000270
Chris Lattner614cdcd2004-01-18 21:07:07 +0000271 // If we emitted all of the function constants, build a compaction table.
272 if (BuildBytecodeInfo && ModuleContainsAllFunctionConstants)
273 buildCompactionTable(F);
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000274
275 // Update the ModuleLevel entries to be accurate.
276 ModuleLevel.resize(getNumPlanes());
277 for (unsigned i = 0, e = getNumPlanes(); i != e; ++i)
278 ModuleLevel[i] = getPlane(i).size();
Chris Lattner9a297902001-09-07 16:31:52 +0000279
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000280 // Iterate over function arguments, adding them to the value table...
Chris Lattnerce439b52003-10-20 19:10:06 +0000281 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000282 getOrCreateSlot(I);
Chris Lattner9a297902001-09-07 16:31:52 +0000283
Chris Lattner614cdcd2004-01-18 21:07:07 +0000284 if (BuildBytecodeInfo && // Assembly writer does not need this!
285 !ModuleContainsAllFunctionConstants) {
286 // Iterate over all of the instructions in the function, looking for
287 // constant values that are referenced. Add these to the value pools
288 // before any nonconstant values. This will be turned into the constant
289 // pool for the bytecode writer.
290 //
291
292 // Emit all of the constants that are being used by the instructions in
293 // the function...
Chris Lattnerce439b52003-10-20 19:10:06 +0000294 for_each(constant_begin(F), constant_end(F),
Chris Lattner614cdcd2004-01-18 21:07:07 +0000295 bind_obj(this, &SlotCalculator::getOrCreateSlot));
296
Chris Lattner9a297902001-09-07 16:31:52 +0000297 // If there is a symbol table, it is possible that the user has names for
298 // constants that are not being used. In this case, we will have problems
299 // if we don't emit the constants now, because otherwise we will get
Chris Lattnera14b0d42004-01-10 23:46:13 +0000300 // symbol table references to constants not in the output. Scan for these
Chris Lattner9a297902001-09-07 16:31:52 +0000301 // constants now.
302 //
Chris Lattnerce439b52003-10-20 19:10:06 +0000303 processSymbolTableConstants(&F->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000304 }
305
Chris Lattner9a297902001-09-07 16:31:52 +0000306 SC_DEBUG("Inserting Instructions:\n");
307
308 // Add all of the instructions to the type planes...
Chris Lattnerd5c59d52004-01-15 20:24:09 +0000309 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
310 getOrCreateSlot(BB);
Chris Lattner389dbfb2003-10-21 17:39:59 +0000311 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
312 getOrCreateSlot(I);
Chris Lattner2765c412003-10-21 17:40:54 +0000313 if (const VANextInst *VAN = dyn_cast<VANextInst>(I))
314 getOrCreateSlot(VAN->getArgType());
Chris Lattner389dbfb2003-10-21 17:39:59 +0000315 }
Chris Lattner9a297902001-09-07 16:31:52 +0000316 }
317
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000318 // If we are building a compaction table, prune out planes that do not benefit
319 // from being compactified.
320 if (!CompactionTable.empty())
321 pruneCompactionTable();
322
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000323 SC_DEBUG("end processFunction!\n");
Chris Lattner00950542001-06-06 20:29:01 +0000324}
325
Chris Lattnerb5794002002-04-07 22:49:37 +0000326void SlotCalculator::purgeFunction() {
Chris Lattner00950542001-06-06 20:29:01 +0000327 assert(ModuleLevel.size() != 0 && "Module not incorporated!");
328 unsigned NumModuleTypes = ModuleLevel.size();
329
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000330 SC_DEBUG("begin purgeFunction!\n");
Chris Lattner9a297902001-09-07 16:31:52 +0000331
Chris Lattner614cdcd2004-01-18 21:07:07 +0000332 // First, free the compaction map if used.
333 CompactionNodeMap.clear();
334
335 // Next, remove values from existing type planes
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000336 for (unsigned i = 0; i != NumModuleTypes; ++i) {
337 // Size of plane before function came
338 unsigned ModuleLev = getModuleLevel(i);
339 assert(int(ModuleLev) >= 0 && "BAD!");
340
341 TypePlane &Plane = getPlane(i);
342
343 assert(ModuleLev <= Plane.size() && "module levels higher than elements?");
344 while (Plane.size() != ModuleLev) {
345 assert(!isa<GlobalValue>(Plane.back()) &&
346 "Functions cannot define globals!");
347 NodeMap.erase(Plane.back()); // Erase from nodemap
348 Plane.pop_back(); // Shrink plane
Chris Lattner00950542001-06-06 20:29:01 +0000349 }
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000350 }
Chris Lattner00950542001-06-06 20:29:01 +0000351
352 // We don't need this state anymore, free it up.
353 ModuleLevel.clear();
354
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000355 // Finally, remove any type planes defined by the function...
Chris Lattner614cdcd2004-01-18 21:07:07 +0000356 if (!CompactionTable.empty()) {
357 CompactionTable.clear();
358 } else {
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000359 while (Table.size() > NumModuleTypes) {
Chris Lattner614cdcd2004-01-18 21:07:07 +0000360 TypePlane &Plane = Table.back();
361 SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
362 << Plane.size() << "\n");
363 while (Plane.size()) {
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000364 assert(!isa<GlobalValue>(Plane.back()) &&
365 "Functions cannot define globals!");
366 NodeMap.erase(Plane.back()); // Erase from nodemap
367 Plane.pop_back(); // Shrink plane
Chris Lattner614cdcd2004-01-18 21:07:07 +0000368 }
369
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000370 Table.pop_back(); // Nuke the plane, we don't like it.
Chris Lattner00950542001-06-06 20:29:01 +0000371 }
Chris Lattner00950542001-06-06 20:29:01 +0000372 }
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000373
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000374 SC_DEBUG("end purgeFunction!\n");
Chris Lattner00950542001-06-06 20:29:01 +0000375}
376
Chris Lattner614cdcd2004-01-18 21:07:07 +0000377static inline bool hasNullValue(unsigned TyID) {
378 return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
379 TyID != Type::VoidTyID;
380}
381
382/// getOrCreateCompactionTableSlot - This method is used to build up the initial
383/// approximation of the compaction table.
384unsigned SlotCalculator::getOrCreateCompactionTableSlot(const Value *V) {
Chris Lattner71151ae2004-02-09 00:15:41 +0000385 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
386 V = CPR->getValue();
Chris Lattner614cdcd2004-01-18 21:07:07 +0000387 std::map<const Value*, unsigned>::iterator I =
388 CompactionNodeMap.lower_bound(V);
389 if (I != CompactionNodeMap.end() && I->first == V)
390 return I->second; // Already exists?
391
392 // Make sure the type is in the table.
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000393 unsigned Ty;
394 if (!CompactionTable[Type::TypeTyID].empty())
395 Ty = getOrCreateCompactionTableSlot(V->getType());
396 else // If the type plane was decompactified, use the global plane ID
397 Ty = getSlot(V->getType());
Chris Lattner614cdcd2004-01-18 21:07:07 +0000398 if (CompactionTable.size() <= Ty)
399 CompactionTable.resize(Ty+1);
400
401 assert(!isa<Type>(V) || ModuleLevel.empty());
402
403 TypePlane &TyPlane = CompactionTable[Ty];
404
405 // Make sure to insert the null entry if the thing we are inserting is not a
406 // null constant.
407 if (TyPlane.empty() && hasNullValue(V->getType()->getPrimitiveID())) {
408 Value *ZeroInitializer = Constant::getNullValue(V->getType());
409 if (V != ZeroInitializer) {
410 TyPlane.push_back(ZeroInitializer);
411 CompactionNodeMap[ZeroInitializer] = 0;
412 }
413 }
414
415 unsigned SlotNo = TyPlane.size();
416 TyPlane.push_back(V);
417 CompactionNodeMap.insert(std::make_pair(V, SlotNo));
418 return SlotNo;
419}
420
421
422/// buildCompactionTable - Since all of the function constants and types are
423/// stored in the module-level constant table, we don't need to emit a function
424/// constant table. Also due to this, the indices for various constants and
425/// types might be very large in large programs. In order to avoid blowing up
426/// the size of instructions in the bytecode encoding, we build a compaction
427/// table, which defines a mapping from function-local identifiers to global
428/// identifiers.
429void SlotCalculator::buildCompactionTable(const Function *F) {
430 assert(CompactionNodeMap.empty() && "Compaction table already built!");
431 // First step, insert the primitive types.
432 CompactionTable.resize(Type::TypeTyID+1);
433 for (unsigned i = 0; i != Type::FirstDerivedTyID; ++i) {
434 const Type *PrimTy = Type::getPrimitiveType((Type::PrimitiveID)i);
435 CompactionTable[Type::TypeTyID].push_back(PrimTy);
436 CompactionNodeMap[PrimTy] = i;
437 }
438
439 // Next, include any types used by function arguments.
440 for (Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
441 getOrCreateCompactionTableSlot(I->getType());
442
443 // Next, find all of the types and values that are referred to by the
444 // instructions in the program.
445 for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
446 getOrCreateCompactionTableSlot(I->getType());
447 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
448 if (isa<Constant>(I->getOperand(op)) ||
449 isa<GlobalValue>(I->getOperand(op)))
450 getOrCreateCompactionTableSlot(I->getOperand(op));
Chris Lattner6ffe5512004-04-27 15:13:33 +0000451 if (const VANextInst *VAN = dyn_cast<VANextInst>(&*I))
Chris Lattner614cdcd2004-01-18 21:07:07 +0000452 getOrCreateCompactionTableSlot(VAN->getArgType());
453 }
454
455 const SymbolTable &ST = F->getSymbolTable();
456 for (SymbolTable::const_iterator I = ST.begin(), E = ST.end(); I != E; ++I)
457 for (SymbolTable::type_const_iterator TI = I->second.begin(),
458 TE = I->second.end(); TI != TE; ++TI)
459 if (isa<Constant>(TI->second) || isa<Type>(TI->second) ||
460 isa<GlobalValue>(TI->second))
461 getOrCreateCompactionTableSlot(TI->second);
462
463 // Now that we have all of the values in the table, and know what types are
464 // referenced, make sure that there is at least the zero initializer in any
465 // used type plane. Since the type was used, we will be emitting instructions
466 // to the plane even if there are no constants in it.
467 CompactionTable.resize(CompactionTable[Type::TypeTyID].size());
468 for (unsigned i = 0, e = CompactionTable.size(); i != e; ++i)
469 if (CompactionTable[i].empty() && i != Type::VoidTyID &&
470 i != Type::LabelTyID) {
471 const Type *Ty = cast<Type>(CompactionTable[Type::TypeTyID][i]);
472 getOrCreateCompactionTableSlot(Constant::getNullValue(Ty));
473 }
474
475 // Okay, now at this point, we have a legal compaction table. Since we want
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000476 // to emit the smallest possible binaries, do not compactify the type plane if
477 // it will not save us anything. Because we have not yet incorporated the
478 // function body itself yet, we don't know whether or not it's a good idea to
479 // compactify other planes. We will defer this decision until later.
480 TypePlane &GlobalTypes = Table[Type::TypeTyID];
481
482 // All of the values types will be scrunched to the start of the types plane
483 // of the global table. Figure out just how many there are.
484 assert(!GlobalTypes.empty() && "No global types???");
485 unsigned NumFCTypes = GlobalTypes.size()-1;
486 while (!cast<Type>(GlobalTypes[NumFCTypes])->isFirstClassType())
487 --NumFCTypes;
Chris Lattner614cdcd2004-01-18 21:07:07 +0000488
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000489 // If there are fewer that 64 types, no instructions will be exploded due to
490 // the size of the type operands. Thus there is no need to compactify types.
491 // Also, if the compaction table contains most of the entries in the global
492 // table, there really is no reason to compactify either.
493 if (NumFCTypes < 64) {
494 // Decompactifying types is tricky, because we have to move type planes all
495 // over the place. At least we don't need to worry about updating the
496 // CompactionNodeMap for non-types though.
497 std::vector<TypePlane> TmpCompactionTable;
498 std::swap(CompactionTable, TmpCompactionTable);
499 TypePlane Types;
500 std::swap(Types, TmpCompactionTable[Type::TypeTyID]);
501
502 // Move each plane back over to the uncompactified plane
503 while (!Types.empty()) {
504 const Type *Ty = cast<Type>(Types.back());
505 Types.pop_back();
506 CompactionNodeMap.erase(Ty); // Decompactify type!
Chris Lattner614cdcd2004-01-18 21:07:07 +0000507
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000508 if (Ty != Type::TypeTy) {
509 // Find the global slot number for this type.
510 int TySlot = getSlot(Ty);
511 assert(TySlot != -1 && "Type doesn't exist in global table?");
512
513 // Now we know where to put the compaction table plane.
514 if (CompactionTable.size() <= unsigned(TySlot))
515 CompactionTable.resize(TySlot+1);
516 // Move the plane back into the compaction table.
517 std::swap(CompactionTable[TySlot], TmpCompactionTable[Types.size()]);
Chris Lattner614cdcd2004-01-18 21:07:07 +0000518
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000519 // And remove the empty plane we just moved in.
520 TmpCompactionTable.pop_back();
521 }
522 }
523 }
Chris Lattner614cdcd2004-01-18 21:07:07 +0000524}
525
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000526
527/// pruneCompactionTable - Once the entire function being processed has been
528/// incorporated into the current compaction table, look over the compaction
529/// table and check to see if there are any values whose compaction will not
530/// save us any space in the bytecode file. If compactifying these values
531/// serves no purpose, then we might as well not even emit the compactification
532/// information to the bytecode file, saving a bit more space.
533///
534/// Note that the type plane has already been compactified if possible.
535///
536void SlotCalculator::pruneCompactionTable() {
537 TypePlane &TyPlane = CompactionTable[Type::TypeTyID];
538 for (unsigned ctp = 0, e = CompactionTable.size(); ctp != e; ++ctp)
539 if (ctp != Type::TypeTyID && !CompactionTable[ctp].empty()) {
540 TypePlane &CPlane = CompactionTable[ctp];
541 unsigned GlobalSlot = ctp;
542 if (!TyPlane.empty())
543 GlobalSlot = getGlobalSlot(TyPlane[ctp]);
544
545 if (GlobalSlot >= Table.size())
546 Table.resize(GlobalSlot+1);
547 TypePlane &GPlane = Table[GlobalSlot];
548
549 unsigned ModLevel = getModuleLevel(ctp);
550 unsigned NumFunctionObjs = CPlane.size()-ModLevel;
551
552 // If the maximum index required if all entries in this plane were merged
553 // into the global plane is less than 64, go ahead and eliminate the
554 // plane.
555 bool PrunePlane = GPlane.size() + NumFunctionObjs < 64;
556
557 // If there are no function-local values defined, and the maximum
558 // referenced global entry is less than 64, we don't need to compactify.
559 if (!PrunePlane && NumFunctionObjs == 0) {
560 unsigned MaxIdx = 0;
561 for (unsigned i = 0; i != ModLevel; ++i) {
562 unsigned Idx = NodeMap[CPlane[i]];
563 if (Idx > MaxIdx) MaxIdx = Idx;
564 }
565 PrunePlane = MaxIdx < 64;
566 }
567
568 // Ok, finally, if we decided to prune this plane out of the compaction
569 // table, do so now.
570 if (PrunePlane) {
571 TypePlane OldPlane;
572 std::swap(OldPlane, CPlane);
573
574 // Loop over the function local objects, relocating them to the global
575 // table plane.
576 for (unsigned i = ModLevel, e = OldPlane.size(); i != e; ++i) {
577 const Value *V = OldPlane[i];
578 CompactionNodeMap.erase(V);
579 assert(NodeMap.count(V) == 0 && "Value already in table??");
580 getOrCreateSlot(V);
581 }
582
583 // For compactified global values, just remove them from the compaction
584 // node map.
585 for (unsigned i = 0; i != ModLevel; ++i)
586 CompactionNodeMap.erase(OldPlane[i]);
587
588 // Update the new modulelevel for this plane.
589 assert(ctp < ModuleLevel.size() && "Cannot set modulelevel!");
590 ModuleLevel[ctp] = GPlane.size()-NumFunctionObjs;
591 assert((int)ModuleLevel[ctp] >= 0 && "Bad computation!");
592 }
593 }
594}
595
596
Chris Lattner8c202cd2004-01-15 18:47:15 +0000597int SlotCalculator::getSlot(const Value *V) const {
Chris Lattner614cdcd2004-01-18 21:07:07 +0000598 // If there is a CompactionTable active...
599 if (!CompactionNodeMap.empty()) {
600 std::map<const Value*, unsigned>::const_iterator I =
601 CompactionNodeMap.find(V);
602 if (I != CompactionNodeMap.end())
603 return (int)I->second;
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000604 // Otherwise, if it's not in the compaction table, it must be in a
605 // non-compactified plane.
Chris Lattner614cdcd2004-01-18 21:07:07 +0000606 }
607
Chris Lattner8c202cd2004-01-15 18:47:15 +0000608 std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
609 if (I != NodeMap.end())
610 return (int)I->second;
611
612 // Do not number ConstantPointerRef's at all. They are an abomination.
613 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
614 return getSlot(CPR->getValue());
615
616 return -1;
Chris Lattner00950542001-06-06 20:29:01 +0000617}
618
Chris Lattner9a297902001-09-07 16:31:52 +0000619
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000620int SlotCalculator::getOrCreateSlot(const Value *V) {
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000621 if (V->getType() == Type::VoidTy) return -1;
622
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000623 int SlotNo = getSlot(V); // Check to see if it's already in!
Chris Lattner9a297902001-09-07 16:31:52 +0000624 if (SlotNo != -1) return SlotNo;
Chris Lattner3413d152003-03-19 20:57:22 +0000625
Chris Lattner8c202cd2004-01-15 18:47:15 +0000626 // Do not number ConstantPointerRef's at all. They are an abomination.
627 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
628 return getOrCreateSlot(CPR->getValue());
629
Chris Lattner614cdcd2004-01-18 21:07:07 +0000630 if (!isa<GlobalValue>(V)) // Initializers for globals are handled explicitly
Chris Lattner3413d152003-03-19 20:57:22 +0000631 if (const Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner614cdcd2004-01-18 21:07:07 +0000632 assert(CompactionNodeMap.empty() &&
633 "All needed constants should be in the compaction map already!");
634
Chris Lattnerdcea6302004-01-14 23:34:39 +0000635 // If we are emitting a bytecode file, do not index the characters that
636 // make up constant strings. We emit constant strings as special
637 // entities that don't require their individual characters to be emitted.
638 if (!BuildBytecodeInfo || !isa<ConstantArray>(C) ||
639 !cast<ConstantArray>(C)->isString()) {
640 // This makes sure that if a constant has uses (for example an array of
641 // const ints), that they are inserted also.
642 //
643 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
644 I != E; ++I)
645 getOrCreateSlot(*I);
646 } else {
647 assert(ModuleLevel.empty() &&
648 "How can a constant string be directly accessed in a function?");
649 // Otherwise, if we are emitting a bytecode file and this IS a string,
650 // remember it.
651 if (!C->isNullValue())
652 ConstantStrings.push_back(cast<ConstantArray>(C));
653 }
Chris Lattner3413d152003-03-19 20:57:22 +0000654 }
655
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000656 return insertValue(V);
Chris Lattner9a297902001-09-07 16:31:52 +0000657}
658
659
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000660int SlotCalculator::insertValue(const Value *D, bool dontIgnore) {
Chris Lattner9a297902001-09-07 16:31:52 +0000661 assert(D && "Can't insert a null value!");
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000662 assert(getSlot(D) == -1 && "Value is already in the table!");
Chris Lattner00950542001-06-06 20:29:01 +0000663
Chris Lattner614cdcd2004-01-18 21:07:07 +0000664 // If we are building a compaction map, and if this plane is being compacted,
665 // insert the value into the compaction map, not into the global map.
666 if (!CompactionNodeMap.empty()) {
667 if (D->getType() == Type::VoidTy) return -1; // Do not insert void values
668 assert(!isa<Type>(D) && !isa<Constant>(D) && !isa<GlobalValue>(D) &&
669 "Types, constants, and globals should be in global SymTab!");
670
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000671 int Plane = getSlot(D->getType());
672 assert(Plane != -1 && CompactionTable.size() > (unsigned)Plane &&
673 "Didn't find value type!");
674 if (!CompactionTable[Plane].empty())
675 return getOrCreateCompactionTableSlot(D);
Chris Lattner614cdcd2004-01-18 21:07:07 +0000676 }
677
Chris Lattner00950542001-06-06 20:29:01 +0000678 // If this node does not contribute to a plane, or if the node has a
Chris Lattner9a297902001-09-07 16:31:52 +0000679 // name and we don't want names, then ignore the silly node... Note that types
680 // do need slot numbers so that we can keep track of where other values land.
Chris Lattner00950542001-06-06 20:29:01 +0000681 //
Chris Lattner9b50c152001-07-26 16:28:37 +0000682 if (!dontIgnore) // Don't ignore nonignorables!
683 if (D->getType() == Type::VoidTy || // Ignore void type nodes
Chris Lattner8ce75012004-01-14 02:49:34 +0000684 (!BuildBytecodeInfo && // Ignore named and constants
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000685 (D->hasName() || isa<Constant>(D)) && !isa<Type>(D))) {
Chris Lattner3413d152003-03-19 20:57:22 +0000686 SC_DEBUG("ignored value " << *D << "\n");
Chris Lattner9a297902001-09-07 16:31:52 +0000687 return -1; // We do need types unconditionally though
688 }
Chris Lattner00950542001-06-06 20:29:01 +0000689
Chris Lattner9a297902001-09-07 16:31:52 +0000690 // If it's a type, make sure that all subtypes of the type are included...
Chris Lattner949a3622003-07-23 15:30:06 +0000691 if (const Type *TheTy = dyn_cast<Type>(D)) {
Chris Lattnerf1fef652001-10-13 06:35:09 +0000692
693 // Insert the current type before any subtypes. This is important because
694 // recursive types elements are inserted in a bottom up order. Changing
695 // this here can break things. For example:
696 //
697 // global { \2 * } { { \2 }* null }
698 //
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000699 int ResultSlot = doInsertValue(TheTy);
700 SC_DEBUG(" Inserted type: " << TheTy->getDescription() << " slot=" <<
701 ResultSlot << "\n");
Chris Lattner9a297902001-09-07 16:31:52 +0000702
Alkis Evlogimenos088eb452003-10-31 03:02:34 +0000703 // Loop over any contained types in the definition... in post
704 // order.
Chris Lattner9a297902001-09-07 16:31:52 +0000705 //
Alkis Evlogimenos088eb452003-10-31 03:02:34 +0000706 for (po_iterator<const Type*> I = po_begin(TheTy), E = po_end(TheTy);
Alkis Evlogimenos74fa84f2003-10-30 21:04:44 +0000707 I != E; ++I) {
Chris Lattner9a297902001-09-07 16:31:52 +0000708 if (*I != TheTy) {
Alkis Evlogimenos74fa84f2003-10-30 21:04:44 +0000709 const Type *SubTy = *I;
Alkis Evlogimenos088eb452003-10-31 03:02:34 +0000710 // If we haven't seen this sub type before, add it to our type table!
711 if (getSlot(SubTy) == -1) {
712 SC_DEBUG(" Inserting subtype: " << SubTy->getDescription() << "\n");
713 int Slot = doInsertValue(SubTy);
714 SC_DEBUG(" Inserted subtype: " << SubTy->getDescription() <<
715 " slot=" << Slot << "\n");
716 }
Alkis Evlogimenos74fa84f2003-10-30 21:04:44 +0000717 }
718 }
Chris Lattnerf1fef652001-10-13 06:35:09 +0000719 return ResultSlot;
Chris Lattner9a297902001-09-07 16:31:52 +0000720 }
721
722 // Okay, everything is happy, actually insert the silly value now...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000723 return doInsertValue(D);
Chris Lattner9a297902001-09-07 16:31:52 +0000724}
725
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000726// doInsertValue - This is a small helper function to be called only
727// be insertValue.
Chris Lattner9a297902001-09-07 16:31:52 +0000728//
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000729int SlotCalculator::doInsertValue(const Value *D) {
Chris Lattner00950542001-06-06 20:29:01 +0000730 const Type *Typ = D->getType();
Chris Lattner9b50c152001-07-26 16:28:37 +0000731 unsigned Ty;
732
733 // Used for debugging DefSlot=-1 assertion...
734 //if (Typ == Type::TypeTy)
Chris Lattnercfe26c92001-10-01 18:26:53 +0000735 // cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
Chris Lattner9b50c152001-07-26 16:28:37 +0000736
Chris Lattner00950542001-06-06 20:29:01 +0000737 if (Typ->isDerivedType()) {
Chris Lattner68e3dbc2004-01-20 00:57:32 +0000738 int ValSlot;
739 if (CompactionTable.empty())
740 ValSlot = getSlot(Typ);
741 else
742 ValSlot = getGlobalSlot(Typ);
Chris Lattner3413d152003-03-19 20:57:22 +0000743 if (ValSlot == -1) { // Have we already entered this type?
Chris Lattner9a297902001-09-07 16:31:52 +0000744 // Nope, this is the first we have seen the type, process it.
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000745 ValSlot = insertValue(Typ, true);
Chris Lattner3413d152003-03-19 20:57:22 +0000746 assert(ValSlot != -1 && "ProcessType returned -1 for a type?");
Chris Lattner00950542001-06-06 20:29:01 +0000747 }
Chris Lattner3413d152003-03-19 20:57:22 +0000748 Ty = (unsigned)ValSlot;
Chris Lattner9b50c152001-07-26 16:28:37 +0000749 } else {
750 Ty = Typ->getPrimitiveID();
Chris Lattner00950542001-06-06 20:29:01 +0000751 }
752
753 if (Table.size() <= Ty) // Make sure we have the type plane allocated...
754 Table.resize(Ty+1, TypePlane());
Chris Lattner3413d152003-03-19 20:57:22 +0000755
756 // If this is the first value to get inserted into the type plane, make sure
757 // to insert the implicit null value...
Chris Lattner80b97342004-01-17 23:25:43 +0000758 if (Table[Ty].empty() && BuildBytecodeInfo && hasNullValue(Ty)) {
Chris Lattner3413d152003-03-19 20:57:22 +0000759 Value *ZeroInitializer = Constant::getNullValue(Typ);
760
761 // If we are pushing zeroinit, it will be handled below.
762 if (D != ZeroInitializer) {
763 Table[Ty].push_back(ZeroInitializer);
764 NodeMap[ZeroInitializer] = 0;
765 }
766 }
767
Chris Lattner9a297902001-09-07 16:31:52 +0000768 // Insert node into table and NodeMap...
769 unsigned DestSlot = NodeMap[D] = Table[Ty].size();
Chris Lattner00950542001-06-06 20:29:01 +0000770 Table[Ty].push_back(D);
Chris Lattner9a297902001-09-07 16:31:52 +0000771
Chris Lattnerf1fef652001-10-13 06:35:09 +0000772 SC_DEBUG(" Inserting value [" << Ty << "] = " << D << " slot=" <<
773 DestSlot << " [");
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000774 // G = Global, C = Constant, T = Type, F = Function, o = other
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000775 SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" :
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000776 (isa<Type>(D) ? "T" : (isa<Function>(D) ? "F" : "o")))));
Chris Lattnerf1fef652001-10-13 06:35:09 +0000777 SC_DEBUG("]\n");
Chris Lattner9a297902001-09-07 16:31:52 +0000778 return (int)DestSlot;
Chris Lattner00950542001-06-06 20:29:01 +0000779}