blob: 4d988f969b6b155796aed6491371678d3a16caae [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000030#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000031#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Reid Spencer38d54be2004-08-17 07:45:14 +000034/// This value needs to be incremented every time the bytecode format changes
35/// so that the reader can distinguish which format of the bytecode file has
36/// been written.
37/// @brief The bytecode version number
Chris Lattnera79e7cc2004-10-16 18:18:16 +000038const unsigned BCVersionNum = 5;
Reid Spencer38d54be2004-08-17 07:45:14 +000039
Chris Lattner635cd932002-07-23 19:56:44 +000040static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
41
Chris Lattnerce6ef112002-07-26 18:40:14 +000042static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000043BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000044
Reid Spencerad89bd62004-07-25 18:07:36 +000045//===----------------------------------------------------------------------===//
46//=== Output Primitives ===//
47//===----------------------------------------------------------------------===//
48
49// output - If a position is specified, it must be in the valid portion of the
50// string... note that this should be inlined always so only the relevant IF
51// body should be included.
52inline void BytecodeWriter::output(unsigned i, int pos) {
53 if (pos == -1) { // Be endian clean, little endian is our friend
54 Out.push_back((unsigned char)i);
55 Out.push_back((unsigned char)(i >> 8));
56 Out.push_back((unsigned char)(i >> 16));
57 Out.push_back((unsigned char)(i >> 24));
58 } else {
59 Out[pos ] = (unsigned char)i;
60 Out[pos+1] = (unsigned char)(i >> 8);
61 Out[pos+2] = (unsigned char)(i >> 16);
62 Out[pos+3] = (unsigned char)(i >> 24);
63 }
64}
65
66inline void BytecodeWriter::output(int i) {
67 output((unsigned)i);
68}
69
70/// output_vbr - Output an unsigned value, by using the least number of bytes
71/// possible. This is useful because many of our "infinite" values are really
72/// very small most of the time; but can be large a few times.
73/// Data format used: If you read a byte with the high bit set, use the low
Reid Spencer38d54be2004-08-17 07:45:14 +000074/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000075inline void BytecodeWriter::output_vbr(uint64_t i) {
76 while (1) {
77 if (i < 0x80) { // done?
78 Out.push_back((unsigned char)i); // We know the high bit is clear...
79 return;
80 }
81
82 // Nope, we are bigger than a character, output the next 7 bits and set the
83 // high bit to say that there is more coming...
84 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
85 i >>= 7; // Shift out 7 bits now...
86 }
87}
88
89inline void BytecodeWriter::output_vbr(unsigned i) {
90 while (1) {
91 if (i < 0x80) { // done?
92 Out.push_back((unsigned char)i); // We know the high bit is clear...
93 return;
94 }
95
96 // Nope, we are bigger than a character, output the next 7 bits and set the
97 // high bit to say that there is more coming...
98 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
99 i >>= 7; // Shift out 7 bits now...
100 }
101}
102
103inline void BytecodeWriter::output_typeid(unsigned i) {
104 if (i <= 0x00FFFFFF)
105 this->output_vbr(i);
106 else {
107 this->output_vbr(0x00FFFFFF);
108 this->output_vbr(i);
109 }
110}
111
112inline void BytecodeWriter::output_vbr(int64_t i) {
113 if (i < 0)
114 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
115 else
116 output_vbr((uint64_t)i << 1); // Low order bit is clear.
117}
118
119
120inline void BytecodeWriter::output_vbr(int i) {
121 if (i < 0)
122 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
123 else
124 output_vbr((unsigned)i << 1); // Low order bit is clear.
125}
126
Reid Spencer38d54be2004-08-17 07:45:14 +0000127inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000128 unsigned Len = s.length();
129 output_vbr(Len ); // Strings may have an arbitrary length...
130 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000131}
132
133inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
134 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
135}
136
137inline void BytecodeWriter::output_float(float& FloatVal) {
138 /// FIXME: This isn't optimal, it has size problems on some platforms
139 /// where FP is not IEEE.
140 union {
141 float f;
142 uint32_t i;
143 } FloatUnion;
144 FloatUnion.f = FloatVal;
145 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
146 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
149}
150
151inline void BytecodeWriter::output_double(double& DoubleVal) {
152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
154 union {
155 double d;
156 uint64_t i;
157 } DoubleUnion;
158 DoubleUnion.d = DoubleVal;
159 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
160 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
167}
168
169inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
170 bool elideIfEmpty, bool hasLongFormat )
171 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
172
173 if (HasLongFormat) {
174 w.output(ID);
175 w.output(0U); // For length in long format
176 } else {
177 w.output(0U); /// Place holder for ID and length for this block
178 }
179 Loc = w.size();
180}
181
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000182inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
183 // of scope...
Reid Spencerad89bd62004-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 Spencerad89bd62004-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 Spencerad89bd62004-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);
Reid Spencerad89bd62004-07-25 18:07:36 +0000238 output_vbr(AT->getNumElements());
239 break;
240 }
241
Brian Gaeke715c90b2004-08-20 06:00:58 +0000242 case Type::PackedTyID: {
243 const PackedType *PT = cast<PackedType>(T);
244 int Slot = Table.getSlot(PT->getElementType());
245 assert(Slot != -1 && "Type used but not available!!");
246 output_typeid((unsigned)Slot);
247 output_vbr(PT->getNumElements());
248 break;
249 }
250
251
Reid Spencerad89bd62004-07-25 18:07:36 +0000252 case Type::StructTyID: {
253 const StructType *ST = cast<StructType>(T);
254
255 // Output all of the element types...
256 for (StructType::element_iterator I = ST->element_begin(),
257 E = ST->element_end(); I != E; ++I) {
258 int Slot = Table.getSlot(*I);
259 assert(Slot != -1 && "Type used but not available!!");
260 output_typeid((unsigned)Slot);
261 }
262
263 // Terminate list with VoidTy
264 output_typeid((unsigned)Type::VoidTyID);
265 break;
266 }
267
268 case Type::PointerTyID: {
269 const PointerType *PT = cast<PointerType>(T);
270 int Slot = Table.getSlot(PT->getElementType());
271 assert(Slot != -1 && "Type used but not available!!");
272 output_typeid((unsigned)Slot);
273 break;
274 }
275
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000276 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000277 // No need to emit anything, just the count of opaque types is enough.
278 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000279
Reid Spencerad89bd62004-07-25 18:07:36 +0000280 default:
281 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
282 << " Type '" << T->getDescription() << "'\n";
283 break;
284 }
285}
286
287void BytecodeWriter::outputConstant(const Constant *CPV) {
288 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
289 "Shouldn't output null constants!");
290
291 // We must check for a ConstantExpr before switching by type because
292 // a ConstantExpr can be of any type, and has no explicit value.
293 //
294 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
295 // FIXME: Encoding of constant exprs could be much more compact!
296 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000297 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerad89bd62004-07-25 18:07:36 +0000298 output_vbr(CE->getOpcode()); // flags as an expr
299
300 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
301 int Slot = Table.getSlot(*OI);
302 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
303 output_vbr((unsigned)Slot);
304 Slot = Table.getSlot((*OI)->getType());
305 output_typeid((unsigned)Slot);
306 }
307 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000308 } else if (isa<UndefValue>(CPV)) {
309 output_vbr(1U); // 1 -> UndefValue constant.
310 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000311 } 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
Brian Gaeke715c90b2004-08-20 06:00:58 +0000349 case Type::PackedTyID: {
350 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
351
352 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
353 int Slot = Table.getSlot(CP->getOperand(i));
354 assert(Slot != -1 && "Constant used but not available!!");
355 output_vbr((unsigned)Slot);
356 }
357 break;
358 }
359
Reid Spencerad89bd62004-07-25 18:07:36 +0000360 case Type::StructTyID: {
361 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000362
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000363 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
364 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000365 assert(Slot != -1 && "Constant used but not available!!");
366 output_vbr((unsigned)Slot);
367 }
368 break;
369 }
370
371 case Type::PointerTyID:
372 assert(0 && "No non-null, non-constant-expr constants allowed!");
373 abort();
374
375 case Type::FloatTyID: { // Floating point types...
376 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
377 output_float(Tmp);
378 break;
379 }
380 case Type::DoubleTyID: {
381 double Tmp = cast<ConstantFP>(CPV)->getValue();
382 output_double(Tmp);
383 break;
384 }
385
386 case Type::VoidTyID:
387 case Type::LabelTyID:
388 default:
389 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
390 << " type '" << *CPV->getType() << "'\n";
391 break;
392 }
393 return;
394}
395
396void BytecodeWriter::outputConstantStrings() {
397 SlotCalculator::string_iterator I = Table.string_begin();
398 SlotCalculator::string_iterator E = Table.string_end();
399 if (I == E) return; // No strings to emit
400
401 // If we have != 0 strings to emit, output them now. Strings are emitted into
402 // the 'void' type plane.
403 output_vbr(unsigned(E-I));
404 output_typeid(Type::VoidTyID);
405
406 // Emit all of the strings.
407 for (I = Table.string_begin(); I != E; ++I) {
408 const ConstantArray *Str = *I;
409 int Slot = Table.getSlot(Str->getType());
410 assert(Slot != -1 && "Constant string of unknown type?");
411 output_typeid((unsigned)Slot);
412
413 // Now that we emitted the type (which indicates the size of the string),
414 // emit all of the characters.
415 std::string Val = Str->getAsString();
416 output_data(Val.c_str(), Val.c_str()+Val.size());
417 }
418}
419
420//===----------------------------------------------------------------------===//
421//=== Instruction Output ===//
422//===----------------------------------------------------------------------===//
423typedef unsigned char uchar;
424
425// outputInstructionFormat0 - Output those wierd instructions that have a large
426// number of operands or have large operands themselves...
427//
428// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
429//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000430void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
431 unsigned Opcode,
432 const SlotCalculator &Table,
433 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000434 // Opcode must have top two bits clear...
435 output_vbr(Opcode << 2); // Instruction Opcode ID
436 output_typeid(Type); // Result type
437
438 unsigned NumArgs = I->getNumOperands();
439 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
440 isa<VAArgInst>(I)));
441
442 if (!isa<GetElementPtrInst>(&I)) {
443 for (unsigned i = 0; i < NumArgs; ++i) {
444 int Slot = Table.getSlot(I->getOperand(i));
445 assert(Slot >= 0 && "No slot number for value!?!?");
446 output_vbr((unsigned)Slot);
447 }
448
449 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
450 int Slot = Table.getSlot(I->getType());
451 assert(Slot != -1 && "Cast return type unknown?");
452 output_typeid((unsigned)Slot);
453 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
454 int Slot = Table.getSlot(VAI->getArgType());
455 assert(Slot != -1 && "VarArg argument type unknown?");
456 output_typeid((unsigned)Slot);
457 }
458
459 } else {
460 int Slot = Table.getSlot(I->getOperand(0));
461 assert(Slot >= 0 && "No slot number for value!?!?");
462 output_vbr(unsigned(Slot));
463
464 // We need to encode the type of sequential type indices into their slot #
465 unsigned Idx = 1;
466 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
467 Idx != NumArgs; ++TI, ++Idx) {
468 Slot = Table.getSlot(I->getOperand(Idx));
469 assert(Slot >= 0 && "No slot number for value!?!?");
470
471 if (isa<SequentialType>(*TI)) {
472 unsigned IdxId;
473 switch (I->getOperand(Idx)->getType()->getTypeID()) {
474 default: assert(0 && "Unknown index type!");
475 case Type::UIntTyID: IdxId = 0; break;
476 case Type::IntTyID: IdxId = 1; break;
477 case Type::ULongTyID: IdxId = 2; break;
478 case Type::LongTyID: IdxId = 3; break;
479 }
480 Slot = (Slot << 2) | IdxId;
481 }
482 output_vbr(unsigned(Slot));
483 }
484 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000485}
486
487
488// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
489// This are more annoying than most because the signature of the call does not
490// tell us anything about the types of the arguments in the varargs portion.
491// Because of this, we encode (as type 0) all of the argument types explicitly
492// before the argument value. This really sucks, but you shouldn't be using
493// varargs functions in your code! *death to printf*!
494//
495// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
496//
497void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
498 unsigned Opcode,
499 const SlotCalculator &Table,
500 unsigned Type) {
501 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
502 // Opcode must have top two bits clear...
503 output_vbr(Opcode << 2); // Instruction Opcode ID
504 output_typeid(Type); // Result type (varargs type)
505
506 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
507 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
508 unsigned NumParams = FTy->getNumParams();
509
510 unsigned NumFixedOperands;
511 if (isa<CallInst>(I)) {
512 // Output an operand for the callee and each fixed argument, then two for
513 // each variable argument.
514 NumFixedOperands = 1+NumParams;
515 } else {
516 assert(isa<InvokeInst>(I) && "Not call or invoke??");
517 // Output an operand for the callee and destinations, then two for each
518 // variable argument.
519 NumFixedOperands = 3+NumParams;
520 }
521 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
522
523 // The type for the function has already been emitted in the type field of the
524 // instruction. Just emit the slot # now.
525 for (unsigned i = 0; i != NumFixedOperands; ++i) {
526 int Slot = Table.getSlot(I->getOperand(i));
527 assert(Slot >= 0 && "No slot number for value!?!?");
528 output_vbr((unsigned)Slot);
529 }
530
531 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
532 // Output Arg Type ID
533 int Slot = Table.getSlot(I->getOperand(i)->getType());
534 assert(Slot >= 0 && "No slot number for value!?!?");
535 output_typeid((unsigned)Slot);
536
537 // Output arg ID itself
538 Slot = Table.getSlot(I->getOperand(i));
539 assert(Slot >= 0 && "No slot number for value!?!?");
540 output_vbr((unsigned)Slot);
541 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000542}
543
544
545// outputInstructionFormat1 - Output one operand instructions, knowing that no
546// operand index is >= 2^12.
547//
548inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
549 unsigned Opcode,
550 unsigned *Slots,
551 unsigned Type) {
552 // bits Instruction format:
553 // --------------------------
554 // 01-00: Opcode type, fixed to 1.
555 // 07-02: Opcode
556 // 19-08: Resulting type plane
557 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
558 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000559 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000560}
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 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000578 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000579}
580
581
582// outputInstructionFormat3 - Output three operand instructions, knowing that no
583// operand index is >= 2^6.
584//
585inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
586 unsigned Opcode,
587 unsigned *Slots,
588 unsigned Type) {
589 // bits Instruction format:
590 // --------------------------
591 // 01-00: Opcode type, fixed to 3.
592 // 07-02: Opcode
593 // 13-08: Resulting type plane
594 // 19-14: Operand #1
595 // 25-20: Operand #2
596 // 31-26: Operand #3
597 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000598 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000599 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000600}
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 Lattnera79e7cc2004-10-16 18:18:16 +0000758 // Output the version identifier and other information.
Reid Spencer38d54be2004-08-17 07:45:14 +0000759 unsigned Version = (BCVersionNum << 4) |
760 (unsigned)isBigEndian | (hasLongPointers << 1) |
761 (hasNoEndianness << 2) |
762 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000763 output_vbr(Version);
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
Chris Lattnerf9d71782004-10-14 01:46:07 +0000785void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000786 // Write the type plane for types first because earlier planes (e.g. for a
787 // primitive type like float) may have constants constructed using types
788 // coming later (e.g., via getelementptr from a pointer type). The type
789 // plane is needed before types can be fwd or bkwd referenced.
790 const std::vector<const Type*>& Types = Table.getTypes();
791 assert(!Types.empty() && "No types at all?");
792 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
793
794 unsigned NumEntries = Types.size() - TypeNum;
795
796 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000797 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000798
799 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
800 outputType(Types[i]);
801}
802
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000803// Helper function for outputConstants().
804// Writes out all the constants in the plane Plane starting at entry StartNo.
805//
806void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
807 &Plane, unsigned StartNo) {
808 unsigned ValNo = StartNo;
809
Chris Lattner83bb3d22004-01-14 23:36:54 +0000810 // Scan through and ignore function arguments, global values, and constant
811 // strings.
812 for (; ValNo < Plane.size() &&
813 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
814 (isa<ConstantArray>(Plane[ValNo]) &&
815 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000816 /*empty*/;
817
818 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000819 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000820 /*empty*/;
821 NC -= ValNo; // Convert from index into count
822 if (NC == 0) return; // Skip empty type planes...
823
Chris Lattnerd6942d72004-01-14 16:54:21 +0000824 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
825 // more compactly.
826
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000827 // Output type header: [num entries][type id number]
828 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000829 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000830
831 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000832 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000833 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000834 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000835
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000836 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
837 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000838 if (const Constant *C = dyn_cast<Constant>(V)) {
839 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000840 }
841 }
842}
843
Chris Lattner80b97342004-01-17 23:25:43 +0000844static inline bool hasNullValue(unsigned TyID) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000845 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Chris Lattner80b97342004-01-17 23:25:43 +0000846}
847
Chris Lattner79df7c02002-03-26 18:01:55 +0000848void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000849 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000850 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000851
852 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000853
Reid Spencere0125b62004-07-18 00:16:21 +0000854 if (isFunction)
855 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000856 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000857 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000858 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000859 outputConstantStrings();
860
Reid Spencercb3595c2004-07-04 11:45:47 +0000861 for (unsigned pno = 0; pno != NumPlanes; pno++) {
862 const std::vector<const Value*> &Plane = Table.getPlane(pno);
863 if (!Plane.empty()) { // Skip empty type planes...
864 unsigned ValNo = 0;
865 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000866 ValNo += Table.getModuleLevel(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000867
868 if (hasNullValue(pno)) {
Reid Spencer0852c802004-07-04 11:46:15 +0000869 // Skip zero initializer
870 if (ValNo == 0)
871 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000872 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000873
874 // Write out constants in the plane
875 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000876 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000877 }
Chris Lattner00950542001-06-06 20:29:01 +0000878}
879
Chris Lattner6b252422003-10-16 18:28:50 +0000880static unsigned getEncodedLinkage(const GlobalValue *GV) {
881 switch (GV->getLinkage()) {
882 default: assert(0 && "Invalid linkage!");
883 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000884 case GlobalValue::WeakLinkage: return 1;
885 case GlobalValue::AppendingLinkage: return 2;
886 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000887 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000888 }
889}
890
Chris Lattner00950542001-06-06 20:29:01 +0000891void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000892 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Chris Lattner00950542001-06-06 20:29:01 +0000893
Chris Lattner70cc3392001-09-10 07:58:01 +0000894 // Output the types for the global variables in the module...
895 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000896 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000897 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000898
Chris Lattner22482a12003-10-18 06:30:21 +0000899 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
900 // bit5+ = Slot # for type
Chris Lattnerf74acc72004-10-14 02:31:35 +0000901 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000902 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000903 output_vbr(oSlot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000904
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000905 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000906 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000907 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000908 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000909 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000910 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000911 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000912 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000913
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000914 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000915 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000916 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000917 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +0000918 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000919 assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
920 unsigned ID = (Slot << 5) + 1;
921 output_vbr(ID);
Chris Lattner00950542001-06-06 20:29:01 +0000922 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000923 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +0000924
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000925 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +0000926 Module::lib_iterator LI = M->lib_begin();
927 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000928 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
929 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +0000930 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000931
932 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000933 output(M->getTargetTriple());
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 Spencer0033c182004-08-27 00:38:44 +00001025 // Avoid writing the compaction table at all if there is no content.
1026 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1027 (!Table.CompactionTableIsEmpty())) {
1028 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1029 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001030 const std::vector<std::vector<const Value*> > &CT =
1031 Table.getCompactionTable();
Reid Spencer0033c182004-08-27 00:38:44 +00001032
1033 // First things first, emit the type compaction table if there is one.
1034 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001035
Reid Spencer0033c182004-08-27 00:38:44 +00001036 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1037 outputCompactionTablePlane(i, CT[i], 0);
1038 }
Chris Lattner00950542001-06-06 20:29:01 +00001039}
1040
Chris Lattner00950542001-06-06 20:29:01 +00001041void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001042 // Do not output the Bytecode block for an empty symbol table, it just wastes
1043 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001044 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001045
Reid Spencerad89bd62004-07-25 18:07:36 +00001046 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001047 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001048
Reid Spencer250c4182004-08-17 02:59:02 +00001049 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001050 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001051
1052 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001053 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1054 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001055 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001056 output_typeid((unsigned)Table.getSlot(TI->second));
Reid Spencer38d54be2004-08-17 07:45:14 +00001057 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001058 }
1059
1060 // Now do each of the type planes in order.
1061 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1062 PE = MST.plane_end(); PI != PE; ++PI) {
1063 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1064 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001065 int Slot;
1066
1067 if (I == End) continue; // Don't mess with an absent type...
1068
Reid Spencer250c4182004-08-17 02:59:02 +00001069 // Write the number of values in this plane
Reid Spencerad89bd62004-07-25 18:07:36 +00001070 output_vbr(MST.type_size(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001071
Reid Spencer250c4182004-08-17 02:59:02 +00001072 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001073 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001074 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001075 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001076
Reid Spencer250c4182004-08-17 02:59:02 +00001077 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001078 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001079 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001080 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001081 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001082 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001083 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001084 }
1085 }
1086}
1087
Reid Spencerad89bd62004-07-25 18:07:36 +00001088void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1089 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001090
Reid Spencerad89bd62004-07-25 18:07:36 +00001091 std::vector<unsigned char> Buffer;
1092 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
Chris Lattner00950542001-06-06 20:29:01 +00001093
1094 // This object populates buffer for us...
Reid Spencerad89bd62004-07-25 18:07:36 +00001095 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001096
Chris Lattnerce6ef112002-07-26 18:40:14 +00001097 // Keep track of how much we've written...
1098 BytesWritten += Buffer.size();
1099
Chris Lattnere8fdde12001-09-07 16:39:41 +00001100 // Okay, write the deque out to the ostream now... the deque is not
1101 // sequential in memory, however, so write out as much as possible in big
1102 // chunks, until we're done.
1103 //
Chris Lattnerf9d71782004-10-14 01:46:07 +00001104 for (std::vector<unsigned char>::const_iterator I = Buffer.begin(),
Chris Lattner823cacc2004-10-14 02:06:48 +00001105 E = Buffer.end(); I != E; ) {
Chris Lattnere8fdde12001-09-07 16:39:41 +00001106 // Scan to see how big this chunk is...
1107 const unsigned char *ChunkPtr = &*I;
1108 const unsigned char *LastPtr = ChunkPtr;
1109 while (I != E) {
1110 const unsigned char *ThisPtr = &*++I;
Chris Lattner036de032004-06-25 20:52:10 +00001111 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
Chris Lattner5cb17412001-11-04 21:32:41 +00001112 break;
Chris Lattnere8fdde12001-09-07 16:39:41 +00001113 }
1114
1115 // Write out the chunk...
Chris Lattnerd6162282004-06-25 00:35:55 +00001116 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
Chris Lattnere8fdde12001-09-07 16:39:41 +00001117 }
Chris Lattner00950542001-06-06 20:29:01 +00001118 Out.flush();
1119}
Reid Spencere0125b62004-07-18 00:16:21 +00001120
1121// vim: sw=2 ai