blob: 92811ada5a992e650e9513c79cba249303369684 [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
Chris Lattner635cd932002-07-23 19:56:44 +000034static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
35
Chris Lattnerce6ef112002-07-26 18:40:14 +000036static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000037BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000038
Reid Spencerad89bd62004-07-25 18:07:36 +000039//===----------------------------------------------------------------------===//
40//=== Output Primitives ===//
41//===----------------------------------------------------------------------===//
42
43// output - If a position is specified, it must be in the valid portion of the
44// string... note that this should be inlined always so only the relevant IF
45// body should be included.
46inline void BytecodeWriter::output(unsigned i, int pos) {
47 if (pos == -1) { // Be endian clean, little endian is our friend
48 Out.push_back((unsigned char)i);
49 Out.push_back((unsigned char)(i >> 8));
50 Out.push_back((unsigned char)(i >> 16));
51 Out.push_back((unsigned char)(i >> 24));
52 } else {
53 Out[pos ] = (unsigned char)i;
54 Out[pos+1] = (unsigned char)(i >> 8);
55 Out[pos+2] = (unsigned char)(i >> 16);
56 Out[pos+3] = (unsigned char)(i >> 24);
57 }
58}
59
60inline void BytecodeWriter::output(int i) {
61 output((unsigned)i);
62}
63
64/// output_vbr - Output an unsigned value, by using the least number of bytes
65/// possible. This is useful because many of our "infinite" values are really
66/// very small most of the time; but can be large a few times.
67/// Data format used: If you read a byte with the high bit set, use the low
68/// seven bits as data and then read another byte. Note that using this may
69/// cause the output buffer to become unaligned.
70inline void BytecodeWriter::output_vbr(uint64_t i) {
71 while (1) {
72 if (i < 0x80) { // done?
73 Out.push_back((unsigned char)i); // We know the high bit is clear...
74 return;
75 }
76
77 // Nope, we are bigger than a character, output the next 7 bits and set the
78 // high bit to say that there is more coming...
79 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
80 i >>= 7; // Shift out 7 bits now...
81 }
82}
83
84inline void BytecodeWriter::output_vbr(unsigned i) {
85 while (1) {
86 if (i < 0x80) { // done?
87 Out.push_back((unsigned char)i); // We know the high bit is clear...
88 return;
89 }
90
91 // Nope, we are bigger than a character, output the next 7 bits and set the
92 // high bit to say that there is more coming...
93 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
94 i >>= 7; // Shift out 7 bits now...
95 }
96}
97
98inline void BytecodeWriter::output_typeid(unsigned i) {
99 if (i <= 0x00FFFFFF)
100 this->output_vbr(i);
101 else {
102 this->output_vbr(0x00FFFFFF);
103 this->output_vbr(i);
104 }
105}
106
107inline void BytecodeWriter::output_vbr(int64_t i) {
108 if (i < 0)
109 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
110 else
111 output_vbr((uint64_t)i << 1); // Low order bit is clear.
112}
113
114
115inline void BytecodeWriter::output_vbr(int i) {
116 if (i < 0)
117 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
118 else
119 output_vbr((unsigned)i << 1); // Low order bit is clear.
120}
121
122// align32 - emit the minimal number of bytes that will bring us to 32 bit
123// alignment...
124//
125inline void BytecodeWriter::align32() {
126 int NumPads = (4-(Out.size() & 3)) & 3; // Bytes to get padding to 32 bits
127 while (NumPads--) Out.push_back((unsigned char)0xAB);
128}
129
130inline void BytecodeWriter::output(const std::string &s, bool Aligned ) {
131 unsigned Len = s.length();
132 output_vbr(Len ); // Strings may have an arbitrary length...
133 Out.insert(Out.end(), s.begin(), s.end());
134
135 if (Aligned)
136 align32(); // Make sure we are now aligned...
137}
138
139inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
140 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
141}
142
143inline void BytecodeWriter::output_float(float& FloatVal) {
144 /// FIXME: This isn't optimal, it has size problems on some platforms
145 /// where FP is not IEEE.
146 union {
147 float f;
148 uint32_t i;
149 } FloatUnion;
150 FloatUnion.f = FloatVal;
151 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
152 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
153 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
154 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
155}
156
157inline void BytecodeWriter::output_double(double& DoubleVal) {
158 /// FIXME: This isn't optimal, it has size problems on some platforms
159 /// where FP is not IEEE.
160 union {
161 double d;
162 uint64_t i;
163 } DoubleUnion;
164 DoubleUnion.d = DoubleVal;
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
167 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
168 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
169 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
170 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
171 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
172 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
173}
174
175inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
176 bool elideIfEmpty, bool hasLongFormat )
177 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
178
179 if (HasLongFormat) {
180 w.output(ID);
181 w.output(0U); // For length in long format
182 } else {
183 w.output(0U); /// Place holder for ID and length for this block
184 }
185 Loc = w.size();
186}
187
188inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
189 // of scope...
190 if (Loc == Writer.size() && ElideIfEmpty) {
191 // If the block is empty, and we are allowed to, do not emit the block at
192 // all!
193 Writer.resize(Writer.size()-(HasLongFormat?8:4));
194 return;
195 }
196
197 //cerr << "OldLoc = " << Loc << " NewLoc = " << NewLoc << " diff = "
198 // << (NewLoc-Loc) << endl;
199 if (HasLongFormat)
200 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
201 else
202 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
203 Writer.align32(); // Blocks must ALWAYS be aligned
204}
205
206//===----------------------------------------------------------------------===//
207//=== Constant Output ===//
208//===----------------------------------------------------------------------===//
209
210void BytecodeWriter::outputType(const Type *T) {
211 output_vbr((unsigned)T->getTypeID());
212
213 // That's all there is to handling primitive types...
214 if (T->isPrimitiveType()) {
215 return; // We might do this if we alias a prim type: %x = type int
216 }
217
218 switch (T->getTypeID()) { // Handle derived types now.
219 case Type::FunctionTyID: {
220 const FunctionType *MT = cast<FunctionType>(T);
221 int Slot = Table.getSlot(MT->getReturnType());
222 assert(Slot != -1 && "Type used but not available!!");
223 output_typeid((unsigned)Slot);
224
225 // Output the number of arguments to function (+1 if varargs):
226 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
227
228 // Output all of the arguments...
229 FunctionType::param_iterator I = MT->param_begin();
230 for (; I != MT->param_end(); ++I) {
231 Slot = Table.getSlot(*I);
232 assert(Slot != -1 && "Type used but not available!!");
233 output_typeid((unsigned)Slot);
234 }
235
236 // Terminate list with VoidTy if we are a varargs function...
237 if (MT->isVarArg())
238 output_typeid((unsigned)Type::VoidTyID);
239 break;
240 }
241
242 case Type::ArrayTyID: {
243 const ArrayType *AT = cast<ArrayType>(T);
244 int Slot = Table.getSlot(AT->getElementType());
245 assert(Slot != -1 && "Type used but not available!!");
246 output_typeid((unsigned)Slot);
247 //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
248
249 output_vbr(AT->getNumElements());
250 break;
251 }
252
253 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
277 case Type::OpaqueTyID: {
278 // No need to emit anything, just the count of opaque types is enough.
279 break;
280 }
281
282 //case Type::PackedTyID:
283 default:
284 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
285 << " Type '" << T->getDescription() << "'\n";
286 break;
287 }
288}
289
290void BytecodeWriter::outputConstant(const Constant *CPV) {
291 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
292 "Shouldn't output null constants!");
293
294 // We must check for a ConstantExpr before switching by type because
295 // a ConstantExpr can be of any type, and has no explicit value.
296 //
297 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
298 // FIXME: Encoding of constant exprs could be much more compact!
299 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
300 output_vbr(CE->getNumOperands()); // flags as an expr
301 output_vbr(CE->getOpcode()); // flags as an expr
302
303 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
304 int Slot = Table.getSlot(*OI);
305 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
306 output_vbr((unsigned)Slot);
307 Slot = Table.getSlot((*OI)->getType());
308 output_typeid((unsigned)Slot);
309 }
310 return;
311 } else {
312 output_vbr(0U); // flag as not a ConstantExpr
313 }
314
315 switch (CPV->getType()->getTypeID()) {
316 case Type::BoolTyID: // Boolean Types
317 if (cast<ConstantBool>(CPV)->getValue())
318 output_vbr(1U);
319 else
320 output_vbr(0U);
321 break;
322
323 case Type::UByteTyID: // Unsigned integer types...
324 case Type::UShortTyID:
325 case Type::UIntTyID:
326 case Type::ULongTyID:
327 output_vbr(cast<ConstantUInt>(CPV)->getValue());
328 break;
329
330 case Type::SByteTyID: // Signed integer types...
331 case Type::ShortTyID:
332 case Type::IntTyID:
333 case Type::LongTyID:
334 output_vbr(cast<ConstantSInt>(CPV)->getValue());
335 break;
336
337 case Type::ArrayTyID: {
338 const ConstantArray *CPA = cast<ConstantArray>(CPV);
339 assert(!CPA->isString() && "Constant strings should be handled specially!");
340
341 for (unsigned i = 0; i != CPA->getNumOperands(); ++i) {
342 int Slot = Table.getSlot(CPA->getOperand(i));
343 assert(Slot != -1 && "Constant used but not available!!");
344 output_vbr((unsigned)Slot);
345 }
346 break;
347 }
348
349 case Type::StructTyID: {
350 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
351 const std::vector<Use> &Vals = CPS->getValues();
352
353 for (unsigned i = 0; i < Vals.size(); ++i) {
354 int Slot = Table.getSlot(Vals[i]);
355 assert(Slot != -1 && "Constant used but not available!!");
356 output_vbr((unsigned)Slot);
357 }
358 break;
359 }
360
361 case Type::PointerTyID:
362 assert(0 && "No non-null, non-constant-expr constants allowed!");
363 abort();
364
365 case Type::FloatTyID: { // Floating point types...
366 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
367 output_float(Tmp);
368 break;
369 }
370 case Type::DoubleTyID: {
371 double Tmp = cast<ConstantFP>(CPV)->getValue();
372 output_double(Tmp);
373 break;
374 }
375
376 case Type::VoidTyID:
377 case Type::LabelTyID:
378 default:
379 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
380 << " type '" << *CPV->getType() << "'\n";
381 break;
382 }
383 return;
384}
385
386void BytecodeWriter::outputConstantStrings() {
387 SlotCalculator::string_iterator I = Table.string_begin();
388 SlotCalculator::string_iterator E = Table.string_end();
389 if (I == E) return; // No strings to emit
390
391 // If we have != 0 strings to emit, output them now. Strings are emitted into
392 // the 'void' type plane.
393 output_vbr(unsigned(E-I));
394 output_typeid(Type::VoidTyID);
395
396 // Emit all of the strings.
397 for (I = Table.string_begin(); I != E; ++I) {
398 const ConstantArray *Str = *I;
399 int Slot = Table.getSlot(Str->getType());
400 assert(Slot != -1 && "Constant string of unknown type?");
401 output_typeid((unsigned)Slot);
402
403 // Now that we emitted the type (which indicates the size of the string),
404 // emit all of the characters.
405 std::string Val = Str->getAsString();
406 output_data(Val.c_str(), Val.c_str()+Val.size());
407 }
408}
409
410//===----------------------------------------------------------------------===//
411//=== Instruction Output ===//
412//===----------------------------------------------------------------------===//
413typedef unsigned char uchar;
414
415// outputInstructionFormat0 - Output those wierd instructions that have a large
416// number of operands or have large operands themselves...
417//
418// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
419//
420void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
421 const SlotCalculator &Table,
422 unsigned Type) {
423 // Opcode must have top two bits clear...
424 output_vbr(Opcode << 2); // Instruction Opcode ID
425 output_typeid(Type); // Result type
426
427 unsigned NumArgs = I->getNumOperands();
428 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
429 isa<VAArgInst>(I)));
430
431 if (!isa<GetElementPtrInst>(&I)) {
432 for (unsigned i = 0; i < NumArgs; ++i) {
433 int Slot = Table.getSlot(I->getOperand(i));
434 assert(Slot >= 0 && "No slot number for value!?!?");
435 output_vbr((unsigned)Slot);
436 }
437
438 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
439 int Slot = Table.getSlot(I->getType());
440 assert(Slot != -1 && "Cast return type unknown?");
441 output_typeid((unsigned)Slot);
442 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
443 int Slot = Table.getSlot(VAI->getArgType());
444 assert(Slot != -1 && "VarArg argument type unknown?");
445 output_typeid((unsigned)Slot);
446 }
447
448 } else {
449 int Slot = Table.getSlot(I->getOperand(0));
450 assert(Slot >= 0 && "No slot number for value!?!?");
451 output_vbr(unsigned(Slot));
452
453 // We need to encode the type of sequential type indices into their slot #
454 unsigned Idx = 1;
455 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
456 Idx != NumArgs; ++TI, ++Idx) {
457 Slot = Table.getSlot(I->getOperand(Idx));
458 assert(Slot >= 0 && "No slot number for value!?!?");
459
460 if (isa<SequentialType>(*TI)) {
461 unsigned IdxId;
462 switch (I->getOperand(Idx)->getType()->getTypeID()) {
463 default: assert(0 && "Unknown index type!");
464 case Type::UIntTyID: IdxId = 0; break;
465 case Type::IntTyID: IdxId = 1; break;
466 case Type::ULongTyID: IdxId = 2; break;
467 case Type::LongTyID: IdxId = 3; break;
468 }
469 Slot = (Slot << 2) | IdxId;
470 }
471 output_vbr(unsigned(Slot));
472 }
473 }
474
475 align32(); // We must maintain correct alignment!
476}
477
478
479// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
480// This are more annoying than most because the signature of the call does not
481// tell us anything about the types of the arguments in the varargs portion.
482// Because of this, we encode (as type 0) all of the argument types explicitly
483// before the argument value. This really sucks, but you shouldn't be using
484// varargs functions in your code! *death to printf*!
485//
486// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
487//
488void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
489 unsigned Opcode,
490 const SlotCalculator &Table,
491 unsigned Type) {
492 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
493 // Opcode must have top two bits clear...
494 output_vbr(Opcode << 2); // Instruction Opcode ID
495 output_typeid(Type); // Result type (varargs type)
496
497 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
498 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
499 unsigned NumParams = FTy->getNumParams();
500
501 unsigned NumFixedOperands;
502 if (isa<CallInst>(I)) {
503 // Output an operand for the callee and each fixed argument, then two for
504 // each variable argument.
505 NumFixedOperands = 1+NumParams;
506 } else {
507 assert(isa<InvokeInst>(I) && "Not call or invoke??");
508 // Output an operand for the callee and destinations, then two for each
509 // variable argument.
510 NumFixedOperands = 3+NumParams;
511 }
512 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
513
514 // The type for the function has already been emitted in the type field of the
515 // instruction. Just emit the slot # now.
516 for (unsigned i = 0; i != NumFixedOperands; ++i) {
517 int Slot = Table.getSlot(I->getOperand(i));
518 assert(Slot >= 0 && "No slot number for value!?!?");
519 output_vbr((unsigned)Slot);
520 }
521
522 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
523 // Output Arg Type ID
524 int Slot = Table.getSlot(I->getOperand(i)->getType());
525 assert(Slot >= 0 && "No slot number for value!?!?");
526 output_typeid((unsigned)Slot);
527
528 // Output arg ID itself
529 Slot = Table.getSlot(I->getOperand(i));
530 assert(Slot >= 0 && "No slot number for value!?!?");
531 output_vbr((unsigned)Slot);
532 }
533 align32(); // We must maintain correct alignment!
534}
535
536
537// outputInstructionFormat1 - Output one operand instructions, knowing that no
538// operand index is >= 2^12.
539//
540inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
541 unsigned Opcode,
542 unsigned *Slots,
543 unsigned Type) {
544 // bits Instruction format:
545 // --------------------------
546 // 01-00: Opcode type, fixed to 1.
547 // 07-02: Opcode
548 // 19-08: Resulting type plane
549 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
550 //
551 unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
552 // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
553 output(Bits);
554}
555
556
557// outputInstructionFormat2 - Output two operand instructions, knowing that no
558// operand index is >= 2^8.
559//
560inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
561 unsigned Opcode,
562 unsigned *Slots,
563 unsigned Type) {
564 // bits Instruction format:
565 // --------------------------
566 // 01-00: Opcode type, fixed to 2.
567 // 07-02: Opcode
568 // 15-08: Resulting type plane
569 // 23-16: Operand #1
570 // 31-24: Operand #2
571 //
572 unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
573 (Slots[0] << 16) | (Slots[1] << 24);
574 // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " "
575 // << Slots[1] << endl;
576 output(Bits);
577}
578
579
580// outputInstructionFormat3 - Output three operand instructions, knowing that no
581// operand index is >= 2^6.
582//
583inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
584 unsigned Opcode,
585 unsigned *Slots,
586 unsigned Type) {
587 // bits Instruction format:
588 // --------------------------
589 // 01-00: Opcode type, fixed to 3.
590 // 07-02: Opcode
591 // 13-08: Resulting type plane
592 // 19-14: Operand #1
593 // 25-20: Operand #2
594 // 31-26: Operand #3
595 //
596 unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
597 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
598 //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " "
599 // << Slots[1] << " " << Slots[2] << endl;
600 output(Bits);
601}
602
603void BytecodeWriter::outputInstruction(const Instruction &I) {
604 assert(I.getOpcode() < 62 && "Opcode too big???");
605 unsigned Opcode = I.getOpcode();
606 unsigned NumOperands = I.getNumOperands();
607
608 // Encode 'volatile load' as 62 and 'volatile store' as 63.
609 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
610 Opcode = 62;
611 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
612 Opcode = 63;
613
614 // Figure out which type to encode with the instruction. Typically we want
615 // the type of the first parameter, as opposed to the type of the instruction
616 // (for example, with setcc, we always know it returns bool, but the type of
617 // the first param is actually interesting). But if we have no arguments
618 // we take the type of the instruction itself.
619 //
620 const Type *Ty;
621 switch (I.getOpcode()) {
622 case Instruction::Select:
623 case Instruction::Malloc:
624 case Instruction::Alloca:
625 Ty = I.getType(); // These ALWAYS want to encode the return type
626 break;
627 case Instruction::Store:
628 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
629 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
630 break;
631 default: // Otherwise use the default behavior...
632 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
633 break;
634 }
635
636 unsigned Type;
637 int Slot = Table.getSlot(Ty);
638 assert(Slot != -1 && "Type not available!!?!");
639 Type = (unsigned)Slot;
640
641 // Varargs calls and invokes are encoded entirely different from any other
642 // instructions.
643 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
644 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
645 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
646 outputInstrVarArgsCall(CI, Opcode, Table, Type);
647 return;
648 }
649 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
650 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
651 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
652 outputInstrVarArgsCall(II, Opcode, Table, Type);
653 return;
654 }
655 }
656
657 if (NumOperands <= 3) {
658 // Make sure that we take the type number into consideration. We don't want
659 // to overflow the field size for the instruction format we select.
660 //
661 unsigned MaxOpSlot = Type;
662 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
663
664 for (unsigned i = 0; i != NumOperands; ++i) {
665 int slot = Table.getSlot(I.getOperand(i));
666 assert(slot != -1 && "Broken bytecode!");
667 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
668 Slots[i] = unsigned(slot);
669 }
670
671 // Handle the special cases for various instructions...
672 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
673 // Cast has to encode the destination type as the second argument in the
674 // packet, or else we won't know what type to cast to!
675 Slots[1] = Table.getSlot(I.getType());
676 assert(Slots[1] != ~0U && "Cast return type unknown?");
677 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
678 NumOperands++;
679 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
680 Slots[1] = Table.getSlot(VANI->getArgType());
681 assert(Slots[1] != ~0U && "va_next return type unknown?");
682 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
683 NumOperands++;
684 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
685 // We need to encode the type of sequential type indices into their slot #
686 unsigned Idx = 1;
687 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
688 I != E; ++I, ++Idx)
689 if (isa<SequentialType>(*I)) {
690 unsigned IdxId;
691 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
692 default: assert(0 && "Unknown index type!");
693 case Type::UIntTyID: IdxId = 0; break;
694 case Type::IntTyID: IdxId = 1; break;
695 case Type::ULongTyID: IdxId = 2; break;
696 case Type::LongTyID: IdxId = 3; break;
697 }
698 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
699 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
700 }
701 }
702
703 // Decide which instruction encoding to use. This is determined primarily
704 // by the number of operands, and secondarily by whether or not the max
705 // operand will fit into the instruction encoding. More operands == fewer
706 // bits per operand.
707 //
708 switch (NumOperands) {
709 case 0:
710 case 1:
711 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
712 outputInstructionFormat1(&I, Opcode, Slots, Type);
713 return;
714 }
715 break;
716
717 case 2:
718 if (MaxOpSlot < (1 << 8)) {
719 outputInstructionFormat2(&I, Opcode, Slots, Type);
720 return;
721 }
722 break;
723
724 case 3:
725 if (MaxOpSlot < (1 << 6)) {
726 outputInstructionFormat3(&I, Opcode, Slots, Type);
727 return;
728 }
729 break;
730 default:
731 break;
732 }
733 }
734
735 // If we weren't handled before here, we either have a large number of
736 // operands or a large operand index that we are referring to.
737 outputInstructionFormat0(&I, Opcode, Table, Type);
738}
739
740//===----------------------------------------------------------------------===//
741//=== Block Output ===//
742//===----------------------------------------------------------------------===//
743
744BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000745 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000746
Chris Lattner83bb3d22004-01-14 23:36:54 +0000747 // Emit the signature...
748 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000749 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000750
751 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000752 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000753
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000754 bool isBigEndian = M->getEndianness() == Module::BigEndian;
755 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
756 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
757 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000758
Chris Lattner5fa428f2004-04-05 01:27:26 +0000759 // Output the version identifier... we are currently on bytecode version #2,
760 // which corresponds to LLVM v1.3.
Reid Spencerad89bd62004-07-25 18:07:36 +0000761 unsigned Version = (3 << 4) | (unsigned)isBigEndian | (hasLongPointers << 1) |
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000762 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000763 output_vbr(Version);
764 align32();
Chris Lattner00950542001-06-06 20:29:01 +0000765
Reid Spencercb3595c2004-07-04 11:45:47 +0000766 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000767 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000768 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000769 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000770 }
Chris Lattner00950542001-06-06 20:29:01 +0000771
Chris Lattner186a1f72003-03-19 20:56:46 +0000772 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000773 outputModuleInfoBlock(M);
774
Chris Lattner186a1f72003-03-19 20:56:46 +0000775 // Output module level constants, used for global variable initializers
776 outputConstants(false);
777
Chris Lattnerb5794002002-04-07 22:49:37 +0000778 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000779 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000780 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000781
782 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000783 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000784}
785
Reid Spencercb3595c2004-07-04 11:45:47 +0000786void BytecodeWriter::outputTypes(unsigned TypeNum)
787{
788 // Write the type plane for types first because earlier planes (e.g. for a
789 // primitive type like float) may have constants constructed using types
790 // coming later (e.g., via getelementptr from a pointer type). The type
791 // plane is needed before types can be fwd or bkwd referenced.
792 const std::vector<const Type*>& Types = Table.getTypes();
793 assert(!Types.empty() && "No types at all?");
794 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
795
796 unsigned NumEntries = Types.size() - TypeNum;
797
798 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000799 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000800
801 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
802 outputType(Types[i]);
803}
804
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000805// Helper function for outputConstants().
806// Writes out all the constants in the plane Plane starting at entry StartNo.
807//
808void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
809 &Plane, unsigned StartNo) {
810 unsigned ValNo = StartNo;
811
Chris Lattner83bb3d22004-01-14 23:36:54 +0000812 // Scan through and ignore function arguments, global values, and constant
813 // strings.
814 for (; ValNo < Plane.size() &&
815 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
816 (isa<ConstantArray>(Plane[ValNo]) &&
817 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000818 /*empty*/;
819
820 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000821 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000822 /*empty*/;
823 NC -= ValNo; // Convert from index into count
824 if (NC == 0) return; // Skip empty type planes...
825
Chris Lattnerd6942d72004-01-14 16:54:21 +0000826 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
827 // more compactly.
828
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000829 // Output type header: [num entries][type id number]
830 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000831 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000832
833 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000834 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000835 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000836 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000837
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000838 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
839 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000840 if (const Constant *C = dyn_cast<Constant>(V)) {
841 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000842 }
843 }
844}
845
Chris Lattner80b97342004-01-17 23:25:43 +0000846static inline bool hasNullValue(unsigned TyID) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000847 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Chris Lattner80b97342004-01-17 23:25:43 +0000848}
849
Chris Lattner79df7c02002-03-26 18:01:55 +0000850void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000851 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000852 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000853
854 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000855
Reid Spencere0125b62004-07-18 00:16:21 +0000856 if (isFunction)
857 // Output the type plane before any constants!
Reid Spencercb3595c2004-07-04 11:45:47 +0000858 outputTypes( Table.getModuleTypeLevel() );
Reid Spencere0125b62004-07-18 00:16:21 +0000859 else
860 // Output module-level string constants before any other constants.x
Chris Lattner83bb3d22004-01-14 23:36:54 +0000861 outputConstantStrings();
862
Reid Spencercb3595c2004-07-04 11:45:47 +0000863 for (unsigned pno = 0; pno != NumPlanes; pno++) {
864 const std::vector<const Value*> &Plane = Table.getPlane(pno);
865 if (!Plane.empty()) { // Skip empty type planes...
866 unsigned ValNo = 0;
867 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000868 ValNo += Table.getModuleLevel(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000869
870 if (hasNullValue(pno)) {
Reid Spencer0852c802004-07-04 11:46:15 +0000871 // Skip zero initializer
872 if (ValNo == 0)
873 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000874 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000875
876 // Write out constants in the plane
877 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000878 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000879 }
Chris Lattner00950542001-06-06 20:29:01 +0000880}
881
Chris Lattner6b252422003-10-16 18:28:50 +0000882static unsigned getEncodedLinkage(const GlobalValue *GV) {
883 switch (GV->getLinkage()) {
884 default: assert(0 && "Invalid linkage!");
885 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000886 case GlobalValue::WeakLinkage: return 1;
887 case GlobalValue::AppendingLinkage: return 2;
888 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000889 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000890 }
891}
892
Chris Lattner00950542001-06-06 20:29:01 +0000893void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000894 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Chris Lattner00950542001-06-06 20:29:01 +0000895
Chris Lattner70cc3392001-09-10 07:58:01 +0000896 // Output the types for the global variables in the module...
897 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000898 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000899 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000900
Chris Lattner22482a12003-10-18 06:30:21 +0000901 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
902 // bit5+ = Slot # for type
903 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000904 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Reid Spencerad89bd62004-07-25 18:07:36 +0000905 output_vbr(oSlot );
Chris Lattnerd70684f2001-09-18 04:01:05 +0000906
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000907 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000908 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000909 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000910 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000911 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000912 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000913 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000914 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000915
Chris Lattnerb5794002002-04-07 22:49:37 +0000916 // Output the types of the functions in this module...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000917 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000918 int Slot = Table.getSlot(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000919 assert(Slot != -1 && "Module const pool is broken!");
920 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000921 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +0000922 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000923 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
924
925 // Put out the list of dependent libraries for the Module
Reid Spencer5ac88122004-07-25 21:32:02 +0000926 Module::lib_iterator LI = M->lib_begin();
927 Module::lib_iterator LE = M->lib_end();
Reid Spencerad89bd62004-07-25 18:07:36 +0000928 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
929 for ( ; LI != LE; ++LI ) {
930 output(*LI, /*aligned=*/false);
931 }
932
933 // Output the target triple from the module
934 output(M->getTargetTriple(), /*aligned=*/ true);
Chris Lattner00950542001-06-06 20:29:01 +0000935}
936
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000937void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000938 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000939 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
940 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
941 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000942}
943
Chris Lattner186a1f72003-03-19 20:56:46 +0000944void BytecodeWriter::outputFunction(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000945 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
946 output_vbr(getEncodedLinkage(F));
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000947
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000948 // If this is an external function, there is nothing else to emit!
949 if (F->isExternal()) return;
Chris Lattner00950542001-06-06 20:29:01 +0000950
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000951 // Get slot information about the function...
952 Table.incorporateFunction(F);
953
954 if (Table.getCompactionTable().empty()) {
955 // Output information about the constants in the function if the compaction
956 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000957 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000958 } else {
959 // Otherwise, emit the compaction table.
960 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000961 }
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000962
963 // Output all of the instructions in the body of the function
964 outputInstructions(F);
965
966 // If needed, output the symbol table for the function...
967 outputSymbolTable(F->getSymbolTable());
968
969 Table.purgeFunction();
970}
971
972void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
973 const std::vector<const Value*> &Plane,
974 unsigned StartNo) {
975 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +0000976 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000977 assert(StartNo < End && "Cannot emit negative range!");
978 assert(StartNo < Plane.size() && End <= Plane.size());
979
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000980 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +0000981 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000982
Chris Lattner24102432004-01-18 22:35:34 +0000983 // Figure out which encoding to use. By far the most common case we have is
984 // to emit 0-2 entries in a compaction table plane.
985 switch (End-StartNo) {
986 case 0: // Avoid emitting two vbr's if possible.
987 case 1:
988 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +0000989 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +0000990 break;
991 default:
992 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +0000993 output_vbr((unsigned(End-StartNo) << 2) | 3);
994 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +0000995 break;
996 }
997
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000998 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +0000999 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001000}
1001
Reid Spencercb3595c2004-07-04 11:45:47 +00001002void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1003 // Get the compaction type table from the slot calculator
1004 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1005
1006 // The compaction types may have been uncompactified back to the
1007 // global types. If so, we just write an empty table
1008 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001009 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001010 return;
1011 }
1012
1013 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1014
1015 // Determine how many types to write
1016 unsigned NumTypes = CTypes.size() - StartNo;
1017
1018 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001019 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001020
1021 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001022 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001023}
1024
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001025void BytecodeWriter::outputCompactionTable() {
Reid Spencerad89bd62004-07-25 18:07:36 +00001026 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1027 true/*ElideIfEmpty*/);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001028 const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1029
1030 // First thing is first, emit the type compaction table if there is one.
Reid Spencercb3595c2004-07-04 11:45:47 +00001031 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001032
1033 for (unsigned i = 0, e = CT.size(); i != e; ++i)
Reid Spencercb3595c2004-07-04 11:45:47 +00001034 outputCompactionTablePlane(i, CT[i], 0);
Chris Lattner00950542001-06-06 20:29:01 +00001035}
1036
Chris Lattner00950542001-06-06 20:29:01 +00001037void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001038 // Do not output the Bytecode block for an empty symbol table, it just wastes
1039 // space!
Reid Spencer6ed81e22004-05-27 20:18:51 +00001040 if ( MST.isEmpty() ) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001041
Reid Spencerad89bd62004-07-25 18:07:36 +00001042 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +00001043 true/* ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001044
Reid Spencercb3595c2004-07-04 11:45:47 +00001045 //Symtab block header for types: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +00001046 output_vbr(MST.num_types());
Reid Spencer94f2df22004-05-25 17:29:59 +00001047 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1048 TE = MST.type_end(); TI != TE; ++TI ) {
1049 //Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001050 output_typeid((unsigned)Table.getSlot(TI->second));
1051 output(TI->first, /*align=*/false);
Reid Spencer94f2df22004-05-25 17:29:59 +00001052 }
1053
1054 // Now do each of the type planes in order.
1055 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1056 PE = MST.plane_end(); PI != PE; ++PI) {
1057 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1058 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001059 int Slot;
1060
1061 if (I == End) continue; // Don't mess with an absent type...
1062
1063 // Symtab block header: [num entries][type id number]
Reid Spencerad89bd62004-07-25 18:07:36 +00001064 output_vbr(MST.type_size(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001065
Reid Spencer94f2df22004-05-25 17:29:59 +00001066 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001067 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001068 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001069
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001070 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001071 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001072 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001073 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001074 output_vbr((unsigned)Slot);
1075 output(I->first, false); // Don't force alignment...
Chris Lattner00950542001-06-06 20:29:01 +00001076 }
1077 }
1078}
1079
Reid Spencerad89bd62004-07-25 18:07:36 +00001080void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1081 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001082
Reid Spencerad89bd62004-07-25 18:07:36 +00001083 std::vector<unsigned char> Buffer;
1084 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
Chris Lattner00950542001-06-06 20:29:01 +00001085
1086 // This object populates buffer for us...
Reid Spencerad89bd62004-07-25 18:07:36 +00001087 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001088
Chris Lattnerce6ef112002-07-26 18:40:14 +00001089 // Keep track of how much we've written...
1090 BytesWritten += Buffer.size();
1091
Chris Lattnere8fdde12001-09-07 16:39:41 +00001092 // Okay, write the deque out to the ostream now... the deque is not
1093 // sequential in memory, however, so write out as much as possible in big
1094 // chunks, until we're done.
1095 //
Chris Lattner036de032004-06-25 20:52:10 +00001096
Reid Spencerad89bd62004-07-25 18:07:36 +00001097 std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001098 while (I != E) { // Loop until it's all written
1099 // Scan to see how big this chunk is...
1100 const unsigned char *ChunkPtr = &*I;
1101 const unsigned char *LastPtr = ChunkPtr;
1102 while (I != E) {
1103 const unsigned char *ThisPtr = &*++I;
Chris Lattner036de032004-06-25 20:52:10 +00001104 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
Chris Lattner5cb17412001-11-04 21:32:41 +00001105 break;
Chris Lattnere8fdde12001-09-07 16:39:41 +00001106 }
1107
1108 // Write out the chunk...
Chris Lattnerd6162282004-06-25 00:35:55 +00001109 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
Chris Lattnere8fdde12001-09-07 16:39:41 +00001110 }
Chris Lattner00950542001-06-06 20:29:01 +00001111 Out.flush();
1112}
Reid Spencere0125b62004-07-18 00:16:21 +00001113
1114// vim: sw=2 ai