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 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
37 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
39 //===----------------------------------------------------------------------===//
40 //=== Output Primitives ===//
41 //===----------------------------------------------------------------------===//
43 // output - If a position is specified, it must be in the valid portion of the
44 // string... note that this should be inlined always so only the relevant IF
45 // body should be included.
46 inline void BytecodeWriter::output(unsigned i, int pos) {
47 if (pos == -1) { // Be endian clean, little endian is our friend
48 Out.push_back((unsigned char)i);
49 Out.push_back((unsigned char)(i >> 8));
50 Out.push_back((unsigned char)(i >> 16));
51 Out.push_back((unsigned char)(i >> 24));
53 Out[pos ] = (unsigned char)i;
54 Out[pos+1] = (unsigned char)(i >> 8);
55 Out[pos+2] = (unsigned char)(i >> 16);
56 Out[pos+3] = (unsigned char)(i >> 24);
60 inline void BytecodeWriter::output(int i) {
64 /// output_vbr - Output an unsigned value, by using the least number of bytes
65 /// possible. This is useful because many of our "infinite" values are really
66 /// very small most of the time; but can be large a few times.
67 /// Data format used: If you read a byte with the high bit set, use the low
68 /// seven bits as data and then read another byte. Note that using this may
69 /// cause the output buffer to become unaligned.
70 inline void BytecodeWriter::output_vbr(uint64_t i) {
72 if (i < 0x80) { // done?
73 Out.push_back((unsigned char)i); // We know the high bit is clear...
77 // Nope, we are bigger than a character, output the next 7 bits and set the
78 // high bit to say that there is more coming...
79 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
80 i >>= 7; // Shift out 7 bits now...
84 inline void BytecodeWriter::output_vbr(unsigned i) {
86 if (i < 0x80) { // done?
87 Out.push_back((unsigned char)i); // We know the high bit is clear...
91 // Nope, we are bigger than a character, output the next 7 bits and set the
92 // high bit to say that there is more coming...
93 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
94 i >>= 7; // Shift out 7 bits now...
98 inline void BytecodeWriter::output_typeid(unsigned i) {
102 this->output_vbr(0x00FFFFFF);
107 inline void BytecodeWriter::output_vbr(int64_t i) {
109 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
111 output_vbr((uint64_t)i << 1); // Low order bit is clear.
115 inline void BytecodeWriter::output_vbr(int i) {
117 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
119 output_vbr((unsigned)i << 1); // Low order bit is clear.
122 // align32 - emit the minimal number of bytes that will bring us to 32 bit
125 inline void BytecodeWriter::align32() {
126 int NumPads = (4-(Out.size() & 3)) & 3; // Bytes to get padding to 32 bits
127 while (NumPads--) Out.push_back((unsigned char)0xAB);
130 inline void BytecodeWriter::output(const std::string &s, bool Aligned ) {
131 unsigned Len = s.length();
132 output_vbr(Len ); // Strings may have an arbitrary length...
133 Out.insert(Out.end(), s.begin(), s.end());
136 align32(); // Make sure we are now aligned...
139 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
140 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
143 inline void BytecodeWriter::output_float(float& FloatVal) {
144 /// FIXME: This isn't optimal, it has size problems on some platforms
145 /// where FP is not IEEE.
150 FloatUnion.f = FloatVal;
151 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
152 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
153 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
154 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
157 inline void BytecodeWriter::output_double(double& DoubleVal) {
158 /// FIXME: This isn't optimal, it has size problems on some platforms
159 /// where FP is not IEEE.
164 DoubleUnion.d = DoubleVal;
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
167 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
168 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
169 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
170 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
171 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
172 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
175 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
176 bool elideIfEmpty, bool hasLongFormat )
177 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
181 w.output(0U); // For length in long format
183 w.output(0U); /// Place holder for ID and length for this block
188 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
190 if (Loc == Writer.size() && ElideIfEmpty) {
191 // If the block is empty, and we are allowed to, do not emit the block at
193 Writer.resize(Writer.size()-(HasLongFormat?8:4));
197 //cerr << "OldLoc = " << Loc << " NewLoc = " << NewLoc << " diff = "
198 // << (NewLoc-Loc) << endl;
200 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
202 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
203 Writer.align32(); // Blocks must ALWAYS be aligned
206 //===----------------------------------------------------------------------===//
207 //=== Constant Output ===//
208 //===----------------------------------------------------------------------===//
210 void BytecodeWriter::outputType(const Type *T) {
211 output_vbr((unsigned)T->getTypeID());
213 // That's all there is to handling primitive types...
214 if (T->isPrimitiveType()) {
215 return; // We might do this if we alias a prim type: %x = type int
218 switch (T->getTypeID()) { // Handle derived types now.
219 case Type::FunctionTyID: {
220 const FunctionType *MT = cast<FunctionType>(T);
221 int Slot = Table.getSlot(MT->getReturnType());
222 assert(Slot != -1 && "Type used but not available!!");
223 output_typeid((unsigned)Slot);
225 // Output the number of arguments to function (+1 if varargs):
226 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
228 // Output all of the arguments...
229 FunctionType::param_iterator I = MT->param_begin();
230 for (; I != MT->param_end(); ++I) {
231 Slot = Table.getSlot(*I);
232 assert(Slot != -1 && "Type used but not available!!");
233 output_typeid((unsigned)Slot);
236 // Terminate list with VoidTy if we are a varargs function...
238 output_typeid((unsigned)Type::VoidTyID);
242 case Type::ArrayTyID: {
243 const ArrayType *AT = cast<ArrayType>(T);
244 int Slot = Table.getSlot(AT->getElementType());
245 assert(Slot != -1 && "Type used but not available!!");
246 output_typeid((unsigned)Slot);
247 //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
249 output_vbr(AT->getNumElements());
253 case Type::StructTyID: {
254 const StructType *ST = cast<StructType>(T);
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);
264 // Terminate list with VoidTy
265 output_typeid((unsigned)Type::VoidTyID);
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);
277 case Type::OpaqueTyID: {
278 // No need to emit anything, just the count of opaque types is enough.
282 //case Type::PackedTyID:
284 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
285 << " Type '" << T->getDescription() << "'\n";
290 void BytecodeWriter::outputConstant(const Constant *CPV) {
291 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
292 "Shouldn't output null constants!");
294 // We must check for a ConstantExpr before switching by type because
295 // a ConstantExpr can be of any type, and has no explicit value.
297 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
298 // FIXME: Encoding of constant exprs could be much more compact!
299 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
300 output_vbr(CE->getNumOperands()); // flags as an expr
301 output_vbr(CE->getOpcode()); // flags as an expr
303 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
304 int Slot = Table.getSlot(*OI);
305 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
306 output_vbr((unsigned)Slot);
307 Slot = Table.getSlot((*OI)->getType());
308 output_typeid((unsigned)Slot);
312 output_vbr(0U); // flag as not a ConstantExpr
315 switch (CPV->getType()->getTypeID()) {
316 case Type::BoolTyID: // Boolean Types
317 if (cast<ConstantBool>(CPV)->getValue())
323 case Type::UByteTyID: // Unsigned integer types...
324 case Type::UShortTyID:
326 case Type::ULongTyID:
327 output_vbr(cast<ConstantUInt>(CPV)->getValue());
330 case Type::SByteTyID: // Signed integer types...
331 case Type::ShortTyID:
334 output_vbr(cast<ConstantSInt>(CPV)->getValue());
337 case Type::ArrayTyID: {
338 const ConstantArray *CPA = cast<ConstantArray>(CPV);
339 assert(!CPA->isString() && "Constant strings should be handled specially!");
341 for (unsigned i = 0; i != CPA->getNumOperands(); ++i) {
342 int Slot = Table.getSlot(CPA->getOperand(i));
343 assert(Slot != -1 && "Constant used but not available!!");
344 output_vbr((unsigned)Slot);
349 case Type::StructTyID: {
350 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
351 const std::vector<Use> &Vals = CPS->getValues();
353 for (unsigned i = 0; i < Vals.size(); ++i) {
354 int Slot = Table.getSlot(Vals[i]);
355 assert(Slot != -1 && "Constant used but not available!!");
356 output_vbr((unsigned)Slot);
361 case Type::PointerTyID:
362 assert(0 && "No non-null, non-constant-expr constants allowed!");
365 case Type::FloatTyID: { // Floating point types...
366 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
370 case Type::DoubleTyID: {
371 double Tmp = cast<ConstantFP>(CPV)->getValue();
377 case Type::LabelTyID:
379 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
380 << " type '" << *CPV->getType() << "'\n";
386 void BytecodeWriter::outputConstantStrings() {
387 SlotCalculator::string_iterator I = Table.string_begin();
388 SlotCalculator::string_iterator E = Table.string_end();
389 if (I == E) return; // No strings to emit
391 // If we have != 0 strings to emit, output them now. Strings are emitted into
392 // the 'void' type plane.
393 output_vbr(unsigned(E-I));
394 output_typeid(Type::VoidTyID);
396 // Emit all of the strings.
397 for (I = Table.string_begin(); I != E; ++I) {
398 const ConstantArray *Str = *I;
399 int Slot = Table.getSlot(Str->getType());
400 assert(Slot != -1 && "Constant string of unknown type?");
401 output_typeid((unsigned)Slot);
403 // Now that we emitted the type (which indicates the size of the string),
404 // emit all of the characters.
405 std::string Val = Str->getAsString();
406 output_data(Val.c_str(), Val.c_str()+Val.size());
410 //===----------------------------------------------------------------------===//
411 //=== Instruction Output ===//
412 //===----------------------------------------------------------------------===//
413 typedef unsigned char uchar;
415 // outputInstructionFormat0 - Output those wierd instructions that have a large
416 // number of operands or have large operands themselves...
418 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
420 void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
421 const SlotCalculator &Table,
423 // Opcode must have top two bits clear...
424 output_vbr(Opcode << 2); // Instruction Opcode ID
425 output_typeid(Type); // Result type
427 unsigned NumArgs = I->getNumOperands();
428 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
431 if (!isa<GetElementPtrInst>(&I)) {
432 for (unsigned i = 0; i < NumArgs; ++i) {
433 int Slot = Table.getSlot(I->getOperand(i));
434 assert(Slot >= 0 && "No slot number for value!?!?");
435 output_vbr((unsigned)Slot);
438 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
439 int Slot = Table.getSlot(I->getType());
440 assert(Slot != -1 && "Cast return type unknown?");
441 output_typeid((unsigned)Slot);
442 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
443 int Slot = Table.getSlot(VAI->getArgType());
444 assert(Slot != -1 && "VarArg argument type unknown?");
445 output_typeid((unsigned)Slot);
449 int Slot = Table.getSlot(I->getOperand(0));
450 assert(Slot >= 0 && "No slot number for value!?!?");
451 output_vbr(unsigned(Slot));
453 // We need to encode the type of sequential type indices into their slot #
455 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
456 Idx != NumArgs; ++TI, ++Idx) {
457 Slot = Table.getSlot(I->getOperand(Idx));
458 assert(Slot >= 0 && "No slot number for value!?!?");
460 if (isa<SequentialType>(*TI)) {
462 switch (I->getOperand(Idx)->getType()->getTypeID()) {
463 default: assert(0 && "Unknown index type!");
464 case Type::UIntTyID: IdxId = 0; break;
465 case Type::IntTyID: IdxId = 1; break;
466 case Type::ULongTyID: IdxId = 2; break;
467 case Type::LongTyID: IdxId = 3; break;
469 Slot = (Slot << 2) | IdxId;
471 output_vbr(unsigned(Slot));
475 align32(); // We must maintain correct alignment!
479 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
480 // This are more annoying than most because the signature of the call does not
481 // tell us anything about the types of the arguments in the varargs portion.
482 // Because of this, we encode (as type 0) all of the argument types explicitly
483 // before the argument value. This really sucks, but you shouldn't be using
484 // varargs functions in your code! *death to printf*!
486 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
488 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
490 const SlotCalculator &Table,
492 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
493 // Opcode must have top two bits clear...
494 output_vbr(Opcode << 2); // Instruction Opcode ID
495 output_typeid(Type); // Result type (varargs type)
497 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
498 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
499 unsigned NumParams = FTy->getNumParams();
501 unsigned NumFixedOperands;
502 if (isa<CallInst>(I)) {
503 // Output an operand for the callee and each fixed argument, then two for
504 // each variable argument.
505 NumFixedOperands = 1+NumParams;
507 assert(isa<InvokeInst>(I) && "Not call or invoke??");
508 // Output an operand for the callee and destinations, then two for each
509 // variable argument.
510 NumFixedOperands = 3+NumParams;
512 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
514 // The type for the function has already been emitted in the type field of the
515 // instruction. Just emit the slot # now.
516 for (unsigned i = 0; i != NumFixedOperands; ++i) {
517 int Slot = Table.getSlot(I->getOperand(i));
518 assert(Slot >= 0 && "No slot number for value!?!?");
519 output_vbr((unsigned)Slot);
522 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
523 // Output Arg Type ID
524 int Slot = Table.getSlot(I->getOperand(i)->getType());
525 assert(Slot >= 0 && "No slot number for value!?!?");
526 output_typeid((unsigned)Slot);
528 // Output arg ID itself
529 Slot = Table.getSlot(I->getOperand(i));
530 assert(Slot >= 0 && "No slot number for value!?!?");
531 output_vbr((unsigned)Slot);
533 align32(); // We must maintain correct alignment!
537 // outputInstructionFormat1 - Output one operand instructions, knowing that no
538 // operand index is >= 2^12.
540 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
544 // bits Instruction format:
545 // --------------------------
546 // 01-00: Opcode type, fixed to 1.
548 // 19-08: Resulting type plane
549 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
551 unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
552 // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
557 // outputInstructionFormat2 - Output two operand instructions, knowing that no
558 // operand index is >= 2^8.
560 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
564 // bits Instruction format:
565 // --------------------------
566 // 01-00: Opcode type, fixed to 2.
568 // 15-08: Resulting type plane
572 unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
573 (Slots[0] << 16) | (Slots[1] << 24);
574 // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " "
575 // << Slots[1] << endl;
580 // outputInstructionFormat3 - Output three operand instructions, knowing that no
581 // operand index is >= 2^6.
583 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
587 // bits Instruction format:
588 // --------------------------
589 // 01-00: Opcode type, fixed to 3.
591 // 13-08: Resulting type plane
596 unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
597 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
598 //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " "
599 // << Slots[1] << " " << Slots[2] << endl;
603 void BytecodeWriter::outputInstruction(const Instruction &I) {
604 assert(I.getOpcode() < 62 && "Opcode too big???");
605 unsigned Opcode = I.getOpcode();
606 unsigned NumOperands = I.getNumOperands();
608 // Encode 'volatile load' as 62 and 'volatile store' as 63.
609 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
611 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
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.
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
627 case Instruction::Store:
628 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
629 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
631 default: // Otherwise use the default behavior...
632 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
637 int Slot = Table.getSlot(Ty);
638 assert(Slot != -1 && "Type not available!!?!");
639 Type = (unsigned)Slot;
641 // Varargs calls and invokes are encoded entirely different from any other
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);
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);
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.
661 unsigned MaxOpSlot = Type;
662 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
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);
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];
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];
684 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
685 // We need to encode the type of sequential type indices into their slot #
687 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
689 if (isa<SequentialType>(*I)) {
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;
698 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
699 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
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
708 switch (NumOperands) {
711 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
712 outputInstructionFormat1(&I, Opcode, Slots, Type);
718 if (MaxOpSlot < (1 << 8)) {
719 outputInstructionFormat2(&I, Opcode, Slots, Type);
725 if (MaxOpSlot < (1 << 6)) {
726 outputInstructionFormat3(&I, Opcode, Slots, Type);
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);
740 //===----------------------------------------------------------------------===//
741 //=== Block Output ===//
742 //===----------------------------------------------------------------------===//
744 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
747 // Emit the signature...
748 static const unsigned char *Sig = (const unsigned char*)"llvm";
749 output_data(Sig, Sig+4);
751 // Emit the top level CLASS block.
752 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
754 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;
759 // Output the version identifier... we are currently on bytecode version #2,
760 // which corresponds to LLVM v1.3.
761 unsigned Version = (3 << 4) | (unsigned)isBigEndian | (hasLongPointers << 1) |
762 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
766 // The Global type plane comes first
768 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
769 outputTypes(Type::FirstDerivedTyID);
772 // The ModuleInfoBlock follows directly after the type information
773 outputModuleInfoBlock(M);
775 // Output module level constants, used for global variable initializers
776 outputConstants(false);
778 // Do the whole module now! Process each function at a time...
779 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
782 // If needed, output the symbol table for the module...
783 outputSymbolTable(M->getSymbolTable());
786 void BytecodeWriter::outputTypes(unsigned TypeNum)
788 // Write the type plane for types first because earlier planes (e.g. for a
789 // primitive type like float) may have constants constructed using types
790 // coming later (e.g., via getelementptr from a pointer type). The type
791 // plane is needed before types can be fwd or bkwd referenced.
792 const std::vector<const Type*>& Types = Table.getTypes();
793 assert(!Types.empty() && "No types at all?");
794 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
796 unsigned NumEntries = Types.size() - TypeNum;
798 // Output type header: [num entries]
799 output_vbr(NumEntries);
801 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
802 outputType(Types[i]);
805 // Helper function for outputConstants().
806 // Writes out all the constants in the plane Plane starting at entry StartNo.
808 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
809 &Plane, unsigned StartNo) {
810 unsigned ValNo = StartNo;
812 // Scan through and ignore function arguments, global values, and constant
814 for (; ValNo < Plane.size() &&
815 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
816 (isa<ConstantArray>(Plane[ValNo]) &&
817 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
820 unsigned NC = ValNo; // Number of constants
821 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
823 NC -= ValNo; // Convert from index into count
824 if (NC == 0) return; // Skip empty type planes...
826 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
829 // Output type header: [num entries][type id number]
833 // Output the Type ID Number...
834 int Slot = Table.getSlot(Plane.front()->getType());
835 assert (Slot != -1 && "Type in constant pool but not in function!!");
836 output_typeid((unsigned)Slot);
838 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
839 const Value *V = Plane[i];
840 if (const Constant *C = dyn_cast<Constant>(V)) {
846 static inline bool hasNullValue(unsigned TyID) {
847 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
850 void BytecodeWriter::outputConstants(bool isFunction) {
851 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
852 true /* Elide block if empty */);
854 unsigned NumPlanes = Table.getNumPlanes();
857 // Output the type plane before any constants!
858 outputTypes( Table.getModuleTypeLevel() );
860 // Output module-level string constants before any other constants.x
861 outputConstantStrings();
863 for (unsigned pno = 0; pno != NumPlanes; pno++) {
864 const std::vector<const Value*> &Plane = Table.getPlane(pno);
865 if (!Plane.empty()) { // Skip empty type planes...
867 if (isFunction) // Don't re-emit module constants
868 ValNo += Table.getModuleLevel(pno);
870 if (hasNullValue(pno)) {
871 // Skip zero initializer
876 // Write out constants in the plane
877 outputConstantsInPlane(Plane, ValNo);
882 static unsigned getEncodedLinkage(const GlobalValue *GV) {
883 switch (GV->getLinkage()) {
884 default: assert(0 && "Invalid linkage!");
885 case GlobalValue::ExternalLinkage: return 0;
886 case GlobalValue::WeakLinkage: return 1;
887 case GlobalValue::AppendingLinkage: return 2;
888 case GlobalValue::InternalLinkage: return 3;
889 case GlobalValue::LinkOnceLinkage: return 4;
893 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
894 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
896 // Output the types for the global variables in the module...
897 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
898 int Slot = Table.getSlot(I->getType());
899 assert(Slot != -1 && "Module global vars is broken!");
901 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
902 // bit5+ = Slot # for type
903 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
904 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
907 // If we have an initializer, output it now.
908 if (I->hasInitializer()) {
909 Slot = Table.getSlot((Value*)I->getInitializer());
910 assert(Slot != -1 && "No slot for global var initializer!");
911 output_vbr((unsigned)Slot);
914 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
916 // Output the types of the functions in this module...
917 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
918 int Slot = Table.getSlot(I->getType());
919 assert(Slot != -1 && "Module const pool is broken!");
920 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
921 output_typeid((unsigned)Slot);
923 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
925 // Put out the list of dependent libraries for the Module
926 Module::lib_iterator LI = M->lib_begin();
927 Module::lib_iterator LE = M->lib_end();
928 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
929 for ( ; LI != LE; ++LI ) {
930 output(*LI, /*aligned=*/false);
933 // Output the target triple from the module
934 output(M->getTargetTriple(), /*aligned=*/ true);
937 void BytecodeWriter::outputInstructions(const Function *F) {
938 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
939 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
940 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
941 outputInstruction(*I);
944 void BytecodeWriter::outputFunction(const Function *F) {
945 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
946 output_vbr(getEncodedLinkage(F));
948 // If this is an external function, there is nothing else to emit!
949 if (F->isExternal()) return;
951 // Get slot information about the function...
952 Table.incorporateFunction(F);
954 if (Table.getCompactionTable().empty()) {
955 // Output information about the constants in the function if the compaction
956 // table is not being used.
957 outputConstants(true);
959 // Otherwise, emit the compaction table.
960 outputCompactionTable();
963 // Output all of the instructions in the body of the function
964 outputInstructions(F);
966 // If needed, output the symbol table for the function...
967 outputSymbolTable(F->getSymbolTable());
969 Table.purgeFunction();
972 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
973 const std::vector<const Value*> &Plane,
975 unsigned End = Table.getModuleLevel(PlaneNo);
976 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
977 assert(StartNo < End && "Cannot emit negative range!");
978 assert(StartNo < Plane.size() && End <= Plane.size());
980 // Do not emit the null initializer!
983 // Figure out which encoding to use. By far the most common case we have is
984 // to emit 0-2 entries in a compaction table plane.
985 switch (End-StartNo) {
986 case 0: // Avoid emitting two vbr's if possible.
989 output_vbr((PlaneNo << 2) | End-StartNo);
992 // Output the number of things.
993 output_vbr((unsigned(End-StartNo) << 2) | 3);
994 output_typeid(PlaneNo); // Emit the type plane this is
998 for (unsigned i = StartNo; i != End; ++i)
999 output_vbr(Table.getGlobalSlot(Plane[i]));
1002 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1003 // Get the compaction type table from the slot calculator
1004 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1006 // The compaction types may have been uncompactified back to the
1007 // global types. If so, we just write an empty table
1008 if (CTypes.size() == 0 ) {
1013 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1015 // Determine how many types to write
1016 unsigned NumTypes = CTypes.size() - StartNo;
1018 // Output the number of types.
1019 output_vbr(NumTypes);
1021 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1022 output_typeid(Table.getGlobalSlot(CTypes[i]));
1025 void BytecodeWriter::outputCompactionTable() {
1026 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1027 true/*ElideIfEmpty*/);
1028 const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1030 // First thing is first, emit the type compaction table if there is one.
1031 outputCompactionTypes(Type::FirstDerivedTyID);
1033 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1034 outputCompactionTablePlane(i, CT[i], 0);
1037 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
1038 // Do not output the Bytecode block for an empty symbol table, it just wastes
1040 if ( MST.isEmpty() ) return;
1042 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
1043 true/* ElideIfEmpty*/);
1045 //Symtab block header for types: [num entries]
1046 output_vbr(MST.num_types());
1047 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1048 TE = MST.type_end(); TI != TE; ++TI ) {
1049 //Symtab entry:[def slot #][name]
1050 output_typeid((unsigned)Table.getSlot(TI->second));
1051 output(TI->first, /*align=*/false);
1054 // Now do each of the type planes in order.
1055 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1056 PE = MST.plane_end(); PI != PE; ++PI) {
1057 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1058 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1061 if (I == End) continue; // Don't mess with an absent type...
1063 // Symtab block header: [num entries][type id number]
1064 output_vbr(MST.type_size(PI->first));
1066 Slot = Table.getSlot(PI->first);
1067 assert(Slot != -1 && "Type in symtab, but not in table!");
1068 output_typeid((unsigned)Slot);
1070 for (; I != End; ++I) {
1071 // Symtab entry: [def slot #][name]
1072 Slot = Table.getSlot(I->second);
1073 assert(Slot != -1 && "Value in symtab but has no slot number!!");
1074 output_vbr((unsigned)Slot);
1075 output(I->first, false); // Don't force alignment...
1080 void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1081 assert(M && "You can't write a null module!!");
1083 std::vector<unsigned char> Buffer;
1084 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
1086 // This object populates buffer for us...
1087 BytecodeWriter BCW(Buffer, M);
1089 // Keep track of how much we've written...
1090 BytesWritten += Buffer.size();
1092 // Okay, write the deque out to the ostream now... the deque is not
1093 // sequential in memory, however, so write out as much as possible in big
1094 // chunks, until we're done.
1097 std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
1098 while (I != E) { // Loop until it's all written
1099 // Scan to see how big this chunk is...
1100 const unsigned char *ChunkPtr = &*I;
1101 const unsigned char *LastPtr = ChunkPtr;
1103 const unsigned char *ThisPtr = &*++I;
1104 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
1108 // Write out the chunk...
1109 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));