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