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_str(const char *Str, unsigned Len) {
136 output_vbr(Len); // Strings may have an arbitrary length.
137 Out.insert(Out.end(), Str, Str+Len);
140 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
141 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
144 inline void BytecodeWriter::output_float(float& FloatVal) {
145 /// FIXME: This isn't optimal, it has size problems on some platforms
146 /// where FP is not IEEE.
147 uint32_t i = FloatToBits(FloatVal);
148 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
151 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
154 inline void BytecodeWriter::output_double(double& DoubleVal) {
155 /// FIXME: This isn't optimal, it has size problems on some platforms
156 /// where FP is not IEEE.
157 uint64_t i = DoubleToBits(DoubleVal);
158 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
168 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
169 bool elideIfEmpty, bool hasLongFormat)
170 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
174 w.output(0U); // For length in long format
176 w.output(0U); /// Place holder for ID and length for this block
181 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
183 if (Loc == Writer.size() && ElideIfEmpty) {
184 // If the block is empty, and we are allowed to, do not emit the block at
186 Writer.resize(Writer.size()-(HasLongFormat?8:4));
191 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
193 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
196 //===----------------------------------------------------------------------===//
197 //=== Constant Output ===//
198 //===----------------------------------------------------------------------===//
200 void BytecodeWriter::outputType(const Type *T) {
201 const StructType* STy = dyn_cast<StructType>(T);
202 if(STy && STy->isPacked())
203 output_vbr((unsigned)Type::PackedStructTyID);
205 output_vbr((unsigned)T->getTypeID());
207 // That's all there is to handling primitive types...
208 if (T->isPrimitiveType())
209 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::IntegerTyID:
213 output_vbr(cast<IntegerType>(T)->getBitWidth());
215 case Type::FunctionTyID: {
216 const FunctionType *MT = cast<FunctionType>(T);
217 output_typeid(Table.getTypeSlot(MT->getReturnType()));
218 output_vbr(unsigned(MT->getParamAttrs(0)));
220 // Output the number of arguments to function (+1 if varargs):
221 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
223 // Output all of the arguments...
224 FunctionType::param_iterator I = MT->param_begin();
226 for (; I != MT->param_end(); ++I) {
227 output_typeid(Table.getTypeSlot(*I));
228 output_vbr(unsigned(MT->getParamAttrs(Idx)));
232 // Terminate list with VoidTy if we are a varargs function...
234 output_typeid((unsigned)Type::VoidTyID);
238 case Type::ArrayTyID: {
239 const ArrayType *AT = cast<ArrayType>(T);
240 output_typeid(Table.getTypeSlot(AT->getElementType()));
241 output_vbr(AT->getNumElements());
245 case Type::PackedTyID: {
246 const PackedType *PT = cast<PackedType>(T);
247 output_typeid(Table.getTypeSlot(PT->getElementType()));
248 output_vbr(PT->getNumElements());
252 case Type::StructTyID: {
253 const StructType *ST = cast<StructType>(T);
254 // Output all of the element types...
255 for (StructType::element_iterator I = ST->element_begin(),
256 E = ST->element_end(); I != E; ++I) {
257 output_typeid(Table.getTypeSlot(*I));
260 // Terminate list with VoidTy
261 output_typeid((unsigned)Type::VoidTyID);
265 case Type::PointerTyID:
266 output_typeid(Table.getTypeSlot(cast<PointerType>(T)->getElementType()));
269 case Type::OpaqueTyID:
270 // No need to emit anything, just the count of opaque types is enough.
274 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
275 << " Type '" << T->getDescription() << "'\n";
280 void BytecodeWriter::outputConstant(const Constant *CPV) {
281 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
282 !CPV->isNullValue()) && "Shouldn't output null constants!");
284 // We must check for a ConstantExpr before switching by type because
285 // a ConstantExpr can be of any type, and has no explicit value.
287 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
288 // FIXME: Encoding of constant exprs could be much more compact!
289 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
290 assert(CE->getNumOperands() != 1 || CE->isCast());
291 output_vbr(1+CE->getNumOperands()); // flags as an expr
292 output_vbr(CE->getOpcode()); // Put out the CE op code
294 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
295 output_vbr(Table.getSlot(*OI));
296 output_typeid(Table.getTypeSlot((*OI)->getType()));
299 output_vbr((unsigned)CE->getPredicate());
301 } else if (isa<UndefValue>(CPV)) {
302 output_vbr(1U); // 1 -> UndefValue constant.
305 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
308 switch (CPV->getType()->getTypeID()) {
309 case Type::IntegerTyID: { // Integer types...
310 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
312 output_vbr(uint32_t(cast<ConstantInt>(CPV)->getZExtValue()));
313 else if (NumBits <= 64)
314 output_vbr(uint64_t(cast<ConstantInt>(CPV)->getZExtValue()));
316 assert(0 && "Integer types > 64 bits not supported.");
320 case Type::ArrayTyID: {
321 const ConstantArray *CPA = cast<ConstantArray>(CPV);
322 assert(!CPA->isString() && "Constant strings should be handled specially!");
324 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
325 output_vbr(Table.getSlot(CPA->getOperand(i)));
329 case Type::PackedTyID: {
330 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
331 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
332 output_vbr(Table.getSlot(CP->getOperand(i)));
336 case Type::StructTyID: {
337 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
339 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
340 output_vbr(Table.getSlot(CPS->getOperand(i)));
344 case Type::PointerTyID:
345 assert(0 && "No non-null, non-constant-expr constants allowed!");
348 case Type::FloatTyID: { // Floating point types...
349 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
353 case Type::DoubleTyID: {
354 double Tmp = cast<ConstantFP>(CPV)->getValue();
360 case Type::LabelTyID:
362 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
363 << " type '" << *CPV->getType() << "'\n";
369 /// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
370 /// be shared by multiple uses.
371 void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
372 // Output a marker, so we know when we have one one parsing the constant pool.
373 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
374 // unique inline asms are rare, this should hardly matter.
377 output(IA->getAsmString());
378 output(IA->getConstraintString());
379 output_vbr(unsigned(IA->hasSideEffects()));
382 void BytecodeWriter::outputConstantStrings() {
383 SlotCalculator::string_iterator I = Table.string_begin();
384 SlotCalculator::string_iterator E = Table.string_end();
385 if (I == E) return; // No strings to emit
387 // If we have != 0 strings to emit, output them now. Strings are emitted into
388 // the 'void' type plane.
389 output_vbr(unsigned(E-I));
390 output_typeid(Type::VoidTyID);
392 // Emit all of the strings.
393 for (I = Table.string_begin(); I != E; ++I) {
394 const ConstantArray *Str = *I;
395 output_typeid(Table.getTypeSlot(Str->getType()));
397 // Now that we emitted the type (which indicates the size of the string),
398 // emit all of the characters.
399 std::string Val = Str->getAsString();
400 output_data(Val.c_str(), Val.c_str()+Val.size());
404 //===----------------------------------------------------------------------===//
405 //=== Instruction Output ===//
406 //===----------------------------------------------------------------------===//
408 // outputInstructionFormat0 - Output those weird instructions that have a large
409 // number of operands or have large operands themselves.
411 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
413 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
415 const SlotCalculator &Table,
417 // Opcode must have top two bits clear...
418 output_vbr(Opcode << 2); // Instruction Opcode ID
419 output_typeid(Type); // Result type
421 unsigned NumArgs = I->getNumOperands();
422 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
423 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
425 if (!isa<GetElementPtrInst>(&I)) {
426 for (unsigned i = 0; i < NumArgs; ++i)
427 output_vbr(Table.getSlot(I->getOperand(i)));
429 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
430 output_typeid(Table.getTypeSlot(I->getType()));
431 } else if (isa<CmpInst>(I)) {
432 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
433 } else if (isa<InvokeInst>(I)) {
434 output_vbr(cast<InvokeInst>(I)->getCallingConv());
435 } else if (Opcode == 58) { // Call escape sequence
436 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
437 unsigned(cast<CallInst>(I)->isTailCall()));
440 output_vbr(Table.getSlot(I->getOperand(0)));
442 // We need to encode the type of sequential type indices into their slot #
444 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
445 Idx != NumArgs; ++TI, ++Idx) {
446 unsigned Slot = Table.getSlot(I->getOperand(Idx));
448 if (isa<SequentialType>(*TI)) {
449 // These should be either 32-bits or 64-bits, however, with bit
450 // accurate types we just distinguish between less than or equal to
451 // 32-bits or greater than 32-bits.
453 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
454 assert(BitWidth == 32 || BitWidth == 64 &&
455 "Invalid bitwidth for GEP index");
456 unsigned IdxId = BitWidth == 32 ? 0 : 1;
457 Slot = (Slot << 1) | IdxId;
465 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
466 // This are more annoying than most because the signature of the call does not
467 // tell us anything about the types of the arguments in the varargs portion.
468 // Because of this, we encode (as type 0) all of the argument types explicitly
469 // before the argument value. This really sucks, but you shouldn't be using
470 // varargs functions in your code! *death to printf*!
472 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
474 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
476 const SlotCalculator &Table,
478 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
479 // Opcode must have top two bits clear...
480 output_vbr(Opcode << 2); // Instruction Opcode ID
481 output_typeid(Type); // Result type (varargs type)
483 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
484 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
485 unsigned NumParams = FTy->getNumParams();
487 unsigned NumFixedOperands;
488 if (isa<CallInst>(I)) {
489 // Output an operand for the callee and each fixed argument, then two for
490 // each variable argument.
491 NumFixedOperands = 1+NumParams;
493 assert(isa<InvokeInst>(I) && "Not call or invoke??");
494 // Output an operand for the callee and destinations, then two for each
495 // variable argument.
496 NumFixedOperands = 3+NumParams;
498 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
499 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
501 // The type for the function has already been emitted in the type field of the
502 // instruction. Just emit the slot # now.
503 for (unsigned i = 0; i != NumFixedOperands; ++i)
504 output_vbr(Table.getSlot(I->getOperand(i)));
506 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
507 // Output Arg Type ID
508 output_typeid(Table.getTypeSlot(I->getOperand(i)->getType()));
510 // Output arg ID itself
511 output_vbr(Table.getSlot(I->getOperand(i)));
514 if (isa<InvokeInst>(I)) {
515 // Emit the tail call/calling conv for invoke instructions
516 output_vbr(cast<InvokeInst>(I)->getCallingConv());
517 } else if (Opcode == 58) {
518 const CallInst *CI = cast<CallInst>(I);
519 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
524 // outputInstructionFormat1 - Output one operand instructions, knowing that no
525 // operand index is >= 2^12.
527 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
531 // bits Instruction format:
532 // --------------------------
533 // 01-00: Opcode type, fixed to 1.
535 // 19-08: Resulting type plane
536 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
538 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
542 // outputInstructionFormat2 - Output two operand instructions, knowing that no
543 // operand index is >= 2^8.
545 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
549 // bits Instruction format:
550 // --------------------------
551 // 01-00: Opcode type, fixed to 2.
553 // 15-08: Resulting type plane
557 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
561 // outputInstructionFormat3 - Output three operand instructions, knowing that no
562 // operand index is >= 2^6.
564 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
568 // bits Instruction format:
569 // --------------------------
570 // 01-00: Opcode type, fixed to 3.
572 // 13-08: Resulting type plane
577 output(3 | (Opcode << 2) | (Type << 8) |
578 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
581 void BytecodeWriter::outputInstruction(const Instruction &I) {
582 assert(I.getOpcode() < 57 && "Opcode too big???");
583 unsigned Opcode = I.getOpcode();
584 unsigned NumOperands = I.getNumOperands();
586 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
588 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
589 if (CI->getCallingConv() == CallingConv::C) {
590 if (CI->isTailCall())
591 Opcode = 61; // CCC + Tail Call
593 ; // Opcode = Instruction::Call
594 } else if (CI->getCallingConv() == CallingConv::Fast) {
595 if (CI->isTailCall())
596 Opcode = 59; // FastCC + TailCall
598 Opcode = 60; // FastCC + Not Tail Call
600 Opcode = 58; // Call escape sequence.
602 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
604 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
608 // Figure out which type to encode with the instruction. Typically we want
609 // the type of the first parameter, as opposed to the type of the instruction
610 // (for example, with setcc, we always know it returns bool, but the type of
611 // the first param is actually interesting). But if we have no arguments
612 // we take the type of the instruction itself.
615 switch (I.getOpcode()) {
616 case Instruction::Select:
617 case Instruction::Malloc:
618 case Instruction::Alloca:
619 Ty = I.getType(); // These ALWAYS want to encode the return type
621 case Instruction::Store:
622 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
623 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
625 default: // Otherwise use the default behavior...
626 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
630 unsigned Type = Table.getTypeSlot(Ty);
632 // Varargs calls and invokes are encoded entirely different from any other
634 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
635 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
636 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
637 outputInstrVarArgsCall(CI, Opcode, Table, Type);
640 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
641 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
642 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
643 outputInstrVarArgsCall(II, Opcode, Table, Type);
648 if (NumOperands <= 3) {
649 // Make sure that we take the type number into consideration. We don't want
650 // to overflow the field size for the instruction format we select.
652 unsigned MaxOpSlot = Type;
653 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
655 for (unsigned i = 0; i != NumOperands; ++i) {
656 unsigned Slot = Table.getSlot(I.getOperand(i));
657 if (Slot > MaxOpSlot) MaxOpSlot = Slot;
661 // Handle the special cases for various instructions...
662 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
663 // Cast has to encode the destination type as the second argument in the
664 // packet, or else we won't know what type to cast to!
665 Slots[1] = Table.getTypeSlot(I.getType());
666 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
668 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
669 assert(NumOperands == 1 && "Bogus allocation!");
670 if (AI->getAlignment()) {
671 Slots[1] = Log2_32(AI->getAlignment())+1;
672 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
675 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
676 // We need to encode the compare instruction's predicate as the third
677 // operand. Its not really a slot, but we don't want to break the
678 // instruction format for these instructions.
680 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
681 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
682 if (Slots[2] > MaxOpSlot)
683 MaxOpSlot = Slots[2];
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)) {
690 // These should be either 32-bits or 64-bits, however, with bit
691 // accurate types we just distinguish between less than or equal to
692 // 32-bits or greater than 32-bits.
694 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
695 assert(BitWidth == 32 || BitWidth == 64 &&
696 "Invalid bitwidth for GEP index");
697 unsigned IdxId = BitWidth == 32 ? 0 : 1;
698 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
699 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
701 } else if (Opcode == 58) {
702 // If this is the escape sequence for call, emit the tailcall/cc info.
703 const CallInst &CI = cast<CallInst>(I);
705 if (NumOperands <= 3) {
706 Slots[NumOperands-1] =
707 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
708 if (Slots[NumOperands-1] > MaxOpSlot)
709 MaxOpSlot = Slots[NumOperands-1];
711 } else if (isa<InvokeInst>(I)) {
712 // Invoke escape seq has at least 4 operands to encode.
716 // Decide which instruction encoding to use. This is determined primarily
717 // by the number of operands, and secondarily by whether or not the max
718 // operand will fit into the instruction encoding. More operands == fewer
721 switch (NumOperands) {
724 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
725 outputInstructionFormat1(&I, Opcode, Slots, Type);
731 if (MaxOpSlot < (1 << 8)) {
732 outputInstructionFormat2(&I, Opcode, Slots, Type);
738 if (MaxOpSlot < (1 << 6)) {
739 outputInstructionFormat3(&I, Opcode, Slots, Type);
748 // If we weren't handled before here, we either have a large number of
749 // operands or a large operand index that we are referring to.
750 outputInstructionFormat0(&I, Opcode, Table, Type);
753 //===----------------------------------------------------------------------===//
754 //=== Block Output ===//
755 //===----------------------------------------------------------------------===//
757 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
760 // Emit the signature...
761 static const unsigned char *Sig = (const unsigned char*)"llvm";
762 output_data(Sig, Sig+4);
764 // Emit the top level CLASS block.
765 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
767 // Output the version identifier
768 output_vbr(BCVersionNum);
770 // The Global type plane comes first
772 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
773 outputTypes(Type::FirstDerivedTyID);
776 // The ModuleInfoBlock follows directly after the type information
777 outputModuleInfoBlock(M);
779 // Output module level constants, used for global variable initializers
782 // Do the whole module now! Process each function at a time...
783 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
786 // Output the symbole table for types
787 outputTypeSymbolTable(M->getTypeSymbolTable());
789 // Output the symbol table for values
790 outputValueSymbolTable(M->getValueSymbolTable());
793 void BytecodeWriter::outputTypes(unsigned TypeNum) {
794 // Write the type plane for types first because earlier planes (e.g. for a
795 // primitive type like float) may have constants constructed using types
796 // coming later (e.g., via getelementptr from a pointer type). The type
797 // plane is needed before types can be fwd or bkwd referenced.
798 const std::vector<const Type*>& Types = Table.getTypes();
799 assert(!Types.empty() && "No types at all?");
800 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
802 unsigned NumEntries = Types.size() - TypeNum;
804 // Output type header: [num entries]
805 output_vbr(NumEntries);
807 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
808 outputType(Types[i]);
811 // Helper function for outputConstants().
812 // Writes out all the constants in the plane Plane starting at entry StartNo.
814 void BytecodeWriter::outputConstantsInPlane(const Value *const *Plane,
817 unsigned ValNo = StartNo;
819 // Scan through and ignore function arguments, global values, and constant
821 for (; ValNo < PlaneSize &&
822 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
823 (isa<ConstantArray>(Plane[ValNo]) &&
824 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
827 unsigned NC = ValNo; // Number of constants
828 for (; NC < PlaneSize && (isa<Constant>(Plane[NC]) ||
829 isa<InlineAsm>(Plane[NC])); NC++)
831 NC -= ValNo; // Convert from index into count
832 if (NC == 0) return; // Skip empty type planes...
834 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
837 // Put out type header: [num entries][type id number]
841 // Put out the Type ID Number.
842 output_typeid(Table.getTypeSlot(Plane[0]->getType()));
844 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
845 const Value *V = Plane[i];
846 if (const Constant *C = dyn_cast<Constant>(V))
849 outputInlineAsm(cast<InlineAsm>(V));
853 static inline bool hasNullValue(const Type *Ty) {
854 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
857 void BytecodeWriter::outputConstants() {
858 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
859 true /* Elide block if empty */);
861 unsigned NumPlanes = Table.getNumPlanes();
863 // Output module-level string constants before any other constants.
864 outputConstantStrings();
866 for (unsigned pno = 0; pno != NumPlanes; pno++) {
867 const SlotCalculator::TypePlane &Plane = Table.getPlane(pno);
868 if (!Plane.empty()) { // Skip empty type planes...
870 if (hasNullValue(Plane[0]->getType())) {
871 // Skip zero initializer
875 // Write out constants in the plane
876 outputConstantsInPlane(&Plane[0], Plane.size(), ValNo);
881 static unsigned getEncodedLinkage(const GlobalValue *GV) {
882 switch (GV->getLinkage()) {
883 default: assert(0 && "Invalid linkage!");
884 case GlobalValue::ExternalLinkage: return 0;
885 case GlobalValue::WeakLinkage: return 1;
886 case GlobalValue::AppendingLinkage: return 2;
887 case GlobalValue::InternalLinkage: return 3;
888 case GlobalValue::LinkOnceLinkage: return 4;
889 case GlobalValue::DLLImportLinkage: return 5;
890 case GlobalValue::DLLExportLinkage: return 6;
891 case GlobalValue::ExternalWeakLinkage: return 7;
895 static unsigned getEncodedVisibility(const GlobalValue *GV) {
896 switch (GV->getVisibility()) {
897 default: assert(0 && "Invalid visibility!");
898 case GlobalValue::DefaultVisibility: return 0;
899 case GlobalValue::HiddenVisibility: return 1;
903 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
904 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
906 // Give numbers to sections as we encounter them.
907 unsigned SectionIDCounter = 0;
908 std::vector<std::string> SectionNames;
909 std::map<std::string, unsigned> SectionID;
911 // Output the types for the global variables in the module...
912 for (Module::const_global_iterator I = M->global_begin(),
913 End = M->global_end(); I != End; ++I) {
914 unsigned Slot = Table.getTypeSlot(I->getType());
916 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
917 "Global must have an initializer or have external linkage!");
919 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
920 // bit5+ = Slot # for type.
921 bool HasExtensionWord = (I->getAlignment() != 0) ||
923 (I->getVisibility() != GlobalValue::DefaultVisibility);
925 // If we need to use the extension byte, set linkage=3(internal) and
926 // initializer = 0 (impossible!).
927 if (!HasExtensionWord) {
928 unsigned oSlot = (Slot << 5) | (getEncodedLinkage(I) << 2) |
929 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
932 unsigned oSlot = (Slot << 5) | (3 << 2) |
933 (0 << 1) | (unsigned)I->isConstant();
936 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
937 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
938 // bits 10-12 = visibility, bits 13+ = future use.
939 unsigned ExtWord = (unsigned)I->hasInitializer() |
940 (getEncodedLinkage(I) << 1) |
941 ((Log2_32(I->getAlignment())+1) << 4) |
942 ((unsigned)I->hasSection() << 9) |
943 (getEncodedVisibility(I) << 10);
945 if (I->hasSection()) {
946 // Give section names unique ID's.
947 unsigned &Entry = SectionID[I->getSection()];
949 Entry = ++SectionIDCounter;
950 SectionNames.push_back(I->getSection());
956 // If we have an initializer, output it now.
957 if (I->hasInitializer())
958 output_vbr(Table.getSlot((Value*)I->getInitializer()));
960 output_typeid(Table.getTypeSlot(Type::VoidTy));
962 // Output the types of the functions in this module.
963 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
964 unsigned Slot = Table.getTypeSlot(I->getType());
965 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
966 unsigned CC = I->getCallingConv()+1;
967 unsigned ID = (Slot << 5) | (CC & 15);
969 if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
972 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
973 (I->isDeclaration() && I->hasDLLImportLinkage()) ||
974 (I->isDeclaration() && I->hasExternalWeakLinkage())
976 ID |= 1 << 31; // Do we need an extension word?
980 if (ID & (1 << 31)) {
981 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
982 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
983 unsigned extLinkage = 0;
985 if (I->isDeclaration()) {
986 if (I->hasDLLImportLinkage()) {
988 } else if (I->hasExternalWeakLinkage()) {
993 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
994 (I->hasSection() << 10) |
995 ((extLinkage & 3) << 11);
998 // Give section names unique ID's.
999 if (I->hasSection()) {
1000 unsigned &Entry = SectionID[I->getSection()];
1002 Entry = ++SectionIDCounter;
1003 SectionNames.push_back(I->getSection());
1009 output_vbr(Table.getTypeSlot(Type::VoidTy) << 5);
1011 // Emit the list of dependent libraries for the Module.
1012 Module::lib_iterator LI = M->lib_begin();
1013 Module::lib_iterator LE = M->lib_end();
1014 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1015 for (; LI != LE; ++LI)
1018 // Output the target triple from the module
1019 output(M->getTargetTriple());
1021 // Output the data layout from the module
1022 output(M->getDataLayout());
1024 // Emit the table of section names.
1025 output_vbr((unsigned)SectionNames.size());
1026 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1027 output(SectionNames[i]);
1029 // Output the inline asm string.
1030 output(M->getModuleInlineAsm());
1033 void BytecodeWriter::outputInstructions(const Function *F) {
1034 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1035 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1036 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1037 outputInstruction(*I);
1040 void BytecodeWriter::outputFunction(const Function *F) {
1041 // If this is an external function, there is nothing else to emit!
1042 if (F->isDeclaration()) return;
1044 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1045 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1048 // Get slot information about the function...
1049 Table.incorporateFunction(F);
1051 // Output all of the instructions in the body of the function
1052 outputInstructions(F);
1054 // If needed, output the symbol table for the function...
1055 outputValueSymbolTable(F->getValueSymbolTable());
1057 Table.purgeFunction();
1061 void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1062 // Do not output the block for an empty symbol table, it just wastes
1064 if (TST.empty()) return;
1066 // Create a header for the symbol table
1067 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
1068 true/*ElideIfEmpty*/);
1069 // Write the number of types
1070 output_vbr(TST.size());
1072 // Write each of the types
1073 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1075 // Symtab entry:[def slot #][name]
1076 output_typeid(Table.getTypeSlot(TI->second));
1081 void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
1082 // Do not output the Bytecode block for an empty symbol table, it just wastes
1084 if (VST.empty()) return;
1086 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1087 true/*ElideIfEmpty*/);
1089 // Organize the symbol table by type
1090 typedef SmallVector<const ValueName*, 8> PlaneMapVector;
1091 typedef DenseMap<const Type*, PlaneMapVector > PlaneMap;
1093 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1095 Planes[SI->getValue()->getType()].push_back(&*SI);
1097 for (PlaneMap::iterator PI = Planes.begin(), PE = Planes.end();
1099 PlaneMapVector::const_iterator I = PI->second.begin();
1100 PlaneMapVector::const_iterator End = PI->second.end();
1102 if (I == End) continue; // Don't mess with an absent type...
1104 // Write the number of values in this plane
1105 output_vbr((unsigned)PI->second.size());
1107 // Write the slot number of the type for this plane
1108 output_typeid(Table.getTypeSlot(PI->first));
1110 // Write each of the values in this plane
1111 for (; I != End; ++I) {
1112 // Symtab entry: [def slot #][name]
1113 output_vbr(Table.getSlot((*I)->getValue()));
1114 output_str((*I)->getKeyData(), (*I)->getKeyLength());
1119 void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
1121 assert(M && "You can't write a null module!!");
1123 // Make sure that std::cout is put into binary mode for systems
1126 sys::Program::ChangeStdoutToBinary();
1128 // Create a vector of unsigned char for the bytecode output. We
1129 // reserve 256KBytes of space in the vector so that we avoid doing
1130 // lots of little allocations. 256KBytes is sufficient for a large
1131 // proportion of the bytecode files we will encounter. Larger files
1132 // will be automatically doubled in size as needed (std::vector
1134 std::vector<unsigned char> Buffer;
1135 Buffer.reserve(256 * 1024);
1137 // The BytecodeWriter populates Buffer for us.
1138 BytecodeWriter BCW(Buffer, M);
1140 // Keep track of how much we've written
1141 BytesWritten += Buffer.size();
1143 // Determine start and end points of the Buffer
1144 const unsigned char *FirstByte = &Buffer.front();
1146 // If we're supposed to compress this mess ...
1149 // We signal compression by using an alternate magic number for the
1150 // file. The compressed bytecode file's magic number is "llvc" instead
1152 char compressed_magic[4];
1153 compressed_magic[0] = 'l';
1154 compressed_magic[1] = 'l';
1155 compressed_magic[2] = 'v';
1156 compressed_magic[3] = 'c';
1158 Out.stream()->write(compressed_magic,4);
1160 // Compress everything after the magic number (which we altered)
1161 Compressor::compressToStream(
1162 (char*)(FirstByte+4), // Skip the magic number
1163 Buffer.size()-4, // Skip the magic number
1164 *Out.stream() // Where to write compressed data
1169 // We're not compressing, so just write the entire block.
1170 Out.stream()->write((char*)FirstByte, Buffer.size());
1173 // make sure it hits disk now
1174 Out.stream()->flush();