blob: 63cb2d0c5a1682744a9ba46d8ad802d175499e36 [file] [log] [blame]
Chris Lattner14999342004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
Misha Brukman23c6d2c2005-04-21 21:48:46 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Writer.h
11//
Chris Lattner00950542001-06-06 20:29:01 +000012// Note that this file uses an unusual technique of outputting all the bytecode
Reid Spencerad89bd62004-07-25 18:07:36 +000013// to a vector of unsigned char, then copies the vector to an ostream. The
Chris Lattner00950542001-06-06 20:29:01 +000014// reason for this is that we must do "seeking" in the stream to do back-
15// patching, and some very important ostreams that we want to support (like
16// pipes) do not support seeking. :( :( :(
17//
Chris Lattner00950542001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
20#include "WriterInternals.h"
Chris Lattner635cd932002-07-23 19:56:44 +000021#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattner83bb3d22004-01-14 23:36:54 +000022#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000024#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/SymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000028#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000031#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000032#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Reid Spencer38d54be2004-08-17 07:45:14 +000035/// This value needs to be incremented every time the bytecode format changes
36/// so that the reader can distinguish which format of the bytecode file has
37/// been written.
38/// @brief The bytecode version number
Chris Lattnera79e7cc2004-10-16 18:18:16 +000039const unsigned BCVersionNum = 5;
Reid Spencer38d54be2004-08-17 07:45:14 +000040
Chris Lattner635cd932002-07-23 19:56:44 +000041static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
42
Misha Brukman23c6d2c2005-04-21 21:48:46 +000043static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000044BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000045
Reid Spencerad89bd62004-07-25 18:07:36 +000046//===----------------------------------------------------------------------===//
47//=== Output Primitives ===//
48//===----------------------------------------------------------------------===//
49
50// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000051// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000052// body should be included.
53inline void BytecodeWriter::output(unsigned i, int pos) {
54 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000055 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000056 Out.push_back((unsigned char)(i >> 8));
57 Out.push_back((unsigned char)(i >> 16));
58 Out.push_back((unsigned char)(i >> 24));
59 } else {
60 Out[pos ] = (unsigned char)i;
61 Out[pos+1] = (unsigned char)(i >> 8);
62 Out[pos+2] = (unsigned char)(i >> 16);
63 Out[pos+3] = (unsigned char)(i >> 24);
64 }
65}
66
67inline void BytecodeWriter::output(int i) {
68 output((unsigned)i);
69}
70
71/// output_vbr - Output an unsigned value, by using the least number of bytes
72/// possible. This is useful because many of our "infinite" values are really
73/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000074/// Data format used: If you read a byte with the high bit set, use the low
75/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000076inline void BytecodeWriter::output_vbr(uint64_t i) {
77 while (1) {
78 if (i < 0x80) { // done?
79 Out.push_back((unsigned char)i); // We know the high bit is clear...
80 return;
81 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000082
Reid Spencerad89bd62004-07-25 18:07:36 +000083 // Nope, we are bigger than a character, output the next 7 bits and set the
84 // high bit to say that there is more coming...
85 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
86 i >>= 7; // Shift out 7 bits now...
87 }
88}
89
90inline void BytecodeWriter::output_vbr(unsigned i) {
91 while (1) {
92 if (i < 0x80) { // done?
93 Out.push_back((unsigned char)i); // We know the high bit is clear...
94 return;
95 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000096
Reid Spencerad89bd62004-07-25 18:07:36 +000097 // Nope, we are bigger than a character, output the next 7 bits and set the
98 // high bit to say that there is more coming...
99 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
100 i >>= 7; // Shift out 7 bits now...
101 }
102}
103
104inline void BytecodeWriter::output_typeid(unsigned i) {
105 if (i <= 0x00FFFFFF)
106 this->output_vbr(i);
107 else {
108 this->output_vbr(0x00FFFFFF);
109 this->output_vbr(i);
110 }
111}
112
113inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000114 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000115 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
116 else
117 output_vbr((uint64_t)i << 1); // Low order bit is clear.
118}
119
120
121inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000122 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000123 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
124 else
125 output_vbr((unsigned)i << 1); // Low order bit is clear.
126}
127
Reid Spencer38d54be2004-08-17 07:45:14 +0000128inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000129 unsigned Len = s.length();
130 output_vbr(Len ); // Strings may have an arbitrary length...
131 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000132}
133
134inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
135 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
136}
137
138inline void BytecodeWriter::output_float(float& FloatVal) {
139 /// FIXME: This isn't optimal, it has size problems on some platforms
140 /// where FP is not IEEE.
141 union {
142 float f;
143 uint32_t i;
144 } FloatUnion;
145 FloatUnion.f = FloatVal;
146 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
150}
151
152inline void BytecodeWriter::output_double(double& DoubleVal) {
153 /// FIXME: This isn't optimal, it has size problems on some platforms
154 /// where FP is not IEEE.
155 union {
156 double d;
157 uint64_t i;
158 } DoubleUnion;
159 DoubleUnion.d = DoubleVal;
160 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
167 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
168}
169
170inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000171 bool elideIfEmpty, bool hasLongFormat )
Reid Spencerad89bd62004-07-25 18:07:36 +0000172 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
173
174 if (HasLongFormat) {
175 w.output(ID);
176 w.output(0U); // For length in long format
177 } else {
178 w.output(0U); /// Place holder for ID and length for this block
179 }
180 Loc = w.size();
181}
182
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000183inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000184 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000185 if (Loc == Writer.size() && ElideIfEmpty) {
186 // If the block is empty, and we are allowed to, do not emit the block at
187 // all!
188 Writer.resize(Writer.size()-(HasLongFormat?8:4));
189 return;
190 }
191
Reid Spencerad89bd62004-07-25 18:07:36 +0000192 if (HasLongFormat)
193 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
194 else
195 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000196}
197
198//===----------------------------------------------------------------------===//
199//=== Constant Output ===//
200//===----------------------------------------------------------------------===//
201
202void BytecodeWriter::outputType(const Type *T) {
203 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000204
Reid Spencerad89bd62004-07-25 18:07:36 +0000205 // That's all there is to handling primitive types...
206 if (T->isPrimitiveType()) {
207 return; // We might do this if we alias a prim type: %x = type int
208 }
209
210 switch (T->getTypeID()) { // Handle derived types now.
211 case Type::FunctionTyID: {
212 const FunctionType *MT = cast<FunctionType>(T);
213 int Slot = Table.getSlot(MT->getReturnType());
214 assert(Slot != -1 && "Type used but not available!!");
215 output_typeid((unsigned)Slot);
216
217 // Output the number of arguments to function (+1 if varargs):
218 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
219
220 // Output all of the arguments...
221 FunctionType::param_iterator I = MT->param_begin();
222 for (; I != MT->param_end(); ++I) {
223 Slot = Table.getSlot(*I);
224 assert(Slot != -1 && "Type used but not available!!");
225 output_typeid((unsigned)Slot);
226 }
227
228 // Terminate list with VoidTy if we are a varargs function...
229 if (MT->isVarArg())
230 output_typeid((unsigned)Type::VoidTyID);
231 break;
232 }
233
234 case Type::ArrayTyID: {
235 const ArrayType *AT = cast<ArrayType>(T);
236 int Slot = Table.getSlot(AT->getElementType());
237 assert(Slot != -1 && "Type used but not available!!");
238 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000239 output_vbr(AT->getNumElements());
240 break;
241 }
242
Brian Gaeke715c90b2004-08-20 06:00:58 +0000243 case Type::PackedTyID: {
244 const PackedType *PT = cast<PackedType>(T);
245 int Slot = Table.getSlot(PT->getElementType());
246 assert(Slot != -1 && "Type used but not available!!");
247 output_typeid((unsigned)Slot);
248 output_vbr(PT->getNumElements());
249 break;
250 }
251
252
Reid Spencerad89bd62004-07-25 18:07:36 +0000253 case Type::StructTyID: {
254 const StructType *ST = cast<StructType>(T);
255
256 // Output all of the element types...
257 for (StructType::element_iterator I = ST->element_begin(),
258 E = ST->element_end(); I != E; ++I) {
259 int Slot = Table.getSlot(*I);
260 assert(Slot != -1 && "Type used but not available!!");
261 output_typeid((unsigned)Slot);
262 }
263
264 // Terminate list with VoidTy
265 output_typeid((unsigned)Type::VoidTyID);
266 break;
267 }
268
269 case Type::PointerTyID: {
270 const PointerType *PT = cast<PointerType>(T);
271 int Slot = Table.getSlot(PT->getElementType());
272 assert(Slot != -1 && "Type used but not available!!");
273 output_typeid((unsigned)Slot);
274 break;
275 }
276
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000277 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000278 // No need to emit anything, just the count of opaque types is enough.
279 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000280
Reid Spencerad89bd62004-07-25 18:07:36 +0000281 default:
282 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
283 << " Type '" << T->getDescription() << "'\n";
284 break;
285 }
286}
287
288void BytecodeWriter::outputConstant(const Constant *CPV) {
289 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
290 "Shouldn't output null constants!");
291
292 // We must check for a ConstantExpr before switching by type because
293 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000294 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000295 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
296 // FIXME: Encoding of constant exprs could be much more compact!
297 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattner129baf62004-12-04 21:28:47 +0000298 assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000299 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerad89bd62004-07-25 18:07:36 +0000300 output_vbr(CE->getOpcode()); // flags as an expr
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000301
Reid Spencerad89bd62004-07-25 18:07:36 +0000302 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
303 int Slot = Table.getSlot(*OI);
304 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
305 output_vbr((unsigned)Slot);
306 Slot = Table.getSlot((*OI)->getType());
307 output_typeid((unsigned)Slot);
308 }
309 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000310 } else if (isa<UndefValue>(CPV)) {
311 output_vbr(1U); // 1 -> UndefValue constant.
312 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000313 } else {
314 output_vbr(0U); // flag as not a ConstantExpr
315 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000316
Reid Spencerad89bd62004-07-25 18:07:36 +0000317 switch (CPV->getType()->getTypeID()) {
318 case Type::BoolTyID: // Boolean Types
319 if (cast<ConstantBool>(CPV)->getValue())
320 output_vbr(1U);
321 else
322 output_vbr(0U);
323 break;
324
325 case Type::UByteTyID: // Unsigned integer types...
326 case Type::UShortTyID:
327 case Type::UIntTyID:
328 case Type::ULongTyID:
329 output_vbr(cast<ConstantUInt>(CPV)->getValue());
330 break;
331
332 case Type::SByteTyID: // Signed integer types...
333 case Type::ShortTyID:
334 case Type::IntTyID:
335 case Type::LongTyID:
336 output_vbr(cast<ConstantSInt>(CPV)->getValue());
337 break;
338
339 case Type::ArrayTyID: {
340 const ConstantArray *CPA = cast<ConstantArray>(CPV);
341 assert(!CPA->isString() && "Constant strings should be handled specially!");
342
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000343 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000344 int Slot = Table.getSlot(CPA->getOperand(i));
345 assert(Slot != -1 && "Constant used but not available!!");
346 output_vbr((unsigned)Slot);
347 }
348 break;
349 }
350
Brian Gaeke715c90b2004-08-20 06:00:58 +0000351 case Type::PackedTyID: {
352 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
353
354 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
355 int Slot = Table.getSlot(CP->getOperand(i));
356 assert(Slot != -1 && "Constant used but not available!!");
357 output_vbr((unsigned)Slot);
358 }
359 break;
360 }
361
Reid Spencerad89bd62004-07-25 18:07:36 +0000362 case Type::StructTyID: {
363 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000364
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000365 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
366 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000367 assert(Slot != -1 && "Constant used but not available!!");
368 output_vbr((unsigned)Slot);
369 }
370 break;
371 }
372
373 case Type::PointerTyID:
374 assert(0 && "No non-null, non-constant-expr constants allowed!");
375 abort();
376
377 case Type::FloatTyID: { // Floating point types...
378 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
379 output_float(Tmp);
380 break;
381 }
382 case Type::DoubleTyID: {
383 double Tmp = cast<ConstantFP>(CPV)->getValue();
384 output_double(Tmp);
385 break;
386 }
387
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000388 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000389 case Type::LabelTyID:
390 default:
391 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
392 << " type '" << *CPV->getType() << "'\n";
393 break;
394 }
395 return;
396}
397
398void BytecodeWriter::outputConstantStrings() {
399 SlotCalculator::string_iterator I = Table.string_begin();
400 SlotCalculator::string_iterator E = Table.string_end();
401 if (I == E) return; // No strings to emit
402
403 // If we have != 0 strings to emit, output them now. Strings are emitted into
404 // the 'void' type plane.
405 output_vbr(unsigned(E-I));
406 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000407
Reid Spencerad89bd62004-07-25 18:07:36 +0000408 // Emit all of the strings.
409 for (I = Table.string_begin(); I != E; ++I) {
410 const ConstantArray *Str = *I;
411 int Slot = Table.getSlot(Str->getType());
412 assert(Slot != -1 && "Constant string of unknown type?");
413 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000414
Reid Spencerad89bd62004-07-25 18:07:36 +0000415 // Now that we emitted the type (which indicates the size of the string),
416 // emit all of the characters.
417 std::string Val = Str->getAsString();
418 output_data(Val.c_str(), Val.c_str()+Val.size());
419 }
420}
421
422//===----------------------------------------------------------------------===//
423//=== Instruction Output ===//
424//===----------------------------------------------------------------------===//
425typedef unsigned char uchar;
426
Chris Lattnerda895d62005-02-27 06:18:25 +0000427// outputInstructionFormat0 - Output those weird instructions that have a large
Reid Spencerad89bd62004-07-25 18:07:36 +0000428// number of operands or have large operands themselves...
429//
430// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
431//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000432void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
433 unsigned Opcode,
434 const SlotCalculator &Table,
435 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000436 // Opcode must have top two bits clear...
437 output_vbr(Opcode << 2); // Instruction Opcode ID
438 output_typeid(Type); // Result type
439
440 unsigned NumArgs = I->getNumOperands();
441 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
442 isa<VAArgInst>(I)));
443
444 if (!isa<GetElementPtrInst>(&I)) {
445 for (unsigned i = 0; i < NumArgs; ++i) {
446 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000447 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000448 output_vbr((unsigned)Slot);
449 }
450
451 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
452 int Slot = Table.getSlot(I->getType());
453 assert(Slot != -1 && "Cast return type unknown?");
454 output_typeid((unsigned)Slot);
455 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
456 int Slot = Table.getSlot(VAI->getArgType());
457 assert(Slot != -1 && "VarArg argument type unknown?");
458 output_typeid((unsigned)Slot);
459 }
460
461 } else {
462 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000463 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000464 output_vbr(unsigned(Slot));
465
466 // We need to encode the type of sequential type indices into their slot #
467 unsigned Idx = 1;
468 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
469 Idx != NumArgs; ++TI, ++Idx) {
470 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000471 assert(Slot >= 0 && "No slot number for value!?!?");
472
Reid Spencerad89bd62004-07-25 18:07:36 +0000473 if (isa<SequentialType>(*TI)) {
474 unsigned IdxId;
475 switch (I->getOperand(Idx)->getType()->getTypeID()) {
476 default: assert(0 && "Unknown index type!");
477 case Type::UIntTyID: IdxId = 0; break;
478 case Type::IntTyID: IdxId = 1; break;
479 case Type::ULongTyID: IdxId = 2; break;
480 case Type::LongTyID: IdxId = 3; break;
481 }
482 Slot = (Slot << 2) | IdxId;
483 }
484 output_vbr(unsigned(Slot));
485 }
486 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000487}
488
489
490// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
491// This are more annoying than most because the signature of the call does not
492// tell us anything about the types of the arguments in the varargs portion.
493// Because of this, we encode (as type 0) all of the argument types explicitly
494// before the argument value. This really sucks, but you shouldn't be using
495// varargs functions in your code! *death to printf*!
496//
497// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
498//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000499void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
500 unsigned Opcode,
501 const SlotCalculator &Table,
502 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000503 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
504 // Opcode must have top two bits clear...
505 output_vbr(Opcode << 2); // Instruction Opcode ID
506 output_typeid(Type); // Result type (varargs type)
507
508 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
510 unsigned NumParams = FTy->getNumParams();
511
512 unsigned NumFixedOperands;
513 if (isa<CallInst>(I)) {
514 // Output an operand for the callee and each fixed argument, then two for
515 // each variable argument.
516 NumFixedOperands = 1+NumParams;
517 } else {
518 assert(isa<InvokeInst>(I) && "Not call or invoke??");
519 // Output an operand for the callee and destinations, then two for each
520 // variable argument.
521 NumFixedOperands = 3+NumParams;
522 }
523 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
524
525 // The type for the function has already been emitted in the type field of the
526 // instruction. Just emit the slot # now.
527 for (unsigned i = 0; i != NumFixedOperands; ++i) {
528 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000529 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000530 output_vbr((unsigned)Slot);
531 }
532
533 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
534 // Output Arg Type ID
535 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000536 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000537 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000538
Reid Spencerad89bd62004-07-25 18:07:36 +0000539 // Output arg ID itself
540 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000541 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000542 output_vbr((unsigned)Slot);
543 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000544}
545
546
547// outputInstructionFormat1 - Output one operand instructions, knowing that no
548// operand index is >= 2^12.
549//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000550inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
551 unsigned Opcode,
552 unsigned *Slots,
553 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000554 // bits Instruction format:
555 // --------------------------
556 // 01-00: Opcode type, fixed to 1.
557 // 07-02: Opcode
558 // 19-08: Resulting type plane
559 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
560 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000561 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000562}
563
564
565// outputInstructionFormat2 - Output two operand instructions, knowing that no
566// operand index is >= 2^8.
567//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000568inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
569 unsigned Opcode,
570 unsigned *Slots,
571 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000572 // bits Instruction format:
573 // --------------------------
574 // 01-00: Opcode type, fixed to 2.
575 // 07-02: Opcode
576 // 15-08: Resulting type plane
577 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000578 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000579 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000580 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000581}
582
583
584// outputInstructionFormat3 - Output three operand instructions, knowing that no
585// operand index is >= 2^6.
586//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000587inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000588 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000589 unsigned *Slots,
590 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000591 // bits Instruction format:
592 // --------------------------
593 // 01-00: Opcode type, fixed to 3.
594 // 07-02: Opcode
595 // 13-08: Resulting type plane
596 // 19-14: Operand #1
597 // 25-20: Operand #2
598 // 31-26: Operand #3
599 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000600 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000601 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000602}
603
604void BytecodeWriter::outputInstruction(const Instruction &I) {
605 assert(I.getOpcode() < 62 && "Opcode too big???");
606 unsigned Opcode = I.getOpcode();
607 unsigned NumOperands = I.getNumOperands();
608
Chris Lattner38287bd2005-05-06 06:13:34 +0000609 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
610 // 63.
611 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
612 Opcode = 61;
Reid Spencerad89bd62004-07-25 18:07:36 +0000613 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
614 Opcode = 62;
615 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
616 Opcode = 63;
617
618 // Figure out which type to encode with the instruction. Typically we want
619 // the type of the first parameter, as opposed to the type of the instruction
620 // (for example, with setcc, we always know it returns bool, but the type of
621 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000622 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000623 //
624 const Type *Ty;
625 switch (I.getOpcode()) {
626 case Instruction::Select:
627 case Instruction::Malloc:
628 case Instruction::Alloca:
629 Ty = I.getType(); // These ALWAYS want to encode the return type
630 break;
631 case Instruction::Store:
632 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
633 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
634 break;
635 default: // Otherwise use the default behavior...
636 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
637 break;
638 }
639
640 unsigned Type;
641 int Slot = Table.getSlot(Ty);
642 assert(Slot != -1 && "Type not available!!?!");
643 Type = (unsigned)Slot;
644
645 // Varargs calls and invokes are encoded entirely different from any other
646 // instructions.
647 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
648 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
649 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
650 outputInstrVarArgsCall(CI, Opcode, Table, Type);
651 return;
652 }
653 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
654 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
655 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
656 outputInstrVarArgsCall(II, Opcode, Table, Type);
657 return;
658 }
659 }
660
661 if (NumOperands <= 3) {
662 // Make sure that we take the type number into consideration. We don't want
663 // to overflow the field size for the instruction format we select.
664 //
665 unsigned MaxOpSlot = Type;
666 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000667
Reid Spencerad89bd62004-07-25 18:07:36 +0000668 for (unsigned i = 0; i != NumOperands; ++i) {
669 int slot = Table.getSlot(I.getOperand(i));
670 assert(slot != -1 && "Broken bytecode!");
671 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
672 Slots[i] = unsigned(slot);
673 }
674
675 // Handle the special cases for various instructions...
676 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
677 // Cast has to encode the destination type as the second argument in the
678 // packet, or else we won't know what type to cast to!
679 Slots[1] = Table.getSlot(I.getType());
680 assert(Slots[1] != ~0U && "Cast return type unknown?");
681 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
682 NumOperands++;
683 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
684 Slots[1] = Table.getSlot(VANI->getArgType());
685 assert(Slots[1] != ~0U && "va_next return type unknown?");
686 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
687 NumOperands++;
688 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
689 // We need to encode the type of sequential type indices into their slot #
690 unsigned Idx = 1;
691 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
692 I != E; ++I, ++Idx)
693 if (isa<SequentialType>(*I)) {
694 unsigned IdxId;
695 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
696 default: assert(0 && "Unknown index type!");
697 case Type::UIntTyID: IdxId = 0; break;
698 case Type::IntTyID: IdxId = 1; break;
699 case Type::ULongTyID: IdxId = 2; break;
700 case Type::LongTyID: IdxId = 3; break;
701 }
702 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
703 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
704 }
705 }
706
707 // Decide which instruction encoding to use. This is determined primarily
708 // by the number of operands, and secondarily by whether or not the max
709 // operand will fit into the instruction encoding. More operands == fewer
710 // bits per operand.
711 //
712 switch (NumOperands) {
713 case 0:
714 case 1:
715 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
716 outputInstructionFormat1(&I, Opcode, Slots, Type);
717 return;
718 }
719 break;
720
721 case 2:
722 if (MaxOpSlot < (1 << 8)) {
723 outputInstructionFormat2(&I, Opcode, Slots, Type);
724 return;
725 }
726 break;
727
728 case 3:
729 if (MaxOpSlot < (1 << 6)) {
730 outputInstructionFormat3(&I, Opcode, Slots, Type);
731 return;
732 }
733 break;
734 default:
735 break;
736 }
737 }
738
739 // If we weren't handled before here, we either have a large number of
740 // operands or a large operand index that we are referring to.
741 outputInstructionFormat0(&I, Opcode, Table, Type);
742}
743
744//===----------------------------------------------------------------------===//
745//=== Block Output ===//
746//===----------------------------------------------------------------------===//
747
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000748BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000749 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000750
Chris Lattner83bb3d22004-01-14 23:36:54 +0000751 // Emit the signature...
752 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000753 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000754
755 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000756 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000757
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000758 bool isBigEndian = M->getEndianness() == Module::BigEndian;
759 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
760 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
761 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000762
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000763 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000764 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000765 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000766 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000767 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000768 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000769
Reid Spencercb3595c2004-07-04 11:45:47 +0000770 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000771 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000772 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000773 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000774 }
Chris Lattner00950542001-06-06 20:29:01 +0000775
Chris Lattner186a1f72003-03-19 20:56:46 +0000776 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000777 outputModuleInfoBlock(M);
778
Chris Lattner186a1f72003-03-19 20:56:46 +0000779 // Output module level constants, used for global variable initializers
780 outputConstants(false);
781
Chris Lattnerb5794002002-04-07 22:49:37 +0000782 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000783 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000784 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000785
786 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000787 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000788}
789
Chris Lattnerf9d71782004-10-14 01:46:07 +0000790void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000791 // Write the type plane for types first because earlier planes (e.g. for a
792 // primitive type like float) may have constants constructed using types
793 // coming later (e.g., via getelementptr from a pointer type). The type
794 // plane is needed before types can be fwd or bkwd referenced.
795 const std::vector<const Type*>& Types = Table.getTypes();
796 assert(!Types.empty() && "No types at all?");
797 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
798
799 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000800
Reid Spencercb3595c2004-07-04 11:45:47 +0000801 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000802 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000803
804 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
805 outputType(Types[i]);
806}
807
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000808// Helper function for outputConstants().
809// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000810//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000811void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
812 &Plane, unsigned StartNo) {
813 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000814
Chris Lattner83bb3d22004-01-14 23:36:54 +0000815 // Scan through and ignore function arguments, global values, and constant
816 // strings.
817 for (; ValNo < Plane.size() &&
818 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
819 (isa<ConstantArray>(Plane[ValNo]) &&
820 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000821 /*empty*/;
822
823 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000824 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000825 /*empty*/;
826 NC -= ValNo; // Convert from index into count
827 if (NC == 0) return; // Skip empty type planes...
828
Chris Lattnerd6942d72004-01-14 16:54:21 +0000829 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
830 // more compactly.
831
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000832 // Output type header: [num entries][type id number]
833 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000834 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000835
836 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000837 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000838 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000839 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000840
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000841 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
842 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000843 if (const Constant *C = dyn_cast<Constant>(V)) {
844 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000845 }
846 }
847}
848
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000849static inline bool hasNullValue(const Type *Ty) {
850 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000851}
852
Chris Lattner79df7c02002-03-26 18:01:55 +0000853void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000854 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000855 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000856
857 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000858
Reid Spencere0125b62004-07-18 00:16:21 +0000859 if (isFunction)
860 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000861 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000862 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000863 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000864 outputConstantStrings();
865
Reid Spencercb3595c2004-07-04 11:45:47 +0000866 for (unsigned pno = 0; pno != NumPlanes; pno++) {
867 const std::vector<const Value*> &Plane = Table.getPlane(pno);
868 if (!Plane.empty()) { // Skip empty type planes...
869 unsigned ValNo = 0;
870 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000871 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000872
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000873 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000874 // Skip zero initializer
875 if (ValNo == 0)
876 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000877 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000878
Reid Spencercb3595c2004-07-04 11:45:47 +0000879 // Write out constants in the plane
880 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000881 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000882 }
Chris Lattner00950542001-06-06 20:29:01 +0000883}
884
Chris Lattner6b252422003-10-16 18:28:50 +0000885static unsigned getEncodedLinkage(const GlobalValue *GV) {
886 switch (GV->getLinkage()) {
887 default: assert(0 && "Invalid linkage!");
888 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000889 case GlobalValue::WeakLinkage: return 1;
890 case GlobalValue::AppendingLinkage: return 2;
891 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000892 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000893 }
894}
895
Chris Lattner00950542001-06-06 20:29:01 +0000896void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000897 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000898
Chris Lattner70cc3392001-09-10 07:58:01 +0000899 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000900 for (Module::const_global_iterator I = M->global_begin(),
901 End = M->global_end(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000902 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000903 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000904
Chris Lattner22482a12003-10-18 06:30:21 +0000905 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
906 // bit5+ = Slot # for type
Chris Lattnerf74acc72004-10-14 02:31:35 +0000907 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000908 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000909 output_vbr(oSlot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000910
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000911 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000912 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000913 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000914 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000915 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000916 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000917 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000918 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000919
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000920 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000921 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000922 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000923 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +0000924 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000925 assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
926 unsigned ID = (Slot << 5) + 1;
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000927 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
928 ID |= 1 << 4;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000929 output_vbr(ID);
Chris Lattner00950542001-06-06 20:29:01 +0000930 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000931 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +0000932
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000933 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +0000934 Module::lib_iterator LI = M->lib_begin();
935 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000936 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
937 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +0000938 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000939
940 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000941 output(M->getTargetTriple());
Chris Lattner00950542001-06-06 20:29:01 +0000942}
943
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000944void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000945 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000946 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
947 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
948 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000949}
950
Chris Lattner186a1f72003-03-19 20:56:46 +0000951void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +0000952 // If this is an external function, there is nothing else to emit!
953 if (F->isExternal()) return;
954
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000955 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
956 output_vbr(getEncodedLinkage(F));
957
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000958 // Get slot information about the function...
959 Table.incorporateFunction(F);
960
961 if (Table.getCompactionTable().empty()) {
962 // Output information about the constants in the function if the compaction
963 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000964 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000965 } else {
966 // Otherwise, emit the compaction table.
967 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000968 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000969
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000970 // Output all of the instructions in the body of the function
971 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000972
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000973 // If needed, output the symbol table for the function...
974 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000975
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000976 Table.purgeFunction();
977}
978
979void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
980 const std::vector<const Value*> &Plane,
981 unsigned StartNo) {
982 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +0000983 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000984 assert(StartNo < End && "Cannot emit negative range!");
985 assert(StartNo < Plane.size() && End <= Plane.size());
986
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000987 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +0000988 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000989
Chris Lattner24102432004-01-18 22:35:34 +0000990 // Figure out which encoding to use. By far the most common case we have is
991 // to emit 0-2 entries in a compaction table plane.
992 switch (End-StartNo) {
993 case 0: // Avoid emitting two vbr's if possible.
994 case 1:
995 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +0000996 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +0000997 break;
998 default:
999 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001000 output_vbr((unsigned(End-StartNo) << 2) | 3);
1001 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001002 break;
1003 }
1004
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001005 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001006 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001007}
1008
Reid Spencercb3595c2004-07-04 11:45:47 +00001009void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1010 // Get the compaction type table from the slot calculator
1011 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1012
1013 // The compaction types may have been uncompactified back to the
1014 // global types. If so, we just write an empty table
1015 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001016 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001017 return;
1018 }
1019
1020 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1021
1022 // Determine how many types to write
1023 unsigned NumTypes = CTypes.size() - StartNo;
1024
1025 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001026 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001027
1028 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001029 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001030}
1031
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001032void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001033 // Avoid writing the compaction table at all if there is no content.
1034 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1035 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001036 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001037 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001038 const std::vector<std::vector<const Value*> > &CT =
1039 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001040
Reid Spencer0033c182004-08-27 00:38:44 +00001041 // First things first, emit the type compaction table if there is one.
1042 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001043
Reid Spencer0033c182004-08-27 00:38:44 +00001044 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1045 outputCompactionTablePlane(i, CT[i], 0);
1046 }
Chris Lattner00950542001-06-06 20:29:01 +00001047}
1048
Chris Lattner00950542001-06-06 20:29:01 +00001049void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001050 // Do not output the Bytecode block for an empty symbol table, it just wastes
1051 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001052 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001053
Reid Spencerad89bd62004-07-25 18:07:36 +00001054 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001055 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001056
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001057 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001058 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001059
1060 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001061 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1062 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001063 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001064 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001065 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001066 }
1067
1068 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001069 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001070 PE = MST.plane_end(); PI != PE; ++PI) {
1071 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1072 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001073 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001074
Chris Lattner00950542001-06-06 20:29:01 +00001075 if (I == End) continue; // Don't mess with an absent type...
1076
Reid Spencer250c4182004-08-17 02:59:02 +00001077 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001078 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001079
Reid Spencer250c4182004-08-17 02:59:02 +00001080 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001081 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001082 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001083 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001084
Reid Spencer250c4182004-08-17 02:59:02 +00001085 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001086 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001087 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001088 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001089 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001090 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001091 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001092 }
1093 }
1094}
1095
Reid Spencer17f52c52004-11-06 23:17:23 +00001096void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1097 bool compress ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001098 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001099
Reid Spencer17f52c52004-11-06 23:17:23 +00001100 // Create a vector of unsigned char for the bytecode output. We
1101 // reserve 256KBytes of space in the vector so that we avoid doing
1102 // lots of little allocations. 256KBytes is sufficient for a large
1103 // proportion of the bytecode files we will encounter. Larger files
1104 // will be automatically doubled in size as needed (std::vector
1105 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001106 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001107 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001108
Reid Spencer17f52c52004-11-06 23:17:23 +00001109 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001110 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001111
Reid Spencer17f52c52004-11-06 23:17:23 +00001112 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001113 BytesWritten += Buffer.size();
1114
Reid Spencer17f52c52004-11-06 23:17:23 +00001115 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001116 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001117
1118 // If we're supposed to compress this mess ...
1119 if (compress) {
1120
1121 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001122 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001123 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001124 char compressed_magic[4];
1125 compressed_magic[0] = 'l';
1126 compressed_magic[1] = 'l';
1127 compressed_magic[2] = 'v';
1128 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001129
Reid Spencer83296f52004-11-07 18:17:38 +00001130 Out.write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001131
Reid Spencera70d84d2004-11-14 22:01:41 +00001132 // Compress everything after the magic number (which we altered)
1133 uint64_t zipSize = Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001134 (char*)(FirstByte+4), // Skip the magic number
1135 Buffer.size()-4, // Skip the magic number
Reid Spencer84472d62004-11-25 19:38:05 +00001136 Out // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001137 );
1138
Reid Spencer17f52c52004-11-06 23:17:23 +00001139 } else {
1140
1141 // We're not compressing, so just write the entire block.
Reid Spencer83296f52004-11-07 18:17:38 +00001142 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001143 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001144
1145 // make sure it hits disk now
Chris Lattner00950542001-06-06 20:29:01 +00001146 Out.flush();
1147}
Reid Spencere0125b62004-07-18 00:16:21 +00001148