blob: b54a513b72db112bf5ba4fe5426e095a759bb7f8 [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 Spencer17f52c52004-11-06 23:17:23 +000028#include "llvm/Support/Compressor.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000031#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000032#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Reid Spencer38d54be2004-08-17 07:45:14 +000035/// This value needs to be incremented every time the bytecode format changes
36/// so that the reader can distinguish which format of the bytecode file has
37/// been written.
38/// @brief The bytecode version number
Chris Lattnera79e7cc2004-10-16 18:18:16 +000039const unsigned BCVersionNum = 5;
Reid Spencer38d54be2004-08-17 07:45:14 +000040
Chris Lattner635cd932002-07-23 19:56:44 +000041static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
42
Chris Lattnerce6ef112002-07-26 18:40:14 +000043static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000044BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000045
Reid Spencerad89bd62004-07-25 18:07:36 +000046//===----------------------------------------------------------------------===//
47//=== Output Primitives ===//
48//===----------------------------------------------------------------------===//
49
50// output - If a position is specified, it must be in the valid portion of the
51// string... note that this should be inlined always so only the relevant IF
52// body should be included.
53inline void BytecodeWriter::output(unsigned i, int pos) {
54 if (pos == -1) { // Be endian clean, little endian is our friend
55 Out.push_back((unsigned char)i);
56 Out.push_back((unsigned char)(i >> 8));
57 Out.push_back((unsigned char)(i >> 16));
58 Out.push_back((unsigned char)(i >> 24));
59 } else {
60 Out[pos ] = (unsigned char)i;
61 Out[pos+1] = (unsigned char)(i >> 8);
62 Out[pos+2] = (unsigned char)(i >> 16);
63 Out[pos+3] = (unsigned char)(i >> 24);
64 }
65}
66
67inline void BytecodeWriter::output(int i) {
68 output((unsigned)i);
69}
70
71/// output_vbr - Output an unsigned value, by using the least number of bytes
72/// possible. This is useful because many of our "infinite" values are really
73/// very small most of the time; but can be large a few times.
74/// Data format used: If you read a byte with the high bit set, use the low
Reid Spencer38d54be2004-08-17 07:45:14 +000075/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000076inline void BytecodeWriter::output_vbr(uint64_t i) {
77 while (1) {
78 if (i < 0x80) { // done?
79 Out.push_back((unsigned char)i); // We know the high bit is clear...
80 return;
81 }
82
83 // Nope, we are bigger than a character, output the next 7 bits and set the
84 // high bit to say that there is more coming...
85 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
86 i >>= 7; // Shift out 7 bits now...
87 }
88}
89
90inline void BytecodeWriter::output_vbr(unsigned i) {
91 while (1) {
92 if (i < 0x80) { // done?
93 Out.push_back((unsigned char)i); // We know the high bit is clear...
94 return;
95 }
96
97 // Nope, we are bigger than a character, output the next 7 bits and set the
98 // high bit to say that there is more coming...
99 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
100 i >>= 7; // Shift out 7 bits now...
101 }
102}
103
104inline void BytecodeWriter::output_typeid(unsigned i) {
105 if (i <= 0x00FFFFFF)
106 this->output_vbr(i);
107 else {
108 this->output_vbr(0x00FFFFFF);
109 this->output_vbr(i);
110 }
111}
112
113inline void BytecodeWriter::output_vbr(int64_t i) {
114 if (i < 0)
115 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
116 else
117 output_vbr((uint64_t)i << 1); // Low order bit is clear.
118}
119
120
121inline void BytecodeWriter::output_vbr(int i) {
122 if (i < 0)
123 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
124 else
125 output_vbr((unsigned)i << 1); // Low order bit is clear.
126}
127
Reid Spencer38d54be2004-08-17 07:45:14 +0000128inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000129 unsigned Len = s.length();
130 output_vbr(Len ); // Strings may have an arbitrary length...
131 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000132}
133
134inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
135 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
136}
137
138inline void BytecodeWriter::output_float(float& FloatVal) {
139 /// FIXME: This isn't optimal, it has size problems on some platforms
140 /// where FP is not IEEE.
141 union {
142 float f;
143 uint32_t i;
144 } FloatUnion;
145 FloatUnion.f = FloatVal;
146 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
150}
151
152inline void BytecodeWriter::output_double(double& DoubleVal) {
153 /// FIXME: This isn't optimal, it has size problems on some platforms
154 /// where FP is not IEEE.
155 union {
156 double d;
157 uint64_t i;
158 } DoubleUnion;
159 DoubleUnion.d = DoubleVal;
160 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
167 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
168}
169
170inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
171 bool elideIfEmpty, bool hasLongFormat )
172 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
173
174 if (HasLongFormat) {
175 w.output(ID);
176 w.output(0U); // For length in long format
177 } else {
178 w.output(0U); /// Place holder for ID and length for this block
179 }
180 Loc = w.size();
181}
182
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000183inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
184 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000185 if (Loc == Writer.size() && ElideIfEmpty) {
186 // If the block is empty, and we are allowed to, do not emit the block at
187 // all!
188 Writer.resize(Writer.size()-(HasLongFormat?8:4));
189 return;
190 }
191
Reid Spencerad89bd62004-07-25 18:07:36 +0000192 if (HasLongFormat)
193 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
194 else
195 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000196}
197
198//===----------------------------------------------------------------------===//
199//=== Constant Output ===//
200//===----------------------------------------------------------------------===//
201
202void BytecodeWriter::outputType(const Type *T) {
203 output_vbr((unsigned)T->getTypeID());
204
205 // That's all there is to handling primitive types...
206 if (T->isPrimitiveType()) {
207 return; // We might do this if we alias a prim type: %x = type int
208 }
209
210 switch (T->getTypeID()) { // Handle derived types now.
211 case Type::FunctionTyID: {
212 const FunctionType *MT = cast<FunctionType>(T);
213 int Slot = Table.getSlot(MT->getReturnType());
214 assert(Slot != -1 && "Type used but not available!!");
215 output_typeid((unsigned)Slot);
216
217 // Output the number of arguments to function (+1 if varargs):
218 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
219
220 // Output all of the arguments...
221 FunctionType::param_iterator I = MT->param_begin();
222 for (; I != MT->param_end(); ++I) {
223 Slot = Table.getSlot(*I);
224 assert(Slot != -1 && "Type used but not available!!");
225 output_typeid((unsigned)Slot);
226 }
227
228 // Terminate list with VoidTy if we are a varargs function...
229 if (MT->isVarArg())
230 output_typeid((unsigned)Type::VoidTyID);
231 break;
232 }
233
234 case Type::ArrayTyID: {
235 const ArrayType *AT = cast<ArrayType>(T);
236 int Slot = Table.getSlot(AT->getElementType());
237 assert(Slot != -1 && "Type used but not available!!");
238 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000239 output_vbr(AT->getNumElements());
240 break;
241 }
242
Brian Gaeke715c90b2004-08-20 06:00:58 +0000243 case Type::PackedTyID: {
244 const PackedType *PT = cast<PackedType>(T);
245 int Slot = Table.getSlot(PT->getElementType());
246 assert(Slot != -1 && "Type used but not available!!");
247 output_typeid((unsigned)Slot);
248 output_vbr(PT->getNumElements());
249 break;
250 }
251
252
Reid Spencerad89bd62004-07-25 18:07:36 +0000253 case Type::StructTyID: {
254 const StructType *ST = cast<StructType>(T);
255
256 // Output all of the element types...
257 for (StructType::element_iterator I = ST->element_begin(),
258 E = ST->element_end(); I != E; ++I) {
259 int Slot = Table.getSlot(*I);
260 assert(Slot != -1 && "Type used but not available!!");
261 output_typeid((unsigned)Slot);
262 }
263
264 // Terminate list with VoidTy
265 output_typeid((unsigned)Type::VoidTyID);
266 break;
267 }
268
269 case Type::PointerTyID: {
270 const PointerType *PT = cast<PointerType>(T);
271 int Slot = Table.getSlot(PT->getElementType());
272 assert(Slot != -1 && "Type used but not available!!");
273 output_typeid((unsigned)Slot);
274 break;
275 }
276
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000277 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000278 // No need to emit anything, just the count of opaque types is enough.
279 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000280
Reid Spencerad89bd62004-07-25 18:07:36 +0000281 default:
282 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
283 << " Type '" << T->getDescription() << "'\n";
284 break;
285 }
286}
287
288void BytecodeWriter::outputConstant(const Constant *CPV) {
289 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
290 "Shouldn't output null constants!");
291
292 // We must check for a ConstantExpr before switching by type because
293 // a ConstantExpr can be of any type, and has no explicit value.
294 //
295 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
296 // FIXME: Encoding of constant exprs could be much more compact!
297 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000298 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerad89bd62004-07-25 18:07:36 +0000299 output_vbr(CE->getOpcode()); // flags as an expr
300
301 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
302 int Slot = Table.getSlot(*OI);
303 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
304 output_vbr((unsigned)Slot);
305 Slot = Table.getSlot((*OI)->getType());
306 output_typeid((unsigned)Slot);
307 }
308 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000309 } else if (isa<UndefValue>(CPV)) {
310 output_vbr(1U); // 1 -> UndefValue constant.
311 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000312 } else {
313 output_vbr(0U); // flag as not a ConstantExpr
314 }
315
316 switch (CPV->getType()->getTypeID()) {
317 case Type::BoolTyID: // Boolean Types
318 if (cast<ConstantBool>(CPV)->getValue())
319 output_vbr(1U);
320 else
321 output_vbr(0U);
322 break;
323
324 case Type::UByteTyID: // Unsigned integer types...
325 case Type::UShortTyID:
326 case Type::UIntTyID:
327 case Type::ULongTyID:
328 output_vbr(cast<ConstantUInt>(CPV)->getValue());
329 break;
330
331 case Type::SByteTyID: // Signed integer types...
332 case Type::ShortTyID:
333 case Type::IntTyID:
334 case Type::LongTyID:
335 output_vbr(cast<ConstantSInt>(CPV)->getValue());
336 break;
337
338 case Type::ArrayTyID: {
339 const ConstantArray *CPA = cast<ConstantArray>(CPV);
340 assert(!CPA->isString() && "Constant strings should be handled specially!");
341
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000342 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000343 int Slot = Table.getSlot(CPA->getOperand(i));
344 assert(Slot != -1 && "Constant used but not available!!");
345 output_vbr((unsigned)Slot);
346 }
347 break;
348 }
349
Brian Gaeke715c90b2004-08-20 06:00:58 +0000350 case Type::PackedTyID: {
351 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
352
353 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
354 int Slot = Table.getSlot(CP->getOperand(i));
355 assert(Slot != -1 && "Constant used but not available!!");
356 output_vbr((unsigned)Slot);
357 }
358 break;
359 }
360
Reid Spencerad89bd62004-07-25 18:07:36 +0000361 case Type::StructTyID: {
362 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000363
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000364 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
365 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000366 assert(Slot != -1 && "Constant used but not available!!");
367 output_vbr((unsigned)Slot);
368 }
369 break;
370 }
371
372 case Type::PointerTyID:
373 assert(0 && "No non-null, non-constant-expr constants allowed!");
374 abort();
375
376 case Type::FloatTyID: { // Floating point types...
377 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
378 output_float(Tmp);
379 break;
380 }
381 case Type::DoubleTyID: {
382 double Tmp = cast<ConstantFP>(CPV)->getValue();
383 output_double(Tmp);
384 break;
385 }
386
387 case Type::VoidTyID:
388 case Type::LabelTyID:
389 default:
390 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
391 << " type '" << *CPV->getType() << "'\n";
392 break;
393 }
394 return;
395}
396
397void BytecodeWriter::outputConstantStrings() {
398 SlotCalculator::string_iterator I = Table.string_begin();
399 SlotCalculator::string_iterator E = Table.string_end();
400 if (I == E) return; // No strings to emit
401
402 // If we have != 0 strings to emit, output them now. Strings are emitted into
403 // the 'void' type plane.
404 output_vbr(unsigned(E-I));
405 output_typeid(Type::VoidTyID);
406
407 // Emit all of the strings.
408 for (I = Table.string_begin(); I != E; ++I) {
409 const ConstantArray *Str = *I;
410 int Slot = Table.getSlot(Str->getType());
411 assert(Slot != -1 && "Constant string of unknown type?");
412 output_typeid((unsigned)Slot);
413
414 // Now that we emitted the type (which indicates the size of the string),
415 // emit all of the characters.
416 std::string Val = Str->getAsString();
417 output_data(Val.c_str(), Val.c_str()+Val.size());
418 }
419}
420
421//===----------------------------------------------------------------------===//
422//=== Instruction Output ===//
423//===----------------------------------------------------------------------===//
424typedef unsigned char uchar;
425
426// outputInstructionFormat0 - Output those wierd instructions that have a large
427// number of operands or have large operands themselves...
428//
429// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
430//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000431void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
432 unsigned Opcode,
433 const SlotCalculator &Table,
434 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000435 // Opcode must have top two bits clear...
436 output_vbr(Opcode << 2); // Instruction Opcode ID
437 output_typeid(Type); // Result type
438
439 unsigned NumArgs = I->getNumOperands();
440 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
441 isa<VAArgInst>(I)));
442
443 if (!isa<GetElementPtrInst>(&I)) {
444 for (unsigned i = 0; i < NumArgs; ++i) {
445 int Slot = Table.getSlot(I->getOperand(i));
446 assert(Slot >= 0 && "No slot number for value!?!?");
447 output_vbr((unsigned)Slot);
448 }
449
450 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
451 int Slot = Table.getSlot(I->getType());
452 assert(Slot != -1 && "Cast return type unknown?");
453 output_typeid((unsigned)Slot);
454 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
455 int Slot = Table.getSlot(VAI->getArgType());
456 assert(Slot != -1 && "VarArg argument type unknown?");
457 output_typeid((unsigned)Slot);
458 }
459
460 } else {
461 int Slot = Table.getSlot(I->getOperand(0));
462 assert(Slot >= 0 && "No slot number for value!?!?");
463 output_vbr(unsigned(Slot));
464
465 // We need to encode the type of sequential type indices into their slot #
466 unsigned Idx = 1;
467 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
468 Idx != NumArgs; ++TI, ++Idx) {
469 Slot = Table.getSlot(I->getOperand(Idx));
470 assert(Slot >= 0 && "No slot number for value!?!?");
471
472 if (isa<SequentialType>(*TI)) {
473 unsigned IdxId;
474 switch (I->getOperand(Idx)->getType()->getTypeID()) {
475 default: assert(0 && "Unknown index type!");
476 case Type::UIntTyID: IdxId = 0; break;
477 case Type::IntTyID: IdxId = 1; break;
478 case Type::ULongTyID: IdxId = 2; break;
479 case Type::LongTyID: IdxId = 3; break;
480 }
481 Slot = (Slot << 2) | IdxId;
482 }
483 output_vbr(unsigned(Slot));
484 }
485 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000486}
487
488
489// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
490// This are more annoying than most because the signature of the call does not
491// tell us anything about the types of the arguments in the varargs portion.
492// Because of this, we encode (as type 0) all of the argument types explicitly
493// before the argument value. This really sucks, but you shouldn't be using
494// varargs functions in your code! *death to printf*!
495//
496// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
497//
498void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
499 unsigned Opcode,
500 const SlotCalculator &Table,
501 unsigned Type) {
502 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
503 // Opcode must have top two bits clear...
504 output_vbr(Opcode << 2); // Instruction Opcode ID
505 output_typeid(Type); // Result type (varargs type)
506
507 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
508 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
509 unsigned NumParams = FTy->getNumParams();
510
511 unsigned NumFixedOperands;
512 if (isa<CallInst>(I)) {
513 // Output an operand for the callee and each fixed argument, then two for
514 // each variable argument.
515 NumFixedOperands = 1+NumParams;
516 } else {
517 assert(isa<InvokeInst>(I) && "Not call or invoke??");
518 // Output an operand for the callee and destinations, then two for each
519 // variable argument.
520 NumFixedOperands = 3+NumParams;
521 }
522 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
523
524 // The type for the function has already been emitted in the type field of the
525 // instruction. Just emit the slot # now.
526 for (unsigned i = 0; i != NumFixedOperands; ++i) {
527 int Slot = Table.getSlot(I->getOperand(i));
528 assert(Slot >= 0 && "No slot number for value!?!?");
529 output_vbr((unsigned)Slot);
530 }
531
532 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
533 // Output Arg Type ID
534 int Slot = Table.getSlot(I->getOperand(i)->getType());
535 assert(Slot >= 0 && "No slot number for value!?!?");
536 output_typeid((unsigned)Slot);
537
538 // Output arg ID itself
539 Slot = Table.getSlot(I->getOperand(i));
540 assert(Slot >= 0 && "No slot number for value!?!?");
541 output_vbr((unsigned)Slot);
542 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000543}
544
545
546// outputInstructionFormat1 - Output one operand instructions, knowing that no
547// operand index is >= 2^12.
548//
549inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
550 unsigned Opcode,
551 unsigned *Slots,
552 unsigned Type) {
553 // bits Instruction format:
554 // --------------------------
555 // 01-00: Opcode type, fixed to 1.
556 // 07-02: Opcode
557 // 19-08: Resulting type plane
558 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
559 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000560 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000561}
562
563
564// outputInstructionFormat2 - Output two operand instructions, knowing that no
565// operand index is >= 2^8.
566//
567inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
568 unsigned Opcode,
569 unsigned *Slots,
570 unsigned Type) {
571 // bits Instruction format:
572 // --------------------------
573 // 01-00: Opcode type, fixed to 2.
574 // 07-02: Opcode
575 // 15-08: Resulting type plane
576 // 23-16: Operand #1
577 // 31-24: Operand #2
578 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000579 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000580}
581
582
583// outputInstructionFormat3 - Output three operand instructions, knowing that no
584// operand index is >= 2^6.
585//
586inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
587 unsigned Opcode,
588 unsigned *Slots,
589 unsigned Type) {
590 // bits Instruction format:
591 // --------------------------
592 // 01-00: Opcode type, fixed to 3.
593 // 07-02: Opcode
594 // 13-08: Resulting type plane
595 // 19-14: Operand #1
596 // 25-20: Operand #2
597 // 31-26: Operand #3
598 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000599 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000600 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000601}
602
603void BytecodeWriter::outputInstruction(const Instruction &I) {
604 assert(I.getOpcode() < 62 && "Opcode too big???");
605 unsigned Opcode = I.getOpcode();
606 unsigned NumOperands = I.getNumOperands();
607
608 // Encode 'volatile load' as 62 and 'volatile store' as 63.
609 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
610 Opcode = 62;
611 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
612 Opcode = 63;
613
614 // Figure out which type to encode with the instruction. Typically we want
615 // the type of the first parameter, as opposed to the type of the instruction
616 // (for example, with setcc, we always know it returns bool, but the type of
617 // the first param is actually interesting). But if we have no arguments
618 // we take the type of the instruction itself.
619 //
620 const Type *Ty;
621 switch (I.getOpcode()) {
622 case Instruction::Select:
623 case Instruction::Malloc:
624 case Instruction::Alloca:
625 Ty = I.getType(); // These ALWAYS want to encode the return type
626 break;
627 case Instruction::Store:
628 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
629 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
630 break;
631 default: // Otherwise use the default behavior...
632 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
633 break;
634 }
635
636 unsigned Type;
637 int Slot = Table.getSlot(Ty);
638 assert(Slot != -1 && "Type not available!!?!");
639 Type = (unsigned)Slot;
640
641 // Varargs calls and invokes are encoded entirely different from any other
642 // instructions.
643 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
644 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
645 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
646 outputInstrVarArgsCall(CI, Opcode, Table, Type);
647 return;
648 }
649 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
650 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
651 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
652 outputInstrVarArgsCall(II, Opcode, Table, Type);
653 return;
654 }
655 }
656
657 if (NumOperands <= 3) {
658 // Make sure that we take the type number into consideration. We don't want
659 // to overflow the field size for the instruction format we select.
660 //
661 unsigned MaxOpSlot = Type;
662 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
663
664 for (unsigned i = 0; i != NumOperands; ++i) {
665 int slot = Table.getSlot(I.getOperand(i));
666 assert(slot != -1 && "Broken bytecode!");
667 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
668 Slots[i] = unsigned(slot);
669 }
670
671 // Handle the special cases for various instructions...
672 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
673 // Cast has to encode the destination type as the second argument in the
674 // packet, or else we won't know what type to cast to!
675 Slots[1] = Table.getSlot(I.getType());
676 assert(Slots[1] != ~0U && "Cast return type unknown?");
677 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
678 NumOperands++;
679 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
680 Slots[1] = Table.getSlot(VANI->getArgType());
681 assert(Slots[1] != ~0U && "va_next return type unknown?");
682 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
683 NumOperands++;
684 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
685 // We need to encode the type of sequential type indices into their slot #
686 unsigned Idx = 1;
687 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
688 I != E; ++I, ++Idx)
689 if (isa<SequentialType>(*I)) {
690 unsigned IdxId;
691 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
692 default: assert(0 && "Unknown index type!");
693 case Type::UIntTyID: IdxId = 0; break;
694 case Type::IntTyID: IdxId = 1; break;
695 case Type::ULongTyID: IdxId = 2; break;
696 case Type::LongTyID: IdxId = 3; break;
697 }
698 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
699 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
700 }
701 }
702
703 // Decide which instruction encoding to use. This is determined primarily
704 // by the number of operands, and secondarily by whether or not the max
705 // operand will fit into the instruction encoding. More operands == fewer
706 // bits per operand.
707 //
708 switch (NumOperands) {
709 case 0:
710 case 1:
711 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
712 outputInstructionFormat1(&I, Opcode, Slots, Type);
713 return;
714 }
715 break;
716
717 case 2:
718 if (MaxOpSlot < (1 << 8)) {
719 outputInstructionFormat2(&I, Opcode, Slots, Type);
720 return;
721 }
722 break;
723
724 case 3:
725 if (MaxOpSlot < (1 << 6)) {
726 outputInstructionFormat3(&I, Opcode, Slots, Type);
727 return;
728 }
729 break;
730 default:
731 break;
732 }
733 }
734
735 // If we weren't handled before here, we either have a large number of
736 // operands or a large operand index that we are referring to.
737 outputInstructionFormat0(&I, Opcode, Table, Type);
738}
739
740//===----------------------------------------------------------------------===//
741//=== Block Output ===//
742//===----------------------------------------------------------------------===//
743
744BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000745 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000746
Chris Lattner83bb3d22004-01-14 23:36:54 +0000747 // Emit the signature...
748 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000749 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000750
751 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000752 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000753
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000754 bool isBigEndian = M->getEndianness() == Module::BigEndian;
755 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
756 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
757 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000758
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000759 // Output the version identifier and other information.
Reid Spencer38d54be2004-08-17 07:45:14 +0000760 unsigned Version = (BCVersionNum << 4) |
761 (unsigned)isBigEndian | (hasLongPointers << 1) |
762 (hasNoEndianness << 2) |
763 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000764 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000765
Reid Spencercb3595c2004-07-04 11:45:47 +0000766 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000767 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000768 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000769 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000770 }
Chris Lattner00950542001-06-06 20:29:01 +0000771
Chris Lattner186a1f72003-03-19 20:56:46 +0000772 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000773 outputModuleInfoBlock(M);
774
Chris Lattner186a1f72003-03-19 20:56:46 +0000775 // Output module level constants, used for global variable initializers
776 outputConstants(false);
777
Chris Lattnerb5794002002-04-07 22:49:37 +0000778 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000779 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000780 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000781
782 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000783 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000784}
785
Chris Lattnerf9d71782004-10-14 01:46:07 +0000786void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000787 // Write the type plane for types first because earlier planes (e.g. for a
788 // primitive type like float) may have constants constructed using types
789 // coming later (e.g., via getelementptr from a pointer type). The type
790 // plane is needed before types can be fwd or bkwd referenced.
791 const std::vector<const Type*>& Types = Table.getTypes();
792 assert(!Types.empty() && "No types at all?");
793 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
794
795 unsigned NumEntries = Types.size() - TypeNum;
796
797 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000798 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000799
800 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
801 outputType(Types[i]);
802}
803
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000804// Helper function for outputConstants().
805// Writes out all the constants in the plane Plane starting at entry StartNo.
806//
807void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
808 &Plane, unsigned StartNo) {
809 unsigned ValNo = StartNo;
810
Chris Lattner83bb3d22004-01-14 23:36:54 +0000811 // Scan through and ignore function arguments, global values, and constant
812 // strings.
813 for (; ValNo < Plane.size() &&
814 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
815 (isa<ConstantArray>(Plane[ValNo]) &&
816 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000817 /*empty*/;
818
819 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000820 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000821 /*empty*/;
822 NC -= ValNo; // Convert from index into count
823 if (NC == 0) return; // Skip empty type planes...
824
Chris Lattnerd6942d72004-01-14 16:54:21 +0000825 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
826 // more compactly.
827
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000828 // Output type header: [num entries][type id number]
829 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000830 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000831
832 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000833 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000834 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000835 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000836
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000837 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
838 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000839 if (const Constant *C = dyn_cast<Constant>(V)) {
840 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000841 }
842 }
843}
844
Chris Lattner80b97342004-01-17 23:25:43 +0000845static inline bool hasNullValue(unsigned TyID) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000846 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Chris Lattner80b97342004-01-17 23:25:43 +0000847}
848
Chris Lattner79df7c02002-03-26 18:01:55 +0000849void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000850 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000851 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000852
853 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000854
Reid Spencere0125b62004-07-18 00:16:21 +0000855 if (isFunction)
856 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000857 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000858 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000859 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000860 outputConstantStrings();
861
Reid Spencercb3595c2004-07-04 11:45:47 +0000862 for (unsigned pno = 0; pno != NumPlanes; pno++) {
863 const std::vector<const Value*> &Plane = Table.getPlane(pno);
864 if (!Plane.empty()) { // Skip empty type planes...
865 unsigned ValNo = 0;
866 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000867 ValNo += Table.getModuleLevel(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000868
869 if (hasNullValue(pno)) {
Reid Spencer0852c802004-07-04 11:46:15 +0000870 // Skip zero initializer
871 if (ValNo == 0)
872 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000873 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000874
875 // Write out constants in the plane
876 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000877 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000878 }
Chris Lattner00950542001-06-06 20:29:01 +0000879}
880
Chris Lattner6b252422003-10-16 18:28:50 +0000881static unsigned getEncodedLinkage(const GlobalValue *GV) {
882 switch (GV->getLinkage()) {
883 default: assert(0 && "Invalid linkage!");
884 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000885 case GlobalValue::WeakLinkage: return 1;
886 case GlobalValue::AppendingLinkage: return 2;
887 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000888 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000889 }
890}
891
Chris Lattner00950542001-06-06 20:29:01 +0000892void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000893 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Chris Lattner00950542001-06-06 20:29:01 +0000894
Chris Lattner70cc3392001-09-10 07:58:01 +0000895 // Output the types for the global variables in the module...
896 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000897 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000898 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000899
Chris Lattner22482a12003-10-18 06:30:21 +0000900 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
901 // bit5+ = Slot # for type
Chris Lattnerf74acc72004-10-14 02:31:35 +0000902 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000903 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000904 output_vbr(oSlot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000905
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000906 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000907 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000908 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000909 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000910 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000911 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000912 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000913 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000914
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000915 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000916 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000917 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000918 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +0000919 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000920 assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
921 unsigned ID = (Slot << 5) + 1;
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000922 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
923 ID |= 1 << 4;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000924 output_vbr(ID);
Chris Lattner00950542001-06-06 20:29:01 +0000925 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000926 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +0000927
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000928 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +0000929 Module::lib_iterator LI = M->lib_begin();
930 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000931 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
932 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +0000933 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000934
935 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000936 output(M->getTargetTriple());
Chris Lattner00950542001-06-06 20:29:01 +0000937}
938
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000939void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000940 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000941 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
942 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
943 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000944}
945
Chris Lattner186a1f72003-03-19 20:56:46 +0000946void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +0000947 // If this is an external function, there is nothing else to emit!
948 if (F->isExternal()) return;
949
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000950 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
951 output_vbr(getEncodedLinkage(F));
952
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000953 // Get slot information about the function...
954 Table.incorporateFunction(F);
955
956 if (Table.getCompactionTable().empty()) {
957 // Output information about the constants in the function if the compaction
958 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000959 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000960 } else {
961 // Otherwise, emit the compaction table.
962 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000963 }
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000964
965 // Output all of the instructions in the body of the function
966 outputInstructions(F);
967
968 // If needed, output the symbol table for the function...
969 outputSymbolTable(F->getSymbolTable());
970
971 Table.purgeFunction();
972}
973
974void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
975 const std::vector<const Value*> &Plane,
976 unsigned StartNo) {
977 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +0000978 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000979 assert(StartNo < End && "Cannot emit negative range!");
980 assert(StartNo < Plane.size() && End <= Plane.size());
981
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000982 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +0000983 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000984
Chris Lattner24102432004-01-18 22:35:34 +0000985 // Figure out which encoding to use. By far the most common case we have is
986 // to emit 0-2 entries in a compaction table plane.
987 switch (End-StartNo) {
988 case 0: // Avoid emitting two vbr's if possible.
989 case 1:
990 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +0000991 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +0000992 break;
993 default:
994 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +0000995 output_vbr((unsigned(End-StartNo) << 2) | 3);
996 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +0000997 break;
998 }
999
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001000 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001001 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001002}
1003
Reid Spencercb3595c2004-07-04 11:45:47 +00001004void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1005 // Get the compaction type table from the slot calculator
1006 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1007
1008 // The compaction types may have been uncompactified back to the
1009 // global types. If so, we just write an empty table
1010 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001011 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001012 return;
1013 }
1014
1015 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1016
1017 // Determine how many types to write
1018 unsigned NumTypes = CTypes.size() - StartNo;
1019
1020 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001021 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001022
1023 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001024 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001025}
1026
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001027void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001028 // Avoid writing the compaction table at all if there is no content.
1029 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1030 (!Table.CompactionTableIsEmpty())) {
1031 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1032 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001033 const std::vector<std::vector<const Value*> > &CT =
1034 Table.getCompactionTable();
Reid Spencer0033c182004-08-27 00:38:44 +00001035
1036 // First things first, emit the type compaction table if there is one.
1037 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001038
Reid Spencer0033c182004-08-27 00:38:44 +00001039 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1040 outputCompactionTablePlane(i, CT[i], 0);
1041 }
Chris Lattner00950542001-06-06 20:29:01 +00001042}
1043
Chris Lattner00950542001-06-06 20:29:01 +00001044void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001045 // Do not output the Bytecode block for an empty symbol table, it just wastes
1046 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001047 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001048
Reid Spencerad89bd62004-07-25 18:07:36 +00001049 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001050 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001051
Reid Spencer250c4182004-08-17 02:59:02 +00001052 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001053 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001054
1055 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001056 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1057 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001058 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001059 output_typeid((unsigned)Table.getSlot(TI->second));
Reid Spencer38d54be2004-08-17 07:45:14 +00001060 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001061 }
1062
1063 // Now do each of the type planes in order.
1064 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1065 PE = MST.plane_end(); PI != PE; ++PI) {
1066 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1067 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001068 int Slot;
1069
1070 if (I == End) continue; // Don't mess with an absent type...
1071
Reid Spencer250c4182004-08-17 02:59:02 +00001072 // Write the number of values in this plane
Reid Spencerad89bd62004-07-25 18:07:36 +00001073 output_vbr(MST.type_size(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001074
Reid Spencer250c4182004-08-17 02:59:02 +00001075 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001076 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001077 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001078 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001079
Reid Spencer250c4182004-08-17 02:59:02 +00001080 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001081 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001082 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001083 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001084 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001085 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001086 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001087 }
1088 }
1089}
1090
Reid Spencer17f52c52004-11-06 23:17:23 +00001091void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1092 bool compress ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001093 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001094
Reid Spencer17f52c52004-11-06 23:17:23 +00001095 // Create a vector of unsigned char for the bytecode output. We
1096 // reserve 256KBytes of space in the vector so that we avoid doing
1097 // lots of little allocations. 256KBytes is sufficient for a large
1098 // proportion of the bytecode files we will encounter. Larger files
1099 // will be automatically doubled in size as needed (std::vector
1100 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001101 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001102 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001103
Reid Spencer17f52c52004-11-06 23:17:23 +00001104 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001105 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001106
Reid Spencer17f52c52004-11-06 23:17:23 +00001107 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001108 BytesWritten += Buffer.size();
1109
Reid Spencer17f52c52004-11-06 23:17:23 +00001110 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001111 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001112
1113 // If we're supposed to compress this mess ...
1114 if (compress) {
1115
1116 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001117 // file. The compressed bytecode file's magic number is "llvc" instead
1118 // of "llvm".
1119 char compressed_magic[4];
1120 compressed_magic[0] = 'l';
1121 compressed_magic[1] = 'l';
1122 compressed_magic[2] = 'v';
1123 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001124
Reid Spencer83296f52004-11-07 18:17:38 +00001125 Out.write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001126
Reid Spencera70d84d2004-11-14 22:01:41 +00001127 // Compress everything after the magic number (which we altered)
1128 uint64_t zipSize = Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001129 (char*)(FirstByte+4), // Skip the magic number
1130 Buffer.size()-4, // Skip the magic number
Reid Spencer84472d62004-11-25 19:38:05 +00001131 Out // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001132 );
1133
Reid Spencer17f52c52004-11-06 23:17:23 +00001134 } else {
1135
1136 // We're not compressing, so just write the entire block.
Reid Spencer83296f52004-11-07 18:17:38 +00001137 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001138 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001139
1140 // make sure it hits disk now
Chris Lattner00950542001-06-06 20:29:01 +00001141 Out.flush();
1142}
Reid Spencere0125b62004-07-18 00:16:21 +00001143
1144// vim: sw=2 ai