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 #define DEBUG_TYPE "bytecodewriter"
21 #include "WriterInternals.h"
22 #include "llvm/Bytecode/WriteBytecodePass.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Module.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ValueSymbolTable.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/Compressor.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Streams.h"
35 #include "llvm/System/Program.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/Statistic.h"
43 /// This value needs to be incremented every time the bytecode format changes
44 /// so that the reader can distinguish which format of the bytecode file has
46 /// @brief The bytecode version number
47 const unsigned BCVersionNum = 7;
49 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
51 STATISTIC(BytesWritten, "Number of bytecode bytes written");
53 //===----------------------------------------------------------------------===//
54 //=== Output Primitives ===//
55 //===----------------------------------------------------------------------===//
57 // output - If a position is specified, it must be in the valid portion of the
58 // string... note that this should be inlined always so only the relevant IF
59 // body should be included.
60 inline void BytecodeWriter::output(unsigned i, int pos) {
61 if (pos == -1) { // Be endian clean, little endian is our friend
62 Out.push_back((unsigned char)i);
63 Out.push_back((unsigned char)(i >> 8));
64 Out.push_back((unsigned char)(i >> 16));
65 Out.push_back((unsigned char)(i >> 24));
67 Out[pos ] = (unsigned char)i;
68 Out[pos+1] = (unsigned char)(i >> 8);
69 Out[pos+2] = (unsigned char)(i >> 16);
70 Out[pos+3] = (unsigned char)(i >> 24);
74 inline void BytecodeWriter::output(int32_t i) {
78 /// output_vbr - Output an unsigned value, by using the least number of bytes
79 /// possible. This is useful because many of our "infinite" values are really
80 /// very small most of the time; but can be large a few times.
81 /// Data format used: If you read a byte with the high bit set, use the low
82 /// seven bits as data and then read another byte.
83 inline void BytecodeWriter::output_vbr(uint64_t i) {
85 if (i < 0x80) { // done?
86 Out.push_back((unsigned char)i); // We know the high bit is clear...
90 // Nope, we are bigger than a character, output the next 7 bits and set the
91 // high bit to say that there is more coming...
92 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
93 i >>= 7; // Shift out 7 bits now...
97 inline void BytecodeWriter::output_vbr(uint32_t i) {
99 if (i < 0x80) { // done?
100 Out.push_back((unsigned char)i); // We know the high bit is clear...
104 // Nope, we are bigger than a character, output the next 7 bits and set the
105 // high bit to say that there is more coming...
106 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
107 i >>= 7; // Shift out 7 bits now...
111 inline void BytecodeWriter::output_typeid(unsigned i) {
115 this->output_vbr(0x00FFFFFF);
120 inline void BytecodeWriter::output_vbr(int64_t i) {
122 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
124 output_vbr((uint64_t)i << 1); // Low order bit is clear.
128 inline void BytecodeWriter::output_vbr(int i) {
130 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
132 output_vbr((unsigned)i << 1); // Low order bit is clear.
135 inline void BytecodeWriter::output(const std::string &s) {
136 unsigned Len = s.length();
137 output_vbr(Len); // Strings may have an arbitrary length.
138 Out.insert(Out.end(), s.begin(), s.end());
141 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
142 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
145 inline void BytecodeWriter::output_float(float& FloatVal) {
146 /// FIXME: This isn't optimal, it has size problems on some platforms
147 /// where FP is not IEEE.
148 uint32_t i = FloatToBits(FloatVal);
149 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
151 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
152 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
155 inline void BytecodeWriter::output_double(double& DoubleVal) {
156 /// FIXME: This isn't optimal, it has size problems on some platforms
157 /// where FP is not IEEE.
158 uint64_t i = DoubleToBits(DoubleVal);
159 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (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));
192 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
194 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
197 //===----------------------------------------------------------------------===//
198 //=== Constant Output ===//
199 //===----------------------------------------------------------------------===//
201 void BytecodeWriter::outputType(const Type *T) {
202 const StructType* STy = dyn_cast<StructType>(T);
203 if(STy && STy->isPacked())
204 output_vbr((unsigned)Type::PackedStructTyID);
206 output_vbr((unsigned)T->getTypeID());
208 // That's all there is to handling primitive types...
209 if (T->isPrimitiveType())
210 return; // We might do this if we alias a prim type: %x = type int
212 switch (T->getTypeID()) { // Handle derived types now.
213 case Type::IntegerTyID:
214 output_vbr(cast<IntegerType>(T)->getBitWidth());
216 case Type::FunctionTyID: {
217 const FunctionType *MT = cast<FunctionType>(T);
218 output_typeid(Table.getTypeSlot(MT->getReturnType()));
219 output_vbr(unsigned(MT->getParamAttrs(0)));
221 // Output the number of arguments to function (+1 if varargs):
222 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
224 // Output all of the arguments...
225 FunctionType::param_iterator I = MT->param_begin();
227 for (; I != MT->param_end(); ++I) {
228 output_typeid(Table.getTypeSlot(*I));
229 output_vbr(unsigned(MT->getParamAttrs(Idx)));
233 // Terminate list with VoidTy if we are a varargs function...
235 output_typeid((unsigned)Type::VoidTyID);
239 case Type::ArrayTyID: {
240 const ArrayType *AT = cast<ArrayType>(T);
241 output_typeid(Table.getTypeSlot(AT->getElementType()));
242 output_vbr(AT->getNumElements());
246 case Type::PackedTyID: {
247 const PackedType *PT = cast<PackedType>(T);
248 output_typeid(Table.getTypeSlot(PT->getElementType()));
249 output_vbr(PT->getNumElements());
253 case Type::StructTyID: {
254 const StructType *ST = cast<StructType>(T);
255 // Output all of the element types...
256 for (StructType::element_iterator I = ST->element_begin(),
257 E = ST->element_end(); I != E; ++I) {
258 output_typeid(Table.getTypeSlot(*I));
261 // Terminate list with VoidTy
262 output_typeid((unsigned)Type::VoidTyID);
266 case Type::PointerTyID:
267 output_typeid(Table.getTypeSlot(cast<PointerType>(T)->getElementType()));
270 case Type::OpaqueTyID:
271 // No need to emit anything, just the count of opaque types is enough.
275 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
276 << " Type '" << T->getDescription() << "'\n";
281 void BytecodeWriter::outputConstant(const Constant *CPV) {
282 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
283 !CPV->isNullValue()) && "Shouldn't output null constants!");
285 // We must check for a ConstantExpr before switching by type because
286 // a ConstantExpr can be of any type, and has no explicit value.
288 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
289 // FIXME: Encoding of constant exprs could be much more compact!
290 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
291 assert(CE->getNumOperands() != 1 || CE->isCast());
292 output_vbr(1+CE->getNumOperands()); // flags as an expr
293 output_vbr(CE->getOpcode()); // Put out the CE op code
295 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
296 output_vbr(Table.getSlot(*OI));
297 output_typeid(Table.getTypeSlot((*OI)->getType()));
300 output_vbr((unsigned)CE->getPredicate());
302 } else if (isa<UndefValue>(CPV)) {
303 output_vbr(1U); // 1 -> UndefValue constant.
306 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
309 switch (CPV->getType()->getTypeID()) {
310 case Type::IntegerTyID: { // Integer types...
311 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
313 output_vbr(uint32_t(cast<ConstantInt>(CPV)->getZExtValue()));
314 else if (NumBits <= 64)
315 output_vbr(uint64_t(cast<ConstantInt>(CPV)->getZExtValue()));
317 assert("Integer types > 64 bits not supported.");
321 case Type::ArrayTyID: {
322 const ConstantArray *CPA = cast<ConstantArray>(CPV);
323 assert(!CPA->isString() && "Constant strings should be handled specially!");
325 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
326 output_vbr(Table.getSlot(CPA->getOperand(i)));
330 case Type::PackedTyID: {
331 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
332 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
333 output_vbr(Table.getSlot(CP->getOperand(i)));
337 case Type::StructTyID: {
338 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
340 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
341 output_vbr(Table.getSlot(CPS->getOperand(i)));
345 case Type::PointerTyID:
346 assert(0 && "No non-null, non-constant-expr constants allowed!");
349 case Type::FloatTyID: { // Floating point types...
350 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
354 case Type::DoubleTyID: {
355 double Tmp = cast<ConstantFP>(CPV)->getValue();
361 case Type::LabelTyID:
363 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
364 << " type '" << *CPV->getType() << "'\n";
370 /// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
371 /// be shared by multiple uses.
372 void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
373 // Output a marker, so we know when we have one one parsing the constant pool.
374 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
375 // unique inline asms are rare, this should hardly matter.
378 output(IA->getAsmString());
379 output(IA->getConstraintString());
380 output_vbr(unsigned(IA->hasSideEffects()));
383 void BytecodeWriter::outputConstantStrings() {
384 SlotCalculator::string_iterator I = Table.string_begin();
385 SlotCalculator::string_iterator E = Table.string_end();
386 if (I == E) return; // No strings to emit
388 // If we have != 0 strings to emit, output them now. Strings are emitted into
389 // the 'void' type plane.
390 output_vbr(unsigned(E-I));
391 output_typeid(Type::VoidTyID);
393 // Emit all of the strings.
394 for (I = Table.string_begin(); I != E; ++I) {
395 const ConstantArray *Str = *I;
396 output_typeid(Table.getTypeSlot(Str->getType()));
398 // Now that we emitted the type (which indicates the size of the string),
399 // emit all of the characters.
400 std::string Val = Str->getAsString();
401 output_data(Val.c_str(), Val.c_str()+Val.size());
405 //===----------------------------------------------------------------------===//
406 //=== Instruction Output ===//
407 //===----------------------------------------------------------------------===//
409 // outputInstructionFormat0 - Output those weird instructions that have a large
410 // number of operands or have large operands themselves.
412 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
414 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
416 const SlotCalculator &Table,
418 // Opcode must have top two bits clear...
419 output_vbr(Opcode << 2); // Instruction Opcode ID
420 output_typeid(Type); // Result type
422 unsigned NumArgs = I->getNumOperands();
423 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
424 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
426 if (!isa<GetElementPtrInst>(&I)) {
427 for (unsigned i = 0; i < NumArgs; ++i)
428 output_vbr(Table.getSlot(I->getOperand(i)));
430 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
431 output_typeid(Table.getTypeSlot(I->getType()));
432 } else if (isa<CmpInst>(I)) {
433 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
434 } else if (isa<InvokeInst>(I)) {
435 output_vbr(cast<InvokeInst>(I)->getCallingConv());
436 } else if (Opcode == 58) { // Call escape sequence
437 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
438 unsigned(cast<CallInst>(I)->isTailCall()));
441 output_vbr(Table.getSlot(I->getOperand(0)));
443 // We need to encode the type of sequential type indices into their slot #
445 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
446 Idx != NumArgs; ++TI, ++Idx) {
447 unsigned Slot = Table.getSlot(I->getOperand(Idx));
449 if (isa<SequentialType>(*TI)) {
450 // These should be either 32-bits or 64-bits, however, with bit
451 // accurate types we just distinguish between less than or equal to
452 // 32-bits or greater than 32-bits.
454 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
455 assert(BitWidth == 32 || BitWidth == 64 &&
456 "Invalid bitwidth for GEP index");
457 unsigned IdxId = BitWidth == 32 ? 0 : 1;
458 Slot = (Slot << 1) | IdxId;
466 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
467 // This are more annoying than most because the signature of the call does not
468 // tell us anything about the types of the arguments in the varargs portion.
469 // Because of this, we encode (as type 0) all of the argument types explicitly
470 // before the argument value. This really sucks, but you shouldn't be using
471 // varargs functions in your code! *death to printf*!
473 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
475 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
477 const SlotCalculator &Table,
479 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
480 // Opcode must have top two bits clear...
481 output_vbr(Opcode << 2); // Instruction Opcode ID
482 output_typeid(Type); // Result type (varargs type)
484 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
485 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
486 unsigned NumParams = FTy->getNumParams();
488 unsigned NumFixedOperands;
489 if (isa<CallInst>(I)) {
490 // Output an operand for the callee and each fixed argument, then two for
491 // each variable argument.
492 NumFixedOperands = 1+NumParams;
494 assert(isa<InvokeInst>(I) && "Not call or invoke??");
495 // Output an operand for the callee and destinations, then two for each
496 // variable argument.
497 NumFixedOperands = 3+NumParams;
499 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
500 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
502 // The type for the function has already been emitted in the type field of the
503 // instruction. Just emit the slot # now.
504 for (unsigned i = 0; i != NumFixedOperands; ++i)
505 output_vbr(Table.getSlot(I->getOperand(i)));
507 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
508 // Output Arg Type ID
509 output_typeid(Table.getTypeSlot(I->getOperand(i)->getType()));
511 // Output arg ID itself
512 output_vbr(Table.getSlot(I->getOperand(i)));
515 if (isa<InvokeInst>(I)) {
516 // Emit the tail call/calling conv for invoke instructions
517 output_vbr(cast<InvokeInst>(I)->getCallingConv());
518 } else if (Opcode == 58) {
519 const CallInst *CI = cast<CallInst>(I);
520 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
525 // outputInstructionFormat1 - Output one operand instructions, knowing that no
526 // operand index is >= 2^12.
528 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
532 // bits Instruction format:
533 // --------------------------
534 // 01-00: Opcode type, fixed to 1.
536 // 19-08: Resulting type plane
537 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
539 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
543 // outputInstructionFormat2 - Output two operand instructions, knowing that no
544 // operand index is >= 2^8.
546 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
550 // bits Instruction format:
551 // --------------------------
552 // 01-00: Opcode type, fixed to 2.
554 // 15-08: Resulting type plane
558 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
562 // outputInstructionFormat3 - Output three operand instructions, knowing that no
563 // operand index is >= 2^6.
565 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
569 // bits Instruction format:
570 // --------------------------
571 // 01-00: Opcode type, fixed to 3.
573 // 13-08: Resulting type plane
578 output(3 | (Opcode << 2) | (Type << 8) |
579 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
582 void BytecodeWriter::outputInstruction(const Instruction &I) {
583 assert(I.getOpcode() < 57 && "Opcode too big???");
584 unsigned Opcode = I.getOpcode();
585 unsigned NumOperands = I.getNumOperands();
587 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
589 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
590 if (CI->getCallingConv() == CallingConv::C) {
591 if (CI->isTailCall())
592 Opcode = 61; // CCC + Tail Call
594 ; // Opcode = Instruction::Call
595 } else if (CI->getCallingConv() == CallingConv::Fast) {
596 if (CI->isTailCall())
597 Opcode = 59; // FastCC + TailCall
599 Opcode = 60; // FastCC + Not Tail Call
601 Opcode = 58; // Call escape sequence.
603 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
605 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
609 // Figure out which type to encode with the instruction. Typically we want
610 // the type of the first parameter, as opposed to the type of the instruction
611 // (for example, with setcc, we always know it returns bool, but the type of
612 // the first param is actually interesting). But if we have no arguments
613 // we take the type of the instruction itself.
616 switch (I.getOpcode()) {
617 case Instruction::Select:
618 case Instruction::Malloc:
619 case Instruction::Alloca:
620 Ty = I.getType(); // These ALWAYS want to encode the return type
622 case Instruction::Store:
623 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
624 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
626 default: // Otherwise use the default behavior...
627 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
631 unsigned Type = Table.getTypeSlot(Ty);
633 // Varargs calls and invokes are encoded entirely different from any other
635 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
636 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
637 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
638 outputInstrVarArgsCall(CI, Opcode, Table, Type);
641 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
642 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
643 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
644 outputInstrVarArgsCall(II, Opcode, Table, Type);
649 if (NumOperands <= 3) {
650 // Make sure that we take the type number into consideration. We don't want
651 // to overflow the field size for the instruction format we select.
653 unsigned MaxOpSlot = Type;
654 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
656 for (unsigned i = 0; i != NumOperands; ++i) {
657 unsigned Slot = Table.getSlot(I.getOperand(i));
658 if (Slot > MaxOpSlot) MaxOpSlot = Slot;
662 // Handle the special cases for various instructions...
663 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
664 // Cast has to encode the destination type as the second argument in the
665 // packet, or else we won't know what type to cast to!
666 Slots[1] = Table.getTypeSlot(I.getType());
667 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
669 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
670 assert(NumOperands == 1 && "Bogus allocation!");
671 if (AI->getAlignment()) {
672 Slots[1] = Log2_32(AI->getAlignment())+1;
673 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
676 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
677 // We need to encode the compare instruction's predicate as the third
678 // operand. Its not really a slot, but we don't want to break the
679 // instruction format for these instructions.
681 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
682 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
683 if (Slots[2] > MaxOpSlot)
684 MaxOpSlot = Slots[2];
685 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
686 // We need to encode the type of sequential type indices into their slot #
688 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
690 if (isa<SequentialType>(*I)) {
691 // These should be either 32-bits or 64-bits, however, with bit
692 // accurate types we just distinguish between less than or equal to
693 // 32-bits or greater than 32-bits.
695 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
696 assert(BitWidth == 32 || BitWidth == 64 &&
697 "Invalid bitwidth for GEP index");
698 unsigned IdxId = BitWidth == 32 ? 0 : 1;
699 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
700 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
702 } else if (Opcode == 58) {
703 // If this is the escape sequence for call, emit the tailcall/cc info.
704 const CallInst &CI = cast<CallInst>(I);
706 if (NumOperands <= 3) {
707 Slots[NumOperands-1] =
708 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
709 if (Slots[NumOperands-1] > MaxOpSlot)
710 MaxOpSlot = Slots[NumOperands-1];
712 } else if (isa<InvokeInst>(I)) {
713 // Invoke escape seq has at least 4 operands to encode.
717 // Decide which instruction encoding to use. This is determined primarily
718 // by the number of operands, and secondarily by whether or not the max
719 // operand will fit into the instruction encoding. More operands == fewer
722 switch (NumOperands) {
725 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
726 outputInstructionFormat1(&I, Opcode, Slots, Type);
732 if (MaxOpSlot < (1 << 8)) {
733 outputInstructionFormat2(&I, Opcode, Slots, Type);
739 if (MaxOpSlot < (1 << 6)) {
740 outputInstructionFormat3(&I, Opcode, Slots, Type);
749 // If we weren't handled before here, we either have a large number of
750 // operands or a large operand index that we are referring to.
751 outputInstructionFormat0(&I, Opcode, Table, Type);
754 //===----------------------------------------------------------------------===//
755 //=== Block Output ===//
756 //===----------------------------------------------------------------------===//
758 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
761 // Emit the signature...
762 static const unsigned char *Sig = (const unsigned char*)"llvm";
763 output_data(Sig, Sig+4);
765 // Emit the top level CLASS block.
766 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
768 // Output the version identifier
769 output_vbr(BCVersionNum);
771 // The Global type plane comes first
773 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
774 outputTypes(Type::FirstDerivedTyID);
777 // The ModuleInfoBlock follows directly after the type information
778 outputModuleInfoBlock(M);
780 // Output module level constants, used for global variable initializers
783 // Do the whole module now! Process each function at a time...
784 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
787 // Output the symbole table for types
788 outputTypeSymbolTable(M->getTypeSymbolTable());
790 // Output the symbol table for values
791 outputValueSymbolTable(M->getValueSymbolTable());
794 void BytecodeWriter::outputTypes(unsigned TypeNum) {
795 // Write the type plane for types first because earlier planes (e.g. for a
796 // primitive type like float) may have constants constructed using types
797 // coming later (e.g., via getelementptr from a pointer type). The type
798 // plane is needed before types can be fwd or bkwd referenced.
799 const std::vector<const Type*>& Types = Table.getTypes();
800 assert(!Types.empty() && "No types at all?");
801 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
803 unsigned NumEntries = Types.size() - TypeNum;
805 // Output type header: [num entries]
806 output_vbr(NumEntries);
808 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
809 outputType(Types[i]);
812 // Helper function for outputConstants().
813 // Writes out all the constants in the plane Plane starting at entry StartNo.
815 void BytecodeWriter::outputConstantsInPlane(const Value *const *Plane,
818 unsigned ValNo = StartNo;
820 // Scan through and ignore function arguments, global values, and constant
822 for (; ValNo < PlaneSize &&
823 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
824 (isa<ConstantArray>(Plane[ValNo]) &&
825 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
828 unsigned NC = ValNo; // Number of constants
829 for (; NC < PlaneSize && (isa<Constant>(Plane[NC]) ||
830 isa<InlineAsm>(Plane[NC])); NC++)
832 NC -= ValNo; // Convert from index into count
833 if (NC == 0) return; // Skip empty type planes...
835 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
838 // Put out type header: [num entries][type id number]
842 // Put out the Type ID Number.
843 output_typeid(Table.getTypeSlot(Plane[0]->getType()));
845 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
846 const Value *V = Plane[i];
847 if (const Constant *C = dyn_cast<Constant>(V))
850 outputInlineAsm(cast<InlineAsm>(V));
854 static inline bool hasNullValue(const Type *Ty) {
855 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
858 void BytecodeWriter::outputConstants() {
859 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
860 true /* Elide block if empty */);
862 unsigned NumPlanes = Table.getNumPlanes();
864 // Output module-level string constants before any other constants.
865 outputConstantStrings();
867 for (unsigned pno = 0; pno != NumPlanes; pno++) {
868 const SlotCalculator::TypePlane &Plane = Table.getPlane(pno);
869 if (!Plane.empty()) { // Skip empty type planes...
871 if (hasNullValue(Plane[0]->getType())) {
872 // Skip zero initializer
876 // Write out constants in the plane
877 outputConstantsInPlane(&Plane[0], Plane.size(), 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;
890 case GlobalValue::DLLImportLinkage: return 5;
891 case GlobalValue::DLLExportLinkage: return 6;
892 case GlobalValue::ExternalWeakLinkage: return 7;
896 static unsigned getEncodedVisibility(const GlobalValue *GV) {
897 switch (GV->getVisibility()) {
898 default: assert(0 && "Invalid visibility!");
899 case GlobalValue::DefaultVisibility: return 0;
900 case GlobalValue::HiddenVisibility: return 1;
904 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
905 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
907 // Give numbers to sections as we encounter them.
908 unsigned SectionIDCounter = 0;
909 std::vector<std::string> SectionNames;
910 std::map<std::string, unsigned> SectionID;
912 // Output the types for the global variables in the module...
913 for (Module::const_global_iterator I = M->global_begin(),
914 End = M->global_end(); I != End; ++I) {
915 unsigned Slot = Table.getTypeSlot(I->getType());
917 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
918 "Global must have an initializer or have external linkage!");
920 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
921 // bit5+ = Slot # for type.
922 bool HasExtensionWord = (I->getAlignment() != 0) ||
924 (I->getVisibility() != GlobalValue::DefaultVisibility);
926 // If we need to use the extension byte, set linkage=3(internal) and
927 // initializer = 0 (impossible!).
928 if (!HasExtensionWord) {
929 unsigned oSlot = (Slot << 5) | (getEncodedLinkage(I) << 2) |
930 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
933 unsigned oSlot = (Slot << 5) | (3 << 2) |
934 (0 << 1) | (unsigned)I->isConstant();
937 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
938 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
939 // bits 10-12 = visibility, bits 13+ = future use.
940 unsigned ExtWord = (unsigned)I->hasInitializer() |
941 (getEncodedLinkage(I) << 1) |
942 ((Log2_32(I->getAlignment())+1) << 4) |
943 ((unsigned)I->hasSection() << 9) |
944 (getEncodedVisibility(I) << 10);
946 if (I->hasSection()) {
947 // Give section names unique ID's.
948 unsigned &Entry = SectionID[I->getSection()];
950 Entry = ++SectionIDCounter;
951 SectionNames.push_back(I->getSection());
957 // If we have an initializer, output it now.
958 if (I->hasInitializer())
959 output_vbr(Table.getSlot((Value*)I->getInitializer()));
961 output_typeid(Table.getTypeSlot(Type::VoidTy));
963 // Output the types of the functions in this module.
964 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
965 unsigned Slot = Table.getTypeSlot(I->getType());
966 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
967 unsigned CC = I->getCallingConv()+1;
968 unsigned ID = (Slot << 5) | (CC & 15);
970 if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
973 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
974 (I->isDeclaration() && I->hasDLLImportLinkage()) ||
975 (I->isDeclaration() && I->hasExternalWeakLinkage())
977 ID |= 1 << 31; // Do we need an extension word?
981 if (ID & (1 << 31)) {
982 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
983 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
984 unsigned extLinkage = 0;
986 if (I->isDeclaration()) {
987 if (I->hasDLLImportLinkage()) {
989 } else if (I->hasExternalWeakLinkage()) {
994 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
995 (I->hasSection() << 10) |
996 ((extLinkage & 3) << 11);
999 // Give section names unique ID's.
1000 if (I->hasSection()) {
1001 unsigned &Entry = SectionID[I->getSection()];
1003 Entry = ++SectionIDCounter;
1004 SectionNames.push_back(I->getSection());
1010 output_vbr(Table.getTypeSlot(Type::VoidTy) << 5);
1012 // Emit the list of dependent libraries for the Module.
1013 Module::lib_iterator LI = M->lib_begin();
1014 Module::lib_iterator LE = M->lib_end();
1015 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1016 for (; LI != LE; ++LI)
1019 // Output the target triple from the module
1020 output(M->getTargetTriple());
1022 // Output the data layout from the module
1023 output(M->getDataLayout());
1025 // Emit the table of section names.
1026 output_vbr((unsigned)SectionNames.size());
1027 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1028 output(SectionNames[i]);
1030 // Output the inline asm string.
1031 output(M->getModuleInlineAsm());
1034 void BytecodeWriter::outputInstructions(const Function *F) {
1035 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1036 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1037 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1038 outputInstruction(*I);
1041 void BytecodeWriter::outputFunction(const Function *F) {
1042 // If this is an external function, there is nothing else to emit!
1043 if (F->isDeclaration()) return;
1045 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1046 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1049 // Get slot information about the function...
1050 Table.incorporateFunction(F);
1052 // Output all of the instructions in the body of the function
1053 outputInstructions(F);
1055 // If needed, output the symbol table for the function...
1056 outputValueSymbolTable(F->getValueSymbolTable());
1058 Table.purgeFunction();
1062 void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1063 // Do not output the block for an empty symbol table, it just wastes
1065 if (TST.empty()) return;
1067 // Create a header for the symbol table
1068 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
1069 true/*ElideIfEmpty*/);
1070 // Write the number of types
1071 output_vbr(TST.size());
1073 // Write each of the types
1074 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1076 // Symtab entry:[def slot #][name]
1077 output_typeid(Table.getTypeSlot(TI->second));
1082 void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
1083 // Do not output the Bytecode block for an empty symbol table, it just wastes
1085 if (VST.empty()) return;
1087 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1088 true/*ElideIfEmpty*/);
1090 // Organize the symbol table by type
1091 typedef std::pair<const std::string*, const Value*> PlaneMapEntry;
1092 typedef SmallVector<PlaneMapEntry, 8> PlaneMapVector;
1093 typedef DenseMap<const Type*, PlaneMapVector > PlaneMap;
1095 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1097 Planes[SI->second->getType()]
1098 .push_back(std::make_pair(&SI->first, SI->second));
1100 for (PlaneMap::iterator PI = Planes.begin(), PE = Planes.end();
1102 PlaneMapVector::const_iterator I = PI->second.begin();
1103 PlaneMapVector::const_iterator End = PI->second.end();
1105 if (I == End) continue; // Don't mess with an absent type...
1107 // Write the number of values in this plane
1108 output_vbr((unsigned)PI->second.size());
1110 // Write the slot number of the type for this plane
1111 output_typeid(Table.getTypeSlot(PI->first));
1113 // Write each of the values in this plane
1114 for (; I != End; ++I) {
1115 // Symtab entry: [def slot #][name]
1116 output_vbr(Table.getSlot(I->second));
1122 void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
1124 assert(M && "You can't write a null module!!");
1126 // Make sure that std::cout is put into binary mode for systems
1129 sys::Program::ChangeStdoutToBinary();
1131 // Create a vector of unsigned char for the bytecode output. We
1132 // reserve 256KBytes of space in the vector so that we avoid doing
1133 // lots of little allocations. 256KBytes is sufficient for a large
1134 // proportion of the bytecode files we will encounter. Larger files
1135 // will be automatically doubled in size as needed (std::vector
1137 std::vector<unsigned char> Buffer;
1138 Buffer.reserve(256 * 1024);
1140 // The BytecodeWriter populates Buffer for us.
1141 BytecodeWriter BCW(Buffer, M);
1143 // Keep track of how much we've written
1144 BytesWritten += Buffer.size();
1146 // Determine start and end points of the Buffer
1147 const unsigned char *FirstByte = &Buffer.front();
1149 // If we're supposed to compress this mess ...
1152 // We signal compression by using an alternate magic number for the
1153 // file. The compressed bytecode file's magic number is "llvc" instead
1155 char compressed_magic[4];
1156 compressed_magic[0] = 'l';
1157 compressed_magic[1] = 'l';
1158 compressed_magic[2] = 'v';
1159 compressed_magic[3] = 'c';
1161 Out.stream()->write(compressed_magic,4);
1163 // Compress everything after the magic number (which we altered)
1164 Compressor::compressToStream(
1165 (char*)(FirstByte+4), // Skip the magic number
1166 Buffer.size()-4, // Skip the magic number
1167 *Out.stream() // Where to write compressed data
1172 // We're not compressing, so just write the entire block.
1173 Out.stream()->write((char*)FirstByte, Buffer.size());
1176 // make sure it hits disk now
1177 Out.stream()->flush();