16a291a24f6e32de6b5e4b79ee9d1ddeae6f3e61
[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 #define DEBUG_TYPE "bcwriter"
21 #include "WriterInternals.h"
22 #include "llvm/Bytecode/WriteBytecodePass.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/ParameterAttributes.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Module.h"
30 #include "llvm/TypeSymbolTable.h"
31 #include "llvm/ValueSymbolTable.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/Compressor.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Streams.h"
36 #include "llvm/System/Program.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/Statistic.h"
40 #include <cstring>
41 #include <algorithm>
42 using namespace llvm;
43
44 /// This value needs to be incremented every time the bytecode format changes
45 /// so that the reader can distinguish which format of the bytecode file has
46 /// been written.
47 /// @brief The bytecode version number
48 const unsigned BCVersionNum = 7;
49
50 const char WriteBytecodePass::ID = 0;
51 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
52
53 STATISTIC(BytesWritten, "Number of bytecode bytes written");
54
55 //===----------------------------------------------------------------------===//
56 //===                           Output Primitives                          ===//
57 //===----------------------------------------------------------------------===//
58
59 // output - If a position is specified, it must be in the valid portion of the
60 // string... note that this should be inlined always so only the relevant IF
61 // body should be included.
62 inline void BytecodeWriter::output(unsigned i, int pos) {
63   if (pos == -1) { // Be endian clean, little endian is our friend
64     Out.push_back((unsigned char)i);
65     Out.push_back((unsigned char)(i >> 8));
66     Out.push_back((unsigned char)(i >> 16));
67     Out.push_back((unsigned char)(i >> 24));
68   } else {
69     Out[pos  ] = (unsigned char)i;
70     Out[pos+1] = (unsigned char)(i >> 8);
71     Out[pos+2] = (unsigned char)(i >> 16);
72     Out[pos+3] = (unsigned char)(i >> 24);
73   }
74 }
75
76 inline void BytecodeWriter::output(int32_t i) {
77   output((uint32_t)i);
78 }
79
80 /// output_vbr - Output an unsigned value, by using the least number of bytes
81 /// possible.  This is useful because many of our "infinite" values are really
82 /// very small most of the time; but can be large a few times.
83 /// Data format used:  If you read a byte with the high bit set, use the low
84 /// seven bits as data and then read another byte.
85 inline void BytecodeWriter::output_vbr(uint64_t i) {
86   while (1) {
87     if (i < 0x80) { // done?
88       Out.push_back((unsigned char)i);   // We know the high bit is clear...
89       return;
90     }
91
92     // Nope, we are bigger than a character, output the next 7 bits and set the
93     // high bit to say that there is more coming...
94     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
95     i >>= 7;  // Shift out 7 bits now...
96   }
97 }
98
99 inline void BytecodeWriter::output_vbr(uint32_t i) {
100   while (1) {
101     if (i < 0x80) { // done?
102       Out.push_back((unsigned char)i);   // We know the high bit is clear...
103       return;
104     }
105
106     // Nope, we are bigger than a character, output the next 7 bits and set the
107     // high bit to say that there is more coming...
108     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
109     i >>= 7;  // Shift out 7 bits now...
110   }
111 }
112
113 inline void BytecodeWriter::output_typeid(unsigned i) {
114   if (i <= 0x00FFFFFF)
115     this->output_vbr(i);
116   else {
117     this->output_vbr(0x00FFFFFF);
118     this->output_vbr(i);
119   }
120 }
121
122 inline void BytecodeWriter::output_vbr(int64_t i) {
123   if (i < 0)
124     output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
125   else
126     output_vbr((uint64_t)i << 1);          // Low order bit is clear.
127 }
128
129
130 inline void BytecodeWriter::output_vbr(int i) {
131   if (i < 0)
132     output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
133   else
134     output_vbr((unsigned)i << 1);          // Low order bit is clear.
135 }
136
137 inline void BytecodeWriter::output_str(const char *Str, unsigned Len) {
138   output_vbr(Len);             // Strings may have an arbitrary length.
139   Out.insert(Out.end(), Str, Str+Len);
140 }
141
142 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
143   Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
144 }
145
146 inline void BytecodeWriter::output_float(float& FloatVal) {
147   /// FIXME: This isn't optimal, it has size problems on some platforms
148   /// where FP is not IEEE.
149   uint32_t i = FloatToBits(FloatVal);
150   Out.push_back( static_cast<unsigned char>( (i      ) & 0xFF));
151   Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
152   Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
153   Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
154 }
155
156 inline void BytecodeWriter::output_double(double& DoubleVal) {
157   /// FIXME: This isn't optimal, it has size problems on some platforms
158   /// where FP is not IEEE.
159   uint64_t i = DoubleToBits(DoubleVal);
160   Out.push_back( static_cast<unsigned char>( (i      ) & 0xFF));
161   Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
162   Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
163   Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
164   Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
165   Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
166   Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
167   Out.push_back( static_cast<unsigned char>( (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::outputParamAttrsList(const ParamAttrsList *Attrs) {
203   if (!Attrs) {
204     output_vbr(unsigned(0));
205     return;
206   }
207   unsigned numAttrs = Attrs->size();
208   output_vbr(numAttrs);
209   for (unsigned i = 0; i < numAttrs; ++i) {
210     uint16_t index = Attrs->getParamIndex(i);
211     uint16_t attrs = Attrs->getParamAttrs(index);
212     output_vbr(uint32_t(index));
213     output_vbr(uint32_t(attrs));
214   }
215 }
216
217 void BytecodeWriter::outputType(const Type *T) {
218   const StructType* STy = dyn_cast<StructType>(T);
219   if(STy && STy->isPacked())
220     output_vbr((unsigned)Type::PackedStructTyID);
221   else
222     output_vbr((unsigned)T->getTypeID());
223
224   // That's all there is to handling primitive types...
225   if (T->isPrimitiveType())
226     return;     // We might do this if we alias a prim type: %x = type int
227
228   switch (T->getTypeID()) {   // Handle derived types now.
229   case Type::IntegerTyID:
230     output_vbr(cast<IntegerType>(T)->getBitWidth());
231     break;
232   case Type::FunctionTyID: {
233     const FunctionType *FT = cast<FunctionType>(T);
234     output_typeid(Table.getTypeSlot(FT->getReturnType()));
235
236     // Output the number of arguments to function (+1 if varargs):
237     output_vbr((unsigned)FT->getNumParams()+FT->isVarArg());
238
239     // Output all of the arguments...
240     FunctionType::param_iterator I = FT->param_begin();
241     for (; I != FT->param_end(); ++I)
242       output_typeid(Table.getTypeSlot(*I));
243
244     // Terminate list with VoidTy if we are a varargs function...
245     if (FT->isVarArg())
246       output_typeid((unsigned)Type::VoidTyID);
247
248     // Put out all the parameter attributes
249     outputParamAttrsList(FT->getParamAttrs());
250     break;
251   }
252
253   case Type::ArrayTyID: {
254     const ArrayType *AT = cast<ArrayType>(T);
255     output_typeid(Table.getTypeSlot(AT->getElementType()));
256     output_vbr(AT->getNumElements());
257     break;
258   }
259
260  case Type::VectorTyID: {
261     const VectorType *PT = cast<VectorType>(T);
262     output_typeid(Table.getTypeSlot(PT->getElementType()));
263     output_vbr(PT->getNumElements());
264     break;
265   }
266
267   case Type::StructTyID: {
268     const StructType *ST = cast<StructType>(T);
269     // Output all of the element types...
270     for (StructType::element_iterator I = ST->element_begin(),
271            E = ST->element_end(); I != E; ++I) {
272       output_typeid(Table.getTypeSlot(*I));
273     }
274
275     // Terminate list with VoidTy
276     output_typeid((unsigned)Type::VoidTyID);
277     break;
278   }
279
280   case Type::PointerTyID:
281     output_typeid(Table.getTypeSlot(cast<PointerType>(T)->getElementType()));
282     break;
283
284   case Type::OpaqueTyID:
285     // No need to emit anything, just the count of opaque types is enough.
286     break;
287
288   default:
289     cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
290          << " Type '" << T->getDescription() << "'\n";
291     break;
292   }
293 }
294
295 void BytecodeWriter::outputConstant(const Constant *CPV) {
296   assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
297           !CPV->isNullValue()) && "Shouldn't output null constants!");
298
299   // We must check for a ConstantExpr before switching by type because
300   // a ConstantExpr can be of any type, and has no explicit value.
301   //
302   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
303     // FIXME: Encoding of constant exprs could be much more compact!
304     assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
305     assert(CE->getNumOperands() != 1 || CE->isCast());
306     output_vbr(1+CE->getNumOperands());   // flags as an expr
307     output_vbr(CE->getOpcode());          // Put out the CE op code
308
309     for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
310       output_vbr(Table.getSlot(*OI));
311       output_typeid(Table.getTypeSlot((*OI)->getType()));
312     }
313     if (CE->isCompare())
314       output_vbr((unsigned)CE->getPredicate());
315     return;
316   } else if (isa<UndefValue>(CPV)) {
317     output_vbr(1U);       // 1 -> UndefValue constant.
318     return;
319   } else {
320     output_vbr(0U);       // flag as not a ConstantExpr (i.e. 0 operands)
321   }
322
323   switch (CPV->getType()->getTypeID()) {
324   case Type::IntegerTyID: { // Integer types...
325     const ConstantInt *CI = cast<ConstantInt>(CPV);
326     unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
327     if (NumBits <= 32)
328       output_vbr(uint32_t(CI->getZExtValue()));
329     else if (NumBits <= 64)
330       output_vbr(uint64_t(CI->getZExtValue()));
331     else {
332       // We have an arbitrary precision integer value to write whose 
333       // bit width is > 64. However, in canonical unsigned integer 
334       // format it is likely that the high bits are going to be zero.
335       // So, we only write the number of active words. 
336       uint32_t activeWords = CI->getValue().getActiveWords();
337       const uint64_t *rawData = CI->getValue().getRawData();
338       output_vbr(activeWords);
339       for (uint32_t i = 0; i < activeWords; ++i)
340         output_vbr(rawData[i]);
341     }
342     break;
343   }
344
345   case Type::ArrayTyID: {
346     const ConstantArray *CPA = cast<ConstantArray>(CPV);
347     assert(!CPA->isString() && "Constant strings should be handled specially!");
348
349     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
350       output_vbr(Table.getSlot(CPA->getOperand(i)));
351     break;
352   }
353
354   case Type::VectorTyID: {
355     const ConstantVector *CP = cast<ConstantVector>(CPV);
356     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
357       output_vbr(Table.getSlot(CP->getOperand(i)));
358     break;
359   }
360
361   case Type::StructTyID: {
362     const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
363
364     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
365       output_vbr(Table.getSlot(CPS->getOperand(i)));
366     break;
367   }
368
369   case Type::PointerTyID:
370     assert(0 && "No non-null, non-constant-expr constants allowed!");
371     abort();
372
373   case Type::FloatTyID: {   // Floating point types...
374     float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
375     output_float(Tmp);
376     break;
377   }
378   case Type::DoubleTyID: {
379     double Tmp = cast<ConstantFP>(CPV)->getValue();
380     output_double(Tmp);
381     break;
382   }
383
384   case Type::VoidTyID:
385   case Type::LabelTyID:
386   default:
387     cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
388          << " type '" << *CPV->getType() << "'\n";
389     break;
390   }
391   return;
392 }
393
394 /// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
395 /// be shared by multiple uses.
396 void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
397   // Output a marker, so we know when we have one one parsing the constant pool.
398   // Note that this encoding is 5 bytes: not very efficient for a marker.  Since
399   // unique inline asms are rare, this should hardly matter.
400   output_vbr(~0U);
401   
402   output(IA->getAsmString());
403   output(IA->getConstraintString());
404   output_vbr(unsigned(IA->hasSideEffects()));
405 }
406
407 void BytecodeWriter::outputConstantStrings() {
408   SlotCalculator::string_iterator I = Table.string_begin();
409   SlotCalculator::string_iterator E = Table.string_end();
410   if (I == E) return;  // No strings to emit
411
412   // If we have != 0 strings to emit, output them now.  Strings are emitted into
413   // the 'void' type plane.
414   output_vbr(unsigned(E-I));
415   output_typeid(Type::VoidTyID);
416
417   // Emit all of the strings.
418   for (I = Table.string_begin(); I != E; ++I) {
419     const ConstantArray *Str = *I;
420     output_typeid(Table.getTypeSlot(Str->getType()));
421
422     // Now that we emitted the type (which indicates the size of the string),
423     // emit all of the characters.
424     std::string Val = Str->getAsString();
425     output_data(Val.c_str(), Val.c_str()+Val.size());
426   }
427 }
428
429 //===----------------------------------------------------------------------===//
430 //===                           Instruction Output                         ===//
431 //===----------------------------------------------------------------------===//
432
433 // outputInstructionFormat0 - Output those weird instructions that have a large
434 // number of operands or have large operands themselves.
435 //
436 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
437 //
438 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
439                                               unsigned Opcode,
440                                               const SlotCalculator &Table,
441                                               unsigned Type) {
442   // Opcode must have top two bits clear...
443   output_vbr(Opcode << 2);                  // Instruction Opcode ID
444   output_typeid(Type);                      // Result type
445
446   unsigned NumArgs = I->getNumOperands();
447   bool HasExtraArg = false;
448   if (isa<CastInst>(I)  || isa<InvokeInst>(I) || 
449       isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58 || 
450       Opcode == 62 || Opcode == 63)
451     HasExtraArg = true;
452   if (const AllocationInst *AI = dyn_cast<AllocationInst>(I))
453     HasExtraArg = AI->getAlignment() != 0;
454   
455   output_vbr(NumArgs + HasExtraArg);
456
457   if (!isa<GetElementPtrInst>(&I)) {
458     for (unsigned i = 0; i < NumArgs; ++i)
459       output_vbr(Table.getSlot(I->getOperand(i)));
460
461     if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
462       output_typeid(Table.getTypeSlot(I->getType()));
463     } else if (isa<CmpInst>(I)) {
464       output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
465     } else if (isa<InvokeInst>(I)) {  
466       output_vbr(cast<InvokeInst>(I)->getCallingConv());
467     } else if (Opcode == 58) {  // Call escape sequence
468       output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
469                  unsigned(cast<CallInst>(I)->isTailCall()));
470     } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(I)) {
471       if (AI->getAlignment())
472         output_vbr((unsigned)Log2_32(AI->getAlignment())+1);
473     } else if (Opcode == 62) { // Attributed load
474       output_vbr((unsigned)(((Log2_32(cast<LoadInst>(I)->getAlignment())+1)<<1)
475                             + (cast<LoadInst>(I)->isVolatile() ? 1 : 0)));
476     } else if (Opcode == 63) { // Attributed store
477       output_vbr((unsigned)(((Log2_32(cast<StoreInst>(I)->getAlignment())+1)<<1)
478                             + (cast<StoreInst>(I)->isVolatile() ? 1 : 0)));
479     }
480   } else {
481     output_vbr(Table.getSlot(I->getOperand(0)));
482
483     // We need to encode the type of sequential type indices into their slot #
484     unsigned Idx = 1;
485     for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
486          Idx != NumArgs; ++TI, ++Idx) {
487       unsigned Slot = Table.getSlot(I->getOperand(Idx));
488
489       if (isa<SequentialType>(*TI)) {
490         // These should be either 32-bits or 64-bits, however, with bit
491         // accurate types we just distinguish between less than or equal to
492         // 32-bits or greater than 32-bits.
493         unsigned BitWidth = 
494           cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
495         assert(BitWidth == 32 || BitWidth == 64 && 
496                "Invalid bitwidth for GEP index");
497         unsigned IdxId = BitWidth == 32 ? 0 : 1;
498         Slot = (Slot << 1) | IdxId;
499       }
500       output_vbr(Slot);
501     }
502   }
503 }
504
505
506 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
507 // This are more annoying than most because the signature of the call does not
508 // tell us anything about the types of the arguments in the varargs portion.
509 // Because of this, we encode (as type 0) all of the argument types explicitly
510 // before the argument value.  This really sucks, but you shouldn't be using
511 // varargs functions in your code! *death to printf*!
512 //
513 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
514 //
515 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
516                                             unsigned Opcode,
517                                             const SlotCalculator &Table,
518                                             unsigned Type) {
519   assert(isa<CallInst>(I) || isa<InvokeInst>(I));
520   // Opcode must have top two bits clear...
521   output_vbr(Opcode << 2);                  // Instruction Opcode ID
522   output_typeid(Type);                      // Result type (varargs type)
523
524   const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
525   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
526   unsigned NumParams = FTy->getNumParams();
527
528   unsigned NumFixedOperands;
529   if (isa<CallInst>(I)) {
530     // Output an operand for the callee and each fixed argument, then two for
531     // each variable argument.
532     NumFixedOperands = 1+NumParams;
533   } else {
534     assert(isa<InvokeInst>(I) && "Not call or invoke??");
535     // Output an operand for the callee and destinations, then two for each
536     // variable argument.
537     NumFixedOperands = 3+NumParams;
538   }
539   output_vbr(2 * I->getNumOperands()-NumFixedOperands + 
540       unsigned(Opcode == 58 || isa<InvokeInst>(I)));
541
542   // The type for the function has already been emitted in the type field of the
543   // instruction.  Just emit the slot # now.
544   for (unsigned i = 0; i != NumFixedOperands; ++i)
545     output_vbr(Table.getSlot(I->getOperand(i)));
546
547   for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
548     // Output Arg Type ID
549     output_typeid(Table.getTypeSlot(I->getOperand(i)->getType()));
550
551     // Output arg ID itself
552     output_vbr(Table.getSlot(I->getOperand(i)));
553   }
554   
555   if (isa<InvokeInst>(I)) {
556     // Emit the tail call/calling conv for invoke instructions
557     output_vbr(cast<InvokeInst>(I)->getCallingConv());
558   } else if (Opcode == 58) {
559     const CallInst *CI = cast<CallInst>(I);
560     output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
561   }
562 }
563
564
565 // outputInstructionFormat1 - Output one operand instructions, knowing that no
566 // operand index is >= 2^12.
567 //
568 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
569                                                      unsigned Opcode,
570                                                      unsigned *Slots,
571                                                      unsigned Type) {
572   // bits   Instruction format:
573   // --------------------------
574   // 01-00: Opcode type, fixed to 1.
575   // 07-02: Opcode
576   // 19-08: Resulting type plane
577   // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
578   //
579   output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
580 }
581
582
583 // outputInstructionFormat2 - Output two operand instructions, knowing that no
584 // operand index is >= 2^8.
585 //
586 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
587                                                      unsigned Opcode,
588                                                      unsigned *Slots,
589                                                      unsigned Type) {
590   // bits   Instruction format:
591   // --------------------------
592   // 01-00: Opcode type, fixed to 2.
593   // 07-02: Opcode
594   // 15-08: Resulting type plane
595   // 23-16: Operand #1
596   // 31-24: Operand #2
597   //
598   output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
599 }
600
601
602 // outputInstructionFormat3 - Output three operand instructions, knowing that no
603 // operand index is >= 2^6.
604 //
605 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
606                                                      unsigned Opcode,
607                                                      unsigned *Slots,
608                                                      unsigned Type) {
609   // bits   Instruction format:
610   // --------------------------
611   // 01-00: Opcode type, fixed to 3.
612   // 07-02: Opcode
613   // 13-08: Resulting type plane
614   // 19-14: Operand #1
615   // 25-20: Operand #2
616   // 31-26: Operand #3
617   //
618   output(3 | (Opcode << 2) | (Type << 8) |
619           (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
620 }
621
622 void BytecodeWriter::outputInstruction(const Instruction &I) {
623   assert(I.getOpcode() < 57 && "Opcode too big???");
624   unsigned Opcode = I.getOpcode();
625   unsigned NumOperands = I.getNumOperands();
626
627   // Encode 'tail call' as 61
628   // 63.
629   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
630     if (CI->getCallingConv() == CallingConv::C) {
631       if (CI->isTailCall())
632         Opcode = 61;   // CCC + Tail Call
633       else
634         ;     // Opcode = Instruction::Call
635     } else if (CI->getCallingConv() == CallingConv::Fast) {
636       if (CI->isTailCall())
637         Opcode = 59;    // FastCC + TailCall
638       else
639         Opcode = 60;    // FastCC + Not Tail Call
640     } else {
641       Opcode = 58;      // Call escape sequence.
642     }
643   }
644
645   // Figure out which type to encode with the instruction.  Typically we want
646   // the type of the first parameter, as opposed to the type of the instruction
647   // (for example, with setcc, we always know it returns bool, but the type of
648   // the first param is actually interesting).  But if we have no arguments
649   // we take the type of the instruction itself.
650   //
651   const Type *Ty;
652   switch (I.getOpcode()) {
653   case Instruction::Select:
654   case Instruction::Malloc:
655   case Instruction::Alloca:
656     Ty = I.getType();  // These ALWAYS want to encode the return type
657     break;
658   case Instruction::Store:
659     Ty = I.getOperand(1)->getType();  // Encode the pointer type...
660     assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
661     break;
662   default:              // Otherwise use the default behavior...
663     Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
664     break;
665   }
666
667   unsigned Type = Table.getTypeSlot(Ty);
668
669   // Varargs calls and invokes are encoded entirely different from any other
670   // instructions.
671   if (const CallInst *CI = dyn_cast<CallInst>(&I)){
672     const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
673     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
674       outputInstrVarArgsCall(CI, Opcode, Table, Type);
675       return;
676     }
677   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
678     const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
679     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
680       outputInstrVarArgsCall(II, Opcode, Table, Type);
681       return;
682     }
683   }
684
685   if (NumOperands <= 3) {
686     // Make sure that we take the type number into consideration.  We don't want
687     // to overflow the field size for the instruction format we select.
688     //
689     unsigned MaxOpSlot = Type;
690     unsigned Slots[3]; Slots[0] = (1 << 12)-1;   // Marker to signify 0 operands
691
692     for (unsigned i = 0; i != NumOperands; ++i) {
693       unsigned Slot = Table.getSlot(I.getOperand(i));
694       if (Slot > MaxOpSlot) MaxOpSlot = Slot;
695       Slots[i] = Slot;
696     }
697
698     // Handle the special cases for various instructions...
699     if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
700       // Cast has to encode the destination type as the second argument in the
701       // packet, or else we won't know what type to cast to!
702       Slots[1] = Table.getTypeSlot(I.getType());
703       if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
704       NumOperands++;
705     } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
706       assert(NumOperands == 1 && "Bogus allocation!");
707       if (AI->getAlignment()) {
708         Slots[1] = Log2_32(AI->getAlignment())+1;
709         if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
710         NumOperands = 2;
711       }
712     } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
713       // We need to encode the compare instruction's predicate as the third
714       // operand. Its not really a slot, but we don't want to break the 
715       // instruction format for these instructions.
716       NumOperands++;
717       assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
718       Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
719       if (Slots[2] > MaxOpSlot)
720         MaxOpSlot = Slots[2];
721     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
722       // We need to encode the type of sequential type indices into their slot #
723       unsigned Idx = 1;
724       for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
725            I != E; ++I, ++Idx)
726         if (isa<SequentialType>(*I)) {
727           // These should be either 32-bits or 64-bits, however, with bit
728           // accurate types we just distinguish between less than or equal to
729           // 32-bits or greater than 32-bits.
730           unsigned BitWidth = 
731             cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
732           assert(BitWidth == 32 || BitWidth == 64 && 
733                  "Invalid bitwidth for GEP index");
734           unsigned IdxId = BitWidth == 32 ? 0 : 1;
735           Slots[Idx] = (Slots[Idx] << 1) | IdxId;
736           if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
737         }
738     } else if (Opcode == 58) {
739       // If this is the escape sequence for call, emit the tailcall/cc info.
740       const CallInst &CI = cast<CallInst>(I);
741       ++NumOperands;
742       if (NumOperands <= 3) {
743         Slots[NumOperands-1] =
744           (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
745         if (Slots[NumOperands-1] > MaxOpSlot)
746           MaxOpSlot = Slots[NumOperands-1];
747       }
748     } else if (isa<InvokeInst>(I)) {
749       // Invoke escape seq has at least 4 operands to encode.
750       ++NumOperands;
751     } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
752       // Encode attributed load as opcode 62
753       // We need to encode the attributes of the load instruction as the second
754       // operand. Its not really a slot, but we don't want to break the 
755       // instruction format for these instructions.
756       if (LI->getAlignment() || LI->isVolatile()) {
757         NumOperands = 2;
758         Slots[1] = ((Log2_32(LI->getAlignment())+1)<<1) + 
759                     (LI->isVolatile() ? 1 : 0);
760         if (Slots[1] > MaxOpSlot) 
761           MaxOpSlot = Slots[1];
762         Opcode = 62;
763       }
764     } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
765       // Encode attributed store as opcode 63
766       // We need to encode the attributes of the store instruction as the third
767       // operand. Its not really a slot, but we don't want to break the 
768       // instruction format for these instructions.
769       if (SI->getAlignment() || SI->isVolatile()) {
770         NumOperands = 3;
771         Slots[2] = ((Log2_32(SI->getAlignment())+1)<<1) + 
772                     (SI->isVolatile() ? 1 : 0);
773         if (Slots[2] > MaxOpSlot) 
774           MaxOpSlot = Slots[2];
775         Opcode = 63;
776       }
777     }
778
779     // Decide which instruction encoding to use.  This is determined primarily
780     // by the number of operands, and secondarily by whether or not the max
781     // operand will fit into the instruction encoding.  More operands == fewer
782     // bits per operand.
783     //
784     switch (NumOperands) {
785     case 0:
786     case 1:
787       if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
788         outputInstructionFormat1(&I, Opcode, Slots, Type);
789         return;
790       }
791       break;
792
793     case 2:
794       if (MaxOpSlot < (1 << 8)) {
795         outputInstructionFormat2(&I, Opcode, Slots, Type);
796         return;
797       }
798       break;
799
800     case 3:
801       if (MaxOpSlot < (1 << 6)) {
802         outputInstructionFormat3(&I, Opcode, Slots, Type);
803         return;
804       }
805       break;
806     default:
807       break;
808     }
809   }
810
811   // If we weren't handled before here, we either have a large number of
812   // operands or a large operand index that we are referring to.
813   outputInstructionFormat0(&I, Opcode, Table, Type);
814 }
815
816 //===----------------------------------------------------------------------===//
817 //===                              Block Output                            ===//
818 //===----------------------------------------------------------------------===//
819
820 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
821   : Out(o), Table(M) {
822
823   // Emit the signature...
824   static const unsigned char *Sig = (const unsigned char*)"llvm";
825   output_data(Sig, Sig+4);
826
827   // Emit the top level CLASS block.
828   BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
829
830   // Output the version identifier
831   output_vbr(BCVersionNum);
832
833   // The Global type plane comes first
834   {
835     BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
836     outputTypes(Type::FirstDerivedTyID);
837   }
838
839   // The ModuleInfoBlock follows directly after the type information
840   outputModuleInfoBlock(M);
841
842   // Output module level constants, used for global variable initializers
843   outputConstants();
844
845   // Do the whole module now! Process each function at a time...
846   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
847     outputFunction(I);
848
849   // Output the symbole table for types
850   outputTypeSymbolTable(M->getTypeSymbolTable());
851
852   // Output the symbol table for values
853   outputValueSymbolTable(M->getValueSymbolTable());
854 }
855
856 void BytecodeWriter::outputTypes(unsigned TypeNum) {
857   // Write the type plane for types first because earlier planes (e.g. for a
858   // primitive type like float) may have constants constructed using types
859   // coming later (e.g., via getelementptr from a pointer type).  The type
860   // plane is needed before types can be fwd or bkwd referenced.
861   const std::vector<const Type*>& Types = Table.getTypes();
862   assert(!Types.empty() && "No types at all?");
863   assert(TypeNum <= Types.size() && "Invalid TypeNo index");
864
865   unsigned NumEntries = Types.size() - TypeNum;
866
867   // Output type header: [num entries]
868   output_vbr(NumEntries);
869
870   for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
871     outputType(Types[i]);
872 }
873
874 // Helper function for outputConstants().
875 // Writes out all the constants in the plane Plane starting at entry StartNo.
876 //
877 void BytecodeWriter::outputConstantsInPlane(const Value *const *Plane,
878                                             unsigned PlaneSize,
879                                             unsigned StartNo) {
880   unsigned ValNo = StartNo;
881
882   // Scan through and ignore function arguments, global values, and constant
883   // strings.
884   for (; ValNo < PlaneSize &&
885          (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
886           (isa<ConstantArray>(Plane[ValNo]) &&
887            cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
888     /*empty*/;
889
890   unsigned NC = ValNo;              // Number of constants
891   for (; NC < PlaneSize && (isa<Constant>(Plane[NC]) || 
892                               isa<InlineAsm>(Plane[NC])); NC++)
893     /*empty*/;
894   NC -= ValNo;                      // Convert from index into count
895   if (NC == 0) return;              // Skip empty type planes...
896
897   // FIXME: Most slabs only have 1 or 2 entries!  We should encode this much
898   // more compactly.
899
900   // Put out type header: [num entries][type id number]
901   //
902   output_vbr(NC);
903
904   // Put out the Type ID Number.
905   output_typeid(Table.getTypeSlot(Plane[0]->getType()));
906
907   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
908     const Value *V = Plane[i];
909     if (const Constant *C = dyn_cast<Constant>(V))
910       outputConstant(C);
911     else
912       outputInlineAsm(cast<InlineAsm>(V));
913   }
914 }
915
916 static inline bool hasNullValue(const Type *Ty) {
917   return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
918 }
919
920 void BytecodeWriter::outputConstants() {
921   BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
922                       true  /* Elide block if empty */);
923
924   unsigned NumPlanes = Table.getNumPlanes();
925
926   // Output module-level string constants before any other constants.
927   outputConstantStrings();
928
929   for (unsigned pno = 0; pno != NumPlanes; pno++) {
930     const SlotCalculator::TypePlane &Plane = Table.getPlane(pno);
931     if (!Plane.empty()) {              // Skip empty type planes...
932       unsigned ValNo = 0;
933       if (hasNullValue(Plane[0]->getType())) {
934         // Skip zero initializer
935         ValNo = 1;
936       }
937
938       // Write out constants in the plane
939       outputConstantsInPlane(&Plane[0], Plane.size(), ValNo);
940     }
941   }
942 }
943
944 static unsigned getEncodedLinkage(const GlobalValue *GV) {
945   switch (GV->getLinkage()) {
946   default: assert(0 && "Invalid linkage!");
947   case GlobalValue::ExternalLinkage:     return 0;
948   case GlobalValue::WeakLinkage:         return 1;
949   case GlobalValue::AppendingLinkage:    return 2;
950   case GlobalValue::InternalLinkage:     return 3;
951   case GlobalValue::LinkOnceLinkage:     return 4;
952   case GlobalValue::DLLImportLinkage:    return 5;
953   case GlobalValue::DLLExportLinkage:    return 6;
954   case GlobalValue::ExternalWeakLinkage: return 7;
955   }
956 }
957
958 static unsigned getEncodedVisibility(const GlobalValue *GV) {
959   switch (GV->getVisibility()) {
960   default: assert(0 && "Invalid visibility!");
961   case GlobalValue::DefaultVisibility:   return 0;
962   case GlobalValue::HiddenVisibility:    return 1;
963   case GlobalValue::ProtectedVisibility: return 2;
964   }
965 }
966
967 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
968   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
969
970   // Give numbers to sections as we encounter them.
971   unsigned SectionIDCounter = 0;
972   std::vector<std::string> SectionNames;
973   std::map<std::string, unsigned> SectionID;
974   
975   // Output the types for the global variables in the module...
976   for (Module::const_global_iterator I = M->global_begin(),
977          End = M->global_end(); I != End; ++I) {
978     unsigned Slot = Table.getTypeSlot(I->getType());
979
980     assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
981            "Global must have an initializer or have external linkage!");
982     
983     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
984     // bit5 = isThreadLocal, bit6+ = Slot # for type.
985     bool HasExtensionWord = (I->getAlignment() != 0) ||
986                             I->hasSection() ||
987       (I->getVisibility() != GlobalValue::DefaultVisibility);
988     
989     // If we need to use the extension byte, set linkage=3(internal) and
990     // initializer = 0 (impossible!).
991     if (!HasExtensionWord) {
992       unsigned oSlot = (Slot << 6)| (((unsigned)I->isThreadLocal()) << 5) |
993                        (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1)
994                        | (unsigned)I->isConstant();
995       output_vbr(oSlot);
996     } else {  
997       unsigned oSlot = (Slot << 6) | (((unsigned)I->isThreadLocal()) << 5) |
998                        (3 << 2) | (0 << 1) | (unsigned)I->isConstant();
999       output_vbr(oSlot);
1000       
1001       // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1002       // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
1003       // bits 10-12 = visibility, bits 13+ = future use.
1004       unsigned ExtWord = (unsigned)I->hasInitializer() |
1005                          (getEncodedLinkage(I) << 1) |
1006                          ((Log2_32(I->getAlignment())+1) << 4) |
1007                          ((unsigned)I->hasSection() << 9) |
1008                          (getEncodedVisibility(I) << 10);
1009       output_vbr(ExtWord);
1010       if (I->hasSection()) {
1011         // Give section names unique ID's.
1012         unsigned &Entry = SectionID[I->getSection()];
1013         if (Entry == 0) {
1014           Entry = ++SectionIDCounter;
1015           SectionNames.push_back(I->getSection());
1016         }
1017         output_vbr(Entry);
1018       }
1019     }
1020
1021     // If we have an initializer, output it now.
1022     if (I->hasInitializer())
1023       output_vbr(Table.getSlot((Value*)I->getInitializer()));
1024   }
1025   output_typeid(Table.getTypeSlot(Type::VoidTy));
1026
1027   // Output the types of the functions in this module.
1028   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
1029     unsigned Slot = Table.getTypeSlot(I->getType());
1030     assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
1031     unsigned CC = I->getCallingConv()+1;
1032     unsigned ID = (Slot << 5) | (CC & 15);
1033
1034     if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
1035       ID |= 1 << 4;
1036     
1037     if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1038         (I->isDeclaration() && I->hasDLLImportLinkage()) ||
1039         (I->isDeclaration() && I->hasExternalWeakLinkage())
1040        )
1041       ID |= 1 << 31;       // Do we need an extension word?
1042     
1043     output_vbr(ID);
1044     
1045     if (ID & (1 << 31)) {
1046       // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
1047       // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1048       unsigned extLinkage = 0;
1049
1050       if (I->isDeclaration()) {
1051         if (I->hasDLLImportLinkage()) {
1052           extLinkage = 1;
1053         } else if (I->hasExternalWeakLinkage()) {
1054           extLinkage = 2;
1055         }
1056       }
1057
1058       ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) | 
1059         (I->hasSection() << 10) |
1060         ((extLinkage & 3) << 11);
1061       output_vbr(ID);
1062       
1063       // Give section names unique ID's.
1064       if (I->hasSection()) {
1065         unsigned &Entry = SectionID[I->getSection()];
1066         if (Entry == 0) {
1067           Entry = ++SectionIDCounter;
1068           SectionNames.push_back(I->getSection());
1069         }
1070         output_vbr(Entry);
1071       }
1072     }
1073   }
1074   output_vbr(Table.getTypeSlot(Type::VoidTy) << 5);
1075
1076   // Emit the list of dependent libraries for the Module.
1077   Module::lib_iterator LI = M->lib_begin();
1078   Module::lib_iterator LE = M->lib_end();
1079   output_vbr(unsigned(LE - LI));   // Emit the number of dependent libraries.
1080   for (; LI != LE; ++LI)
1081     output(*LI);
1082
1083   // Output the target triple from the module
1084   output(M->getTargetTriple());
1085
1086   // Output the data layout from the module
1087   output(M->getDataLayout());
1088   
1089   // Emit the table of section names.
1090   output_vbr((unsigned)SectionNames.size());
1091   for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1092     output(SectionNames[i]);
1093
1094   // Output the inline asm string.
1095   output(M->getModuleInlineAsm());
1096
1097   // Output aliases
1098   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1099        I != E; ++I) {
1100     unsigned TypeSlotNo    = Table.getTypeSlot(I->getType());
1101     unsigned AliaseeSlotNo = Table.getSlot(I->getAliasee());
1102     assert(((TypeSlotNo << 3) >> 3) == TypeSlotNo && "Slot # too big!");
1103     unsigned aliasLinkage = 0;
1104     unsigned isConstantAliasee = ((!isa<GlobalValue>(I->getAliasee())) << 2);
1105     switch (I->getLinkage()) {
1106      case GlobalValue::ExternalLinkage:
1107       aliasLinkage = 0;
1108       break;
1109      case GlobalValue::InternalLinkage:
1110       aliasLinkage = 1;
1111       break;
1112      case GlobalValue::WeakLinkage:
1113       aliasLinkage = 2;
1114       break;
1115      default:
1116       assert(0 && "Invalid alias linkage");
1117     }    
1118     output_vbr((TypeSlotNo << 3) | isConstantAliasee | aliasLinkage);
1119     output_vbr(AliaseeSlotNo);
1120   }
1121   output_typeid(Table.getTypeSlot(Type::VoidTy));
1122 }
1123
1124 void BytecodeWriter::outputInstructions(const Function *F) {
1125   BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1126   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1127     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1128       outputInstruction(*I);
1129 }
1130
1131 void BytecodeWriter::outputFunction(const Function *F) {
1132   // If this is an external function, there is nothing else to emit!
1133   if (F->isDeclaration()) return;
1134
1135   BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1136   unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1137   output_vbr(rWord);
1138
1139   // Get slot information about the function...
1140   Table.incorporateFunction(F);
1141
1142   // Output all of the instructions in the body of the function
1143   outputInstructions(F);
1144
1145   // If needed, output the symbol table for the function...
1146   outputValueSymbolTable(F->getValueSymbolTable());
1147
1148   Table.purgeFunction();
1149 }
1150
1151
1152 void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1153   // Do not output the block for an empty symbol table, it just wastes
1154   // space!
1155   if (TST.empty()) return;
1156
1157   // Create a header for the symbol table
1158   BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
1159                             true/*ElideIfEmpty*/);
1160   // Write the number of types
1161   output_vbr(TST.size());
1162
1163   // Write each of the types
1164   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
1165        TI != TE; ++TI) {
1166     // Symtab entry:[def slot #][name]
1167     output_typeid(Table.getTypeSlot(TI->second));
1168     output(TI->first);
1169   }
1170 }
1171
1172 void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
1173   // Do not output the Bytecode block for an empty symbol table, it just wastes
1174   // space!
1175   if (VST.empty()) return;
1176
1177   BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1178                             true/*ElideIfEmpty*/);
1179
1180   // Organize the symbol table by type
1181   typedef SmallVector<const ValueName*, 8> PlaneMapVector;
1182   typedef DenseMap<const Type*, PlaneMapVector> PlaneMap;
1183   PlaneMap Planes;
1184   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1185        SI != SE; ++SI) 
1186     Planes[SI->getValue()->getType()].push_back(&*SI);
1187
1188   for (PlaneMap::iterator PI = Planes.begin(), PE = Planes.end();
1189        PI != PE; ++PI) {
1190     PlaneMapVector::const_iterator I = PI->second.begin(); 
1191     PlaneMapVector::const_iterator End = PI->second.end(); 
1192
1193     if (I == End) continue;  // Don't mess with an absent type...
1194
1195     // Write the number of values in this plane
1196     output_vbr((unsigned)PI->second.size());
1197
1198     // Write the slot number of the type for this plane
1199     output_typeid(Table.getTypeSlot(PI->first));
1200
1201     // Write each of the values in this plane
1202     for (; I != End; ++I) {
1203       // Symtab entry: [def slot #][name]
1204       output_vbr(Table.getSlot((*I)->getValue()));
1205       output_str((*I)->getKeyData(), (*I)->getKeyLength());
1206     }
1207   }
1208 }
1209
1210 void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
1211                                bool compress) {
1212   assert(M && "You can't write a null module!!");
1213
1214   // Make sure that std::cout is put into binary mode for systems
1215   // that care.
1216   if (Out == cout)
1217     sys::Program::ChangeStdoutToBinary();
1218
1219   // Create a vector of unsigned char for the bytecode output. We
1220   // reserve 256KBytes of space in the vector so that we avoid doing
1221   // lots of little allocations. 256KBytes is sufficient for a large
1222   // proportion of the bytecode files we will encounter. Larger files
1223   // will be automatically doubled in size as needed (std::vector
1224   // behavior).
1225   std::vector<unsigned char> Buffer;
1226   Buffer.reserve(256 * 1024);
1227
1228   // The BytecodeWriter populates Buffer for us.
1229   BytecodeWriter BCW(Buffer, M);
1230
1231   // Keep track of how much we've written
1232   BytesWritten += Buffer.size();
1233
1234   // Determine start and end points of the Buffer
1235   const unsigned char *FirstByte = &Buffer.front();
1236
1237   // If we're supposed to compress this mess ...
1238   if (compress) {
1239
1240     // We signal compression by using an alternate magic number for the
1241     // file. The compressed bytecode file's magic number is "llvc" instead
1242     // of "llvm".
1243     char compressed_magic[4];
1244     compressed_magic[0] = 'l';
1245     compressed_magic[1] = 'l';
1246     compressed_magic[2] = 'v';
1247     compressed_magic[3] = 'c';
1248
1249     Out.stream()->write(compressed_magic,4);
1250
1251     // Compress everything after the magic number (which we altered)
1252     Compressor::compressToStream(
1253       (char*)(FirstByte+4),        // Skip the magic number
1254       Buffer.size()-4,             // Skip the magic number
1255       *Out.stream()                // Where to write compressed data
1256     );
1257
1258   } else {
1259
1260     // We're not compressing, so just write the entire block.
1261     Out.stream()->write((char*)FirstByte, Buffer.size());
1262   }
1263
1264   // make sure it hits disk now
1265   Out.stream()->flush();
1266 }