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/STLExtras.h"
37 #include "llvm/ADT/Statistic.h"
42 /// This value needs to be incremented every time the bytecode format changes
43 /// so that the reader can distinguish which format of the bytecode file has
45 /// @brief The bytecode version number
46 const unsigned BCVersionNum = 7;
48 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
50 STATISTIC(BytesWritten, "Number of bytecode bytes written");
52 //===----------------------------------------------------------------------===//
53 //=== Output Primitives ===//
54 //===----------------------------------------------------------------------===//
56 // output - If a position is specified, it must be in the valid portion of the
57 // string... note that this should be inlined always so only the relevant IF
58 // body should be included.
59 inline void BytecodeWriter::output(unsigned i, int pos) {
60 if (pos == -1) { // Be endian clean, little endian is our friend
61 Out.push_back((unsigned char)i);
62 Out.push_back((unsigned char)(i >> 8));
63 Out.push_back((unsigned char)(i >> 16));
64 Out.push_back((unsigned char)(i >> 24));
66 Out[pos ] = (unsigned char)i;
67 Out[pos+1] = (unsigned char)(i >> 8);
68 Out[pos+2] = (unsigned char)(i >> 16);
69 Out[pos+3] = (unsigned char)(i >> 24);
73 inline void BytecodeWriter::output(int i) {
77 /// output_vbr - Output an unsigned value, by using the least number of bytes
78 /// possible. This is useful because many of our "infinite" values are really
79 /// very small most of the time; but can be large a few times.
80 /// Data format used: If you read a byte with the high bit set, use the low
81 /// seven bits as data and then read another byte.
82 inline void BytecodeWriter::output_vbr(uint64_t i) {
84 if (i < 0x80) { // done?
85 Out.push_back((unsigned char)i); // We know the high bit is clear...
89 // Nope, we are bigger than a character, output the next 7 bits and set the
90 // high bit to say that there is more coming...
91 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
92 i >>= 7; // Shift out 7 bits now...
96 inline void BytecodeWriter::output_vbr(unsigned i) {
98 if (i < 0x80) { // done?
99 Out.push_back((unsigned char)i); // We know the high bit is clear...
103 // Nope, we are bigger than a character, output the next 7 bits and set the
104 // high bit to say that there is more coming...
105 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
106 i >>= 7; // Shift out 7 bits now...
110 inline void BytecodeWriter::output_typeid(unsigned i) {
114 this->output_vbr(0x00FFFFFF);
119 inline void BytecodeWriter::output_vbr(int64_t i) {
121 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
123 output_vbr((uint64_t)i << 1); // Low order bit is clear.
127 inline void BytecodeWriter::output_vbr(int i) {
129 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
131 output_vbr((unsigned)i << 1); // Low order bit is clear.
134 inline void BytecodeWriter::output(const std::string &s) {
135 unsigned Len = s.length();
136 output_vbr(Len); // Strings may have an arbitrary length.
137 Out.insert(Out.end(), s.begin(), s.end());
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 int Slot = Table.getSlot(MT->getReturnType());
218 assert(Slot != -1 && "Type used but not available!!");
219 output_typeid((unsigned)Slot);
220 output_vbr(unsigned(MT->getParamAttrs(0)));
222 // Output the number of arguments to function (+1 if varargs):
223 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
225 // Output all of the arguments...
226 FunctionType::param_iterator I = MT->param_begin();
228 for (; I != MT->param_end(); ++I) {
229 Slot = Table.getSlot(*I);
230 assert(Slot != -1 && "Type used but not available!!");
231 output_typeid((unsigned)Slot);
232 output_vbr(unsigned(MT->getParamAttrs(Idx)));
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 output_vbr(AT->getNumElements());
251 case Type::PackedTyID: {
252 const PackedType *PT = cast<PackedType>(T);
253 int Slot = Table.getSlot(PT->getElementType());
254 assert(Slot != -1 && "Type used but not available!!");
255 output_typeid((unsigned)Slot);
256 output_vbr(PT->getNumElements());
260 case Type::StructTyID: {
261 const StructType *ST = cast<StructType>(T);
262 // Output all of the element types...
263 for (StructType::element_iterator I = ST->element_begin(),
264 E = ST->element_end(); I != E; ++I) {
265 int Slot = Table.getSlot(*I);
266 assert(Slot != -1 && "Type used but not available!!");
267 output_typeid((unsigned)Slot);
270 // Terminate list with VoidTy
271 output_typeid((unsigned)Type::VoidTyID);
275 case Type::PointerTyID: {
276 const PointerType *PT = cast<PointerType>(T);
277 int Slot = Table.getSlot(PT->getElementType());
278 assert(Slot != -1 && "Type used but not available!!");
279 output_typeid((unsigned)Slot);
283 case Type::OpaqueTyID:
284 // No need to emit anything, just the count of opaque types is enough.
288 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
289 << " Type '" << T->getDescription() << "'\n";
294 void BytecodeWriter::outputConstant(const Constant *CPV) {
295 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
296 !CPV->isNullValue()) && "Shouldn't output null constants!");
298 // We must check for a ConstantExpr before switching by type because
299 // a ConstantExpr can be of any type, and has no explicit value.
301 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
302 // FIXME: Encoding of constant exprs could be much more compact!
303 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
304 assert(CE->getNumOperands() != 1 || CE->isCast());
305 output_vbr(1+CE->getNumOperands()); // flags as an expr
306 output_vbr(CE->getOpcode()); // Put out the CE op code
308 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
309 int Slot = Table.getSlot(*OI);
310 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
311 output_vbr((unsigned)Slot);
312 Slot = Table.getSlot((*OI)->getType());
313 output_typeid((unsigned)Slot);
316 output_vbr((unsigned)CE->getPredicate());
318 } else if (isa<UndefValue>(CPV)) {
319 output_vbr(1U); // 1 -> UndefValue constant.
322 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
325 switch (CPV->getType()->getTypeID()) {
326 case Type::IntegerTyID: { // Integer types...
327 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
329 output_vbr(uint32_t(cast<ConstantInt>(CPV)->getZExtValue()));
330 else if (NumBits <= 64)
331 output_vbr(uint64_t(cast<ConstantInt>(CPV)->getZExtValue()));
333 assert("Integer types > 64 bits not supported.");
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, e = CPA->getNumOperands(); i != e; ++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::PackedTyID: {
350 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
352 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
353 int Slot = Table.getSlot(CP->getOperand(i));
354 assert(Slot != -1 && "Constant used but not available!!");
355 output_vbr((unsigned)Slot);
360 case Type::StructTyID: {
361 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
363 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
364 int Slot = Table.getSlot(CPS->getOperand(i));
365 assert(Slot != -1 && "Constant used but not available!!");
366 output_vbr((unsigned)Slot);
371 case Type::PointerTyID:
372 assert(0 && "No non-null, non-constant-expr constants allowed!");
375 case Type::FloatTyID: { // Floating point types...
376 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
380 case Type::DoubleTyID: {
381 double Tmp = cast<ConstantFP>(CPV)->getValue();
387 case Type::LabelTyID:
389 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
390 << " type '" << *CPV->getType() << "'\n";
396 /// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
397 /// be shared by multiple uses.
398 void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
399 // Output a marker, so we know when we have one one parsing the constant pool.
400 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
401 // unique inline asms are rare, this should hardly matter.
404 output(IA->getAsmString());
405 output(IA->getConstraintString());
406 output_vbr(unsigned(IA->hasSideEffects()));
409 void BytecodeWriter::outputConstantStrings() {
410 SlotCalculator::string_iterator I = Table.string_begin();
411 SlotCalculator::string_iterator E = Table.string_end();
412 if (I == E) return; // No strings to emit
414 // If we have != 0 strings to emit, output them now. Strings are emitted into
415 // the 'void' type plane.
416 output_vbr(unsigned(E-I));
417 output_typeid(Type::VoidTyID);
419 // Emit all of the strings.
420 for (I = Table.string_begin(); I != E; ++I) {
421 const ConstantArray *Str = *I;
422 int Slot = Table.getSlot(Str->getType());
423 assert(Slot != -1 && "Constant string of unknown type?");
424 output_typeid((unsigned)Slot);
426 // Now that we emitted the type (which indicates the size of the string),
427 // emit all of the characters.
428 std::string Val = Str->getAsString();
429 output_data(Val.c_str(), Val.c_str()+Val.size());
433 //===----------------------------------------------------------------------===//
434 //=== Instruction Output ===//
435 //===----------------------------------------------------------------------===//
437 // outputInstructionFormat0 - Output those weird instructions that have a large
438 // number of operands or have large operands themselves.
440 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
442 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
444 const SlotCalculator &Table,
446 // Opcode must have top two bits clear...
447 output_vbr(Opcode << 2); // Instruction Opcode ID
448 output_typeid(Type); // Result type
450 unsigned NumArgs = I->getNumOperands();
451 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
452 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
454 if (!isa<GetElementPtrInst>(&I)) {
455 for (unsigned i = 0; i < NumArgs; ++i) {
456 int Slot = Table.getSlot(I->getOperand(i));
457 assert(Slot >= 0 && "No slot number for value!?!?");
458 output_vbr((unsigned)Slot);
461 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
462 int Slot = Table.getSlot(I->getType());
463 assert(Slot != -1 && "Cast return type unknown?");
464 output_typeid((unsigned)Slot);
465 } else if (isa<CmpInst>(I)) {
466 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
467 } else if (isa<InvokeInst>(I)) {
468 output_vbr(cast<InvokeInst>(I)->getCallingConv());
469 } else if (Opcode == 58) { // Call escape sequence
470 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
471 unsigned(cast<CallInst>(I)->isTailCall()));
474 int Slot = Table.getSlot(I->getOperand(0));
475 assert(Slot >= 0 && "No slot number for value!?!?");
476 output_vbr(unsigned(Slot));
478 // We need to encode the type of sequential type indices into their slot #
480 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
481 Idx != NumArgs; ++TI, ++Idx) {
482 Slot = Table.getSlot(I->getOperand(Idx));
483 assert(Slot >= 0 && "No slot number for value!?!?");
485 if (isa<SequentialType>(*TI)) {
486 // These should be either 32-bits or 64-bits, however, with bit
487 // accurate types we just distinguish between less than or equal to
488 // 32-bits or greater than 32-bits.
490 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
491 assert(BitWidth == 32 || BitWidth == 64 &&
492 "Invalid bitwidth for GEP index");
493 unsigned IdxId = BitWidth == 32 ? 0 : 1;
494 Slot = (Slot << 1) | IdxId;
496 output_vbr(unsigned(Slot));
502 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
503 // This are more annoying than most because the signature of the call does not
504 // tell us anything about the types of the arguments in the varargs portion.
505 // Because of this, we encode (as type 0) all of the argument types explicitly
506 // before the argument value. This really sucks, but you shouldn't be using
507 // varargs functions in your code! *death to printf*!
509 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
511 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
513 const SlotCalculator &Table,
515 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
516 // Opcode must have top two bits clear...
517 output_vbr(Opcode << 2); // Instruction Opcode ID
518 output_typeid(Type); // Result type (varargs type)
520 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
521 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
522 unsigned NumParams = FTy->getNumParams();
524 unsigned NumFixedOperands;
525 if (isa<CallInst>(I)) {
526 // Output an operand for the callee and each fixed argument, then two for
527 // each variable argument.
528 NumFixedOperands = 1+NumParams;
530 assert(isa<InvokeInst>(I) && "Not call or invoke??");
531 // Output an operand for the callee and destinations, then two for each
532 // variable argument.
533 NumFixedOperands = 3+NumParams;
535 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
536 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
538 // The type for the function has already been emitted in the type field of the
539 // instruction. Just emit the slot # now.
540 for (unsigned i = 0; i != NumFixedOperands; ++i) {
541 int Slot = Table.getSlot(I->getOperand(i));
542 assert(Slot >= 0 && "No slot number for value!?!?");
543 output_vbr((unsigned)Slot);
546 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
547 // Output Arg Type ID
548 int Slot = Table.getSlot(I->getOperand(i)->getType());
549 assert(Slot >= 0 && "No slot number for value!?!?");
550 output_typeid((unsigned)Slot);
552 // Output arg ID itself
553 Slot = Table.getSlot(I->getOperand(i));
554 assert(Slot >= 0 && "No slot number for value!?!?");
555 output_vbr((unsigned)Slot);
558 if (isa<InvokeInst>(I)) {
559 // Emit the tail call/calling conv for invoke instructions
560 output_vbr(cast<InvokeInst>(I)->getCallingConv());
561 } else if (Opcode == 58) {
562 const CallInst *CI = cast<CallInst>(I);
563 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
568 // outputInstructionFormat1 - Output one operand instructions, knowing that no
569 // operand index is >= 2^12.
571 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
575 // bits Instruction format:
576 // --------------------------
577 // 01-00: Opcode type, fixed to 1.
579 // 19-08: Resulting type plane
580 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
582 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
586 // outputInstructionFormat2 - Output two operand instructions, knowing that no
587 // operand index is >= 2^8.
589 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
593 // bits Instruction format:
594 // --------------------------
595 // 01-00: Opcode type, fixed to 2.
597 // 15-08: Resulting type plane
601 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
605 // outputInstructionFormat3 - Output three operand instructions, knowing that no
606 // operand index is >= 2^6.
608 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
612 // bits Instruction format:
613 // --------------------------
614 // 01-00: Opcode type, fixed to 3.
616 // 13-08: Resulting type plane
621 output(3 | (Opcode << 2) | (Type << 8) |
622 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
625 void BytecodeWriter::outputInstruction(const Instruction &I) {
626 assert(I.getOpcode() < 57 && "Opcode too big???");
627 unsigned Opcode = I.getOpcode();
628 unsigned NumOperands = I.getNumOperands();
630 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
632 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
633 if (CI->getCallingConv() == CallingConv::C) {
634 if (CI->isTailCall())
635 Opcode = 61; // CCC + Tail Call
637 ; // Opcode = Instruction::Call
638 } else if (CI->getCallingConv() == CallingConv::Fast) {
639 if (CI->isTailCall())
640 Opcode = 59; // FastCC + TailCall
642 Opcode = 60; // FastCC + Not Tail Call
644 Opcode = 58; // Call escape sequence.
646 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
648 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
652 // Figure out which type to encode with the instruction. Typically we want
653 // the type of the first parameter, as opposed to the type of the instruction
654 // (for example, with setcc, we always know it returns bool, but the type of
655 // the first param is actually interesting). But if we have no arguments
656 // we take the type of the instruction itself.
659 switch (I.getOpcode()) {
660 case Instruction::Select:
661 case Instruction::Malloc:
662 case Instruction::Alloca:
663 Ty = I.getType(); // These ALWAYS want to encode the return type
665 case Instruction::Store:
666 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
667 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
669 default: // Otherwise use the default behavior...
670 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
675 int Slot = Table.getSlot(Ty);
676 assert(Slot != -1 && "Type not available!!?!");
677 Type = (unsigned)Slot;
679 // Varargs calls and invokes are encoded entirely different from any other
681 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
682 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
683 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
684 outputInstrVarArgsCall(CI, Opcode, Table, Type);
687 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
688 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
689 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
690 outputInstrVarArgsCall(II, Opcode, Table, Type);
695 if (NumOperands <= 3) {
696 // Make sure that we take the type number into consideration. We don't want
697 // to overflow the field size for the instruction format we select.
699 unsigned MaxOpSlot = Type;
700 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
702 for (unsigned i = 0; i != NumOperands; ++i) {
703 int slot = Table.getSlot(I.getOperand(i));
704 assert(slot != -1 && "Broken bytecode!");
705 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
706 Slots[i] = unsigned(slot);
709 // Handle the special cases for various instructions...
710 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
711 // Cast has to encode the destination type as the second argument in the
712 // packet, or else we won't know what type to cast to!
713 Slots[1] = Table.getSlot(I.getType());
714 assert(Slots[1] != ~0U && "Cast return type unknown?");
715 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
717 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
718 assert(NumOperands == 1 && "Bogus allocation!");
719 if (AI->getAlignment()) {
720 Slots[1] = Log2_32(AI->getAlignment())+1;
721 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
724 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
725 // We need to encode the compare instruction's predicate as the third
726 // operand. Its not really a slot, but we don't want to break the
727 // instruction format for these instructions.
729 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
730 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
731 if (Slots[2] > MaxOpSlot)
732 MaxOpSlot = Slots[2];
733 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
734 // We need to encode the type of sequential type indices into their slot #
736 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
738 if (isa<SequentialType>(*I)) {
739 // These should be either 32-bits or 64-bits, however, with bit
740 // accurate types we just distinguish between less than or equal to
741 // 32-bits or greater than 32-bits.
743 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
744 assert(BitWidth == 32 || BitWidth == 64 &&
745 "Invalid bitwidth for GEP index");
746 unsigned IdxId = BitWidth == 32 ? 0 : 1;
747 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
748 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
750 } else if (Opcode == 58) {
751 // If this is the escape sequence for call, emit the tailcall/cc info.
752 const CallInst &CI = cast<CallInst>(I);
754 if (NumOperands <= 3) {
755 Slots[NumOperands-1] =
756 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
757 if (Slots[NumOperands-1] > MaxOpSlot)
758 MaxOpSlot = Slots[NumOperands-1];
760 } else if (isa<InvokeInst>(I)) {
761 // Invoke escape seq has at least 4 operands to encode.
765 // Decide which instruction encoding to use. This is determined primarily
766 // by the number of operands, and secondarily by whether or not the max
767 // operand will fit into the instruction encoding. More operands == fewer
770 switch (NumOperands) {
773 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
774 outputInstructionFormat1(&I, Opcode, Slots, Type);
780 if (MaxOpSlot < (1 << 8)) {
781 outputInstructionFormat2(&I, Opcode, Slots, Type);
787 if (MaxOpSlot < (1 << 6)) {
788 outputInstructionFormat3(&I, Opcode, Slots, Type);
797 // If we weren't handled before here, we either have a large number of
798 // operands or a large operand index that we are referring to.
799 outputInstructionFormat0(&I, Opcode, Table, Type);
802 //===----------------------------------------------------------------------===//
803 //=== Block Output ===//
804 //===----------------------------------------------------------------------===//
806 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
809 // Emit the signature...
810 static const unsigned char *Sig = (const unsigned char*)"llvm";
811 output_data(Sig, Sig+4);
813 // Emit the top level CLASS block.
814 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
816 // Output the version identifier
817 output_vbr(BCVersionNum);
819 // The Global type plane comes first
821 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
822 outputTypes(Type::FirstDerivedTyID);
825 // The ModuleInfoBlock follows directly after the type information
826 outputModuleInfoBlock(M);
828 // Output module level constants, used for global variable initializers
829 outputConstants(false);
831 // Do the whole module now! Process each function at a time...
832 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
835 // Output the symbole table for types
836 outputTypeSymbolTable(M->getTypeSymbolTable());
838 // Output the symbol table for values
839 outputValueSymbolTable(M->getValueSymbolTable());
842 void BytecodeWriter::outputTypes(unsigned TypeNum) {
843 // Write the type plane for types first because earlier planes (e.g. for a
844 // primitive type like float) may have constants constructed using types
845 // coming later (e.g., via getelementptr from a pointer type). The type
846 // plane is needed before types can be fwd or bkwd referenced.
847 const std::vector<const Type*>& Types = Table.getTypes();
848 assert(!Types.empty() && "No types at all?");
849 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
851 unsigned NumEntries = Types.size() - TypeNum;
853 // Output type header: [num entries]
854 output_vbr(NumEntries);
856 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
857 outputType(Types[i]);
860 // Helper function for outputConstants().
861 // Writes out all the constants in the plane Plane starting at entry StartNo.
863 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
864 &Plane, unsigned StartNo) {
865 unsigned ValNo = StartNo;
867 // Scan through and ignore function arguments, global values, and constant
869 for (; ValNo < Plane.size() &&
870 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
871 (isa<ConstantArray>(Plane[ValNo]) &&
872 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
875 unsigned NC = ValNo; // Number of constants
876 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
877 isa<InlineAsm>(Plane[NC])); NC++)
879 NC -= ValNo; // Convert from index into count
880 if (NC == 0) return; // Skip empty type planes...
882 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
885 // Put out type header: [num entries][type id number]
889 // Put out the Type ID Number...
890 int Slot = Table.getSlot(Plane.front()->getType());
891 assert (Slot != -1 && "Type in constant pool but not in function!!");
892 output_typeid((unsigned)Slot);
894 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
895 const Value *V = Plane[i];
896 if (const Constant *C = dyn_cast<Constant>(V))
899 outputInlineAsm(cast<InlineAsm>(V));
903 static inline bool hasNullValue(const Type *Ty) {
904 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
907 void BytecodeWriter::outputConstants(bool isFunction) {
908 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
909 true /* Elide block if empty */);
911 unsigned NumPlanes = Table.getNumPlanes();
914 // Output the type plane before any constants!
915 outputTypes(Table.getModuleTypeLevel());
917 // Output module-level string constants before any other constants.
918 outputConstantStrings();
920 for (unsigned pno = 0; pno != NumPlanes; pno++) {
921 const std::vector<const Value*> &Plane = Table.getPlane(pno);
922 if (!Plane.empty()) { // Skip empty type planes...
924 if (isFunction) // Don't re-emit module constants
925 ValNo += Table.getModuleLevel(pno);
927 if (hasNullValue(Plane[0]->getType())) {
928 // Skip zero initializer
933 // Write out constants in the plane
934 outputConstantsInPlane(Plane, ValNo);
939 static unsigned getEncodedLinkage(const GlobalValue *GV) {
940 switch (GV->getLinkage()) {
941 default: assert(0 && "Invalid linkage!");
942 case GlobalValue::ExternalLinkage: return 0;
943 case GlobalValue::WeakLinkage: return 1;
944 case GlobalValue::AppendingLinkage: return 2;
945 case GlobalValue::InternalLinkage: return 3;
946 case GlobalValue::LinkOnceLinkage: return 4;
947 case GlobalValue::DLLImportLinkage: return 5;
948 case GlobalValue::DLLExportLinkage: return 6;
949 case GlobalValue::ExternalWeakLinkage: return 7;
953 static unsigned getEncodedVisibility(const GlobalValue *GV) {
954 switch (GV->getVisibility()) {
955 default: assert(0 && "Invalid visibility!");
956 case GlobalValue::DefaultVisibility: return 0;
957 case GlobalValue::HiddenVisibility: return 1;
961 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
962 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
964 // Give numbers to sections as we encounter them.
965 unsigned SectionIDCounter = 0;
966 std::vector<std::string> SectionNames;
967 std::map<std::string, unsigned> SectionID;
969 // Output the types for the global variables in the module...
970 for (Module::const_global_iterator I = M->global_begin(),
971 End = M->global_end(); I != End; ++I) {
972 int Slot = Table.getSlot(I->getType());
973 assert(Slot != -1 && "Module global vars is broken!");
975 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
976 "Global must have an initializer or have external linkage!");
978 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
979 // bit5+ = Slot # for type.
980 bool HasExtensionWord = (I->getAlignment() != 0) ||
982 (I->getVisibility() != GlobalValue::DefaultVisibility);
984 // If we need to use the extension byte, set linkage=3(internal) and
985 // initializer = 0 (impossible!).
986 if (!HasExtensionWord) {
987 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
988 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
991 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
992 (0 << 1) | (unsigned)I->isConstant();
995 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
996 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
997 // bits 10-12 = visibility, bits 13+ = future use.
998 unsigned ExtWord = (unsigned)I->hasInitializer() |
999 (getEncodedLinkage(I) << 1) |
1000 ((Log2_32(I->getAlignment())+1) << 4) |
1001 ((unsigned)I->hasSection() << 9) |
1002 (getEncodedVisibility(I) << 10);
1003 output_vbr(ExtWord);
1004 if (I->hasSection()) {
1005 // Give section names unique ID's.
1006 unsigned &Entry = SectionID[I->getSection()];
1008 Entry = ++SectionIDCounter;
1009 SectionNames.push_back(I->getSection());
1015 // If we have an initializer, output it now.
1016 if (I->hasInitializer()) {
1017 Slot = Table.getSlot((Value*)I->getInitializer());
1018 assert(Slot != -1 && "No slot for global var initializer!");
1019 output_vbr((unsigned)Slot);
1022 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
1024 // Output the types of the functions in this module.
1025 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
1026 int Slot = Table.getSlot(I->getType());
1027 assert(Slot != -1 && "Module slot calculator is broken!");
1028 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
1029 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
1030 unsigned CC = I->getCallingConv()+1;
1031 unsigned ID = (Slot << 5) | (CC & 15);
1033 if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
1036 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1037 (I->isDeclaration() && I->hasDLLImportLinkage()) ||
1038 (I->isDeclaration() && I->hasExternalWeakLinkage())
1040 ID |= 1 << 31; // Do we need an extension word?
1044 if (ID & (1 << 31)) {
1045 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
1046 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1047 unsigned extLinkage = 0;
1049 if (I->isDeclaration()) {
1050 if (I->hasDLLImportLinkage()) {
1052 } else if (I->hasExternalWeakLinkage()) {
1057 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
1058 (I->hasSection() << 10) |
1059 ((extLinkage & 3) << 11);
1062 // Give section names unique ID's.
1063 if (I->hasSection()) {
1064 unsigned &Entry = SectionID[I->getSection()];
1066 Entry = ++SectionIDCounter;
1067 SectionNames.push_back(I->getSection());
1073 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
1075 // Emit the list of dependent libraries for the Module.
1076 Module::lib_iterator LI = M->lib_begin();
1077 Module::lib_iterator LE = M->lib_end();
1078 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1079 for (; LI != LE; ++LI)
1082 // Output the target triple from the module
1083 output(M->getTargetTriple());
1085 // Output the data layout from the module
1086 output(M->getDataLayout());
1088 // Emit the table of section names.
1089 output_vbr((unsigned)SectionNames.size());
1090 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1091 output(SectionNames[i]);
1093 // Output the inline asm string.
1094 output(M->getModuleInlineAsm());
1097 void BytecodeWriter::outputInstructions(const Function *F) {
1098 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1099 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1100 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1101 outputInstruction(*I);
1104 void BytecodeWriter::outputFunction(const Function *F) {
1105 // If this is an external function, there is nothing else to emit!
1106 if (F->isDeclaration()) return;
1108 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1109 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1112 // Get slot information about the function...
1113 Table.incorporateFunction(F);
1115 outputConstants(true);
1117 // Output all of the instructions in the body of the function
1118 outputInstructions(F);
1120 // If needed, output the symbol table for the function...
1121 outputValueSymbolTable(F->getValueSymbolTable());
1123 Table.purgeFunction();
1127 void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1128 // Do not output the block for an empty symbol table, it just wastes
1130 if (TST.empty()) return;
1132 // Create a header for the symbol table
1133 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
1134 true/*ElideIfEmpty*/);
1135 // Write the number of types
1136 output_vbr(TST.size());
1138 // Write each of the types
1139 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1141 // Symtab entry:[def slot #][name]
1142 output_typeid((unsigned)Table.getSlot(TI->second));
1147 void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
1148 // Do not output the Bytecode block for an empty symbol table, it just wastes
1150 if (VST.empty()) return;
1152 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1153 true/*ElideIfEmpty*/);
1155 // Organize the symbol table by type
1156 typedef std::pair<std::string, const Value*> PlaneMapEntry;
1157 typedef std::vector<PlaneMapEntry> PlaneMapVector;
1158 typedef std::map<const Type*, PlaneMapVector > PlaneMap;
1160 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1162 Planes[SI->second->getType()].push_back(
1163 std::make_pair(SI->first,SI->second));
1165 for (PlaneMap::const_iterator PI = Planes.begin(), PE = Planes.end();
1169 PlaneMapVector::const_iterator I = PI->second.begin();
1170 PlaneMapVector::const_iterator End = PI->second.end();
1172 if (I == End) continue; // Don't mess with an absent type...
1174 // Write the number of values in this plane
1175 output_vbr((unsigned)PI->second.size());
1177 // Write the slot number of the type for this plane
1178 Slot = Table.getSlot(PI->first);
1179 assert(Slot != -1 && "Type in symtab, but not in table!");
1180 output_typeid((unsigned)Slot);
1182 // Write each of the values in this plane
1183 for (; I != End; ++I) {
1184 // Symtab entry: [def slot #][name]
1185 Slot = Table.getSlot(I->second);
1186 assert(Slot != -1 && "Value in symtab but has no slot number!!");
1187 output_vbr((unsigned)Slot);
1193 void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
1195 assert(M && "You can't write a null module!!");
1197 // Make sure that std::cout is put into binary mode for systems
1200 sys::Program::ChangeStdoutToBinary();
1202 // Create a vector of unsigned char for the bytecode output. We
1203 // reserve 256KBytes of space in the vector so that we avoid doing
1204 // lots of little allocations. 256KBytes is sufficient for a large
1205 // proportion of the bytecode files we will encounter. Larger files
1206 // will be automatically doubled in size as needed (std::vector
1208 std::vector<unsigned char> Buffer;
1209 Buffer.reserve(256 * 1024);
1211 // The BytecodeWriter populates Buffer for us.
1212 BytecodeWriter BCW(Buffer, M);
1214 // Keep track of how much we've written
1215 BytesWritten += Buffer.size();
1217 // Determine start and end points of the Buffer
1218 const unsigned char *FirstByte = &Buffer.front();
1220 // If we're supposed to compress this mess ...
1223 // We signal compression by using an alternate magic number for the
1224 // file. The compressed bytecode file's magic number is "llvc" instead
1226 char compressed_magic[4];
1227 compressed_magic[0] = 'l';
1228 compressed_magic[1] = 'l';
1229 compressed_magic[2] = 'v';
1230 compressed_magic[3] = 'c';
1232 Out.stream()->write(compressed_magic,4);
1234 // Compress everything after the magic number (which we altered)
1235 Compressor::compressToStream(
1236 (char*)(FirstByte+4), // Skip the magic number
1237 Buffer.size()-4, // Skip the magic number
1238 *Out.stream() // Where to write compressed data
1243 // We're not compressing, so just write the entire block.
1244 Out.stream()->write((char*)FirstByte, Buffer.size());
1247 // make sure it hits disk now
1248 Out.stream()->flush();