Fix an apparent ambiguity compiling on PPC
[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 "llvm/Support/Compressor.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <cstring>
32 #include <algorithm>
33 using namespace llvm;
34
35 /// This value needs to be incremented every time the bytecode format changes
36 /// so that the reader can distinguish which format of the bytecode file has
37 /// been written.
38 /// @brief The bytecode version number
39 const unsigned BCVersionNum = 5;
40
41 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
42
43 static Statistic<> 
44 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
45
46 //===----------------------------------------------------------------------===//
47 //===                           Output Primitives                          ===//
48 //===----------------------------------------------------------------------===//
49
50 // output - If a position is specified, it must be in the valid portion of the
51 // string... note that this should be inlined always so only the relevant IF 
52 // body should be included.
53 inline void BytecodeWriter::output(unsigned i, int pos) {
54   if (pos == -1) { // Be endian clean, little endian is our friend
55     Out.push_back((unsigned char)i); 
56     Out.push_back((unsigned char)(i >> 8));
57     Out.push_back((unsigned char)(i >> 16));
58     Out.push_back((unsigned char)(i >> 24));
59   } else {
60     Out[pos  ] = (unsigned char)i;
61     Out[pos+1] = (unsigned char)(i >> 8);
62     Out[pos+2] = (unsigned char)(i >> 16);
63     Out[pos+3] = (unsigned char)(i >> 24);
64   }
65 }
66
67 inline void BytecodeWriter::output(int i) {
68   output((unsigned)i);
69 }
70
71 /// output_vbr - Output an unsigned value, by using the least number of bytes
72 /// possible.  This is useful because many of our "infinite" values are really
73 /// very small most of the time; but can be large a few times.
74 /// Data format used:  If you read a byte with the high bit set, use the low 
75 /// seven bits as data and then read another byte. 
76 inline void BytecodeWriter::output_vbr(uint64_t i) {
77   while (1) {
78     if (i < 0x80) { // done?
79       Out.push_back((unsigned char)i);   // We know the high bit is clear...
80       return;
81     }
82     
83     // Nope, we are bigger than a character, output the next 7 bits and set the
84     // high bit to say that there is more coming...
85     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
86     i >>= 7;  // Shift out 7 bits now...
87   }
88 }
89
90 inline void BytecodeWriter::output_vbr(unsigned i) {
91   while (1) {
92     if (i < 0x80) { // done?
93       Out.push_back((unsigned char)i);   // We know the high bit is clear...
94       return;
95     }
96     
97     // Nope, we are bigger than a character, output the next 7 bits and set the
98     // high bit to say that there is more coming...
99     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
100     i >>= 7;  // Shift out 7 bits now...
101   }
102 }
103
104 inline void BytecodeWriter::output_typeid(unsigned i) {
105   if (i <= 0x00FFFFFF)
106     this->output_vbr(i);
107   else {
108     this->output_vbr(0x00FFFFFF);
109     this->output_vbr(i);
110   }
111 }
112
113 inline void BytecodeWriter::output_vbr(int64_t i) {
114   if (i < 0) 
115     output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
116   else
117     output_vbr((uint64_t)i << 1);          // Low order bit is clear.
118 }
119
120
121 inline void BytecodeWriter::output_vbr(int i) {
122   if (i < 0) 
123     output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
124   else
125     output_vbr((unsigned)i << 1);          // Low order bit is clear.
126 }
127
128 inline void BytecodeWriter::output(const std::string &s) {
129   unsigned Len = s.length();
130   output_vbr(Len );             // Strings may have an arbitrary length...
131   Out.insert(Out.end(), s.begin(), s.end());
132 }
133
134 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
135   Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
136 }
137
138 inline void BytecodeWriter::output_float(float& FloatVal) {
139   /// FIXME: This isn't optimal, it has size problems on some platforms
140   /// where FP is not IEEE.
141   union {
142     float f;
143     uint32_t i;
144   } FloatUnion;
145   FloatUnion.f = FloatVal;
146   Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
147   Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
148   Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
149   Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
150 }
151
152 inline void BytecodeWriter::output_double(double& DoubleVal) {
153   /// FIXME: This isn't optimal, it has size problems on some platforms
154   /// where FP is not IEEE.
155   union {
156     double d;
157     uint64_t i;
158   } DoubleUnion;
159   DoubleUnion.d = DoubleVal;
160   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
161   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
162   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
163   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
164   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
165   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
166   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
167   Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
168 }
169
170 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
171                      bool elideIfEmpty, bool hasLongFormat )
172   : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
173
174   if (HasLongFormat) {
175     w.output(ID);
176     w.output(0U); // For length in long format
177   } else {
178     w.output(0U); /// Place holder for ID and length for this block
179   }
180   Loc = w.size();
181 }
182
183 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
184                                          // of scope...
185   if (Loc == Writer.size() && ElideIfEmpty) {
186     // If the block is empty, and we are allowed to, do not emit the block at
187     // all!
188     Writer.resize(Writer.size()-(HasLongFormat?8:4));
189     return;
190   }
191
192   if (HasLongFormat)
193     Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
194   else
195     Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
196 }
197
198 //===----------------------------------------------------------------------===//
199 //===                           Constant Output                            ===//
200 //===----------------------------------------------------------------------===//
201
202 void BytecodeWriter::outputType(const Type *T) {
203   output_vbr((unsigned)T->getTypeID());
204   
205   // That's all there is to handling primitive types...
206   if (T->isPrimitiveType()) {
207     return;     // We might do this if we alias a prim type: %x = type int
208   }
209
210   switch (T->getTypeID()) {   // Handle derived types now.
211   case Type::FunctionTyID: {
212     const FunctionType *MT = cast<FunctionType>(T);
213     int Slot = Table.getSlot(MT->getReturnType());
214     assert(Slot != -1 && "Type used but not available!!");
215     output_typeid((unsigned)Slot);
216
217     // Output the number of arguments to function (+1 if varargs):
218     output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
219
220     // Output all of the arguments...
221     FunctionType::param_iterator I = MT->param_begin();
222     for (; I != MT->param_end(); ++I) {
223       Slot = Table.getSlot(*I);
224       assert(Slot != -1 && "Type used but not available!!");
225       output_typeid((unsigned)Slot);
226     }
227
228     // Terminate list with VoidTy if we are a varargs function...
229     if (MT->isVarArg())
230       output_typeid((unsigned)Type::VoidTyID);
231     break;
232   }
233
234   case Type::ArrayTyID: {
235     const ArrayType *AT = cast<ArrayType>(T);
236     int Slot = Table.getSlot(AT->getElementType());
237     assert(Slot != -1 && "Type used but not available!!");
238     output_typeid((unsigned)Slot);
239     output_vbr(AT->getNumElements());
240     break;
241   }
242
243  case Type::PackedTyID: {
244     const PackedType *PT = cast<PackedType>(T);
245     int Slot = Table.getSlot(PT->getElementType());
246     assert(Slot != -1 && "Type used but not available!!");
247     output_typeid((unsigned)Slot);
248     output_vbr(PT->getNumElements());
249     break;
250   }
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   default:
282     std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
283               << " Type '" << T->getDescription() << "'\n";
284     break;
285   }
286 }
287
288 void BytecodeWriter::outputConstant(const Constant *CPV) {
289   assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
290          "Shouldn't output null constants!");
291
292   // We must check for a ConstantExpr before switching by type because
293   // a ConstantExpr can be of any type, and has no explicit value.
294   // 
295   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
296     // FIXME: Encoding of constant exprs could be much more compact!
297     assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
298     assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
299     output_vbr(1+CE->getNumOperands());   // flags as an expr
300     output_vbr(CE->getOpcode());        // flags as an expr
301     
302     for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
303       int Slot = Table.getSlot(*OI);
304       assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
305       output_vbr((unsigned)Slot);
306       Slot = Table.getSlot((*OI)->getType());
307       output_typeid((unsigned)Slot);
308     }
309     return;
310   } else if (isa<UndefValue>(CPV)) {
311     output_vbr(1U);       // 1 -> UndefValue constant.
312     return;
313   } else {
314     output_vbr(0U);       // flag as not a ConstantExpr
315   }
316   
317   switch (CPV->getType()->getTypeID()) {
318   case Type::BoolTyID:    // Boolean Types
319     if (cast<ConstantBool>(CPV)->getValue())
320       output_vbr(1U);
321     else
322       output_vbr(0U);
323     break;
324
325   case Type::UByteTyID:   // Unsigned integer types...
326   case Type::UShortTyID:
327   case Type::UIntTyID:
328   case Type::ULongTyID:
329     output_vbr(cast<ConstantUInt>(CPV)->getValue());
330     break;
331
332   case Type::SByteTyID:   // Signed integer types...
333   case Type::ShortTyID:
334   case Type::IntTyID:
335   case Type::LongTyID:
336     output_vbr(cast<ConstantSInt>(CPV)->getValue());
337     break;
338
339   case Type::ArrayTyID: {
340     const ConstantArray *CPA = cast<ConstantArray>(CPV);
341     assert(!CPA->isString() && "Constant strings should be handled specially!");
342
343     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
344       int Slot = Table.getSlot(CPA->getOperand(i));
345       assert(Slot != -1 && "Constant used but not available!!");
346       output_vbr((unsigned)Slot);
347     }
348     break;
349   }
350
351   case Type::PackedTyID: {
352     const ConstantPacked *CP = cast<ConstantPacked>(CPV);
353
354     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
355       int Slot = Table.getSlot(CP->getOperand(i));
356       assert(Slot != -1 && "Constant used but not available!!");
357       output_vbr((unsigned)Slot);
358     }
359     break;
360   }
361
362   case Type::StructTyID: {
363     const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
364
365     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
366       int Slot = Table.getSlot(CPS->getOperand(i));
367       assert(Slot != -1 && "Constant used but not available!!");
368       output_vbr((unsigned)Slot);
369     }
370     break;
371   }
372
373   case Type::PointerTyID:
374     assert(0 && "No non-null, non-constant-expr constants allowed!");
375     abort();
376
377   case Type::FloatTyID: {   // Floating point types...
378     float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
379     output_float(Tmp);
380     break;
381   }
382   case Type::DoubleTyID: {
383     double Tmp = cast<ConstantFP>(CPV)->getValue();
384     output_double(Tmp);
385     break;
386   }
387
388   case Type::VoidTyID: 
389   case Type::LabelTyID:
390   default:
391     std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
392               << " type '" << *CPV->getType() << "'\n";
393     break;
394   }
395   return;
396 }
397
398 void BytecodeWriter::outputConstantStrings() {
399   SlotCalculator::string_iterator I = Table.string_begin();
400   SlotCalculator::string_iterator E = Table.string_end();
401   if (I == E) return;  // No strings to emit
402
403   // If we have != 0 strings to emit, output them now.  Strings are emitted into
404   // the 'void' type plane.
405   output_vbr(unsigned(E-I));
406   output_typeid(Type::VoidTyID);
407     
408   // Emit all of the strings.
409   for (I = Table.string_begin(); I != E; ++I) {
410     const ConstantArray *Str = *I;
411     int Slot = Table.getSlot(Str->getType());
412     assert(Slot != -1 && "Constant string of unknown type?");
413     output_typeid((unsigned)Slot);
414     
415     // Now that we emitted the type (which indicates the size of the string),
416     // emit all of the characters.
417     std::string Val = Str->getAsString();
418     output_data(Val.c_str(), Val.c_str()+Val.size());
419   }
420 }
421
422 //===----------------------------------------------------------------------===//
423 //===                           Instruction Output                         ===//
424 //===----------------------------------------------------------------------===//
425 typedef unsigned char uchar;
426
427 // outputInstructionFormat0 - Output those weird instructions that have a large
428 // number of operands or have large operands themselves...
429 //
430 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
431 //
432 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
433                                               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   output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
562 }
563
564
565 // outputInstructionFormat2 - Output two operand instructions, knowing that no
566 // operand index is >= 2^8.
567 //
568 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I, 
569                                                      unsigned Opcode,
570                                                      unsigned *Slots, 
571                                                      unsigned Type) {
572   // bits   Instruction format:
573   // --------------------------
574   // 01-00: Opcode type, fixed to 2.
575   // 07-02: Opcode
576   // 15-08: Resulting type plane
577   // 23-16: Operand #1
578   // 31-24: Operand #2  
579   //
580   output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
581 }
582
583
584 // outputInstructionFormat3 - Output three operand instructions, knowing that no
585 // operand index is >= 2^6.
586 //
587 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I, 
588                                                      unsigned Opcode,
589                                                      unsigned *Slots, 
590                                                      unsigned Type) {
591   // bits   Instruction format:
592   // --------------------------
593   // 01-00: Opcode type, fixed to 3.
594   // 07-02: Opcode
595   // 13-08: Resulting type plane
596   // 19-14: Operand #1
597   // 25-20: Operand #2
598   // 31-26: Operand #3
599   //
600   output(3 | (Opcode << 2) | (Type << 8) |
601           (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
602 }
603
604 void BytecodeWriter::outputInstruction(const Instruction &I) {
605   assert(I.getOpcode() < 62 && "Opcode too big???");
606   unsigned Opcode = I.getOpcode();
607   unsigned NumOperands = I.getNumOperands();
608
609   // Encode 'volatile load' as 62 and 'volatile store' as 63.
610   if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
611     Opcode = 62;
612   if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
613     Opcode = 63;
614
615   // Figure out which type to encode with the instruction.  Typically we want
616   // the type of the first parameter, as opposed to the type of the instruction
617   // (for example, with setcc, we always know it returns bool, but the type of
618   // the first param is actually interesting).  But if we have no arguments
619   // we take the type of the instruction itself.  
620   //
621   const Type *Ty;
622   switch (I.getOpcode()) {
623   case Instruction::Select:
624   case Instruction::Malloc:
625   case Instruction::Alloca:
626     Ty = I.getType();  // These ALWAYS want to encode the return type
627     break;
628   case Instruction::Store:
629     Ty = I.getOperand(1)->getType();  // Encode the pointer type...
630     assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
631     break;
632   default:              // Otherwise use the default behavior...
633     Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
634     break;
635   }
636
637   unsigned Type;
638   int Slot = Table.getSlot(Ty);
639   assert(Slot != -1 && "Type not available!!?!");
640   Type = (unsigned)Slot;
641
642   // Varargs calls and invokes are encoded entirely different from any other
643   // instructions.
644   if (const CallInst *CI = dyn_cast<CallInst>(&I)){
645     const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
646     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
647       outputInstrVarArgsCall(CI, Opcode, Table, Type);
648       return;
649     }
650   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
651     const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
652     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
653       outputInstrVarArgsCall(II, Opcode, Table, Type);
654       return;
655     }
656   }
657
658   if (NumOperands <= 3) {
659     // Make sure that we take the type number into consideration.  We don't want
660     // to overflow the field size for the instruction format we select.
661     //
662     unsigned MaxOpSlot = Type;
663     unsigned Slots[3]; Slots[0] = (1 << 12)-1;   // Marker to signify 0 operands
664     
665     for (unsigned i = 0; i != NumOperands; ++i) {
666       int slot = Table.getSlot(I.getOperand(i));
667       assert(slot != -1 && "Broken bytecode!");
668       if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
669       Slots[i] = unsigned(slot);
670     }
671
672     // Handle the special cases for various instructions...
673     if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
674       // Cast has to encode the destination type as the second argument in the
675       // packet, or else we won't know what type to cast to!
676       Slots[1] = Table.getSlot(I.getType());
677       assert(Slots[1] != ~0U && "Cast return type unknown?");
678       if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
679       NumOperands++;
680     } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
681       Slots[1] = Table.getSlot(VANI->getArgType());
682       assert(Slots[1] != ~0U && "va_next return type unknown?");
683       if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
684       NumOperands++;
685     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
686       // We need to encode the type of sequential type indices into their slot #
687       unsigned Idx = 1;
688       for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
689            I != E; ++I, ++Idx)
690         if (isa<SequentialType>(*I)) {
691           unsigned IdxId;
692           switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
693           default: assert(0 && "Unknown index type!");
694           case Type::UIntTyID:  IdxId = 0; break;
695           case Type::IntTyID:   IdxId = 1; break;
696           case Type::ULongTyID: IdxId = 2; break;
697           case Type::LongTyID:  IdxId = 3; break;
698           }
699           Slots[Idx] = (Slots[Idx] << 2) | IdxId;
700           if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
701         }
702     }
703
704     // Decide which instruction encoding to use.  This is determined primarily
705     // by the number of operands, and secondarily by whether or not the max
706     // operand will fit into the instruction encoding.  More operands == fewer
707     // bits per operand.
708     //
709     switch (NumOperands) {
710     case 0:
711     case 1:
712       if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
713         outputInstructionFormat1(&I, Opcode, Slots, Type);
714         return;
715       }
716       break;
717
718     case 2:
719       if (MaxOpSlot < (1 << 8)) {
720         outputInstructionFormat2(&I, Opcode, Slots, Type);
721         return;
722       }
723       break;
724
725     case 3:
726       if (MaxOpSlot < (1 << 6)) {
727         outputInstructionFormat3(&I, Opcode, Slots, Type);
728         return;
729       }
730       break;
731     default:
732       break;
733     }
734   }
735
736   // If we weren't handled before here, we either have a large number of
737   // operands or a large operand index that we are referring to.
738   outputInstructionFormat0(&I, Opcode, Table, Type);
739 }
740
741 //===----------------------------------------------------------------------===//
742 //===                              Block Output                            ===//
743 //===----------------------------------------------------------------------===//
744
745 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M) 
746   : Out(o), Table(M) {
747
748   // Emit the signature...
749   static const unsigned char *Sig =  (const unsigned char*)"llvm";
750   output_data(Sig, Sig+4);
751
752   // Emit the top level CLASS block.
753   BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
754
755   bool isBigEndian      = M->getEndianness() == Module::BigEndian;
756   bool hasLongPointers  = M->getPointerSize() == Module::Pointer64;
757   bool hasNoEndianness  = M->getEndianness() == Module::AnyEndianness;
758   bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
759
760   // Output the version identifier and other information.
761   unsigned Version = (BCVersionNum << 4) | 
762                      (unsigned)isBigEndian | (hasLongPointers << 1) |
763                      (hasNoEndianness << 2) | 
764                      (hasNoPointerSize << 3);
765   output_vbr(Version);
766
767   // The Global type plane comes first
768   {
769       BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
770       outputTypes(Type::FirstDerivedTyID);
771   }
772
773   // The ModuleInfoBlock follows directly after the type information
774   outputModuleInfoBlock(M);
775
776   // Output module level constants, used for global variable initializers
777   outputConstants(false);
778
779   // Do the whole module now! Process each function at a time...
780   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
781     outputFunction(I);
782
783   // If needed, output the symbol table for the module...
784   outputSymbolTable(M->getSymbolTable());
785 }
786
787 void BytecodeWriter::outputTypes(unsigned TypeNum) {
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.
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 slot calculator is broken!");
920     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
921     assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
922     unsigned ID = (Slot << 5) + 1;
923     if (I->isExternal())   // If external, we don't have an FunctionInfo block.
924       ID |= 1 << 4;
925     output_vbr(ID);
926   }
927   output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
928
929   // Emit the list of dependent libraries for the Module.
930   Module::lib_iterator LI = M->lib_begin();
931   Module::lib_iterator LE = M->lib_end();
932   output_vbr(unsigned(LE - LI));   // Emit the number of dependent libraries.
933   for (; LI != LE; ++LI)
934     output(*LI);
935
936   // Output the target triple from the module
937   output(M->getTargetTriple());
938 }
939
940 void BytecodeWriter::outputInstructions(const Function *F) {
941   BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
942   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
943     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
944       outputInstruction(*I);
945 }
946
947 void BytecodeWriter::outputFunction(const Function *F) {
948   // If this is an external function, there is nothing else to emit!
949   if (F->isExternal()) return;
950
951   BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
952   output_vbr(getEncodedLinkage(F));
953
954   // Get slot information about the function...
955   Table.incorporateFunction(F);
956
957   if (Table.getCompactionTable().empty()) {
958     // Output information about the constants in the function if the compaction
959     // table is not being used.
960     outputConstants(true);
961   } else {
962     // Otherwise, emit the compaction table.
963     outputCompactionTable();
964   }
965   
966   // Output all of the instructions in the body of the function
967   outputInstructions(F);
968   
969   // If needed, output the symbol table for the function...
970   outputSymbolTable(F->getSymbolTable());
971   
972   Table.purgeFunction();
973 }
974
975 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
976                                          const std::vector<const Value*> &Plane,
977                                                 unsigned StartNo) {
978   unsigned End = Table.getModuleLevel(PlaneNo);
979   if (Plane.empty() || StartNo == End || End == 0) return;   // Nothing to emit
980   assert(StartNo < End && "Cannot emit negative range!");
981   assert(StartNo < Plane.size() && End <= Plane.size());
982
983   // Do not emit the null initializer!
984   ++StartNo;
985
986   // Figure out which encoding to use.  By far the most common case we have is
987   // to emit 0-2 entries in a compaction table plane.
988   switch (End-StartNo) {
989   case 0:         // Avoid emitting two vbr's if possible.
990   case 1:
991   case 2:
992     output_vbr((PlaneNo << 2) | End-StartNo);
993     break;
994   default:
995     // Output the number of things.
996     output_vbr((unsigned(End-StartNo) << 2) | 3);
997     output_typeid(PlaneNo);                 // Emit the type plane this is
998     break;
999   }
1000
1001   for (unsigned i = StartNo; i != End; ++i)
1002     output_vbr(Table.getGlobalSlot(Plane[i]));
1003 }
1004
1005 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1006   // Get the compaction type table from the slot calculator
1007   const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1008
1009   // The compaction types may have been uncompactified back to the
1010   // global types. If so, we just write an empty table
1011   if (CTypes.size() == 0 ) {
1012     output_vbr(0U);
1013     return;
1014   }
1015
1016   assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1017
1018   // Determine how many types to write
1019   unsigned NumTypes = CTypes.size() - StartNo;
1020
1021   // Output the number of types.
1022   output_vbr(NumTypes);
1023
1024   for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1025     output_typeid(Table.getGlobalSlot(CTypes[i]));
1026 }
1027
1028 void BytecodeWriter::outputCompactionTable() {
1029   // Avoid writing the compaction table at all if there is no content.
1030   if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1031       (!Table.CompactionTableIsEmpty())) {
1032     BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this, 
1033                       true/*ElideIfEmpty*/);
1034     const std::vector<std::vector<const Value*> > &CT =
1035       Table.getCompactionTable();
1036     
1037     // First things first, emit the type compaction table if there is one.
1038     outputCompactionTypes(Type::FirstDerivedTyID);
1039
1040     for (unsigned i = 0, e = CT.size(); i != e; ++i)
1041       outputCompactionTablePlane(i, CT[i], 0);
1042   }
1043 }
1044
1045 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
1046   // Do not output the Bytecode block for an empty symbol table, it just wastes
1047   // space!
1048   if (MST.isEmpty()) return;
1049
1050   BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
1051                             true/*ElideIfEmpty*/);
1052
1053   // Write the number of types 
1054   output_vbr(MST.num_types());
1055
1056   // Write each of the types
1057   for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1058        TE = MST.type_end(); TI != TE; ++TI ) {
1059     // Symtab entry:[def slot #][name]
1060     output_typeid((unsigned)Table.getSlot(TI->second));
1061     output(TI->first); 
1062   }
1063
1064   // Now do each of the type planes in order.
1065   for (SymbolTable::plane_const_iterator PI = MST.plane_begin(), 
1066        PE = MST.plane_end(); PI != PE;  ++PI) {
1067     SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1068     SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1069     int Slot;
1070     
1071     if (I == End) continue;  // Don't mess with an absent type...
1072
1073     // Write the number of values in this plane
1074     output_vbr((unsigned)PI->second.size());
1075
1076     // Write the slot number of the type for this plane
1077     Slot = Table.getSlot(PI->first);
1078     assert(Slot != -1 && "Type in symtab, but not in table!");
1079     output_typeid((unsigned)Slot);
1080
1081     // Write each of the values in this plane
1082     for (; I != End; ++I) {
1083       // Symtab entry: [def slot #][name]
1084       Slot = Table.getSlot(I->second);
1085       assert(Slot != -1 && "Value in symtab but has no slot number!!");
1086       output_vbr((unsigned)Slot);
1087       output(I->first);
1088     }
1089   }
1090 }
1091
1092 void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1093                                bool compress ) {
1094   assert(M && "You can't write a null module!!");
1095
1096   // Create a vector of unsigned char for the bytecode output. We
1097   // reserve 256KBytes of space in the vector so that we avoid doing
1098   // lots of little allocations. 256KBytes is sufficient for a large
1099   // proportion of the bytecode files we will encounter. Larger files
1100   // will be automatically doubled in size as needed (std::vector
1101   // behavior).
1102   std::vector<unsigned char> Buffer;
1103   Buffer.reserve(256 * 1024);
1104
1105   // The BytecodeWriter 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   // Determine start and end points of the Buffer
1112   const unsigned char *FirstByte = &Buffer.front();
1113
1114   // If we're supposed to compress this mess ...
1115   if (compress) {
1116
1117     // We signal compression by using an alternate magic number for the
1118     // file. The compressed bytecode file's magic number is "llvc" instead
1119     // of "llvm". 
1120     char compressed_magic[4];
1121     compressed_magic[0] = 'l';
1122     compressed_magic[1] = 'l';
1123     compressed_magic[2] = 'v';
1124     compressed_magic[3] = 'c';
1125
1126     Out.write(compressed_magic,4);
1127
1128     // Compress everything after the magic number (which we altered)
1129     uint64_t zipSize = Compressor::compressToStream(
1130       (char*)(FirstByte+4),        // Skip the magic number
1131       Buffer.size()-4,             // Skip the magic number
1132       Out                          // Where to write compressed data
1133     );
1134
1135   } else {
1136
1137     // We're not compressing, so just write the entire block.
1138     Out.write((char*)FirstByte, Buffer.size());
1139   }
1140
1141   // make sure it hits disk now
1142   Out.flush();
1143 }
1144
1145 // vim: sw=2 ai