blob: fe9212171a98aec94c7ad7b5e4be5eb0027910d3 [file] [log] [blame]
Chris Lattnerb0a59642004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
John Criswell482202a2003-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 Lattner2f7c9632001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Writer.h
11//
Chris Lattner2f7c9632001-06-06 20:29:01 +000012// Note that this file uses an unusual technique of outputting all the bytecode
Reid Spencerb2bdb942004-07-25 18:07:36 +000013// to a vector of unsigned char, then copies the vector to an ostream. The
Chris Lattner2f7c9632001-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 Lattner2f7c9632001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
20#include "WriterInternals.h"
Chris Lattner36d2c7c2002-07-23 19:56:44 +000021#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattner6229fbf2004-01-14 23:36:54 +000022#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
Reid Spencerb2bdb942004-07-25 18:07:36 +000024#include "llvm/Instructions.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000025#include "llvm/Module.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000026#include "llvm/SymbolTable.h"
Reid Spencerb2bdb942004-07-25 18:07:36 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
Chris Lattner0c530312004-01-10 19:10:01 +000030#include <cstring>
Chris Lattner2f7c9632001-06-06 20:29:01 +000031#include <algorithm>
Chris Lattnerdfe03462004-01-10 18:49:43 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Reid Spencerc3e43642004-08-17 07:45:14 +000034/// This value needs to be incremented every time the bytecode format changes
35/// so that the reader can distinguish which format of the bytecode file has
36/// been written.
37/// @brief The bytecode version number
38const unsigned BCVersionNum = 4;
39
Chris Lattner36d2c7c2002-07-23 19:56:44 +000040static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
41
Chris Lattner64eea742002-07-26 18:40:14 +000042static Statistic<>
Chris Lattnerbf3a0992002-10-01 22:38:41 +000043BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner36d2c7c2002-07-23 19:56:44 +000044
Reid Spencerb2bdb942004-07-25 18:07:36 +000045//===----------------------------------------------------------------------===//
46//=== Output Primitives ===//
47//===----------------------------------------------------------------------===//
48
49// output - If a position is specified, it must be in the valid portion of the
50// string... note that this should be inlined always so only the relevant IF
51// body should be included.
52inline void BytecodeWriter::output(unsigned i, int pos) {
53 if (pos == -1) { // Be endian clean, little endian is our friend
54 Out.push_back((unsigned char)i);
55 Out.push_back((unsigned char)(i >> 8));
56 Out.push_back((unsigned char)(i >> 16));
57 Out.push_back((unsigned char)(i >> 24));
58 } else {
59 Out[pos ] = (unsigned char)i;
60 Out[pos+1] = (unsigned char)(i >> 8);
61 Out[pos+2] = (unsigned char)(i >> 16);
62 Out[pos+3] = (unsigned char)(i >> 24);
63 }
64}
65
66inline void BytecodeWriter::output(int i) {
67 output((unsigned)i);
68}
69
70/// output_vbr - Output an unsigned value, by using the least number of bytes
71/// possible. This is useful because many of our "infinite" values are really
72/// very small most of the time; but can be large a few times.
73/// Data format used: If you read a byte with the high bit set, use the low
Reid Spencerc3e43642004-08-17 07:45:14 +000074/// seven bits as data and then read another byte.
Reid Spencerb2bdb942004-07-25 18:07:36 +000075inline void BytecodeWriter::output_vbr(uint64_t i) {
76 while (1) {
77 if (i < 0x80) { // done?
78 Out.push_back((unsigned char)i); // We know the high bit is clear...
79 return;
80 }
81
82 // Nope, we are bigger than a character, output the next 7 bits and set the
83 // high bit to say that there is more coming...
84 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
85 i >>= 7; // Shift out 7 bits now...
86 }
87}
88
89inline void BytecodeWriter::output_vbr(unsigned i) {
90 while (1) {
91 if (i < 0x80) { // done?
92 Out.push_back((unsigned char)i); // We know the high bit is clear...
93 return;
94 }
95
96 // Nope, we are bigger than a character, output the next 7 bits and set the
97 // high bit to say that there is more coming...
98 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
99 i >>= 7; // Shift out 7 bits now...
100 }
101}
102
103inline void BytecodeWriter::output_typeid(unsigned i) {
104 if (i <= 0x00FFFFFF)
105 this->output_vbr(i);
106 else {
107 this->output_vbr(0x00FFFFFF);
108 this->output_vbr(i);
109 }
110}
111
112inline void BytecodeWriter::output_vbr(int64_t i) {
113 if (i < 0)
114 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
115 else
116 output_vbr((uint64_t)i << 1); // Low order bit is clear.
117}
118
119
120inline void BytecodeWriter::output_vbr(int i) {
121 if (i < 0)
122 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
123 else
124 output_vbr((unsigned)i << 1); // Low order bit is clear.
125}
126
Reid Spencerc3e43642004-08-17 07:45:14 +0000127inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000128 unsigned Len = s.length();
129 output_vbr(Len ); // Strings may have an arbitrary length...
130 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerb2bdb942004-07-25 18:07:36 +0000131}
132
133inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
134 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
135}
136
137inline void BytecodeWriter::output_float(float& FloatVal) {
138 /// FIXME: This isn't optimal, it has size problems on some platforms
139 /// where FP is not IEEE.
140 union {
141 float f;
142 uint32_t i;
143 } FloatUnion;
144 FloatUnion.f = FloatVal;
145 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
146 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
149}
150
151inline void BytecodeWriter::output_double(double& DoubleVal) {
152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
154 union {
155 double d;
156 uint64_t i;
157 } DoubleUnion;
158 DoubleUnion.d = DoubleVal;
159 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
160 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
167}
168
169inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
170 bool elideIfEmpty, bool hasLongFormat )
171 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
172
173 if (HasLongFormat) {
174 w.output(ID);
175 w.output(0U); // For length in long format
176 } else {
177 w.output(0U); /// Place holder for ID and length for this block
178 }
179 Loc = w.size();
180}
181
Chris Lattnereddbc202004-10-14 01:35:17 +0000182inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
183 // of scope...
Reid Spencerb2bdb942004-07-25 18:07:36 +0000184 if (Loc == Writer.size() && ElideIfEmpty) {
185 // If the block is empty, and we are allowed to, do not emit the block at
186 // all!
187 Writer.resize(Writer.size()-(HasLongFormat?8:4));
188 return;
189 }
190
Reid Spencerb2bdb942004-07-25 18:07:36 +0000191 if (HasLongFormat)
192 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
193 else
194 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000195}
196
197//===----------------------------------------------------------------------===//
198//=== Constant Output ===//
199//===----------------------------------------------------------------------===//
200
201void BytecodeWriter::outputType(const Type *T) {
202 output_vbr((unsigned)T->getTypeID());
203
204 // That's all there is to handling primitive types...
205 if (T->isPrimitiveType()) {
206 return; // We might do this if we alias a prim type: %x = type int
207 }
208
209 switch (T->getTypeID()) { // Handle derived types now.
210 case Type::FunctionTyID: {
211 const FunctionType *MT = cast<FunctionType>(T);
212 int Slot = Table.getSlot(MT->getReturnType());
213 assert(Slot != -1 && "Type used but not available!!");
214 output_typeid((unsigned)Slot);
215
216 // Output the number of arguments to function (+1 if varargs):
217 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
218
219 // Output all of the arguments...
220 FunctionType::param_iterator I = MT->param_begin();
221 for (; I != MT->param_end(); ++I) {
222 Slot = Table.getSlot(*I);
223 assert(Slot != -1 && "Type used but not available!!");
224 output_typeid((unsigned)Slot);
225 }
226
227 // Terminate list with VoidTy if we are a varargs function...
228 if (MT->isVarArg())
229 output_typeid((unsigned)Type::VoidTyID);
230 break;
231 }
232
233 case Type::ArrayTyID: {
234 const ArrayType *AT = cast<ArrayType>(T);
235 int Slot = Table.getSlot(AT->getElementType());
236 assert(Slot != -1 && "Type used but not available!!");
237 output_typeid((unsigned)Slot);
238 //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
239
240 output_vbr(AT->getNumElements());
241 break;
242 }
243
Brian Gaeke02209042004-08-20 06:00:58 +0000244 case Type::PackedTyID: {
245 const PackedType *PT = cast<PackedType>(T);
246 int Slot = Table.getSlot(PT->getElementType());
247 assert(Slot != -1 && "Type used but not available!!");
248 output_typeid((unsigned)Slot);
249 output_vbr(PT->getNumElements());
250 break;
251 }
252
253
Reid Spencerb2bdb942004-07-25 18:07:36 +0000254 case Type::StructTyID: {
255 const StructType *ST = cast<StructType>(T);
256
257 // Output all of the element types...
258 for (StructType::element_iterator I = ST->element_begin(),
259 E = ST->element_end(); I != E; ++I) {
260 int Slot = Table.getSlot(*I);
261 assert(Slot != -1 && "Type used but not available!!");
262 output_typeid((unsigned)Slot);
263 }
264
265 // Terminate list with VoidTy
266 output_typeid((unsigned)Type::VoidTyID);
267 break;
268 }
269
270 case Type::PointerTyID: {
271 const PointerType *PT = cast<PointerType>(T);
272 int Slot = Table.getSlot(PT->getElementType());
273 assert(Slot != -1 && "Type used but not available!!");
274 output_typeid((unsigned)Slot);
275 break;
276 }
277
Chris Lattnereddbc202004-10-14 01:35:17 +0000278 case Type::OpaqueTyID:
Reid Spencerb2bdb942004-07-25 18:07:36 +0000279 // No need to emit anything, just the count of opaque types is enough.
280 break;
Reid Spencerb2bdb942004-07-25 18:07:36 +0000281
Reid Spencerb2bdb942004-07-25 18:07:36 +0000282 default:
283 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
284 << " Type '" << T->getDescription() << "'\n";
285 break;
286 }
287}
288
289void BytecodeWriter::outputConstant(const Constant *CPV) {
290 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
291 "Shouldn't output null constants!");
292
293 // We must check for a ConstantExpr before switching by type because
294 // a ConstantExpr can be of any type, and has no explicit value.
295 //
296 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
297 // FIXME: Encoding of constant exprs could be much more compact!
298 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
299 output_vbr(CE->getNumOperands()); // flags as an expr
300 output_vbr(CE->getOpcode()); // flags as an expr
301
302 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
303 int Slot = Table.getSlot(*OI);
304 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
305 output_vbr((unsigned)Slot);
306 Slot = Table.getSlot((*OI)->getType());
307 output_typeid((unsigned)Slot);
308 }
309 return;
310 } else {
311 output_vbr(0U); // flag as not a ConstantExpr
312 }
313
314 switch (CPV->getType()->getTypeID()) {
315 case Type::BoolTyID: // Boolean Types
316 if (cast<ConstantBool>(CPV)->getValue())
317 output_vbr(1U);
318 else
319 output_vbr(0U);
320 break;
321
322 case Type::UByteTyID: // Unsigned integer types...
323 case Type::UShortTyID:
324 case Type::UIntTyID:
325 case Type::ULongTyID:
326 output_vbr(cast<ConstantUInt>(CPV)->getValue());
327 break;
328
329 case Type::SByteTyID: // Signed integer types...
330 case Type::ShortTyID:
331 case Type::IntTyID:
332 case Type::LongTyID:
333 output_vbr(cast<ConstantSInt>(CPV)->getValue());
334 break;
335
336 case Type::ArrayTyID: {
337 const ConstantArray *CPA = cast<ConstantArray>(CPV);
338 assert(!CPA->isString() && "Constant strings should be handled specially!");
339
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000340 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000341 int Slot = Table.getSlot(CPA->getOperand(i));
342 assert(Slot != -1 && "Constant used but not available!!");
343 output_vbr((unsigned)Slot);
344 }
345 break;
346 }
347
Brian Gaeke02209042004-08-20 06:00:58 +0000348 case Type::PackedTyID: {
349 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
350
351 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
352 int Slot = Table.getSlot(CP->getOperand(i));
353 assert(Slot != -1 && "Constant used but not available!!");
354 output_vbr((unsigned)Slot);
355 }
356 break;
357 }
358
Reid Spencerb2bdb942004-07-25 18:07:36 +0000359 case Type::StructTyID: {
360 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerb2bdb942004-07-25 18:07:36 +0000361
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000362 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
363 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerb2bdb942004-07-25 18:07:36 +0000364 assert(Slot != -1 && "Constant used but not available!!");
365 output_vbr((unsigned)Slot);
366 }
367 break;
368 }
369
370 case Type::PointerTyID:
371 assert(0 && "No non-null, non-constant-expr constants allowed!");
372 abort();
373
374 case Type::FloatTyID: { // Floating point types...
375 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
376 output_float(Tmp);
377 break;
378 }
379 case Type::DoubleTyID: {
380 double Tmp = cast<ConstantFP>(CPV)->getValue();
381 output_double(Tmp);
382 break;
383 }
384
385 case Type::VoidTyID:
386 case Type::LabelTyID:
387 default:
388 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
389 << " type '" << *CPV->getType() << "'\n";
390 break;
391 }
392 return;
393}
394
395void BytecodeWriter::outputConstantStrings() {
396 SlotCalculator::string_iterator I = Table.string_begin();
397 SlotCalculator::string_iterator E = Table.string_end();
398 if (I == E) return; // No strings to emit
399
400 // If we have != 0 strings to emit, output them now. Strings are emitted into
401 // the 'void' type plane.
402 output_vbr(unsigned(E-I));
403 output_typeid(Type::VoidTyID);
404
405 // Emit all of the strings.
406 for (I = Table.string_begin(); I != E; ++I) {
407 const ConstantArray *Str = *I;
408 int Slot = Table.getSlot(Str->getType());
409 assert(Slot != -1 && "Constant string of unknown type?");
410 output_typeid((unsigned)Slot);
411
412 // Now that we emitted the type (which indicates the size of the string),
413 // emit all of the characters.
414 std::string Val = Str->getAsString();
415 output_data(Val.c_str(), Val.c_str()+Val.size());
416 }
417}
418
419//===----------------------------------------------------------------------===//
420//=== Instruction Output ===//
421//===----------------------------------------------------------------------===//
422typedef unsigned char uchar;
423
424// outputInstructionFormat0 - Output those wierd instructions that have a large
425// number of operands or have large operands themselves...
426//
427// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
428//
429void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
430 const SlotCalculator &Table,
431 unsigned Type) {
432 // Opcode must have top two bits clear...
433 output_vbr(Opcode << 2); // Instruction Opcode ID
434 output_typeid(Type); // Result type
435
436 unsigned NumArgs = I->getNumOperands();
437 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
438 isa<VAArgInst>(I)));
439
440 if (!isa<GetElementPtrInst>(&I)) {
441 for (unsigned i = 0; i < NumArgs; ++i) {
442 int Slot = Table.getSlot(I->getOperand(i));
443 assert(Slot >= 0 && "No slot number for value!?!?");
444 output_vbr((unsigned)Slot);
445 }
446
447 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
448 int Slot = Table.getSlot(I->getType());
449 assert(Slot != -1 && "Cast return type unknown?");
450 output_typeid((unsigned)Slot);
451 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
452 int Slot = Table.getSlot(VAI->getArgType());
453 assert(Slot != -1 && "VarArg argument type unknown?");
454 output_typeid((unsigned)Slot);
455 }
456
457 } else {
458 int Slot = Table.getSlot(I->getOperand(0));
459 assert(Slot >= 0 && "No slot number for value!?!?");
460 output_vbr(unsigned(Slot));
461
462 // We need to encode the type of sequential type indices into their slot #
463 unsigned Idx = 1;
464 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
465 Idx != NumArgs; ++TI, ++Idx) {
466 Slot = Table.getSlot(I->getOperand(Idx));
467 assert(Slot >= 0 && "No slot number for value!?!?");
468
469 if (isa<SequentialType>(*TI)) {
470 unsigned IdxId;
471 switch (I->getOperand(Idx)->getType()->getTypeID()) {
472 default: assert(0 && "Unknown index type!");
473 case Type::UIntTyID: IdxId = 0; break;
474 case Type::IntTyID: IdxId = 1; break;
475 case Type::ULongTyID: IdxId = 2; break;
476 case Type::LongTyID: IdxId = 3; break;
477 }
478 Slot = (Slot << 2) | IdxId;
479 }
480 output_vbr(unsigned(Slot));
481 }
482 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000483}
484
485
486// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
487// This are more annoying than most because the signature of the call does not
488// tell us anything about the types of the arguments in the varargs portion.
489// Because of this, we encode (as type 0) all of the argument types explicitly
490// before the argument value. This really sucks, but you shouldn't be using
491// varargs functions in your code! *death to printf*!
492//
493// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
494//
495void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
496 unsigned Opcode,
497 const SlotCalculator &Table,
498 unsigned Type) {
499 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
500 // Opcode must have top two bits clear...
501 output_vbr(Opcode << 2); // Instruction Opcode ID
502 output_typeid(Type); // Result type (varargs type)
503
504 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
505 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
506 unsigned NumParams = FTy->getNumParams();
507
508 unsigned NumFixedOperands;
509 if (isa<CallInst>(I)) {
510 // Output an operand for the callee and each fixed argument, then two for
511 // each variable argument.
512 NumFixedOperands = 1+NumParams;
513 } else {
514 assert(isa<InvokeInst>(I) && "Not call or invoke??");
515 // Output an operand for the callee and destinations, then two for each
516 // variable argument.
517 NumFixedOperands = 3+NumParams;
518 }
519 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
520
521 // The type for the function has already been emitted in the type field of the
522 // instruction. Just emit the slot # now.
523 for (unsigned i = 0; i != NumFixedOperands; ++i) {
524 int Slot = Table.getSlot(I->getOperand(i));
525 assert(Slot >= 0 && "No slot number for value!?!?");
526 output_vbr((unsigned)Slot);
527 }
528
529 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
530 // Output Arg Type ID
531 int Slot = Table.getSlot(I->getOperand(i)->getType());
532 assert(Slot >= 0 && "No slot number for value!?!?");
533 output_typeid((unsigned)Slot);
534
535 // Output arg ID itself
536 Slot = Table.getSlot(I->getOperand(i));
537 assert(Slot >= 0 && "No slot number for value!?!?");
538 output_vbr((unsigned)Slot);
539 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000540}
541
542
543// outputInstructionFormat1 - Output one operand instructions, knowing that no
544// operand index is >= 2^12.
545//
546inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
547 unsigned Opcode,
548 unsigned *Slots,
549 unsigned Type) {
550 // bits Instruction format:
551 // --------------------------
552 // 01-00: Opcode type, fixed to 1.
553 // 07-02: Opcode
554 // 19-08: Resulting type plane
555 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
556 //
557 unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
558 // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
559 output(Bits);
560}
561
562
563// outputInstructionFormat2 - Output two operand instructions, knowing that no
564// operand index is >= 2^8.
565//
566inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
567 unsigned Opcode,
568 unsigned *Slots,
569 unsigned Type) {
570 // bits Instruction format:
571 // --------------------------
572 // 01-00: Opcode type, fixed to 2.
573 // 07-02: Opcode
574 // 15-08: Resulting type plane
575 // 23-16: Operand #1
576 // 31-24: Operand #2
577 //
578 unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
579 (Slots[0] << 16) | (Slots[1] << 24);
580 // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " "
581 // << Slots[1] << endl;
582 output(Bits);
583}
584
585
586// outputInstructionFormat3 - Output three operand instructions, knowing that no
587// operand index is >= 2^6.
588//
589inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
590 unsigned Opcode,
591 unsigned *Slots,
592 unsigned Type) {
593 // bits Instruction format:
594 // --------------------------
595 // 01-00: Opcode type, fixed to 3.
596 // 07-02: Opcode
597 // 13-08: Resulting type plane
598 // 19-14: Operand #1
599 // 25-20: Operand #2
600 // 31-26: Operand #3
601 //
602 unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
603 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
604 //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " "
605 // << Slots[1] << " " << Slots[2] << endl;
606 output(Bits);
607}
608
609void BytecodeWriter::outputInstruction(const Instruction &I) {
610 assert(I.getOpcode() < 62 && "Opcode too big???");
611 unsigned Opcode = I.getOpcode();
612 unsigned NumOperands = I.getNumOperands();
613
614 // Encode 'volatile load' as 62 and 'volatile store' as 63.
615 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
616 Opcode = 62;
617 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
618 Opcode = 63;
619
620 // Figure out which type to encode with the instruction. Typically we want
621 // the type of the first parameter, as opposed to the type of the instruction
622 // (for example, with setcc, we always know it returns bool, but the type of
623 // the first param is actually interesting). But if we have no arguments
624 // we take the type of the instruction itself.
625 //
626 const Type *Ty;
627 switch (I.getOpcode()) {
628 case Instruction::Select:
629 case Instruction::Malloc:
630 case Instruction::Alloca:
631 Ty = I.getType(); // These ALWAYS want to encode the return type
632 break;
633 case Instruction::Store:
634 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
635 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
636 break;
637 default: // Otherwise use the default behavior...
638 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
639 break;
640 }
641
642 unsigned Type;
643 int Slot = Table.getSlot(Ty);
644 assert(Slot != -1 && "Type not available!!?!");
645 Type = (unsigned)Slot;
646
647 // Varargs calls and invokes are encoded entirely different from any other
648 // instructions.
649 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
650 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
651 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
652 outputInstrVarArgsCall(CI, Opcode, Table, Type);
653 return;
654 }
655 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
656 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
657 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
658 outputInstrVarArgsCall(II, Opcode, Table, Type);
659 return;
660 }
661 }
662
663 if (NumOperands <= 3) {
664 // Make sure that we take the type number into consideration. We don't want
665 // to overflow the field size for the instruction format we select.
666 //
667 unsigned MaxOpSlot = Type;
668 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
669
670 for (unsigned i = 0; i != NumOperands; ++i) {
671 int slot = Table.getSlot(I.getOperand(i));
672 assert(slot != -1 && "Broken bytecode!");
673 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
674 Slots[i] = unsigned(slot);
675 }
676
677 // Handle the special cases for various instructions...
678 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
679 // Cast has to encode the destination type as the second argument in the
680 // packet, or else we won't know what type to cast to!
681 Slots[1] = Table.getSlot(I.getType());
682 assert(Slots[1] != ~0U && "Cast return type unknown?");
683 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
684 NumOperands++;
685 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
686 Slots[1] = Table.getSlot(VANI->getArgType());
687 assert(Slots[1] != ~0U && "va_next return type unknown?");
688 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
689 NumOperands++;
690 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
691 // We need to encode the type of sequential type indices into their slot #
692 unsigned Idx = 1;
693 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
694 I != E; ++I, ++Idx)
695 if (isa<SequentialType>(*I)) {
696 unsigned IdxId;
697 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
698 default: assert(0 && "Unknown index type!");
699 case Type::UIntTyID: IdxId = 0; break;
700 case Type::IntTyID: IdxId = 1; break;
701 case Type::ULongTyID: IdxId = 2; break;
702 case Type::LongTyID: IdxId = 3; break;
703 }
704 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
705 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
706 }
707 }
708
709 // Decide which instruction encoding to use. This is determined primarily
710 // by the number of operands, and secondarily by whether or not the max
711 // operand will fit into the instruction encoding. More operands == fewer
712 // bits per operand.
713 //
714 switch (NumOperands) {
715 case 0:
716 case 1:
717 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
718 outputInstructionFormat1(&I, Opcode, Slots, Type);
719 return;
720 }
721 break;
722
723 case 2:
724 if (MaxOpSlot < (1 << 8)) {
725 outputInstructionFormat2(&I, Opcode, Slots, Type);
726 return;
727 }
728 break;
729
730 case 3:
731 if (MaxOpSlot < (1 << 6)) {
732 outputInstructionFormat3(&I, Opcode, Slots, Type);
733 return;
734 }
735 break;
736 default:
737 break;
738 }
739 }
740
741 // If we weren't handled before here, we either have a large number of
742 // operands or a large operand index that we are referring to.
743 outputInstructionFormat0(&I, Opcode, Table, Type);
744}
745
746//===----------------------------------------------------------------------===//
747//=== Block Output ===//
748//===----------------------------------------------------------------------===//
749
750BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer0aff01a2004-05-26 07:37:11 +0000751 : Out(o), Table(M) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000752
Chris Lattner6229fbf2004-01-14 23:36:54 +0000753 // Emit the signature...
754 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerb2bdb942004-07-25 18:07:36 +0000755 output_data(Sig, Sig+4);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000756
757 // Emit the top level CLASS block.
Reid Spencerb2bdb942004-07-25 18:07:36 +0000758 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000759
Chris Lattner55a07ad2003-08-24 13:47:36 +0000760 bool isBigEndian = M->getEndianness() == Module::BigEndian;
761 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
762 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
763 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner428bf5a2003-03-19 20:56:46 +0000764
Chris Lattner15701e82004-04-05 01:27:26 +0000765 // Output the version identifier... we are currently on bytecode version #2,
766 // which corresponds to LLVM v1.3.
Reid Spencerc3e43642004-08-17 07:45:14 +0000767 unsigned Version = (BCVersionNum << 4) |
768 (unsigned)isBigEndian | (hasLongPointers << 1) |
769 (hasNoEndianness << 2) |
770 (hasNoPointerSize << 3);
Reid Spencerb2bdb942004-07-25 18:07:36 +0000771 output_vbr(Version);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000772
Reid Spencera52b0002004-07-04 11:45:47 +0000773 // The Global type plane comes first
Chris Lattner428bf5a2003-03-19 20:56:46 +0000774 {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000775 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencera52b0002004-07-04 11:45:47 +0000776 outputTypes(Type::FirstDerivedTyID);
Chris Lattner428bf5a2003-03-19 20:56:46 +0000777 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000778
Chris Lattner428bf5a2003-03-19 20:56:46 +0000779 // The ModuleInfoBlock follows directly after the type information
Chris Lattnerb97ef9f2001-09-07 16:39:41 +0000780 outputModuleInfoBlock(M);
781
Chris Lattner428bf5a2003-03-19 20:56:46 +0000782 // Output module level constants, used for global variable initializers
783 outputConstants(false);
784
Chris Lattner6915f8f2002-04-07 22:49:37 +0000785 // Do the whole module now! Process each function at a time...
Chris Lattner7076ff22002-06-25 16:13:21 +0000786 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner428bf5a2003-03-19 20:56:46 +0000787 outputFunction(I);
Chris Lattnerb97ef9f2001-09-07 16:39:41 +0000788
789 // If needed, output the symbol table for the module...
Chris Lattner98cf1f52002-11-20 18:36:02 +0000790 outputSymbolTable(M->getSymbolTable());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000791}
792
Reid Spencera52b0002004-07-04 11:45:47 +0000793void BytecodeWriter::outputTypes(unsigned TypeNum)
794{
795 // Write the type plane for types first because earlier planes (e.g. for a
796 // primitive type like float) may have constants constructed using types
797 // coming later (e.g., via getelementptr from a pointer type). The type
798 // plane is needed before types can be fwd or bkwd referenced.
799 const std::vector<const Type*>& Types = Table.getTypes();
800 assert(!Types.empty() && "No types at all?");
801 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
802
803 unsigned NumEntries = Types.size() - TypeNum;
804
805 // Output type header: [num entries]
Reid Spencerb2bdb942004-07-25 18:07:36 +0000806 output_vbr(NumEntries);
Reid Spencera52b0002004-07-04 11:45:47 +0000807
808 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
809 outputType(Types[i]);
810}
811
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000812// Helper function for outputConstants().
813// Writes out all the constants in the plane Plane starting at entry StartNo.
814//
815void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
816 &Plane, unsigned StartNo) {
817 unsigned ValNo = StartNo;
818
Chris Lattner6229fbf2004-01-14 23:36:54 +0000819 // Scan through and ignore function arguments, global values, and constant
820 // strings.
821 for (; ValNo < Plane.size() &&
822 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
823 (isa<ConstantArray>(Plane[ValNo]) &&
824 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000825 /*empty*/;
826
827 unsigned NC = ValNo; // Number of constants
Reid Spencera52b0002004-07-04 11:45:47 +0000828 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000829 /*empty*/;
830 NC -= ValNo; // Convert from index into count
831 if (NC == 0) return; // Skip empty type planes...
832
Chris Lattner9a38c78f2004-01-14 16:54:21 +0000833 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
834 // more compactly.
835
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000836 // Output type header: [num entries][type id number]
837 //
Reid Spencerb2bdb942004-07-25 18:07:36 +0000838 output_vbr(NC);
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000839
840 // Output the Type ID Number...
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +0000841 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000842 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000843 output_typeid((unsigned)Slot);
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000844
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000845 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
846 const Value *V = Plane[i];
Reid Spencer51fe3362004-07-18 00:16:21 +0000847 if (const Constant *C = dyn_cast<Constant>(V)) {
848 outputConstant(C);
Vikram S. Advec1b6474a2002-07-14 23:07:51 +0000849 }
850 }
851}
852
Chris Lattner677af4a2004-01-17 23:25:43 +0000853static inline bool hasNullValue(unsigned TyID) {
Reid Spencera52b0002004-07-04 11:45:47 +0000854 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Chris Lattner677af4a2004-01-17 23:25:43 +0000855}
856
Chris Lattner57698e22002-03-26 18:01:55 +0000857void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000858 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner4c572672004-01-15 21:06:57 +0000859 true /* Elide block if empty */);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000860
861 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattner4a207912003-05-22 18:35:38 +0000862
Reid Spencer51fe3362004-07-18 00:16:21 +0000863 if (isFunction)
864 // Output the type plane before any constants!
Reid Spencera52b0002004-07-04 11:45:47 +0000865 outputTypes( Table.getModuleTypeLevel() );
Reid Spencer51fe3362004-07-18 00:16:21 +0000866 else
867 // Output module-level string constants before any other constants.x
Chris Lattner6229fbf2004-01-14 23:36:54 +0000868 outputConstantStrings();
869
Reid Spencera52b0002004-07-04 11:45:47 +0000870 for (unsigned pno = 0; pno != NumPlanes; pno++) {
871 const std::vector<const Value*> &Plane = Table.getPlane(pno);
872 if (!Plane.empty()) { // Skip empty type planes...
873 unsigned ValNo = 0;
874 if (isFunction) // Don't re-emit module constants
Reid Spencer2fa95bc2004-07-04 11:46:15 +0000875 ValNo += Table.getModuleLevel(pno);
Reid Spencera52b0002004-07-04 11:45:47 +0000876
877 if (hasNullValue(pno)) {
Reid Spencer2fa95bc2004-07-04 11:46:15 +0000878 // Skip zero initializer
879 if (ValNo == 0)
880 ValNo = 1;
Chris Lattner4a207912003-05-22 18:35:38 +0000881 }
Reid Spencera52b0002004-07-04 11:45:47 +0000882
883 // Write out constants in the plane
884 outputConstantsInPlane(Plane, ValNo);
Chris Lattner4a207912003-05-22 18:35:38 +0000885 }
Reid Spencera52b0002004-07-04 11:45:47 +0000886 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000887}
888
Chris Lattner2d05c602003-10-16 18:28:50 +0000889static unsigned getEncodedLinkage(const GlobalValue *GV) {
890 switch (GV->getLinkage()) {
891 default: assert(0 && "Invalid linkage!");
892 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner2d05c602003-10-16 18:28:50 +0000893 case GlobalValue::WeakLinkage: return 1;
894 case GlobalValue::AppendingLinkage: return 2;
895 case GlobalValue::InternalLinkage: return 3;
Chris Lattnerdc832932003-10-18 06:30:21 +0000896 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner2d05c602003-10-16 18:28:50 +0000897 }
898}
899
Chris Lattner2f7c9632001-06-06 20:29:01 +0000900void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000901 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000902
Chris Lattnerda975502001-09-10 07:58:01 +0000903 // Output the types for the global variables in the module...
904 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +0000905 int Slot = Table.getSlot(I->getType());
Chris Lattnerda975502001-09-10 07:58:01 +0000906 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattner37798642001-09-18 04:01:05 +0000907
Chris Lattnerdc832932003-10-18 06:30:21 +0000908 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
909 // bit5+ = Slot # for type
910 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner4ba8a8d2004-06-25 20:52:10 +0000911 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Reid Spencerb2bdb942004-07-25 18:07:36 +0000912 output_vbr(oSlot );
Chris Lattner37798642001-09-18 04:01:05 +0000913
Chris Lattner81125b62001-10-13 06:48:38 +0000914 // If we have an initializer, output it now.
Chris Lattner7076ff22002-06-25 16:13:21 +0000915 if (I->hasInitializer()) {
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +0000916 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattner37798642001-09-18 04:01:05 +0000917 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000918 output_vbr((unsigned)Slot);
Chris Lattner37798642001-09-18 04:01:05 +0000919 }
Chris Lattnerda975502001-09-10 07:58:01 +0000920 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000921 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattnerda975502001-09-10 07:58:01 +0000922
Chris Lattner6915f8f2002-04-07 22:49:37 +0000923 // Output the types of the functions in this module...
Chris Lattner4cee8d82001-06-27 23:41:11 +0000924 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +0000925 int Slot = Table.getSlot(I->getType());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000926 assert(Slot != -1 && "Module const pool is broken!");
927 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Reid Spencerb2bdb942004-07-25 18:07:36 +0000928 output_typeid((unsigned)Slot);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000929 }
Reid Spencerb2bdb942004-07-25 18:07:36 +0000930 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
931
932 // Put out the list of dependent libraries for the Module
Reid Spencerb95885b2004-07-25 21:32:02 +0000933 Module::lib_iterator LI = M->lib_begin();
934 Module::lib_iterator LE = M->lib_end();
Reid Spencerb2bdb942004-07-25 18:07:36 +0000935 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
936 for ( ; LI != LE; ++LI ) {
Reid Spencerc3e43642004-08-17 07:45:14 +0000937 output(*LI);
Reid Spencerb2bdb942004-07-25 18:07:36 +0000938 }
939
940 // Output the target triple from the module
Reid Spencerc3e43642004-08-17 07:45:14 +0000941 output(M->getTargetTriple());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000942}
943
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000944void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000945 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000946 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
947 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
948 outputInstruction(*I);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000949}
950
Chris Lattner428bf5a2003-03-19 20:56:46 +0000951void BytecodeWriter::outputFunction(const Function *F) {
Reid Spencerb2bdb942004-07-25 18:07:36 +0000952 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
953 output_vbr(getEncodedLinkage(F));
Chris Lattner22637332001-11-26 18:56:10 +0000954
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000955 // If this is an external function, there is nothing else to emit!
956 if (F->isExternal()) return;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000957
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000958 // Get slot information about the function...
959 Table.incorporateFunction(F);
960
961 if (Table.getCompactionTable().empty()) {
962 // Output information about the constants in the function if the compaction
963 // table is not being used.
Chris Lattnerb97ef9f2001-09-07 16:39:41 +0000964 outputConstants(true);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000965 } else {
966 // Otherwise, emit the compaction table.
967 outputCompactionTable();
Chris Lattnerb97ef9f2001-09-07 16:39:41 +0000968 }
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000969
970 // Output all of the instructions in the body of the function
971 outputInstructions(F);
972
973 // If needed, output the symbol table for the function...
974 outputSymbolTable(F->getSymbolTable());
975
976 Table.purgeFunction();
977}
978
979void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
980 const std::vector<const Value*> &Plane,
981 unsigned StartNo) {
982 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattnera3953242004-01-20 00:54:06 +0000983 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000984 assert(StartNo < End && "Cannot emit negative range!");
985 assert(StartNo < Plane.size() && End <= Plane.size());
986
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000987 // Do not emit the null initializer!
Reid Spencera52b0002004-07-04 11:45:47 +0000988 ++StartNo;
Chris Lattnerbc02f4c2004-01-18 21:08:52 +0000989
Chris Lattner5a66bb72004-01-18 22:35:34 +0000990 // Figure out which encoding to use. By far the most common case we have is
991 // to emit 0-2 entries in a compaction table plane.
992 switch (End-StartNo) {
993 case 0: // Avoid emitting two vbr's if possible.
994 case 1:
995 case 2:
Reid Spencerb2bdb942004-07-25 18:07:36 +0000996 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner5a66bb72004-01-18 22:35:34 +0000997 break;
998 default:
999 // Output the number of things.
Reid Spencerb2bdb942004-07-25 18:07:36 +00001000 output_vbr((unsigned(End-StartNo) << 2) | 3);
1001 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner5a66bb72004-01-18 22:35:34 +00001002 break;
1003 }
1004
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001005 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerb2bdb942004-07-25 18:07:36 +00001006 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001007}
1008
Reid Spencera52b0002004-07-04 11:45:47 +00001009void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1010 // Get the compaction type table from the slot calculator
1011 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1012
1013 // The compaction types may have been uncompactified back to the
1014 // global types. If so, we just write an empty table
1015 if (CTypes.size() == 0 ) {
Reid Spencerb2bdb942004-07-25 18:07:36 +00001016 output_vbr(0U);
Reid Spencera52b0002004-07-04 11:45:47 +00001017 return;
1018 }
1019
1020 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1021
1022 // Determine how many types to write
1023 unsigned NumTypes = CTypes.size() - StartNo;
1024
1025 // Output the number of types.
Reid Spencerb2bdb942004-07-25 18:07:36 +00001026 output_vbr(NumTypes);
Reid Spencera52b0002004-07-04 11:45:47 +00001027
1028 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerb2bdb942004-07-25 18:07:36 +00001029 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencera52b0002004-07-04 11:45:47 +00001030}
1031
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001032void BytecodeWriter::outputCompactionTable() {
Reid Spencer248c06d2004-08-27 00:38:44 +00001033 // Avoid writing the compaction table at all if there is no content.
1034 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1035 (!Table.CompactionTableIsEmpty())) {
1036 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1037 true/*ElideIfEmpty*/);
1038 const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1039
1040 // First things first, emit the type compaction table if there is one.
1041 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnerbc02f4c2004-01-18 21:08:52 +00001042
Reid Spencer248c06d2004-08-27 00:38:44 +00001043 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1044 outputCompactionTablePlane(i, CT[i], 0);
1045 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00001046}
1047
Chris Lattner2f7c9632001-06-06 20:29:01 +00001048void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattnera2bfab82004-01-10 19:56:59 +00001049 // Do not output the Bytecode block for an empty symbol table, it just wastes
1050 // space!
Reid Spencerf2f34b32004-05-27 20:18:51 +00001051 if ( MST.isEmpty() ) return;
Chris Lattnera2bfab82004-01-10 19:56:59 +00001052
Reid Spencerb2bdb942004-07-25 18:07:36 +00001053 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattner4c572672004-01-15 21:06:57 +00001054 true/* ElideIfEmpty*/);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001055
Reid Spencerf8a18092004-08-17 02:59:02 +00001056 // Write the number of types
Reid Spencerb2bdb942004-07-25 18:07:36 +00001057 output_vbr(MST.num_types());
Reid Spencerf8a18092004-08-17 02:59:02 +00001058
1059 // Write each of the types
Reid Spencer660ea5f2004-05-25 17:29:59 +00001060 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1061 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencerf8a18092004-08-17 02:59:02 +00001062 // Symtab entry:[def slot #][name]
Reid Spencerb2bdb942004-07-25 18:07:36 +00001063 output_typeid((unsigned)Table.getSlot(TI->second));
Reid Spencerc3e43642004-08-17 07:45:14 +00001064 output(TI->first);
Reid Spencer660ea5f2004-05-25 17:29:59 +00001065 }
1066
1067 // Now do each of the type planes in order.
1068 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1069 PE = MST.plane_end(); PI != PE; ++PI) {
1070 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1071 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001072 int Slot;
1073
1074 if (I == End) continue; // Don't mess with an absent type...
1075
Reid Spencerf8a18092004-08-17 02:59:02 +00001076 // Write the number of values in this plane
Reid Spencerb2bdb942004-07-25 18:07:36 +00001077 output_vbr(MST.type_size(PI->first));
Chris Lattner2f7c9632001-06-06 20:29:01 +00001078
Reid Spencerf8a18092004-08-17 02:59:02 +00001079 // Write the slot number of the type for this plane
Reid Spencer660ea5f2004-05-25 17:29:59 +00001080 Slot = Table.getSlot(PI->first);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001081 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerb2bdb942004-07-25 18:07:36 +00001082 output_typeid((unsigned)Slot);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001083
Reid Spencerf8a18092004-08-17 02:59:02 +00001084 // Write each of the values in this plane
Chris Lattner4cee8d82001-06-27 23:41:11 +00001085 for (; I != End; ++I) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001086 // Symtab entry: [def slot #][name]
Alkis Evlogimenos8faf8d92003-10-17 02:02:40 +00001087 Slot = Table.getSlot(I->second);
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001088 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerb2bdb942004-07-25 18:07:36 +00001089 output_vbr((unsigned)Slot);
Reid Spencerc3e43642004-08-17 07:45:14 +00001090 output(I->first);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001091 }
1092 }
1093}
1094
Reid Spencerb2bdb942004-07-25 18:07:36 +00001095void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1096 assert(M && "You can't write a null module!!");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001097
Reid Spencerb2bdb942004-07-25 18:07:36 +00001098 std::vector<unsigned char> Buffer;
1099 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
Chris Lattner2f7c9632001-06-06 20:29:01 +00001100
1101 // This object populates buffer for us...
Reid Spencerb2bdb942004-07-25 18:07:36 +00001102 BytecodeWriter BCW(Buffer, M);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001103
Chris Lattner64eea742002-07-26 18:40:14 +00001104 // Keep track of how much we've written...
1105 BytesWritten += Buffer.size();
1106
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001107 // Okay, write the deque out to the ostream now... the deque is not
1108 // sequential in memory, however, so write out as much as possible in big
1109 // chunks, until we're done.
1110 //
Chris Lattner4ba8a8d2004-06-25 20:52:10 +00001111
Reid Spencerb2bdb942004-07-25 18:07:36 +00001112 std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001113 while (I != E) { // Loop until it's all written
1114 // Scan to see how big this chunk is...
1115 const unsigned char *ChunkPtr = &*I;
1116 const unsigned char *LastPtr = ChunkPtr;
1117 while (I != E) {
1118 const unsigned char *ThisPtr = &*++I;
Chris Lattner4ba8a8d2004-06-25 20:52:10 +00001119 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
Chris Lattnerdc194d52001-11-04 21:32:41 +00001120 break;
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001121 }
1122
1123 // Write out the chunk...
Chris Lattnerccd8ed12004-06-25 00:35:55 +00001124 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
Chris Lattnerb97ef9f2001-09-07 16:39:41 +00001125 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00001126 Out.flush();
1127}
Reid Spencer51fe3362004-07-18 00:16:21 +00001128
1129// vim: sw=2 ai