blob: 906835b09590242cc26bf5bb9756cf827085d8f4 [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
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000341 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000342 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);
Reid Spencerad89bd62004-07-25 18:07:36 +0000351
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000352 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
353 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000354 assert(Slot != -1 && "Constant used but not available!!");
355 output_vbr((unsigned)Slot);
356 }
357 break;
358 }
359
360 case Type::PointerTyID:
361 assert(0 && "No non-null, non-constant-expr constants allowed!");
362 abort();
363
364 case Type::FloatTyID: { // Floating point types...
365 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
366 output_float(Tmp);
367 break;
368 }
369 case Type::DoubleTyID: {
370 double Tmp = cast<ConstantFP>(CPV)->getValue();
371 output_double(Tmp);
372 break;
373 }
374
375 case Type::VoidTyID:
376 case Type::LabelTyID:
377 default:
378 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
379 << " type '" << *CPV->getType() << "'\n";
380 break;
381 }
382 return;
383}
384
385void BytecodeWriter::outputConstantStrings() {
386 SlotCalculator::string_iterator I = Table.string_begin();
387 SlotCalculator::string_iterator E = Table.string_end();
388 if (I == E) return; // No strings to emit
389
390 // If we have != 0 strings to emit, output them now. Strings are emitted into
391 // the 'void' type plane.
392 output_vbr(unsigned(E-I));
393 output_typeid(Type::VoidTyID);
394
395 // Emit all of the strings.
396 for (I = Table.string_begin(); I != E; ++I) {
397 const ConstantArray *Str = *I;
398 int Slot = Table.getSlot(Str->getType());
399 assert(Slot != -1 && "Constant string of unknown type?");
400 output_typeid((unsigned)Slot);
401
402 // Now that we emitted the type (which indicates the size of the string),
403 // emit all of the characters.
404 std::string Val = Str->getAsString();
405 output_data(Val.c_str(), Val.c_str()+Val.size());
406 }
407}
408
409//===----------------------------------------------------------------------===//
410//=== Instruction Output ===//
411//===----------------------------------------------------------------------===//
412typedef unsigned char uchar;
413
414// outputInstructionFormat0 - Output those wierd instructions that have a large
415// number of operands or have large operands themselves...
416//
417// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
418//
419void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
420 const SlotCalculator &Table,
421 unsigned Type) {
422 // Opcode must have top two bits clear...
423 output_vbr(Opcode << 2); // Instruction Opcode ID
424 output_typeid(Type); // Result type
425
426 unsigned NumArgs = I->getNumOperands();
427 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
428 isa<VAArgInst>(I)));
429
430 if (!isa<GetElementPtrInst>(&I)) {
431 for (unsigned i = 0; i < NumArgs; ++i) {
432 int Slot = Table.getSlot(I->getOperand(i));
433 assert(Slot >= 0 && "No slot number for value!?!?");
434 output_vbr((unsigned)Slot);
435 }
436
437 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
438 int Slot = Table.getSlot(I->getType());
439 assert(Slot != -1 && "Cast return type unknown?");
440 output_typeid((unsigned)Slot);
441 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
442 int Slot = Table.getSlot(VAI->getArgType());
443 assert(Slot != -1 && "VarArg argument type unknown?");
444 output_typeid((unsigned)Slot);
445 }
446
447 } else {
448 int Slot = Table.getSlot(I->getOperand(0));
449 assert(Slot >= 0 && "No slot number for value!?!?");
450 output_vbr(unsigned(Slot));
451
452 // We need to encode the type of sequential type indices into their slot #
453 unsigned Idx = 1;
454 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
455 Idx != NumArgs; ++TI, ++Idx) {
456 Slot = Table.getSlot(I->getOperand(Idx));
457 assert(Slot >= 0 && "No slot number for value!?!?");
458
459 if (isa<SequentialType>(*TI)) {
460 unsigned IdxId;
461 switch (I->getOperand(Idx)->getType()->getTypeID()) {
462 default: assert(0 && "Unknown index type!");
463 case Type::UIntTyID: IdxId = 0; break;
464 case Type::IntTyID: IdxId = 1; break;
465 case Type::ULongTyID: IdxId = 2; break;
466 case Type::LongTyID: IdxId = 3; break;
467 }
468 Slot = (Slot << 2) | IdxId;
469 }
470 output_vbr(unsigned(Slot));
471 }
472 }
473
474 align32(); // We must maintain correct alignment!
475}
476
477
478// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
479// This are more annoying than most because the signature of the call does not
480// tell us anything about the types of the arguments in the varargs portion.
481// Because of this, we encode (as type 0) all of the argument types explicitly
482// before the argument value. This really sucks, but you shouldn't be using
483// varargs functions in your code! *death to printf*!
484//
485// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
486//
487void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
488 unsigned Opcode,
489 const SlotCalculator &Table,
490 unsigned Type) {
491 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
492 // Opcode must have top two bits clear...
493 output_vbr(Opcode << 2); // Instruction Opcode ID
494 output_typeid(Type); // Result type (varargs type)
495
496 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
497 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
498 unsigned NumParams = FTy->getNumParams();
499
500 unsigned NumFixedOperands;
501 if (isa<CallInst>(I)) {
502 // Output an operand for the callee and each fixed argument, then two for
503 // each variable argument.
504 NumFixedOperands = 1+NumParams;
505 } else {
506 assert(isa<InvokeInst>(I) && "Not call or invoke??");
507 // Output an operand for the callee and destinations, then two for each
508 // variable argument.
509 NumFixedOperands = 3+NumParams;
510 }
511 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
512
513 // The type for the function has already been emitted in the type field of the
514 // instruction. Just emit the slot # now.
515 for (unsigned i = 0; i != NumFixedOperands; ++i) {
516 int Slot = Table.getSlot(I->getOperand(i));
517 assert(Slot >= 0 && "No slot number for value!?!?");
518 output_vbr((unsigned)Slot);
519 }
520
521 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
522 // Output Arg Type ID
523 int Slot = Table.getSlot(I->getOperand(i)->getType());
524 assert(Slot >= 0 && "No slot number for value!?!?");
525 output_typeid((unsigned)Slot);
526
527 // Output arg ID itself
528 Slot = Table.getSlot(I->getOperand(i));
529 assert(Slot >= 0 && "No slot number for value!?!?");
530 output_vbr((unsigned)Slot);
531 }
532 align32(); // We must maintain correct alignment!
533}
534
535
536// outputInstructionFormat1 - Output one operand instructions, knowing that no
537// operand index is >= 2^12.
538//
539inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
540 unsigned Opcode,
541 unsigned *Slots,
542 unsigned Type) {
543 // bits Instruction format:
544 // --------------------------
545 // 01-00: Opcode type, fixed to 1.
546 // 07-02: Opcode
547 // 19-08: Resulting type plane
548 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
549 //
550 unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
551 // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
552 output(Bits);
553}
554
555
556// outputInstructionFormat2 - Output two operand instructions, knowing that no
557// operand index is >= 2^8.
558//
559inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
560 unsigned Opcode,
561 unsigned *Slots,
562 unsigned Type) {
563 // bits Instruction format:
564 // --------------------------
565 // 01-00: Opcode type, fixed to 2.
566 // 07-02: Opcode
567 // 15-08: Resulting type plane
568 // 23-16: Operand #1
569 // 31-24: Operand #2
570 //
571 unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
572 (Slots[0] << 16) | (Slots[1] << 24);
573 // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " "
574 // << Slots[1] << endl;
575 output(Bits);
576}
577
578
579// outputInstructionFormat3 - Output three operand instructions, knowing that no
580// operand index is >= 2^6.
581//
582inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
583 unsigned Opcode,
584 unsigned *Slots,
585 unsigned Type) {
586 // bits Instruction format:
587 // --------------------------
588 // 01-00: Opcode type, fixed to 3.
589 // 07-02: Opcode
590 // 13-08: Resulting type plane
591 // 19-14: Operand #1
592 // 25-20: Operand #2
593 // 31-26: Operand #3
594 //
595 unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
596 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
597 //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " "
598 // << Slots[1] << " " << Slots[2] << endl;
599 output(Bits);
600}
601
602void BytecodeWriter::outputInstruction(const Instruction &I) {
603 assert(I.getOpcode() < 62 && "Opcode too big???");
604 unsigned Opcode = I.getOpcode();
605 unsigned NumOperands = I.getNumOperands();
606
607 // Encode 'volatile load' as 62 and 'volatile store' as 63.
608 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
609 Opcode = 62;
610 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
611 Opcode = 63;
612
613 // Figure out which type to encode with the instruction. Typically we want
614 // the type of the first parameter, as opposed to the type of the instruction
615 // (for example, with setcc, we always know it returns bool, but the type of
616 // the first param is actually interesting). But if we have no arguments
617 // we take the type of the instruction itself.
618 //
619 const Type *Ty;
620 switch (I.getOpcode()) {
621 case Instruction::Select:
622 case Instruction::Malloc:
623 case Instruction::Alloca:
624 Ty = I.getType(); // These ALWAYS want to encode the return type
625 break;
626 case Instruction::Store:
627 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
628 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
629 break;
630 default: // Otherwise use the default behavior...
631 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
632 break;
633 }
634
635 unsigned Type;
636 int Slot = Table.getSlot(Ty);
637 assert(Slot != -1 && "Type not available!!?!");
638 Type = (unsigned)Slot;
639
640 // Varargs calls and invokes are encoded entirely different from any other
641 // instructions.
642 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
643 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
644 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
645 outputInstrVarArgsCall(CI, Opcode, Table, Type);
646 return;
647 }
648 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
649 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
650 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
651 outputInstrVarArgsCall(II, Opcode, Table, Type);
652 return;
653 }
654 }
655
656 if (NumOperands <= 3) {
657 // Make sure that we take the type number into consideration. We don't want
658 // to overflow the field size for the instruction format we select.
659 //
660 unsigned MaxOpSlot = Type;
661 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
662
663 for (unsigned i = 0; i != NumOperands; ++i) {
664 int slot = Table.getSlot(I.getOperand(i));
665 assert(slot != -1 && "Broken bytecode!");
666 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
667 Slots[i] = unsigned(slot);
668 }
669
670 // Handle the special cases for various instructions...
671 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
672 // Cast has to encode the destination type as the second argument in the
673 // packet, or else we won't know what type to cast to!
674 Slots[1] = Table.getSlot(I.getType());
675 assert(Slots[1] != ~0U && "Cast return type unknown?");
676 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
677 NumOperands++;
678 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
679 Slots[1] = Table.getSlot(VANI->getArgType());
680 assert(Slots[1] != ~0U && "va_next return type unknown?");
681 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
682 NumOperands++;
683 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
684 // We need to encode the type of sequential type indices into their slot #
685 unsigned Idx = 1;
686 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
687 I != E; ++I, ++Idx)
688 if (isa<SequentialType>(*I)) {
689 unsigned IdxId;
690 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
691 default: assert(0 && "Unknown index type!");
692 case Type::UIntTyID: IdxId = 0; break;
693 case Type::IntTyID: IdxId = 1; break;
694 case Type::ULongTyID: IdxId = 2; break;
695 case Type::LongTyID: IdxId = 3; break;
696 }
697 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
698 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
699 }
700 }
701
702 // Decide which instruction encoding to use. This is determined primarily
703 // by the number of operands, and secondarily by whether or not the max
704 // operand will fit into the instruction encoding. More operands == fewer
705 // bits per operand.
706 //
707 switch (NumOperands) {
708 case 0:
709 case 1:
710 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
711 outputInstructionFormat1(&I, Opcode, Slots, Type);
712 return;
713 }
714 break;
715
716 case 2:
717 if (MaxOpSlot < (1 << 8)) {
718 outputInstructionFormat2(&I, Opcode, Slots, Type);
719 return;
720 }
721 break;
722
723 case 3:
724 if (MaxOpSlot < (1 << 6)) {
725 outputInstructionFormat3(&I, Opcode, Slots, Type);
726 return;
727 }
728 break;
729 default:
730 break;
731 }
732 }
733
734 // If we weren't handled before here, we either have a large number of
735 // operands or a large operand index that we are referring to.
736 outputInstructionFormat0(&I, Opcode, Table, Type);
737}
738
739//===----------------------------------------------------------------------===//
740//=== Block Output ===//
741//===----------------------------------------------------------------------===//
742
743BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000744 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000745
Chris Lattner83bb3d22004-01-14 23:36:54 +0000746 // Emit the signature...
747 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000748 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000749
750 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000751 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000752
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000753 bool isBigEndian = M->getEndianness() == Module::BigEndian;
754 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
755 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
756 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000757
Chris Lattner5fa428f2004-04-05 01:27:26 +0000758 // Output the version identifier... we are currently on bytecode version #2,
759 // which corresponds to LLVM v1.3.
Reid Spencerad89bd62004-07-25 18:07:36 +0000760 unsigned Version = (3 << 4) | (unsigned)isBigEndian | (hasLongPointers << 1) |
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000761 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000762 output_vbr(Version);
763 align32();
Chris Lattner00950542001-06-06 20:29:01 +0000764
Reid Spencercb3595c2004-07-04 11:45:47 +0000765 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000766 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000767 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000768 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000769 }
Chris Lattner00950542001-06-06 20:29:01 +0000770
Chris Lattner186a1f72003-03-19 20:56:46 +0000771 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000772 outputModuleInfoBlock(M);
773
Chris Lattner186a1f72003-03-19 20:56:46 +0000774 // Output module level constants, used for global variable initializers
775 outputConstants(false);
776
Chris Lattnerb5794002002-04-07 22:49:37 +0000777 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000778 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000779 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000780
781 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000782 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000783}
784
Reid Spencercb3595c2004-07-04 11:45:47 +0000785void BytecodeWriter::outputTypes(unsigned TypeNum)
786{
787 // Write the type plane for types first because earlier planes (e.g. for a
788 // primitive type like float) may have constants constructed using types
789 // coming later (e.g., via getelementptr from a pointer type). The type
790 // plane is needed before types can be fwd or bkwd referenced.
791 const std::vector<const Type*>& Types = Table.getTypes();
792 assert(!Types.empty() && "No types at all?");
793 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
794
795 unsigned NumEntries = Types.size() - TypeNum;
796
797 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000798 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000799
800 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
801 outputType(Types[i]);
802}
803
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000804// Helper function for outputConstants().
805// Writes out all the constants in the plane Plane starting at entry StartNo.
806//
807void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
808 &Plane, unsigned StartNo) {
809 unsigned ValNo = StartNo;
810
Chris Lattner83bb3d22004-01-14 23:36:54 +0000811 // Scan through and ignore function arguments, global values, and constant
812 // strings.
813 for (; ValNo < Plane.size() &&
814 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
815 (isa<ConstantArray>(Plane[ValNo]) &&
816 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000817 /*empty*/;
818
819 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000820 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000821 /*empty*/;
822 NC -= ValNo; // Convert from index into count
823 if (NC == 0) return; // Skip empty type planes...
824
Chris Lattnerd6942d72004-01-14 16:54:21 +0000825 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
826 // more compactly.
827
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000828 // Output type header: [num entries][type id number]
829 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000830 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000831
832 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000833 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000834 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000835 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000836
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000837 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
838 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000839 if (const Constant *C = dyn_cast<Constant>(V)) {
840 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000841 }
842 }
843}
844
Chris Lattner80b97342004-01-17 23:25:43 +0000845static inline bool hasNullValue(unsigned TyID) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000846 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Chris Lattner80b97342004-01-17 23:25:43 +0000847}
848
Chris Lattner79df7c02002-03-26 18:01:55 +0000849void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000850 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000851 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000852
853 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000854
Reid Spencere0125b62004-07-18 00:16:21 +0000855 if (isFunction)
856 // Output the type plane before any constants!
Reid Spencercb3595c2004-07-04 11:45:47 +0000857 outputTypes( Table.getModuleTypeLevel() );
Reid Spencere0125b62004-07-18 00:16:21 +0000858 else
859 // Output module-level string constants before any other constants.x
Chris Lattner83bb3d22004-01-14 23:36:54 +0000860 outputConstantStrings();
861
Reid Spencercb3595c2004-07-04 11:45:47 +0000862 for (unsigned pno = 0; pno != NumPlanes; pno++) {
863 const std::vector<const Value*> &Plane = Table.getPlane(pno);
864 if (!Plane.empty()) { // Skip empty type planes...
865 unsigned ValNo = 0;
866 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000867 ValNo += Table.getModuleLevel(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000868
869 if (hasNullValue(pno)) {
Reid Spencer0852c802004-07-04 11:46:15 +0000870 // Skip zero initializer
871 if (ValNo == 0)
872 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000873 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000874
875 // Write out constants in the plane
876 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000877 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000878 }
Chris Lattner00950542001-06-06 20:29:01 +0000879}
880
Chris Lattner6b252422003-10-16 18:28:50 +0000881static unsigned getEncodedLinkage(const GlobalValue *GV) {
882 switch (GV->getLinkage()) {
883 default: assert(0 && "Invalid linkage!");
884 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000885 case GlobalValue::WeakLinkage: return 1;
886 case GlobalValue::AppendingLinkage: return 2;
887 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000888 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000889 }
890}
891
Chris Lattner00950542001-06-06 20:29:01 +0000892void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000893 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Chris Lattner00950542001-06-06 20:29:01 +0000894
Chris Lattner70cc3392001-09-10 07:58:01 +0000895 // Output the types for the global variables in the module...
896 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000897 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000898 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000899
Chris Lattner22482a12003-10-18 06:30:21 +0000900 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
901 // bit5+ = Slot # for type
902 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000903 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Reid Spencerad89bd62004-07-25 18:07:36 +0000904 output_vbr(oSlot );
Chris Lattnerd70684f2001-09-18 04:01:05 +0000905
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000906 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000907 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000908 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000909 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000910 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000911 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000912 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000913 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000914
Chris Lattnerb5794002002-04-07 22:49:37 +0000915 // Output the types of the functions in this module...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000916 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000917 int Slot = Table.getSlot(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000918 assert(Slot != -1 && "Module const pool is broken!");
919 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000920 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +0000921 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000922 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
923
924 // Put out the list of dependent libraries for the Module
Reid Spencer5ac88122004-07-25 21:32:02 +0000925 Module::lib_iterator LI = M->lib_begin();
926 Module::lib_iterator LE = M->lib_end();
Reid Spencerad89bd62004-07-25 18:07:36 +0000927 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
928 for ( ; LI != LE; ++LI ) {
929 output(*LI, /*aligned=*/false);
930 }
931
932 // Output the target triple from the module
933 output(M->getTargetTriple(), /*aligned=*/ true);
Chris Lattner00950542001-06-06 20:29:01 +0000934}
935
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000936void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000937 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000938 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
939 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
940 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000941}
942
Chris Lattner186a1f72003-03-19 20:56:46 +0000943void BytecodeWriter::outputFunction(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000944 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
945 output_vbr(getEncodedLinkage(F));
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000946
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000947 // If this is an external function, there is nothing else to emit!
948 if (F->isExternal()) return;
Chris Lattner00950542001-06-06 20:29:01 +0000949
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000950 // Get slot information about the function...
951 Table.incorporateFunction(F);
952
953 if (Table.getCompactionTable().empty()) {
954 // Output information about the constants in the function if the compaction
955 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000956 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000957 } else {
958 // Otherwise, emit the compaction table.
959 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000960 }
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000961
962 // Output all of the instructions in the body of the function
963 outputInstructions(F);
964
965 // If needed, output the symbol table for the function...
966 outputSymbolTable(F->getSymbolTable());
967
968 Table.purgeFunction();
969}
970
971void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
972 const std::vector<const Value*> &Plane,
973 unsigned StartNo) {
974 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +0000975 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000976 assert(StartNo < End && "Cannot emit negative range!");
977 assert(StartNo < Plane.size() && End <= Plane.size());
978
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000979 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +0000980 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000981
Chris Lattner24102432004-01-18 22:35:34 +0000982 // Figure out which encoding to use. By far the most common case we have is
983 // to emit 0-2 entries in a compaction table plane.
984 switch (End-StartNo) {
985 case 0: // Avoid emitting two vbr's if possible.
986 case 1:
987 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +0000988 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +0000989 break;
990 default:
991 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +0000992 output_vbr((unsigned(End-StartNo) << 2) | 3);
993 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +0000994 break;
995 }
996
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000997 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +0000998 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000999}
1000
Reid Spencercb3595c2004-07-04 11:45:47 +00001001void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1002 // Get the compaction type table from the slot calculator
1003 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1004
1005 // The compaction types may have been uncompactified back to the
1006 // global types. If so, we just write an empty table
1007 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001008 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001009 return;
1010 }
1011
1012 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1013
1014 // Determine how many types to write
1015 unsigned NumTypes = CTypes.size() - StartNo;
1016
1017 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001018 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001019
1020 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001021 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001022}
1023
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001024void BytecodeWriter::outputCompactionTable() {
Reid Spencerad89bd62004-07-25 18:07:36 +00001025 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1026 true/*ElideIfEmpty*/);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001027 const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1028
1029 // First thing is first, emit the type compaction table if there is one.
Reid Spencercb3595c2004-07-04 11:45:47 +00001030 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001031
1032 for (unsigned i = 0, e = CT.size(); i != e; ++i)
Reid Spencercb3595c2004-07-04 11:45:47 +00001033 outputCompactionTablePlane(i, CT[i], 0);
Chris Lattner00950542001-06-06 20:29:01 +00001034}
1035
Chris Lattner00950542001-06-06 20:29:01 +00001036void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001037 // Do not output the Bytecode block for an empty symbol table, it just wastes
1038 // space!
Reid Spencer6ed81e22004-05-27 20:18:51 +00001039 if ( MST.isEmpty() ) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001040
Reid Spencerad89bd62004-07-25 18:07:36 +00001041 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +00001042 true/* ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001043
Reid Spencer250c4182004-08-17 02:59:02 +00001044 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001045 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001046
1047 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001048 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1049 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001050 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001051 output_typeid((unsigned)Table.getSlot(TI->second));
1052 output(TI->first, /*align=*/false);
Reid Spencer94f2df22004-05-25 17:29:59 +00001053 }
1054
1055 // Now do each of the type planes in order.
1056 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1057 PE = MST.plane_end(); PI != PE; ++PI) {
1058 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1059 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001060 int Slot;
1061
1062 if (I == End) continue; // Don't mess with an absent type...
1063
Reid Spencer250c4182004-08-17 02:59:02 +00001064 // Write the number of values in this plane
Reid Spencerad89bd62004-07-25 18:07:36 +00001065 output_vbr(MST.type_size(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001066
Reid Spencer250c4182004-08-17 02:59:02 +00001067 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001068 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001069 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001070 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001071
Reid Spencer250c4182004-08-17 02:59:02 +00001072 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001073 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001074 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001075 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001076 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001077 output_vbr((unsigned)Slot);
1078 output(I->first, false); // Don't force alignment...
Chris Lattner00950542001-06-06 20:29:01 +00001079 }
1080 }
1081}
1082
Reid Spencerad89bd62004-07-25 18:07:36 +00001083void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1084 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001085
Reid Spencerad89bd62004-07-25 18:07:36 +00001086 std::vector<unsigned char> Buffer;
1087 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
Chris Lattner00950542001-06-06 20:29:01 +00001088
1089 // This object populates buffer for us...
Reid Spencerad89bd62004-07-25 18:07:36 +00001090 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001091
Chris Lattnerce6ef112002-07-26 18:40:14 +00001092 // Keep track of how much we've written...
1093 BytesWritten += Buffer.size();
1094
Chris Lattnere8fdde12001-09-07 16:39:41 +00001095 // Okay, write the deque out to the ostream now... the deque is not
1096 // sequential in memory, however, so write out as much as possible in big
1097 // chunks, until we're done.
1098 //
Chris Lattner036de032004-06-25 20:52:10 +00001099
Reid Spencerad89bd62004-07-25 18:07:36 +00001100 std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001101 while (I != E) { // Loop until it's all written
1102 // Scan to see how big this chunk is...
1103 const unsigned char *ChunkPtr = &*I;
1104 const unsigned char *LastPtr = ChunkPtr;
1105 while (I != E) {
1106 const unsigned char *ThisPtr = &*++I;
Chris Lattner036de032004-06-25 20:52:10 +00001107 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
Chris Lattner5cb17412001-11-04 21:32:41 +00001108 break;
Chris Lattnere8fdde12001-09-07 16:39:41 +00001109 }
1110
1111 // Write out the chunk...
Chris Lattnerd6162282004-06-25 00:35:55 +00001112 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
Chris Lattnere8fdde12001-09-07 16:39:41 +00001113 }
Chris Lattner00950542001-06-06 20:29:01 +00001114 Out.flush();
1115}
Reid Spencere0125b62004-07-18 00:16:21 +00001116
1117// vim: sw=2 ai