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