1 //===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Writer.h
12 // Note that this file uses an unusual technique of outputting all the bytecode
13 // to a vector of unsigned char, then copies the vector to an ostream. The
14 // 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. :( :( :(
18 //===----------------------------------------------------------------------===//
20 #include "WriterInternals.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "Support/STLExtras.h"
29 #include "Support/Statistic.h"
34 /// 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
37 /// @brief The bytecode version number
38 const unsigned BCVersionNum = 4;
40 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
43 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
45 //===----------------------------------------------------------------------===//
46 //=== Output Primitives ===//
47 //===----------------------------------------------------------------------===//
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.
52 inline 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));
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);
66 inline void BytecodeWriter::output(int i) {
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
74 /// seven bits as data and then read another byte.
75 inline void BytecodeWriter::output_vbr(uint64_t i) {
77 if (i < 0x80) { // done?
78 Out.push_back((unsigned char)i); // We know the high bit is clear...
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...
89 inline void BytecodeWriter::output_vbr(unsigned i) {
91 if (i < 0x80) { // done?
92 Out.push_back((unsigned char)i); // We know the high bit is clear...
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...
103 inline void BytecodeWriter::output_typeid(unsigned i) {
107 this->output_vbr(0x00FFFFFF);
112 inline void BytecodeWriter::output_vbr(int64_t i) {
114 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
116 output_vbr((uint64_t)i << 1); // Low order bit is clear.
120 inline void BytecodeWriter::output_vbr(int i) {
122 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
124 output_vbr((unsigned)i << 1); // Low order bit is clear.
127 inline void BytecodeWriter::output(const std::string &s) {
128 unsigned Len = s.length();
129 output_vbr(Len ); // Strings may have an arbitrary length...
130 Out.insert(Out.end(), s.begin(), s.end());
133 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
134 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
137 inline 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.
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));
151 inline 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.
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));
169 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
170 bool elideIfEmpty, bool hasLongFormat )
171 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
175 w.output(0U); // For length in long format
177 w.output(0U); /// Place holder for ID and length for this block
182 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
184 if (Loc == Writer.size() && ElideIfEmpty) {
185 // If the block is empty, and we are allowed to, do not emit the block at
187 Writer.resize(Writer.size()-(HasLongFormat?8:4));
191 //cerr << "OldLoc = " << Loc << " NewLoc = " << NewLoc << " diff = "
192 // << (NewLoc-Loc) << endl;
194 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
196 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
199 //===----------------------------------------------------------------------===//
200 //=== Constant Output ===//
201 //===----------------------------------------------------------------------===//
203 void BytecodeWriter::outputType(const Type *T) {
204 output_vbr((unsigned)T->getTypeID());
206 // That's all there is to handling primitive types...
207 if (T->isPrimitiveType()) {
208 return; // We might do this if we alias a prim type: %x = type int
211 switch (T->getTypeID()) { // Handle derived types now.
212 case Type::FunctionTyID: {
213 const FunctionType *MT = cast<FunctionType>(T);
214 int Slot = Table.getSlot(MT->getReturnType());
215 assert(Slot != -1 && "Type used but not available!!");
216 output_typeid((unsigned)Slot);
218 // Output the number of arguments to function (+1 if varargs):
219 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
221 // Output all of the arguments...
222 FunctionType::param_iterator I = MT->param_begin();
223 for (; I != MT->param_end(); ++I) {
224 Slot = Table.getSlot(*I);
225 assert(Slot != -1 && "Type used but not available!!");
226 output_typeid((unsigned)Slot);
229 // Terminate list with VoidTy if we are a varargs function...
231 output_typeid((unsigned)Type::VoidTyID);
235 case Type::ArrayTyID: {
236 const ArrayType *AT = cast<ArrayType>(T);
237 int Slot = Table.getSlot(AT->getElementType());
238 assert(Slot != -1 && "Type used but not available!!");
239 output_typeid((unsigned)Slot);
240 //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
242 output_vbr(AT->getNumElements());
246 case Type::StructTyID: {
247 const StructType *ST = cast<StructType>(T);
249 // Output all of the element types...
250 for (StructType::element_iterator I = ST->element_begin(),
251 E = ST->element_end(); I != E; ++I) {
252 int Slot = Table.getSlot(*I);
253 assert(Slot != -1 && "Type used but not available!!");
254 output_typeid((unsigned)Slot);
257 // Terminate list with VoidTy
258 output_typeid((unsigned)Type::VoidTyID);
262 case Type::PointerTyID: {
263 const PointerType *PT = cast<PointerType>(T);
264 int Slot = Table.getSlot(PT->getElementType());
265 assert(Slot != -1 && "Type used but not available!!");
266 output_typeid((unsigned)Slot);
270 case Type::OpaqueTyID: {
271 // No need to emit anything, just the count of opaque types is enough.
275 //case Type::PackedTyID:
277 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
278 << " Type '" << T->getDescription() << "'\n";
283 void BytecodeWriter::outputConstant(const Constant *CPV) {
284 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
285 "Shouldn't output null constants!");
287 // We must check for a ConstantExpr before switching by type because
288 // a ConstantExpr can be of any type, and has no explicit value.
290 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
291 // FIXME: Encoding of constant exprs could be much more compact!
292 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
293 output_vbr(CE->getNumOperands()); // flags as an expr
294 output_vbr(CE->getOpcode()); // flags as an expr
296 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
297 int Slot = Table.getSlot(*OI);
298 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
299 output_vbr((unsigned)Slot);
300 Slot = Table.getSlot((*OI)->getType());
301 output_typeid((unsigned)Slot);
305 output_vbr(0U); // flag as not a ConstantExpr
308 switch (CPV->getType()->getTypeID()) {
309 case Type::BoolTyID: // Boolean Types
310 if (cast<ConstantBool>(CPV)->getValue())
316 case Type::UByteTyID: // Unsigned integer types...
317 case Type::UShortTyID:
319 case Type::ULongTyID:
320 output_vbr(cast<ConstantUInt>(CPV)->getValue());
323 case Type::SByteTyID: // Signed integer types...
324 case Type::ShortTyID:
327 output_vbr(cast<ConstantSInt>(CPV)->getValue());
330 case Type::ArrayTyID: {
331 const ConstantArray *CPA = cast<ConstantArray>(CPV);
332 assert(!CPA->isString() && "Constant strings should be handled specially!");
334 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
335 int Slot = Table.getSlot(CPA->getOperand(i));
336 assert(Slot != -1 && "Constant used but not available!!");
337 output_vbr((unsigned)Slot);
342 case Type::StructTyID: {
343 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
345 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
346 int Slot = Table.getSlot(CPS->getOperand(i));
347 assert(Slot != -1 && "Constant used but not available!!");
348 output_vbr((unsigned)Slot);
353 case Type::PointerTyID:
354 assert(0 && "No non-null, non-constant-expr constants allowed!");
357 case Type::FloatTyID: { // Floating point types...
358 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
362 case Type::DoubleTyID: {
363 double Tmp = cast<ConstantFP>(CPV)->getValue();
369 case Type::LabelTyID:
371 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
372 << " type '" << *CPV->getType() << "'\n";
378 void BytecodeWriter::outputConstantStrings() {
379 SlotCalculator::string_iterator I = Table.string_begin();
380 SlotCalculator::string_iterator E = Table.string_end();
381 if (I == E) return; // No strings to emit
383 // If we have != 0 strings to emit, output them now. Strings are emitted into
384 // the 'void' type plane.
385 output_vbr(unsigned(E-I));
386 output_typeid(Type::VoidTyID);
388 // Emit all of the strings.
389 for (I = Table.string_begin(); I != E; ++I) {
390 const ConstantArray *Str = *I;
391 int Slot = Table.getSlot(Str->getType());
392 assert(Slot != -1 && "Constant string of unknown type?");
393 output_typeid((unsigned)Slot);
395 // Now that we emitted the type (which indicates the size of the string),
396 // emit all of the characters.
397 std::string Val = Str->getAsString();
398 output_data(Val.c_str(), Val.c_str()+Val.size());
402 //===----------------------------------------------------------------------===//
403 //=== Instruction Output ===//
404 //===----------------------------------------------------------------------===//
405 typedef unsigned char uchar;
407 // outputInstructionFormat0 - Output those wierd instructions that have a large
408 // number of operands or have large operands themselves...
410 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
412 void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
413 const SlotCalculator &Table,
415 // Opcode must have top two bits clear...
416 output_vbr(Opcode << 2); // Instruction Opcode ID
417 output_typeid(Type); // Result type
419 unsigned NumArgs = I->getNumOperands();
420 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
423 if (!isa<GetElementPtrInst>(&I)) {
424 for (unsigned i = 0; i < NumArgs; ++i) {
425 int Slot = Table.getSlot(I->getOperand(i));
426 assert(Slot >= 0 && "No slot number for value!?!?");
427 output_vbr((unsigned)Slot);
430 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
431 int Slot = Table.getSlot(I->getType());
432 assert(Slot != -1 && "Cast return type unknown?");
433 output_typeid((unsigned)Slot);
434 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
435 int Slot = Table.getSlot(VAI->getArgType());
436 assert(Slot != -1 && "VarArg argument type unknown?");
437 output_typeid((unsigned)Slot);
441 int Slot = Table.getSlot(I->getOperand(0));
442 assert(Slot >= 0 && "No slot number for value!?!?");
443 output_vbr(unsigned(Slot));
445 // We need to encode the type of sequential type indices into their slot #
447 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
448 Idx != NumArgs; ++TI, ++Idx) {
449 Slot = Table.getSlot(I->getOperand(Idx));
450 assert(Slot >= 0 && "No slot number for value!?!?");
452 if (isa<SequentialType>(*TI)) {
454 switch (I->getOperand(Idx)->getType()->getTypeID()) {
455 default: assert(0 && "Unknown index type!");
456 case Type::UIntTyID: IdxId = 0; break;
457 case Type::IntTyID: IdxId = 1; break;
458 case Type::ULongTyID: IdxId = 2; break;
459 case Type::LongTyID: IdxId = 3; break;
461 Slot = (Slot << 2) | IdxId;
463 output_vbr(unsigned(Slot));
469 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
470 // This are more annoying than most because the signature of the call does not
471 // tell us anything about the types of the arguments in the varargs portion.
472 // Because of this, we encode (as type 0) all of the argument types explicitly
473 // before the argument value. This really sucks, but you shouldn't be using
474 // varargs functions in your code! *death to printf*!
476 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
478 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
480 const SlotCalculator &Table,
482 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
483 // Opcode must have top two bits clear...
484 output_vbr(Opcode << 2); // Instruction Opcode ID
485 output_typeid(Type); // Result type (varargs type)
487 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
488 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
489 unsigned NumParams = FTy->getNumParams();
491 unsigned NumFixedOperands;
492 if (isa<CallInst>(I)) {
493 // Output an operand for the callee and each fixed argument, then two for
494 // each variable argument.
495 NumFixedOperands = 1+NumParams;
497 assert(isa<InvokeInst>(I) && "Not call or invoke??");
498 // Output an operand for the callee and destinations, then two for each
499 // variable argument.
500 NumFixedOperands = 3+NumParams;
502 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
504 // The type for the function has already been emitted in the type field of the
505 // instruction. Just emit the slot # now.
506 for (unsigned i = 0; i != NumFixedOperands; ++i) {
507 int Slot = Table.getSlot(I->getOperand(i));
508 assert(Slot >= 0 && "No slot number for value!?!?");
509 output_vbr((unsigned)Slot);
512 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
513 // Output Arg Type ID
514 int Slot = Table.getSlot(I->getOperand(i)->getType());
515 assert(Slot >= 0 && "No slot number for value!?!?");
516 output_typeid((unsigned)Slot);
518 // Output arg ID itself
519 Slot = Table.getSlot(I->getOperand(i));
520 assert(Slot >= 0 && "No slot number for value!?!?");
521 output_vbr((unsigned)Slot);
526 // outputInstructionFormat1 - Output one operand instructions, knowing that no
527 // operand index is >= 2^12.
529 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
533 // bits Instruction format:
534 // --------------------------
535 // 01-00: Opcode type, fixed to 1.
537 // 19-08: Resulting type plane
538 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
540 unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
541 // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
546 // outputInstructionFormat2 - Output two operand instructions, knowing that no
547 // operand index is >= 2^8.
549 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
553 // bits Instruction format:
554 // --------------------------
555 // 01-00: Opcode type, fixed to 2.
557 // 15-08: Resulting type plane
561 unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
562 (Slots[0] << 16) | (Slots[1] << 24);
563 // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " "
564 // << Slots[1] << endl;
569 // outputInstructionFormat3 - Output three operand instructions, knowing that no
570 // operand index is >= 2^6.
572 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
576 // bits Instruction format:
577 // --------------------------
578 // 01-00: Opcode type, fixed to 3.
580 // 13-08: Resulting type plane
585 unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
586 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
587 //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " "
588 // << Slots[1] << " " << Slots[2] << endl;
592 void BytecodeWriter::outputInstruction(const Instruction &I) {
593 assert(I.getOpcode() < 62 && "Opcode too big???");
594 unsigned Opcode = I.getOpcode();
595 unsigned NumOperands = I.getNumOperands();
597 // Encode 'volatile load' as 62 and 'volatile store' as 63.
598 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
600 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
603 // Figure out which type to encode with the instruction. Typically we want
604 // the type of the first parameter, as opposed to the type of the instruction
605 // (for example, with setcc, we always know it returns bool, but the type of
606 // the first param is actually interesting). But if we have no arguments
607 // we take the type of the instruction itself.
610 switch (I.getOpcode()) {
611 case Instruction::Select:
612 case Instruction::Malloc:
613 case Instruction::Alloca:
614 Ty = I.getType(); // These ALWAYS want to encode the return type
616 case Instruction::Store:
617 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
618 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
620 default: // Otherwise use the default behavior...
621 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
626 int Slot = Table.getSlot(Ty);
627 assert(Slot != -1 && "Type not available!!?!");
628 Type = (unsigned)Slot;
630 // Varargs calls and invokes are encoded entirely different from any other
632 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
633 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
634 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
635 outputInstrVarArgsCall(CI, Opcode, Table, Type);
638 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
639 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
640 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
641 outputInstrVarArgsCall(II, Opcode, Table, Type);
646 if (NumOperands <= 3) {
647 // Make sure that we take the type number into consideration. We don't want
648 // to overflow the field size for the instruction format we select.
650 unsigned MaxOpSlot = Type;
651 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
653 for (unsigned i = 0; i != NumOperands; ++i) {
654 int slot = Table.getSlot(I.getOperand(i));
655 assert(slot != -1 && "Broken bytecode!");
656 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
657 Slots[i] = unsigned(slot);
660 // Handle the special cases for various instructions...
661 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
662 // Cast has to encode the destination type as the second argument in the
663 // packet, or else we won't know what type to cast to!
664 Slots[1] = Table.getSlot(I.getType());
665 assert(Slots[1] != ~0U && "Cast return type unknown?");
666 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
668 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
669 Slots[1] = Table.getSlot(VANI->getArgType());
670 assert(Slots[1] != ~0U && "va_next return type unknown?");
671 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
673 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
674 // We need to encode the type of sequential type indices into their slot #
676 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
678 if (isa<SequentialType>(*I)) {
680 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
681 default: assert(0 && "Unknown index type!");
682 case Type::UIntTyID: IdxId = 0; break;
683 case Type::IntTyID: IdxId = 1; break;
684 case Type::ULongTyID: IdxId = 2; break;
685 case Type::LongTyID: IdxId = 3; break;
687 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
688 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
692 // Decide which instruction encoding to use. This is determined primarily
693 // by the number of operands, and secondarily by whether or not the max
694 // operand will fit into the instruction encoding. More operands == fewer
697 switch (NumOperands) {
700 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
701 outputInstructionFormat1(&I, Opcode, Slots, Type);
707 if (MaxOpSlot < (1 << 8)) {
708 outputInstructionFormat2(&I, Opcode, Slots, Type);
714 if (MaxOpSlot < (1 << 6)) {
715 outputInstructionFormat3(&I, Opcode, Slots, Type);
724 // If we weren't handled before here, we either have a large number of
725 // operands or a large operand index that we are referring to.
726 outputInstructionFormat0(&I, Opcode, Table, Type);
729 //===----------------------------------------------------------------------===//
730 //=== Block Output ===//
731 //===----------------------------------------------------------------------===//
733 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
736 // Emit the signature...
737 static const unsigned char *Sig = (const unsigned char*)"llvm";
738 output_data(Sig, Sig+4);
740 // Emit the top level CLASS block.
741 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
743 bool isBigEndian = M->getEndianness() == Module::BigEndian;
744 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
745 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
746 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
748 // Output the version identifier... we are currently on bytecode version #2,
749 // which corresponds to LLVM v1.3.
750 unsigned Version = (BCVersionNum << 4) |
751 (unsigned)isBigEndian | (hasLongPointers << 1) |
752 (hasNoEndianness << 2) |
753 (hasNoPointerSize << 3);
756 // The Global type plane comes first
758 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
759 outputTypes(Type::FirstDerivedTyID);
762 // The ModuleInfoBlock follows directly after the type information
763 outputModuleInfoBlock(M);
765 // Output module level constants, used for global variable initializers
766 outputConstants(false);
768 // Do the whole module now! Process each function at a time...
769 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
772 // If needed, output the symbol table for the module...
773 outputSymbolTable(M->getSymbolTable());
776 void BytecodeWriter::outputTypes(unsigned TypeNum)
778 // Write the type plane for types first because earlier planes (e.g. for a
779 // primitive type like float) may have constants constructed using types
780 // coming later (e.g., via getelementptr from a pointer type). The type
781 // plane is needed before types can be fwd or bkwd referenced.
782 const std::vector<const Type*>& Types = Table.getTypes();
783 assert(!Types.empty() && "No types at all?");
784 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
786 unsigned NumEntries = Types.size() - TypeNum;
788 // Output type header: [num entries]
789 output_vbr(NumEntries);
791 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
792 outputType(Types[i]);
795 // Helper function for outputConstants().
796 // Writes out all the constants in the plane Plane starting at entry StartNo.
798 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
799 &Plane, unsigned StartNo) {
800 unsigned ValNo = StartNo;
802 // Scan through and ignore function arguments, global values, and constant
804 for (; ValNo < Plane.size() &&
805 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
806 (isa<ConstantArray>(Plane[ValNo]) &&
807 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
810 unsigned NC = ValNo; // Number of constants
811 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
813 NC -= ValNo; // Convert from index into count
814 if (NC == 0) return; // Skip empty type planes...
816 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
819 // Output type header: [num entries][type id number]
823 // Output the Type ID Number...
824 int Slot = Table.getSlot(Plane.front()->getType());
825 assert (Slot != -1 && "Type in constant pool but not in function!!");
826 output_typeid((unsigned)Slot);
828 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
829 const Value *V = Plane[i];
830 if (const Constant *C = dyn_cast<Constant>(V)) {
836 static inline bool hasNullValue(unsigned TyID) {
837 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
840 void BytecodeWriter::outputConstants(bool isFunction) {
841 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
842 true /* Elide block if empty */);
844 unsigned NumPlanes = Table.getNumPlanes();
847 // Output the type plane before any constants!
848 outputTypes( Table.getModuleTypeLevel() );
850 // Output module-level string constants before any other constants.x
851 outputConstantStrings();
853 for (unsigned pno = 0; pno != NumPlanes; pno++) {
854 const std::vector<const Value*> &Plane = Table.getPlane(pno);
855 if (!Plane.empty()) { // Skip empty type planes...
857 if (isFunction) // Don't re-emit module constants
858 ValNo += Table.getModuleLevel(pno);
860 if (hasNullValue(pno)) {
861 // Skip zero initializer
866 // Write out constants in the plane
867 outputConstantsInPlane(Plane, ValNo);
872 static unsigned getEncodedLinkage(const GlobalValue *GV) {
873 switch (GV->getLinkage()) {
874 default: assert(0 && "Invalid linkage!");
875 case GlobalValue::ExternalLinkage: return 0;
876 case GlobalValue::WeakLinkage: return 1;
877 case GlobalValue::AppendingLinkage: return 2;
878 case GlobalValue::InternalLinkage: return 3;
879 case GlobalValue::LinkOnceLinkage: return 4;
883 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
884 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
886 // Output the types for the global variables in the module...
887 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
888 int Slot = Table.getSlot(I->getType());
889 assert(Slot != -1 && "Module global vars is broken!");
891 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
892 // bit5+ = Slot # for type
893 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
894 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
897 // If we have an initializer, output it now.
898 if (I->hasInitializer()) {
899 Slot = Table.getSlot((Value*)I->getInitializer());
900 assert(Slot != -1 && "No slot for global var initializer!");
901 output_vbr((unsigned)Slot);
904 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
906 // Output the types of the functions in this module...
907 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
908 int Slot = Table.getSlot(I->getType());
909 assert(Slot != -1 && "Module const pool is broken!");
910 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
911 output_typeid((unsigned)Slot);
913 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
915 // Put out the list of dependent libraries for the Module
916 Module::lib_iterator LI = M->lib_begin();
917 Module::lib_iterator LE = M->lib_end();
918 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
919 for ( ; LI != LE; ++LI ) {
923 // Output the target triple from the module
924 output(M->getTargetTriple());
927 void BytecodeWriter::outputInstructions(const Function *F) {
928 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
929 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
930 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
931 outputInstruction(*I);
934 void BytecodeWriter::outputFunction(const Function *F) {
935 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
936 output_vbr(getEncodedLinkage(F));
938 // If this is an external function, there is nothing else to emit!
939 if (F->isExternal()) return;
941 // Get slot information about the function...
942 Table.incorporateFunction(F);
944 if (Table.getCompactionTable().empty()) {
945 // Output information about the constants in the function if the compaction
946 // table is not being used.
947 outputConstants(true);
949 // Otherwise, emit the compaction table.
950 outputCompactionTable();
953 // Output all of the instructions in the body of the function
954 outputInstructions(F);
956 // If needed, output the symbol table for the function...
957 outputSymbolTable(F->getSymbolTable());
959 Table.purgeFunction();
962 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
963 const std::vector<const Value*> &Plane,
965 unsigned End = Table.getModuleLevel(PlaneNo);
966 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
967 assert(StartNo < End && "Cannot emit negative range!");
968 assert(StartNo < Plane.size() && End <= Plane.size());
970 // Do not emit the null initializer!
973 // Figure out which encoding to use. By far the most common case we have is
974 // to emit 0-2 entries in a compaction table plane.
975 switch (End-StartNo) {
976 case 0: // Avoid emitting two vbr's if possible.
979 output_vbr((PlaneNo << 2) | End-StartNo);
982 // Output the number of things.
983 output_vbr((unsigned(End-StartNo) << 2) | 3);
984 output_typeid(PlaneNo); // Emit the type plane this is
988 for (unsigned i = StartNo; i != End; ++i)
989 output_vbr(Table.getGlobalSlot(Plane[i]));
992 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
993 // Get the compaction type table from the slot calculator
994 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
996 // The compaction types may have been uncompactified back to the
997 // global types. If so, we just write an empty table
998 if (CTypes.size() == 0 ) {
1003 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1005 // Determine how many types to write
1006 unsigned NumTypes = CTypes.size() - StartNo;
1008 // Output the number of types.
1009 output_vbr(NumTypes);
1011 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1012 output_typeid(Table.getGlobalSlot(CTypes[i]));
1015 void BytecodeWriter::outputCompactionTable() {
1016 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1017 true/*ElideIfEmpty*/);
1018 const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1020 // First thing is first, emit the type compaction table if there is one.
1021 outputCompactionTypes(Type::FirstDerivedTyID);
1023 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1024 outputCompactionTablePlane(i, CT[i], 0);
1027 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
1028 // Do not output the Bytecode block for an empty symbol table, it just wastes
1030 if ( MST.isEmpty() ) return;
1032 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
1033 true/* ElideIfEmpty*/);
1035 // Write the number of types
1036 output_vbr(MST.num_types());
1038 // Write each of the types
1039 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1040 TE = MST.type_end(); TI != TE; ++TI ) {
1041 // Symtab entry:[def slot #][name]
1042 output_typeid((unsigned)Table.getSlot(TI->second));
1046 // Now do each of the type planes in order.
1047 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1048 PE = MST.plane_end(); PI != PE; ++PI) {
1049 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1050 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1053 if (I == End) continue; // Don't mess with an absent type...
1055 // Write the number of values in this plane
1056 output_vbr(MST.type_size(PI->first));
1058 // Write the slot number of the type for this plane
1059 Slot = Table.getSlot(PI->first);
1060 assert(Slot != -1 && "Type in symtab, but not in table!");
1061 output_typeid((unsigned)Slot);
1063 // Write each of the values in this plane
1064 for (; I != End; ++I) {
1065 // Symtab entry: [def slot #][name]
1066 Slot = Table.getSlot(I->second);
1067 assert(Slot != -1 && "Value in symtab but has no slot number!!");
1068 output_vbr((unsigned)Slot);
1074 void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1075 assert(M && "You can't write a null module!!");
1077 std::vector<unsigned char> Buffer;
1078 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
1080 // This object populates buffer for us...
1081 BytecodeWriter BCW(Buffer, M);
1083 // Keep track of how much we've written...
1084 BytesWritten += Buffer.size();
1086 // Okay, write the deque out to the ostream now... the deque is not
1087 // sequential in memory, however, so write out as much as possible in big
1088 // chunks, until we're done.
1091 std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
1092 while (I != E) { // Loop until it's all written
1093 // Scan to see how big this chunk is...
1094 const unsigned char *ChunkPtr = &*I;
1095 const unsigned char *LastPtr = ChunkPtr;
1097 const unsigned char *ThisPtr = &*++I;
1098 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
1102 // Write out the chunk...
1103 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));