blob: c3fad712f2bb00dc1dacc5379db18e6f6ab5c210 [file] [log] [blame]
Chris Lattner14999342004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
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//
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"
Chris Lattnerf60dc882001-11-29 16:32:16 +000028#include "Support/STLExtras.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000029#include "Support/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000030#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000031#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Reid Spencer38d54be2004-08-17 07:45:14 +000034/// This value needs to be incremented every time the bytecode format changes
35/// so that the reader can distinguish which format of the bytecode file has
36/// been written.
37/// @brief The bytecode version number
38const unsigned BCVersionNum = 4;
39
Chris Lattner635cd932002-07-23 19:56:44 +000040static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
41
Chris Lattnerce6ef112002-07-26 18:40:14 +000042static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000043BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000044
Reid Spencerad89bd62004-07-25 18:07:36 +000045//===----------------------------------------------------------------------===//
46//=== Output Primitives ===//
47//===----------------------------------------------------------------------===//
48
49// output - If a position is specified, it must be in the valid portion of the
50// string... note that this should be inlined always so only the relevant IF
51// body should be included.
52inline void BytecodeWriter::output(unsigned i, int pos) {
53 if (pos == -1) { // Be endian clean, little endian is our friend
54 Out.push_back((unsigned char)i);
55 Out.push_back((unsigned char)(i >> 8));
56 Out.push_back((unsigned char)(i >> 16));
57 Out.push_back((unsigned char)(i >> 24));
58 } else {
59 Out[pos ] = (unsigned char)i;
60 Out[pos+1] = (unsigned char)(i >> 8);
61 Out[pos+2] = (unsigned char)(i >> 16);
62 Out[pos+3] = (unsigned char)(i >> 24);
63 }
64}
65
66inline void BytecodeWriter::output(int i) {
67 output((unsigned)i);
68}
69
70/// output_vbr - Output an unsigned value, by using the least number of bytes
71/// possible. This is useful because many of our "infinite" values are really
72/// very small most of the time; but can be large a few times.
73/// Data format used: If you read a byte with the high bit set, use the low
Reid Spencer38d54be2004-08-17 07:45:14 +000074/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000075inline void BytecodeWriter::output_vbr(uint64_t i) {
76 while (1) {
77 if (i < 0x80) { // done?
78 Out.push_back((unsigned char)i); // We know the high bit is clear...
79 return;
80 }
81
82 // Nope, we are bigger than a character, output the next 7 bits and set the
83 // high bit to say that there is more coming...
84 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
85 i >>= 7; // Shift out 7 bits now...
86 }
87}
88
89inline void BytecodeWriter::output_vbr(unsigned i) {
90 while (1) {
91 if (i < 0x80) { // done?
92 Out.push_back((unsigned char)i); // We know the high bit is clear...
93 return;
94 }
95
96 // Nope, we are bigger than a character, output the next 7 bits and set the
97 // high bit to say that there is more coming...
98 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
99 i >>= 7; // Shift out 7 bits now...
100 }
101}
102
103inline void BytecodeWriter::output_typeid(unsigned i) {
104 if (i <= 0x00FFFFFF)
105 this->output_vbr(i);
106 else {
107 this->output_vbr(0x00FFFFFF);
108 this->output_vbr(i);
109 }
110}
111
112inline void BytecodeWriter::output_vbr(int64_t i) {
113 if (i < 0)
114 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
115 else
116 output_vbr((uint64_t)i << 1); // Low order bit is clear.
117}
118
119
120inline void BytecodeWriter::output_vbr(int i) {
121 if (i < 0)
122 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
123 else
124 output_vbr((unsigned)i << 1); // Low order bit is clear.
125}
126
Reid Spencer38d54be2004-08-17 07:45:14 +0000127inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000128 unsigned Len = s.length();
129 output_vbr(Len ); // Strings may have an arbitrary length...
130 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000131}
132
133inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
134 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
135}
136
137inline void BytecodeWriter::output_float(float& FloatVal) {
138 /// FIXME: This isn't optimal, it has size problems on some platforms
139 /// where FP is not IEEE.
140 union {
141 float f;
142 uint32_t i;
143 } FloatUnion;
144 FloatUnion.f = FloatVal;
145 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
146 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
149}
150
151inline void BytecodeWriter::output_double(double& DoubleVal) {
152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
154 union {
155 double d;
156 uint64_t i;
157 } DoubleUnion;
158 DoubleUnion.d = DoubleVal;
159 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
160 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
167}
168
169inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
170 bool elideIfEmpty, bool hasLongFormat )
171 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
172
173 if (HasLongFormat) {
174 w.output(ID);
175 w.output(0U); // For length in long format
176 } else {
177 w.output(0U); /// Place holder for ID and length for this block
178 }
179 Loc = w.size();
180}
181
182inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
183 // of scope...
184 if (Loc == Writer.size() && ElideIfEmpty) {
185 // If the block is empty, and we are allowed to, do not emit the block at
186 // all!
187 Writer.resize(Writer.size()-(HasLongFormat?8:4));
188 return;
189 }
190
191 //cerr << "OldLoc = " << Loc << " NewLoc = " << NewLoc << " diff = "
192 // << (NewLoc-Loc) << endl;
193 if (HasLongFormat)
194 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
195 else
196 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000197}
198
199//===----------------------------------------------------------------------===//
200//=== Constant Output ===//
201//===----------------------------------------------------------------------===//
202
203void BytecodeWriter::outputType(const Type *T) {
204 output_vbr((unsigned)T->getTypeID());
205
206 // That's all there is to handling primitive types...
207 if (T->isPrimitiveType()) {
208 return; // We might do this if we alias a prim type: %x = type int
209 }
210
211 switch (T->getTypeID()) { // Handle derived types now.
212 case Type::FunctionTyID: {
213 const FunctionType *MT = cast<FunctionType>(T);
214 int Slot = Table.getSlot(MT->getReturnType());
215 assert(Slot != -1 && "Type used but not available!!");
216 output_typeid((unsigned)Slot);
217
218 // Output the number of arguments to function (+1 if varargs):
219 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
220
221 // Output all of the arguments...
222 FunctionType::param_iterator I = MT->param_begin();
223 for (; I != MT->param_end(); ++I) {
224 Slot = Table.getSlot(*I);
225 assert(Slot != -1 && "Type used but not available!!");
226 output_typeid((unsigned)Slot);
227 }
228
229 // Terminate list with VoidTy if we are a varargs function...
230 if (MT->isVarArg())
231 output_typeid((unsigned)Type::VoidTyID);
232 break;
233 }
234
235 case Type::ArrayTyID: {
236 const ArrayType *AT = cast<ArrayType>(T);
237 int Slot = Table.getSlot(AT->getElementType());
238 assert(Slot != -1 && "Type used but not available!!");
239 output_typeid((unsigned)Slot);
240 //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
241
242 output_vbr(AT->getNumElements());
243 break;
244 }
245
246 case Type::StructTyID: {
247 const StructType *ST = cast<StructType>(T);
248
249 // Output all of the element types...
250 for (StructType::element_iterator I = ST->element_begin(),
251 E = ST->element_end(); I != E; ++I) {
252 int Slot = Table.getSlot(*I);
253 assert(Slot != -1 && "Type used but not available!!");
254 output_typeid((unsigned)Slot);
255 }
256
257 // Terminate list with VoidTy
258 output_typeid((unsigned)Type::VoidTyID);
259 break;
260 }
261
262 case Type::PointerTyID: {
263 const PointerType *PT = cast<PointerType>(T);
264 int Slot = Table.getSlot(PT->getElementType());
265 assert(Slot != -1 && "Type used but not available!!");
266 output_typeid((unsigned)Slot);
267 break;
268 }
269
270 case Type::OpaqueTyID: {
271 // No need to emit anything, just the count of opaque types is enough.
272 break;
273 }
274
275 //case Type::PackedTyID:
276 default:
277 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
278 << " Type '" << T->getDescription() << "'\n";
279 break;
280 }
281}
282
283void BytecodeWriter::outputConstant(const Constant *CPV) {
284 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
285 "Shouldn't output null constants!");
286
287 // We must check for a ConstantExpr before switching by type because
288 // a ConstantExpr can be of any type, and has no explicit value.
289 //
290 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
291 // FIXME: Encoding of constant exprs could be much more compact!
292 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
293 output_vbr(CE->getNumOperands()); // flags as an expr
294 output_vbr(CE->getOpcode()); // flags as an expr
295
296 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
297 int Slot = Table.getSlot(*OI);
298 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
299 output_vbr((unsigned)Slot);
300 Slot = Table.getSlot((*OI)->getType());
301 output_typeid((unsigned)Slot);
302 }
303 return;
304 } else {
305 output_vbr(0U); // flag as not a ConstantExpr
306 }
307
308 switch (CPV->getType()->getTypeID()) {
309 case Type::BoolTyID: // Boolean Types
310 if (cast<ConstantBool>(CPV)->getValue())
311 output_vbr(1U);
312 else
313 output_vbr(0U);
314 break;
315
316 case Type::UByteTyID: // Unsigned integer types...
317 case Type::UShortTyID:
318 case Type::UIntTyID:
319 case Type::ULongTyID:
320 output_vbr(cast<ConstantUInt>(CPV)->getValue());
321 break;
322
323 case Type::SByteTyID: // Signed integer types...
324 case Type::ShortTyID:
325 case Type::IntTyID:
326 case Type::LongTyID:
327 output_vbr(cast<ConstantSInt>(CPV)->getValue());
328 break;
329
330 case Type::ArrayTyID: {
331 const ConstantArray *CPA = cast<ConstantArray>(CPV);
332 assert(!CPA->isString() && "Constant strings should be handled specially!");
333
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000334 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000335 int Slot = Table.getSlot(CPA->getOperand(i));
336 assert(Slot != -1 && "Constant used but not available!!");
337 output_vbr((unsigned)Slot);
338 }
339 break;
340 }
341
342 case Type::StructTyID: {
343 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000344
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000345 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
346 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000347 assert(Slot != -1 && "Constant used but not available!!");
348 output_vbr((unsigned)Slot);
349 }
350 break;
351 }
352
353 case Type::PointerTyID:
354 assert(0 && "No non-null, non-constant-expr constants allowed!");
355 abort();
356
357 case Type::FloatTyID: { // Floating point types...
358 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
359 output_float(Tmp);
360 break;
361 }
362 case Type::DoubleTyID: {
363 double Tmp = cast<ConstantFP>(CPV)->getValue();
364 output_double(Tmp);
365 break;
366 }
367
368 case Type::VoidTyID:
369 case Type::LabelTyID:
370 default:
371 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
372 << " type '" << *CPV->getType() << "'\n";
373 break;
374 }
375 return;
376}
377
378void BytecodeWriter::outputConstantStrings() {
379 SlotCalculator::string_iterator I = Table.string_begin();
380 SlotCalculator::string_iterator E = Table.string_end();
381 if (I == E) return; // No strings to emit
382
383 // If we have != 0 strings to emit, output them now. Strings are emitted into
384 // the 'void' type plane.
385 output_vbr(unsigned(E-I));
386 output_typeid(Type::VoidTyID);
387
388 // Emit all of the strings.
389 for (I = Table.string_begin(); I != E; ++I) {
390 const ConstantArray *Str = *I;
391 int Slot = Table.getSlot(Str->getType());
392 assert(Slot != -1 && "Constant string of unknown type?");
393 output_typeid((unsigned)Slot);
394
395 // Now that we emitted the type (which indicates the size of the string),
396 // emit all of the characters.
397 std::string Val = Str->getAsString();
398 output_data(Val.c_str(), Val.c_str()+Val.size());
399 }
400}
401
402//===----------------------------------------------------------------------===//
403//=== Instruction Output ===//
404//===----------------------------------------------------------------------===//
405typedef unsigned char uchar;
406
407// outputInstructionFormat0 - Output those wierd instructions that have a large
408// number of operands or have large operands themselves...
409//
410// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
411//
412void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
413 const SlotCalculator &Table,
414 unsigned Type) {
415 // Opcode must have top two bits clear...
416 output_vbr(Opcode << 2); // Instruction Opcode ID
417 output_typeid(Type); // Result type
418
419 unsigned NumArgs = I->getNumOperands();
420 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
421 isa<VAArgInst>(I)));
422
423 if (!isa<GetElementPtrInst>(&I)) {
424 for (unsigned i = 0; i < NumArgs; ++i) {
425 int Slot = Table.getSlot(I->getOperand(i));
426 assert(Slot >= 0 && "No slot number for value!?!?");
427 output_vbr((unsigned)Slot);
428 }
429
430 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
431 int Slot = Table.getSlot(I->getType());
432 assert(Slot != -1 && "Cast return type unknown?");
433 output_typeid((unsigned)Slot);
434 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
435 int Slot = Table.getSlot(VAI->getArgType());
436 assert(Slot != -1 && "VarArg argument type unknown?");
437 output_typeid((unsigned)Slot);
438 }
439
440 } else {
441 int Slot = Table.getSlot(I->getOperand(0));
442 assert(Slot >= 0 && "No slot number for value!?!?");
443 output_vbr(unsigned(Slot));
444
445 // We need to encode the type of sequential type indices into their slot #
446 unsigned Idx = 1;
447 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
448 Idx != NumArgs; ++TI, ++Idx) {
449 Slot = Table.getSlot(I->getOperand(Idx));
450 assert(Slot >= 0 && "No slot number for value!?!?");
451
452 if (isa<SequentialType>(*TI)) {
453 unsigned IdxId;
454 switch (I->getOperand(Idx)->getType()->getTypeID()) {
455 default: assert(0 && "Unknown index type!");
456 case Type::UIntTyID: IdxId = 0; break;
457 case Type::IntTyID: IdxId = 1; break;
458 case Type::ULongTyID: IdxId = 2; break;
459 case Type::LongTyID: IdxId = 3; break;
460 }
461 Slot = (Slot << 2) | IdxId;
462 }
463 output_vbr(unsigned(Slot));
464 }
465 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000466}
467
468
469// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
470// This are more annoying than most because the signature of the call does not
471// tell us anything about the types of the arguments in the varargs portion.
472// Because of this, we encode (as type 0) all of the argument types explicitly
473// before the argument value. This really sucks, but you shouldn't be using
474// varargs functions in your code! *death to printf*!
475//
476// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
477//
478void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
479 unsigned Opcode,
480 const SlotCalculator &Table,
481 unsigned Type) {
482 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
483 // Opcode must have top two bits clear...
484 output_vbr(Opcode << 2); // Instruction Opcode ID
485 output_typeid(Type); // Result type (varargs type)
486
487 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
488 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
489 unsigned NumParams = FTy->getNumParams();
490
491 unsigned NumFixedOperands;
492 if (isa<CallInst>(I)) {
493 // Output an operand for the callee and each fixed argument, then two for
494 // each variable argument.
495 NumFixedOperands = 1+NumParams;
496 } else {
497 assert(isa<InvokeInst>(I) && "Not call or invoke??");
498 // Output an operand for the callee and destinations, then two for each
499 // variable argument.
500 NumFixedOperands = 3+NumParams;
501 }
502 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
503
504 // The type for the function has already been emitted in the type field of the
505 // instruction. Just emit the slot # now.
506 for (unsigned i = 0; i != NumFixedOperands; ++i) {
507 int Slot = Table.getSlot(I->getOperand(i));
508 assert(Slot >= 0 && "No slot number for value!?!?");
509 output_vbr((unsigned)Slot);
510 }
511
512 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
513 // Output Arg Type ID
514 int Slot = Table.getSlot(I->getOperand(i)->getType());
515 assert(Slot >= 0 && "No slot number for value!?!?");
516 output_typeid((unsigned)Slot);
517
518 // Output arg ID itself
519 Slot = Table.getSlot(I->getOperand(i));
520 assert(Slot >= 0 && "No slot number for value!?!?");
521 output_vbr((unsigned)Slot);
522 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000523}
524
525
526// outputInstructionFormat1 - Output one operand instructions, knowing that no
527// operand index is >= 2^12.
528//
529inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
530 unsigned Opcode,
531 unsigned *Slots,
532 unsigned Type) {
533 // bits Instruction format:
534 // --------------------------
535 // 01-00: Opcode type, fixed to 1.
536 // 07-02: Opcode
537 // 19-08: Resulting type plane
538 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
539 //
540 unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
541 // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
542 output(Bits);
543}
544
545
546// outputInstructionFormat2 - Output two operand instructions, knowing that no
547// operand index is >= 2^8.
548//
549inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
550 unsigned Opcode,
551 unsigned *Slots,
552 unsigned Type) {
553 // bits Instruction format:
554 // --------------------------
555 // 01-00: Opcode type, fixed to 2.
556 // 07-02: Opcode
557 // 15-08: Resulting type plane
558 // 23-16: Operand #1
559 // 31-24: Operand #2
560 //
561 unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
562 (Slots[0] << 16) | (Slots[1] << 24);
563 // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " "
564 // << Slots[1] << endl;
565 output(Bits);
566}
567
568
569// outputInstructionFormat3 - Output three operand instructions, knowing that no
570// operand index is >= 2^6.
571//
572inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
573 unsigned Opcode,
574 unsigned *Slots,
575 unsigned Type) {
576 // bits Instruction format:
577 // --------------------------
578 // 01-00: Opcode type, fixed to 3.
579 // 07-02: Opcode
580 // 13-08: Resulting type plane
581 // 19-14: Operand #1
582 // 25-20: Operand #2
583 // 31-26: Operand #3
584 //
585 unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
586 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
587 //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " "
588 // << Slots[1] << " " << Slots[2] << endl;
589 output(Bits);
590}
591
592void BytecodeWriter::outputInstruction(const Instruction &I) {
593 assert(I.getOpcode() < 62 && "Opcode too big???");
594 unsigned Opcode = I.getOpcode();
595 unsigned NumOperands = I.getNumOperands();
596
597 // Encode 'volatile load' as 62 and 'volatile store' as 63.
598 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
599 Opcode = 62;
600 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
601 Opcode = 63;
602
603 // Figure out which type to encode with the instruction. Typically we want
604 // the type of the first parameter, as opposed to the type of the instruction
605 // (for example, with setcc, we always know it returns bool, but the type of
606 // the first param is actually interesting). But if we have no arguments
607 // we take the type of the instruction itself.
608 //
609 const Type *Ty;
610 switch (I.getOpcode()) {
611 case Instruction::Select:
612 case Instruction::Malloc:
613 case Instruction::Alloca:
614 Ty = I.getType(); // These ALWAYS want to encode the return type
615 break;
616 case Instruction::Store:
617 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
618 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
619 break;
620 default: // Otherwise use the default behavior...
621 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
622 break;
623 }
624
625 unsigned Type;
626 int Slot = Table.getSlot(Ty);
627 assert(Slot != -1 && "Type not available!!?!");
628 Type = (unsigned)Slot;
629
630 // Varargs calls and invokes are encoded entirely different from any other
631 // instructions.
632 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
633 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
634 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
635 outputInstrVarArgsCall(CI, Opcode, Table, Type);
636 return;
637 }
638 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
639 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
640 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
641 outputInstrVarArgsCall(II, Opcode, Table, Type);
642 return;
643 }
644 }
645
646 if (NumOperands <= 3) {
647 // Make sure that we take the type number into consideration. We don't want
648 // to overflow the field size for the instruction format we select.
649 //
650 unsigned MaxOpSlot = Type;
651 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
652
653 for (unsigned i = 0; i != NumOperands; ++i) {
654 int slot = Table.getSlot(I.getOperand(i));
655 assert(slot != -1 && "Broken bytecode!");
656 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
657 Slots[i] = unsigned(slot);
658 }
659
660 // Handle the special cases for various instructions...
661 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
662 // Cast has to encode the destination type as the second argument in the
663 // packet, or else we won't know what type to cast to!
664 Slots[1] = Table.getSlot(I.getType());
665 assert(Slots[1] != ~0U && "Cast return type unknown?");
666 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
667 NumOperands++;
668 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
669 Slots[1] = Table.getSlot(VANI->getArgType());
670 assert(Slots[1] != ~0U && "va_next return type unknown?");
671 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
672 NumOperands++;
673 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
674 // We need to encode the type of sequential type indices into their slot #
675 unsigned Idx = 1;
676 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
677 I != E; ++I, ++Idx)
678 if (isa<SequentialType>(*I)) {
679 unsigned IdxId;
680 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
681 default: assert(0 && "Unknown index type!");
682 case Type::UIntTyID: IdxId = 0; break;
683 case Type::IntTyID: IdxId = 1; break;
684 case Type::ULongTyID: IdxId = 2; break;
685 case Type::LongTyID: IdxId = 3; break;
686 }
687 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
688 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
689 }
690 }
691
692 // Decide which instruction encoding to use. This is determined primarily
693 // by the number of operands, and secondarily by whether or not the max
694 // operand will fit into the instruction encoding. More operands == fewer
695 // bits per operand.
696 //
697 switch (NumOperands) {
698 case 0:
699 case 1:
700 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
701 outputInstructionFormat1(&I, Opcode, Slots, Type);
702 return;
703 }
704 break;
705
706 case 2:
707 if (MaxOpSlot < (1 << 8)) {
708 outputInstructionFormat2(&I, Opcode, Slots, Type);
709 return;
710 }
711 break;
712
713 case 3:
714 if (MaxOpSlot < (1 << 6)) {
715 outputInstructionFormat3(&I, Opcode, Slots, Type);
716 return;
717 }
718 break;
719 default:
720 break;
721 }
722 }
723
724 // If we weren't handled before here, we either have a large number of
725 // operands or a large operand index that we are referring to.
726 outputInstructionFormat0(&I, Opcode, Table, Type);
727}
728
729//===----------------------------------------------------------------------===//
730//=== Block Output ===//
731//===----------------------------------------------------------------------===//
732
733BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000734 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000735
Chris Lattner83bb3d22004-01-14 23:36:54 +0000736 // Emit the signature...
737 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000738 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000739
740 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000741 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000742
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000743 bool isBigEndian = M->getEndianness() == Module::BigEndian;
744 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
745 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
746 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000747
Chris Lattner5fa428f2004-04-05 01:27:26 +0000748 // Output the version identifier... we are currently on bytecode version #2,
749 // which corresponds to LLVM v1.3.
Reid Spencer38d54be2004-08-17 07:45:14 +0000750 unsigned Version = (BCVersionNum << 4) |
751 (unsigned)isBigEndian | (hasLongPointers << 1) |
752 (hasNoEndianness << 2) |
753 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000754 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000755
Reid Spencercb3595c2004-07-04 11:45:47 +0000756 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000757 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000758 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000759 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000760 }
Chris Lattner00950542001-06-06 20:29:01 +0000761
Chris Lattner186a1f72003-03-19 20:56:46 +0000762 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000763 outputModuleInfoBlock(M);
764
Chris Lattner186a1f72003-03-19 20:56:46 +0000765 // Output module level constants, used for global variable initializers
766 outputConstants(false);
767
Chris Lattnerb5794002002-04-07 22:49:37 +0000768 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000769 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000770 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000771
772 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000773 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000774}
775
Reid Spencercb3595c2004-07-04 11:45:47 +0000776void BytecodeWriter::outputTypes(unsigned TypeNum)
777{
778 // Write the type plane for types first because earlier planes (e.g. for a
779 // primitive type like float) may have constants constructed using types
780 // coming later (e.g., via getelementptr from a pointer type). The type
781 // plane is needed before types can be fwd or bkwd referenced.
782 const std::vector<const Type*>& Types = Table.getTypes();
783 assert(!Types.empty() && "No types at all?");
784 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
785
786 unsigned NumEntries = Types.size() - TypeNum;
787
788 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000789 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000790
791 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
792 outputType(Types[i]);
793}
794
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000795// Helper function for outputConstants().
796// Writes out all the constants in the plane Plane starting at entry StartNo.
797//
798void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
799 &Plane, unsigned StartNo) {
800 unsigned ValNo = StartNo;
801
Chris Lattner83bb3d22004-01-14 23:36:54 +0000802 // Scan through and ignore function arguments, global values, and constant
803 // strings.
804 for (; ValNo < Plane.size() &&
805 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
806 (isa<ConstantArray>(Plane[ValNo]) &&
807 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000808 /*empty*/;
809
810 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000811 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000812 /*empty*/;
813 NC -= ValNo; // Convert from index into count
814 if (NC == 0) return; // Skip empty type planes...
815
Chris Lattnerd6942d72004-01-14 16:54:21 +0000816 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
817 // more compactly.
818
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000819 // Output type header: [num entries][type id number]
820 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000821 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000822
823 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000824 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000825 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000826 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000827
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000828 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
829 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000830 if (const Constant *C = dyn_cast<Constant>(V)) {
831 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000832 }
833 }
834}
835
Chris Lattner80b97342004-01-17 23:25:43 +0000836static inline bool hasNullValue(unsigned TyID) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000837 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Chris Lattner80b97342004-01-17 23:25:43 +0000838}
839
Chris Lattner79df7c02002-03-26 18:01:55 +0000840void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000841 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000842 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000843
844 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000845
Reid Spencere0125b62004-07-18 00:16:21 +0000846 if (isFunction)
847 // Output the type plane before any constants!
Reid Spencercb3595c2004-07-04 11:45:47 +0000848 outputTypes( Table.getModuleTypeLevel() );
Reid Spencere0125b62004-07-18 00:16:21 +0000849 else
850 // Output module-level string constants before any other constants.x
Chris Lattner83bb3d22004-01-14 23:36:54 +0000851 outputConstantStrings();
852
Reid Spencercb3595c2004-07-04 11:45:47 +0000853 for (unsigned pno = 0; pno != NumPlanes; pno++) {
854 const std::vector<const Value*> &Plane = Table.getPlane(pno);
855 if (!Plane.empty()) { // Skip empty type planes...
856 unsigned ValNo = 0;
857 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000858 ValNo += Table.getModuleLevel(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000859
860 if (hasNullValue(pno)) {
Reid Spencer0852c802004-07-04 11:46:15 +0000861 // Skip zero initializer
862 if (ValNo == 0)
863 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000864 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000865
866 // Write out constants in the plane
867 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000868 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000869 }
Chris Lattner00950542001-06-06 20:29:01 +0000870}
871
Chris Lattner6b252422003-10-16 18:28:50 +0000872static unsigned getEncodedLinkage(const GlobalValue *GV) {
873 switch (GV->getLinkage()) {
874 default: assert(0 && "Invalid linkage!");
875 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000876 case GlobalValue::WeakLinkage: return 1;
877 case GlobalValue::AppendingLinkage: return 2;
878 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000879 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000880 }
881}
882
Chris Lattner00950542001-06-06 20:29:01 +0000883void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000884 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Chris Lattner00950542001-06-06 20:29:01 +0000885
Chris Lattner70cc3392001-09-10 07:58:01 +0000886 // Output the types for the global variables in the module...
887 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000888 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000889 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000890
Chris Lattner22482a12003-10-18 06:30:21 +0000891 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
892 // bit5+ = Slot # for type
893 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000894 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Reid Spencerad89bd62004-07-25 18:07:36 +0000895 output_vbr(oSlot );
Chris Lattnerd70684f2001-09-18 04:01:05 +0000896
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000897 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000898 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000899 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000900 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000901 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000902 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000903 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000904 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000905
Chris Lattnerb5794002002-04-07 22:49:37 +0000906 // Output the types of the functions in this module...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000907 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000908 int Slot = Table.getSlot(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000909 assert(Slot != -1 && "Module const pool is broken!");
910 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000911 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +0000912 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000913 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
914
915 // Put out the list of dependent libraries for the Module
Reid Spencer5ac88122004-07-25 21:32:02 +0000916 Module::lib_iterator LI = M->lib_begin();
917 Module::lib_iterator LE = M->lib_end();
Reid Spencerad89bd62004-07-25 18:07:36 +0000918 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
919 for ( ; LI != LE; ++LI ) {
Reid Spencer38d54be2004-08-17 07:45:14 +0000920 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000921 }
922
923 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000924 output(M->getTargetTriple());
Chris Lattner00950542001-06-06 20:29:01 +0000925}
926
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000927void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000928 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000929 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
930 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
931 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000932}
933
Chris Lattner186a1f72003-03-19 20:56:46 +0000934void BytecodeWriter::outputFunction(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000935 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
936 output_vbr(getEncodedLinkage(F));
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000937
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000938 // If this is an external function, there is nothing else to emit!
939 if (F->isExternal()) return;
Chris Lattner00950542001-06-06 20:29:01 +0000940
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000941 // Get slot information about the function...
942 Table.incorporateFunction(F);
943
944 if (Table.getCompactionTable().empty()) {
945 // Output information about the constants in the function if the compaction
946 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000947 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000948 } else {
949 // Otherwise, emit the compaction table.
950 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000951 }
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000952
953 // Output all of the instructions in the body of the function
954 outputInstructions(F);
955
956 // If needed, output the symbol table for the function...
957 outputSymbolTable(F->getSymbolTable());
958
959 Table.purgeFunction();
960}
961
962void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
963 const std::vector<const Value*> &Plane,
964 unsigned StartNo) {
965 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +0000966 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000967 assert(StartNo < End && "Cannot emit negative range!");
968 assert(StartNo < Plane.size() && End <= Plane.size());
969
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000970 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +0000971 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000972
Chris Lattner24102432004-01-18 22:35:34 +0000973 // Figure out which encoding to use. By far the most common case we have is
974 // to emit 0-2 entries in a compaction table plane.
975 switch (End-StartNo) {
976 case 0: // Avoid emitting two vbr's if possible.
977 case 1:
978 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +0000979 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +0000980 break;
981 default:
982 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +0000983 output_vbr((unsigned(End-StartNo) << 2) | 3);
984 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +0000985 break;
986 }
987
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000988 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +0000989 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000990}
991
Reid Spencercb3595c2004-07-04 11:45:47 +0000992void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
993 // Get the compaction type table from the slot calculator
994 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
995
996 // The compaction types may have been uncompactified back to the
997 // global types. If so, we just write an empty table
998 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000999 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001000 return;
1001 }
1002
1003 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1004
1005 // Determine how many types to write
1006 unsigned NumTypes = CTypes.size() - StartNo;
1007
1008 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001009 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001010
1011 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001012 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001013}
1014
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001015void BytecodeWriter::outputCompactionTable() {
Reid Spencerad89bd62004-07-25 18:07:36 +00001016 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1017 true/*ElideIfEmpty*/);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001018 const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1019
1020 // First thing is first, emit the type compaction table if there is one.
Reid Spencercb3595c2004-07-04 11:45:47 +00001021 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001022
1023 for (unsigned i = 0, e = CT.size(); i != e; ++i)
Reid Spencercb3595c2004-07-04 11:45:47 +00001024 outputCompactionTablePlane(i, CT[i], 0);
Chris Lattner00950542001-06-06 20:29:01 +00001025}
1026
Chris Lattner00950542001-06-06 20:29:01 +00001027void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001028 // Do not output the Bytecode block for an empty symbol table, it just wastes
1029 // space!
Reid Spencer6ed81e22004-05-27 20:18:51 +00001030 if ( MST.isEmpty() ) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001031
Reid Spencerad89bd62004-07-25 18:07:36 +00001032 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +00001033 true/* ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001034
Reid Spencer250c4182004-08-17 02:59:02 +00001035 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001036 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001037
1038 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001039 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1040 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001041 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001042 output_typeid((unsigned)Table.getSlot(TI->second));
Reid Spencer38d54be2004-08-17 07:45:14 +00001043 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001044 }
1045
1046 // Now do each of the type planes in order.
1047 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1048 PE = MST.plane_end(); PI != PE; ++PI) {
1049 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1050 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001051 int Slot;
1052
1053 if (I == End) continue; // Don't mess with an absent type...
1054
Reid Spencer250c4182004-08-17 02:59:02 +00001055 // Write the number of values in this plane
Reid Spencerad89bd62004-07-25 18:07:36 +00001056 output_vbr(MST.type_size(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001057
Reid Spencer250c4182004-08-17 02:59:02 +00001058 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001059 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001060 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001061 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001062
Reid Spencer250c4182004-08-17 02:59:02 +00001063 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001064 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001065 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001066 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001067 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001068 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001069 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001070 }
1071 }
1072}
1073
Reid Spencerad89bd62004-07-25 18:07:36 +00001074void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1075 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001076
Reid Spencerad89bd62004-07-25 18:07:36 +00001077 std::vector<unsigned char> Buffer;
1078 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
Chris Lattner00950542001-06-06 20:29:01 +00001079
1080 // This object populates buffer for us...
Reid Spencerad89bd62004-07-25 18:07:36 +00001081 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001082
Chris Lattnerce6ef112002-07-26 18:40:14 +00001083 // Keep track of how much we've written...
1084 BytesWritten += Buffer.size();
1085
Chris Lattnere8fdde12001-09-07 16:39:41 +00001086 // Okay, write the deque out to the ostream now... the deque is not
1087 // sequential in memory, however, so write out as much as possible in big
1088 // chunks, until we're done.
1089 //
Chris Lattner036de032004-06-25 20:52:10 +00001090
Reid Spencerad89bd62004-07-25 18:07:36 +00001091 std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001092 while (I != E) { // Loop until it's all written
1093 // Scan to see how big this chunk is...
1094 const unsigned char *ChunkPtr = &*I;
1095 const unsigned char *LastPtr = ChunkPtr;
1096 while (I != E) {
1097 const unsigned char *ThisPtr = &*++I;
Chris Lattner036de032004-06-25 20:52:10 +00001098 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
Chris Lattner5cb17412001-11-04 21:32:41 +00001099 break;
Chris Lattnere8fdde12001-09-07 16:39:41 +00001100 }
1101
1102 // Write out the chunk...
Chris Lattnerd6162282004-06-25 00:35:55 +00001103 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
Chris Lattnere8fdde12001-09-07 16:39:41 +00001104 }
Chris Lattner00950542001-06-06 20:29:01 +00001105 Out.flush();
1106}
Reid Spencere0125b62004-07-18 00:16:21 +00001107
1108// vim: sw=2 ai