Bytecode File Format Changes:
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Bytecode/Writer.h
11 //
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.  :( :( :(
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "WriterInternals.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "Support/STLExtras.h"
29 #include "Support/Statistic.h"
30 #include <cstring>
31 #include <algorithm>
32 using namespace llvm;
33
34 /// This value needs to be incremented every time the bytecode format changes
35 /// so that the reader can distinguish which format of the bytecode file has
36 /// been written.
37 /// @brief The bytecode version number
38 const unsigned BCVersionNum = 4;
39
40 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
41
42 static Statistic<> 
43 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
44
45 //===----------------------------------------------------------------------===//
46 //===                           Output Primitives                          ===//
47 //===----------------------------------------------------------------------===//
48
49 // output - If a position is specified, it must be in the valid portion of the
50 // string... note that this should be inlined always so only the relevant IF 
51 // body should be included.
52 inline void BytecodeWriter::output(unsigned i, int pos) {
53   if (pos == -1) { // Be endian clean, little endian is our friend
54     Out.push_back((unsigned char)i); 
55     Out.push_back((unsigned char)(i >> 8));
56     Out.push_back((unsigned char)(i >> 16));
57     Out.push_back((unsigned char)(i >> 24));
58   } else {
59     Out[pos  ] = (unsigned char)i;
60     Out[pos+1] = (unsigned char)(i >> 8);
61     Out[pos+2] = (unsigned char)(i >> 16);
62     Out[pos+3] = (unsigned char)(i >> 24);
63   }
64 }
65
66 inline void BytecodeWriter::output(int i) {
67   output((unsigned)i);
68 }
69
70 /// output_vbr - Output an unsigned value, by using the least number of bytes
71 /// possible.  This is useful because many of our "infinite" values are really
72 /// very small most of the time; but can be large a few times.
73 /// Data format used:  If you read a byte with the high bit set, use the low 
74 /// seven bits as data and then read another byte. 
75 inline void BytecodeWriter::output_vbr(uint64_t i) {
76   while (1) {
77     if (i < 0x80) { // done?
78       Out.push_back((unsigned char)i);   // We know the high bit is clear...
79       return;
80     }
81     
82     // Nope, we are bigger than a character, output the next 7 bits and set the
83     // high bit to say that there is more coming...
84     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
85     i >>= 7;  // Shift out 7 bits now...
86   }
87 }
88
89 inline void BytecodeWriter::output_vbr(unsigned i) {
90   while (1) {
91     if (i < 0x80) { // done?
92       Out.push_back((unsigned char)i);   // We know the high bit is clear...
93       return;
94     }
95     
96     // Nope, we are bigger than a character, output the next 7 bits and set the
97     // high bit to say that there is more coming...
98     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
99     i >>= 7;  // Shift out 7 bits now...
100   }
101 }
102
103 inline void BytecodeWriter::output_typeid(unsigned i) {
104   if (i <= 0x00FFFFFF)
105     this->output_vbr(i);
106   else {
107     this->output_vbr(0x00FFFFFF);
108     this->output_vbr(i);
109   }
110 }
111
112 inline void BytecodeWriter::output_vbr(int64_t i) {
113   if (i < 0) 
114     output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
115   else
116     output_vbr((uint64_t)i << 1);          // Low order bit is clear.
117 }
118
119
120 inline void BytecodeWriter::output_vbr(int i) {
121   if (i < 0) 
122     output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
123   else
124     output_vbr((unsigned)i << 1);          // Low order bit is clear.
125 }
126
127 inline void BytecodeWriter::output(const std::string &s) {
128   unsigned Len = s.length();
129   output_vbr(Len );             // Strings may have an arbitrary length...
130   Out.insert(Out.end(), s.begin(), s.end());
131 }
132
133 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
134   Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
135 }
136
137 inline void BytecodeWriter::output_float(float& FloatVal) {
138   /// FIXME: This isn't optimal, it has size problems on some platforms
139   /// where FP is not IEEE.
140   union {
141     float f;
142     uint32_t i;
143   } FloatUnion;
144   FloatUnion.f = FloatVal;
145   Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
146   Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
147   Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
148   Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
149 }
150
151 inline void BytecodeWriter::output_double(double& DoubleVal) {
152   /// FIXME: This isn't optimal, it has size problems on some platforms
153   /// where FP is not IEEE.
154   union {
155     double d;
156     uint64_t i;
157   } DoubleUnion;
158   DoubleUnion.d = DoubleVal;
159   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
160   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
161   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
162   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
163   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
164   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
165   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
166   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
167 }
168
169 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
170                      bool elideIfEmpty, bool hasLongFormat )
171   : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
172
173   if (HasLongFormat) {
174     w.output(ID);
175     w.output(0U); // For length in long format
176   } else {
177     w.output(0U); /// Place holder for ID and length for this block
178   }
179   Loc = w.size();
180 }
181
182 inline BytecodeBlock::~BytecodeBlock() {           // Do backpatch when block goes out
183                                     // of scope...
184   if (Loc == Writer.size() && ElideIfEmpty) {
185     // If the block is empty, and we are allowed to, do not emit the block at
186     // all!
187     Writer.resize(Writer.size()-(HasLongFormat?8:4));
188     return;
189   }
190
191   //cerr << "OldLoc = " << Loc << " NewLoc = " << NewLoc << " diff = "
192   //     << (NewLoc-Loc) << endl;
193   if (HasLongFormat)
194     Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
195   else
196     Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
197 }
198
199 //===----------------------------------------------------------------------===//
200 //===                           Constant Output                            ===//
201 //===----------------------------------------------------------------------===//
202
203 void BytecodeWriter::outputType(const Type *T) {
204   output_vbr((unsigned)T->getTypeID());
205   
206   // That's all there is to handling primitive types...
207   if (T->isPrimitiveType()) {
208     return;     // We might do this if we alias a prim type: %x = type int
209   }
210
211   switch (T->getTypeID()) {   // Handle derived types now.
212   case Type::FunctionTyID: {
213     const FunctionType *MT = cast<FunctionType>(T);
214     int Slot = Table.getSlot(MT->getReturnType());
215     assert(Slot != -1 && "Type used but not available!!");
216     output_typeid((unsigned)Slot);
217
218     // Output the number of arguments to function (+1 if varargs):
219     output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
220
221     // Output all of the arguments...
222     FunctionType::param_iterator I = MT->param_begin();
223     for (; I != MT->param_end(); ++I) {
224       Slot = Table.getSlot(*I);
225       assert(Slot != -1 && "Type used but not available!!");
226       output_typeid((unsigned)Slot);
227     }
228
229     // Terminate list with VoidTy if we are a varargs function...
230     if (MT->isVarArg())
231       output_typeid((unsigned)Type::VoidTyID);
232     break;
233   }
234
235   case Type::ArrayTyID: {
236     const ArrayType *AT = cast<ArrayType>(T);
237     int Slot = Table.getSlot(AT->getElementType());
238     assert(Slot != -1 && "Type used but not available!!");
239     output_typeid((unsigned)Slot);
240     //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
241
242     output_vbr(AT->getNumElements());
243     break;
244   }
245
246   case Type::StructTyID: {
247     const StructType *ST = cast<StructType>(T);
248
249     // Output all of the element types...
250     for (StructType::element_iterator I = ST->element_begin(),
251            E = ST->element_end(); I != E; ++I) {
252       int Slot = Table.getSlot(*I);
253       assert(Slot != -1 && "Type used but not available!!");
254       output_typeid((unsigned)Slot);
255     }
256
257     // Terminate list with VoidTy
258     output_typeid((unsigned)Type::VoidTyID);
259     break;
260   }
261
262   case Type::PointerTyID: {
263     const PointerType *PT = cast<PointerType>(T);
264     int Slot = Table.getSlot(PT->getElementType());
265     assert(Slot != -1 && "Type used but not available!!");
266     output_typeid((unsigned)Slot);
267     break;
268   }
269
270   case Type::OpaqueTyID: {
271     // No need to emit anything, just the count of opaque types is enough.
272     break;
273   }
274
275   //case Type::PackedTyID:
276   default:
277     std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
278               << " Type '" << T->getDescription() << "'\n";
279     break;
280   }
281 }
282
283 void BytecodeWriter::outputConstant(const Constant *CPV) {
284   assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
285          "Shouldn't output null constants!");
286
287   // We must check for a ConstantExpr before switching by type because
288   // a ConstantExpr can be of any type, and has no explicit value.
289   // 
290   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
291     // FIXME: Encoding of constant exprs could be much more compact!
292     assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
293     output_vbr(CE->getNumOperands());   // flags as an expr
294     output_vbr(CE->getOpcode());        // flags as an expr
295     
296     for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
297       int Slot = Table.getSlot(*OI);
298       assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
299       output_vbr((unsigned)Slot);
300       Slot = Table.getSlot((*OI)->getType());
301       output_typeid((unsigned)Slot);
302     }
303     return;
304   } else {
305     output_vbr(0U);       // flag as not a ConstantExpr
306   }
307   
308   switch (CPV->getType()->getTypeID()) {
309   case Type::BoolTyID:    // Boolean Types
310     if (cast<ConstantBool>(CPV)->getValue())
311       output_vbr(1U);
312     else
313       output_vbr(0U);
314     break;
315
316   case Type::UByteTyID:   // Unsigned integer types...
317   case Type::UShortTyID:
318   case Type::UIntTyID:
319   case Type::ULongTyID:
320     output_vbr(cast<ConstantUInt>(CPV)->getValue());
321     break;
322
323   case Type::SByteTyID:   // Signed integer types...
324   case Type::ShortTyID:
325   case Type::IntTyID:
326   case Type::LongTyID:
327     output_vbr(cast<ConstantSInt>(CPV)->getValue());
328     break;
329
330   case Type::ArrayTyID: {
331     const ConstantArray *CPA = cast<ConstantArray>(CPV);
332     assert(!CPA->isString() && "Constant strings should be handled specially!");
333
334     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
335       int Slot = Table.getSlot(CPA->getOperand(i));
336       assert(Slot != -1 && "Constant used but not available!!");
337       output_vbr((unsigned)Slot);
338     }
339     break;
340   }
341
342   case Type::StructTyID: {
343     const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
344
345     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
346       int Slot = Table.getSlot(CPS->getOperand(i));
347       assert(Slot != -1 && "Constant used but not available!!");
348       output_vbr((unsigned)Slot);
349     }
350     break;
351   }
352
353   case Type::PointerTyID:
354     assert(0 && "No non-null, non-constant-expr constants allowed!");
355     abort();
356
357   case Type::FloatTyID: {   // Floating point types...
358     float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
359     output_float(Tmp);
360     break;
361   }
362   case Type::DoubleTyID: {
363     double Tmp = cast<ConstantFP>(CPV)->getValue();
364     output_double(Tmp);
365     break;
366   }
367
368   case Type::VoidTyID: 
369   case Type::LabelTyID:
370   default:
371     std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
372               << " type '" << *CPV->getType() << "'\n";
373     break;
374   }
375   return;
376 }
377
378 void BytecodeWriter::outputConstantStrings() {
379   SlotCalculator::string_iterator I = Table.string_begin();
380   SlotCalculator::string_iterator E = Table.string_end();
381   if (I == E) return;  // No strings to emit
382
383   // If we have != 0 strings to emit, output them now.  Strings are emitted into
384   // the 'void' type plane.
385   output_vbr(unsigned(E-I));
386   output_typeid(Type::VoidTyID);
387     
388   // Emit all of the strings.
389   for (I = Table.string_begin(); I != E; ++I) {
390     const ConstantArray *Str = *I;
391     int Slot = Table.getSlot(Str->getType());
392     assert(Slot != -1 && "Constant string of unknown type?");
393     output_typeid((unsigned)Slot);
394     
395     // Now that we emitted the type (which indicates the size of the string),
396     // emit all of the characters.
397     std::string Val = Str->getAsString();
398     output_data(Val.c_str(), Val.c_str()+Val.size());
399   }
400 }
401
402 //===----------------------------------------------------------------------===//
403 //===                           Instruction Output                         ===//
404 //===----------------------------------------------------------------------===//
405 typedef unsigned char uchar;
406
407 // outputInstructionFormat0 - Output those wierd instructions that have a large
408 // number of operands or have large operands themselves...
409 //
410 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
411 //
412 void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
413                                      const SlotCalculator &Table,
414                                      unsigned Type) {
415   // Opcode must have top two bits clear...
416   output_vbr(Opcode << 2);                  // Instruction Opcode ID
417   output_typeid(Type);                      // Result type
418
419   unsigned NumArgs = I->getNumOperands();
420   output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
421                         isa<VAArgInst>(I)));
422
423   if (!isa<GetElementPtrInst>(&I)) {
424     for (unsigned i = 0; i < NumArgs; ++i) {
425       int Slot = Table.getSlot(I->getOperand(i));
426       assert(Slot >= 0 && "No slot number for value!?!?");      
427       output_vbr((unsigned)Slot);
428     }
429
430     if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
431       int Slot = Table.getSlot(I->getType());
432       assert(Slot != -1 && "Cast return type unknown?");
433       output_typeid((unsigned)Slot);
434     } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
435       int Slot = Table.getSlot(VAI->getArgType());
436       assert(Slot != -1 && "VarArg argument type unknown?");
437       output_typeid((unsigned)Slot);
438     }
439
440   } else {
441     int Slot = Table.getSlot(I->getOperand(0));
442     assert(Slot >= 0 && "No slot number for value!?!?");      
443     output_vbr(unsigned(Slot));
444
445     // We need to encode the type of sequential type indices into their slot #
446     unsigned Idx = 1;
447     for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
448          Idx != NumArgs; ++TI, ++Idx) {
449       Slot = Table.getSlot(I->getOperand(Idx));
450       assert(Slot >= 0 && "No slot number for value!?!?");      
451     
452       if (isa<SequentialType>(*TI)) {
453         unsigned IdxId;
454         switch (I->getOperand(Idx)->getType()->getTypeID()) {
455         default: assert(0 && "Unknown index type!");
456         case Type::UIntTyID:  IdxId = 0; break;
457         case Type::IntTyID:   IdxId = 1; break;
458         case Type::ULongTyID: IdxId = 2; break;
459         case Type::LongTyID:  IdxId = 3; break;
460         }
461         Slot = (Slot << 2) | IdxId;
462       }
463       output_vbr(unsigned(Slot));
464     }
465   }
466 }
467
468
469 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
470 // This are more annoying than most because the signature of the call does not
471 // tell us anything about the types of the arguments in the varargs portion.
472 // Because of this, we encode (as type 0) all of the argument types explicitly
473 // before the argument value.  This really sucks, but you shouldn't be using
474 // varargs functions in your code! *death to printf*!
475 //
476 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
477 //
478 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I, 
479                                             unsigned Opcode,
480                                             const SlotCalculator &Table,
481                                             unsigned Type) {
482   assert(isa<CallInst>(I) || isa<InvokeInst>(I));
483   // Opcode must have top two bits clear...
484   output_vbr(Opcode << 2);                  // Instruction Opcode ID
485   output_typeid(Type);                      // Result type (varargs type)
486
487   const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
488   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
489   unsigned NumParams = FTy->getNumParams();
490
491   unsigned NumFixedOperands;
492   if (isa<CallInst>(I)) {
493     // Output an operand for the callee and each fixed argument, then two for
494     // each variable argument.
495     NumFixedOperands = 1+NumParams;
496   } else {
497     assert(isa<InvokeInst>(I) && "Not call or invoke??");
498     // Output an operand for the callee and destinations, then two for each
499     // variable argument.
500     NumFixedOperands = 3+NumParams;
501   }
502   output_vbr(2 * I->getNumOperands()-NumFixedOperands);
503
504   // The type for the function has already been emitted in the type field of the
505   // instruction.  Just emit the slot # now.
506   for (unsigned i = 0; i != NumFixedOperands; ++i) {
507     int Slot = Table.getSlot(I->getOperand(i));
508     assert(Slot >= 0 && "No slot number for value!?!?");      
509     output_vbr((unsigned)Slot);
510   }
511
512   for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
513     // Output Arg Type ID
514     int Slot = Table.getSlot(I->getOperand(i)->getType());
515     assert(Slot >= 0 && "No slot number for value!?!?");      
516     output_typeid((unsigned)Slot);
517     
518     // Output arg ID itself
519     Slot = Table.getSlot(I->getOperand(i));
520     assert(Slot >= 0 && "No slot number for value!?!?");      
521     output_vbr((unsigned)Slot);
522   }
523 }
524
525
526 // outputInstructionFormat1 - Output one operand instructions, knowing that no
527 // operand index is >= 2^12.
528 //
529 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I, 
530                                                      unsigned Opcode,
531                                                      unsigned *Slots, 
532                                                      unsigned Type) {
533   // bits   Instruction format:
534   // --------------------------
535   // 01-00: Opcode type, fixed to 1.
536   // 07-02: Opcode
537   // 19-08: Resulting type plane
538   // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
539   //
540   unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
541   //  cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
542   output(Bits);
543 }
544
545
546 // outputInstructionFormat2 - Output two operand instructions, knowing that no
547 // operand index is >= 2^8.
548 //
549 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I, 
550                                                      unsigned Opcode,
551                                                      unsigned *Slots, 
552                                                      unsigned Type) {
553   // bits   Instruction format:
554   // --------------------------
555   // 01-00: Opcode type, fixed to 2.
556   // 07-02: Opcode
557   // 15-08: Resulting type plane
558   // 23-16: Operand #1
559   // 31-24: Operand #2  
560   //
561   unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
562                     (Slots[0] << 16) | (Slots[1] << 24);
563   //  cerr << "2 " << IType << " " << Type << " " << Slots[0] << " " 
564   //       << Slots[1] << endl;
565   output(Bits);
566 }
567
568
569 // outputInstructionFormat3 - Output three operand instructions, knowing that no
570 // operand index is >= 2^6.
571 //
572 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I, 
573                                                      unsigned Opcode,
574                                                      unsigned *Slots, 
575                                                      unsigned Type) {
576   // bits   Instruction format:
577   // --------------------------
578   // 01-00: Opcode type, fixed to 3.
579   // 07-02: Opcode
580   // 13-08: Resulting type plane
581   // 19-14: Operand #1
582   // 25-20: Operand #2
583   // 31-26: Operand #3
584   //
585   unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
586           (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
587   //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " " 
588   //     << Slots[1] << " " << Slots[2] << endl;
589   output(Bits);
590 }
591
592 void BytecodeWriter::outputInstruction(const Instruction &I) {
593   assert(I.getOpcode() < 62 && "Opcode too big???");
594   unsigned Opcode = I.getOpcode();
595   unsigned NumOperands = I.getNumOperands();
596
597   // Encode 'volatile load' as 62 and 'volatile store' as 63.
598   if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
599     Opcode = 62;
600   if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
601     Opcode = 63;
602
603   // Figure out which type to encode with the instruction.  Typically we want
604   // the type of the first parameter, as opposed to the type of the instruction
605   // (for example, with setcc, we always know it returns bool, but the type of
606   // the first param is actually interesting).  But if we have no arguments
607   // we take the type of the instruction itself.  
608   //
609   const Type *Ty;
610   switch (I.getOpcode()) {
611   case Instruction::Select:
612   case Instruction::Malloc:
613   case Instruction::Alloca:
614     Ty = I.getType();  // These ALWAYS want to encode the return type
615     break;
616   case Instruction::Store:
617     Ty = I.getOperand(1)->getType();  // Encode the pointer type...
618     assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
619     break;
620   default:              // Otherwise use the default behavior...
621     Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
622     break;
623   }
624
625   unsigned Type;
626   int Slot = Table.getSlot(Ty);
627   assert(Slot != -1 && "Type not available!!?!");
628   Type = (unsigned)Slot;
629
630   // Varargs calls and invokes are encoded entirely different from any other
631   // instructions.
632   if (const CallInst *CI = dyn_cast<CallInst>(&I)){
633     const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
634     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
635       outputInstrVarArgsCall(CI, Opcode, Table, Type);
636       return;
637     }
638   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
639     const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
640     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
641       outputInstrVarArgsCall(II, Opcode, Table, Type);
642       return;
643     }
644   }
645
646   if (NumOperands <= 3) {
647     // Make sure that we take the type number into consideration.  We don't want
648     // to overflow the field size for the instruction format we select.
649     //
650     unsigned MaxOpSlot = Type;
651     unsigned Slots[3]; Slots[0] = (1 << 12)-1;   // Marker to signify 0 operands
652     
653     for (unsigned i = 0; i != NumOperands; ++i) {
654       int slot = Table.getSlot(I.getOperand(i));
655       assert(slot != -1 && "Broken bytecode!");
656       if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
657       Slots[i] = unsigned(slot);
658     }
659
660     // Handle the special cases for various instructions...
661     if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
662       // Cast has to encode the destination type as the second argument in the
663       // packet, or else we won't know what type to cast to!
664       Slots[1] = Table.getSlot(I.getType());
665       assert(Slots[1] != ~0U && "Cast return type unknown?");
666       if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
667       NumOperands++;
668     } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
669       Slots[1] = Table.getSlot(VANI->getArgType());
670       assert(Slots[1] != ~0U && "va_next return type unknown?");
671       if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
672       NumOperands++;
673     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
674       // We need to encode the type of sequential type indices into their slot #
675       unsigned Idx = 1;
676       for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
677            I != E; ++I, ++Idx)
678         if (isa<SequentialType>(*I)) {
679           unsigned IdxId;
680           switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
681           default: assert(0 && "Unknown index type!");
682           case Type::UIntTyID:  IdxId = 0; break;
683           case Type::IntTyID:   IdxId = 1; break;
684           case Type::ULongTyID: IdxId = 2; break;
685           case Type::LongTyID:  IdxId = 3; break;
686           }
687           Slots[Idx] = (Slots[Idx] << 2) | IdxId;
688           if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
689         }
690     }
691
692     // Decide which instruction encoding to use.  This is determined primarily
693     // by the number of operands, and secondarily by whether or not the max
694     // operand will fit into the instruction encoding.  More operands == fewer
695     // bits per operand.
696     //
697     switch (NumOperands) {
698     case 0:
699     case 1:
700       if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
701         outputInstructionFormat1(&I, Opcode, Slots, Type);
702         return;
703       }
704       break;
705
706     case 2:
707       if (MaxOpSlot < (1 << 8)) {
708         outputInstructionFormat2(&I, Opcode, Slots, Type);
709         return;
710       }
711       break;
712
713     case 3:
714       if (MaxOpSlot < (1 << 6)) {
715         outputInstructionFormat3(&I, Opcode, Slots, Type);
716         return;
717       }
718       break;
719     default:
720       break;
721     }
722   }
723
724   // If we weren't handled before here, we either have a large number of
725   // operands or a large operand index that we are referring to.
726   outputInstructionFormat0(&I, Opcode, Table, Type);
727 }
728
729 //===----------------------------------------------------------------------===//
730 //===                              Block Output                            ===//
731 //===----------------------------------------------------------------------===//
732
733 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M) 
734   : Out(o), Table(M) {
735
736   // Emit the signature...
737   static const unsigned char *Sig =  (const unsigned char*)"llvm";
738   output_data(Sig, Sig+4);
739
740   // Emit the top level CLASS block.
741   BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
742
743   bool isBigEndian      = M->getEndianness() == Module::BigEndian;
744   bool hasLongPointers  = M->getPointerSize() == Module::Pointer64;
745   bool hasNoEndianness  = M->getEndianness() == Module::AnyEndianness;
746   bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
747
748   // Output the version identifier... we are currently on bytecode version #2,
749   // which corresponds to LLVM v1.3.
750   unsigned Version = (BCVersionNum << 4) | 
751                      (unsigned)isBigEndian | (hasLongPointers << 1) |
752                      (hasNoEndianness << 2) | 
753                      (hasNoPointerSize << 3);
754   output_vbr(Version);
755
756   // The Global type plane comes first
757   {
758       BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
759       outputTypes(Type::FirstDerivedTyID);
760   }
761
762   // The ModuleInfoBlock follows directly after the type information
763   outputModuleInfoBlock(M);
764
765   // Output module level constants, used for global variable initializers
766   outputConstants(false);
767
768   // Do the whole module now! Process each function at a time...
769   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
770     outputFunction(I);
771
772   // If needed, output the symbol table for the module...
773   outputSymbolTable(M->getSymbolTable());
774 }
775
776 void BytecodeWriter::outputTypes(unsigned TypeNum)
777 {
778   // Write the type plane for types first because earlier planes (e.g. for a
779   // primitive type like float) may have constants constructed using types
780   // coming later (e.g., via getelementptr from a pointer type).  The type
781   // plane is needed before types can be fwd or bkwd referenced.
782   const std::vector<const Type*>& Types = Table.getTypes();
783   assert(!Types.empty() && "No types at all?");
784   assert(TypeNum <= Types.size() && "Invalid TypeNo index");
785
786   unsigned NumEntries = Types.size() - TypeNum;
787   
788   // Output type header: [num entries]
789   output_vbr(NumEntries);
790
791   for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
792     outputType(Types[i]);
793 }
794
795 // Helper function for outputConstants().
796 // Writes out all the constants in the plane Plane starting at entry StartNo.
797 // 
798 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
799                                             &Plane, unsigned StartNo) {
800   unsigned ValNo = StartNo;
801   
802   // Scan through and ignore function arguments, global values, and constant
803   // strings.
804   for (; ValNo < Plane.size() &&
805          (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
806           (isa<ConstantArray>(Plane[ValNo]) &&
807            cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
808     /*empty*/;
809
810   unsigned NC = ValNo;              // Number of constants
811   for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
812     /*empty*/;
813   NC -= ValNo;                      // Convert from index into count
814   if (NC == 0) return;              // Skip empty type planes...
815
816   // FIXME: Most slabs only have 1 or 2 entries!  We should encode this much
817   // more compactly.
818
819   // Output type header: [num entries][type id number]
820   //
821   output_vbr(NC);
822
823   // Output the Type ID Number...
824   int Slot = Table.getSlot(Plane.front()->getType());
825   assert (Slot != -1 && "Type in constant pool but not in function!!");
826   output_typeid((unsigned)Slot);
827
828   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
829     const Value *V = Plane[i];
830     if (const Constant *C = dyn_cast<Constant>(V)) {
831       outputConstant(C);
832     }
833   }
834 }
835
836 static inline bool hasNullValue(unsigned TyID) {
837   return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
838 }
839
840 void BytecodeWriter::outputConstants(bool isFunction) {
841   BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
842                       true  /* Elide block if empty */);
843
844   unsigned NumPlanes = Table.getNumPlanes();
845
846   if (isFunction)
847     // Output the type plane before any constants!
848     outputTypes( Table.getModuleTypeLevel() );
849   else
850     // Output module-level string constants before any other constants.x
851     outputConstantStrings();
852
853   for (unsigned pno = 0; pno != NumPlanes; pno++) {
854     const std::vector<const Value*> &Plane = Table.getPlane(pno);
855     if (!Plane.empty()) {              // Skip empty type planes...
856       unsigned ValNo = 0;
857       if (isFunction)                  // Don't re-emit module constants
858         ValNo += Table.getModuleLevel(pno);
859       
860       if (hasNullValue(pno)) {
861         // Skip zero initializer
862         if (ValNo == 0)
863           ValNo = 1;
864       }
865       
866       // Write out constants in the plane
867       outputConstantsInPlane(Plane, ValNo);
868     }
869   }
870 }
871
872 static unsigned getEncodedLinkage(const GlobalValue *GV) {
873   switch (GV->getLinkage()) {
874   default: assert(0 && "Invalid linkage!");
875   case GlobalValue::ExternalLinkage:  return 0;
876   case GlobalValue::WeakLinkage:      return 1;
877   case GlobalValue::AppendingLinkage: return 2;
878   case GlobalValue::InternalLinkage:  return 3;
879   case GlobalValue::LinkOnceLinkage:  return 4;
880   }
881 }
882
883 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
884   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
885   
886   // Output the types for the global variables in the module...
887   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
888     int Slot = Table.getSlot(I->getType());
889     assert(Slot != -1 && "Module global vars is broken!");
890
891     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
892     // bit5+ = Slot # for type
893     unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
894                      (I->hasInitializer() << 1) | (unsigned)I->isConstant();
895     output_vbr(oSlot );
896
897     // If we have an initializer, output it now.
898     if (I->hasInitializer()) {
899       Slot = Table.getSlot((Value*)I->getInitializer());
900       assert(Slot != -1 && "No slot for global var initializer!");
901       output_vbr((unsigned)Slot);
902     }
903   }
904   output_typeid((unsigned)Table.getSlot(Type::VoidTy));
905
906   // Output the types of the functions in this module...
907   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
908     int Slot = Table.getSlot(I->getType());
909     assert(Slot != -1 && "Module const pool is broken!");
910     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
911     output_typeid((unsigned)Slot);
912   }
913   output_typeid((unsigned)Table.getSlot(Type::VoidTy));
914
915   // Put out the list of dependent libraries for the Module
916   Module::lib_iterator LI = M->lib_begin();
917   Module::lib_iterator LE = M->lib_end();
918   output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
919   for ( ; LI != LE; ++LI ) {
920     output(*LI);
921   }
922
923   // Output the target triple from the module
924   output(M->getTargetTriple());
925 }
926
927 void BytecodeWriter::outputInstructions(const Function *F) {
928   BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
929   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
930     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
931       outputInstruction(*I);
932 }
933
934 void BytecodeWriter::outputFunction(const Function *F) {
935   BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
936   output_vbr(getEncodedLinkage(F));
937
938   // If this is an external function, there is nothing else to emit!
939   if (F->isExternal()) return;
940
941   // Get slot information about the function...
942   Table.incorporateFunction(F);
943
944   if (Table.getCompactionTable().empty()) {
945     // Output information about the constants in the function if the compaction
946     // table is not being used.
947     outputConstants(true);
948   } else {
949     // Otherwise, emit the compaction table.
950     outputCompactionTable();
951   }
952   
953   // Output all of the instructions in the body of the function
954   outputInstructions(F);
955   
956   // If needed, output the symbol table for the function...
957   outputSymbolTable(F->getSymbolTable());
958   
959   Table.purgeFunction();
960 }
961
962 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
963                                          const std::vector<const Value*> &Plane,
964                                                 unsigned StartNo) {
965   unsigned End = Table.getModuleLevel(PlaneNo);
966   if (Plane.empty() || StartNo == End || End == 0) return;   // Nothing to emit
967   assert(StartNo < End && "Cannot emit negative range!");
968   assert(StartNo < Plane.size() && End <= Plane.size());
969
970   // Do not emit the null initializer!
971   ++StartNo;
972
973   // Figure out which encoding to use.  By far the most common case we have is
974   // to emit 0-2 entries in a compaction table plane.
975   switch (End-StartNo) {
976   case 0:         // Avoid emitting two vbr's if possible.
977   case 1:
978   case 2:
979     output_vbr((PlaneNo << 2) | End-StartNo);
980     break;
981   default:
982     // Output the number of things.
983     output_vbr((unsigned(End-StartNo) << 2) | 3);
984     output_typeid(PlaneNo);                 // Emit the type plane this is
985     break;
986   }
987
988   for (unsigned i = StartNo; i != End; ++i)
989     output_vbr(Table.getGlobalSlot(Plane[i]));
990 }
991
992 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
993   // Get the compaction type table from the slot calculator
994   const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
995
996   // The compaction types may have been uncompactified back to the
997   // global types. If so, we just write an empty table
998   if (CTypes.size() == 0 ) {
999     output_vbr(0U);
1000     return;
1001   }
1002
1003   assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1004
1005   // Determine how many types to write
1006   unsigned NumTypes = CTypes.size() - StartNo;
1007
1008   // Output the number of types.
1009   output_vbr(NumTypes);
1010
1011   for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1012     output_typeid(Table.getGlobalSlot(CTypes[i]));
1013 }
1014
1015 void BytecodeWriter::outputCompactionTable() {
1016   BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this, 
1017                     true/*ElideIfEmpty*/);
1018   const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1019   
1020   // First thing is first, emit the type compaction table if there is one.
1021   outputCompactionTypes(Type::FirstDerivedTyID);
1022
1023   for (unsigned i = 0, e = CT.size(); i != e; ++i)
1024     outputCompactionTablePlane(i, CT[i], 0);
1025 }
1026
1027 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
1028   // Do not output the Bytecode block for an empty symbol table, it just wastes
1029   // space!
1030   if ( MST.isEmpty() ) return;
1031
1032   BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
1033                             true/* ElideIfEmpty*/);
1034
1035   // Write the number of types 
1036   output_vbr(MST.num_types());
1037
1038   // Write each of the types
1039   for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1040        TE = MST.type_end(); TI != TE; ++TI ) {
1041     // Symtab entry:[def slot #][name]
1042     output_typeid((unsigned)Table.getSlot(TI->second));
1043     output(TI->first); 
1044   }
1045
1046   // Now do each of the type planes in order.
1047   for (SymbolTable::plane_const_iterator PI = MST.plane_begin(), 
1048        PE = MST.plane_end(); PI != PE;  ++PI) {
1049     SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1050     SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1051     int Slot;
1052     
1053     if (I == End) continue;  // Don't mess with an absent type...
1054
1055     // Write the number of values in this plane
1056     output_vbr(MST.type_size(PI->first));
1057
1058     // Write the slot number of the type for this plane
1059     Slot = Table.getSlot(PI->first);
1060     assert(Slot != -1 && "Type in symtab, but not in table!");
1061     output_typeid((unsigned)Slot);
1062
1063     // Write each of the values in this plane
1064     for (; I != End; ++I) {
1065       // Symtab entry: [def slot #][name]
1066       Slot = Table.getSlot(I->second);
1067       assert(Slot != -1 && "Value in symtab but has no slot number!!");
1068       output_vbr((unsigned)Slot);
1069       output(I->first);
1070     }
1071   }
1072 }
1073
1074 void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1075   assert(M && "You can't write a null module!!");
1076
1077   std::vector<unsigned char> Buffer;
1078   Buffer.reserve(64 * 1024); // avoid lots of little reallocs
1079
1080   // This object populates buffer for us...
1081   BytecodeWriter BCW(Buffer, M);
1082
1083   // Keep track of how much we've written...
1084   BytesWritten += Buffer.size();
1085
1086   // Okay, write the deque out to the ostream now... the deque is not
1087   // sequential in memory, however, so write out as much as possible in big
1088   // chunks, until we're done.
1089   //
1090
1091   std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
1092   while (I != E) {                           // Loop until it's all written
1093     // Scan to see how big this chunk is...
1094     const unsigned char *ChunkPtr = &*I;
1095     const unsigned char *LastPtr = ChunkPtr;
1096     while (I != E) {
1097       const unsigned char *ThisPtr = &*++I;
1098       if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
1099         break;
1100     }
1101     
1102     // Write out the chunk...
1103     Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
1104   }
1105   Out.flush();
1106 }
1107
1108 // vim: sw=2 ai