Add abbreviations to the TYPE_BLOCK for pointers, functions, structs and arrays.
[oota-llvm.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Bitcode writer implementation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ParameterAttributes.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/Support/MathExtras.h"
26 using namespace llvm;
27
28 /// These are manifest constants used by the bitcode writer. They do not need to
29 /// be kept in sync with the reader, but need to be consistent within this file.
30 enum {
31   CurVersion = 0,
32   
33   // VALUE_SYMTAB_BLOCK abbrev id's.
34   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
35   VST_ENTRY_7_ABBREV,
36   VST_ENTRY_6_ABBREV,
37   VST_BBENTRY_6_ABBREV
38 };
39
40
41 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
42   switch (Opcode) {
43   default: assert(0 && "Unknown cast instruction!");
44   case Instruction::Trunc   : return bitc::CAST_TRUNC;
45   case Instruction::ZExt    : return bitc::CAST_ZEXT;
46   case Instruction::SExt    : return bitc::CAST_SEXT;
47   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
48   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
49   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
50   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
51   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
52   case Instruction::FPExt   : return bitc::CAST_FPEXT;
53   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
54   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
55   case Instruction::BitCast : return bitc::CAST_BITCAST;
56   }
57 }
58
59 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
60   switch (Opcode) {
61   default: assert(0 && "Unknown binary instruction!");
62   case Instruction::Add:  return bitc::BINOP_ADD;
63   case Instruction::Sub:  return bitc::BINOP_SUB;
64   case Instruction::Mul:  return bitc::BINOP_MUL;
65   case Instruction::UDiv: return bitc::BINOP_UDIV;
66   case Instruction::FDiv:
67   case Instruction::SDiv: return bitc::BINOP_SDIV;
68   case Instruction::URem: return bitc::BINOP_UREM;
69   case Instruction::FRem:
70   case Instruction::SRem: return bitc::BINOP_SREM;
71   case Instruction::Shl:  return bitc::BINOP_SHL;
72   case Instruction::LShr: return bitc::BINOP_LSHR;
73   case Instruction::AShr: return bitc::BINOP_ASHR;
74   case Instruction::And:  return bitc::BINOP_AND;
75   case Instruction::Or:   return bitc::BINOP_OR;
76   case Instruction::Xor:  return bitc::BINOP_XOR;
77   }
78 }
79
80
81
82 static void WriteStringRecord(unsigned Code, const std::string &Str, 
83                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
84   SmallVector<unsigned, 64> Vals;
85   
86   // Code: [strchar x N]
87   for (unsigned i = 0, e = Str.size(); i != e; ++i)
88     Vals.push_back(Str[i]);
89     
90   // Emit the finished record.
91   Stream.EmitRecord(Code, Vals, AbbrevToUse);
92 }
93
94 // Emit information about parameter attributes.
95 static void WriteParamAttrTable(const ValueEnumerator &VE, 
96                                 BitstreamWriter &Stream) {
97   const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
98   if (Attrs.empty()) return;
99   
100   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
101
102   SmallVector<uint64_t, 64> Record;
103   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
104     const ParamAttrsList *A = Attrs[i];
105     for (unsigned op = 0, e = A->size(); op != e; ++op) {
106       Record.push_back(A->getParamIndex(op));
107       Record.push_back(A->getParamAttrsAtIndex(op));
108     }
109     
110     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
111     Record.clear();
112   }
113   
114   Stream.ExitBlock();
115 }
116
117 /// WriteTypeTable - Write out the type table for a module.
118 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
119   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
120   
121   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
122   SmallVector<uint64_t, 64> TypeVals;
123   
124   // Abbrev for TYPE_CODE_POINTER.
125   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
126   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
127   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
128                             Log2_32_Ceil(VE.getTypes().size()+1)));
129   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
130   
131   // Abbrev for TYPE_CODE_FUNCTION.
132   Abbv = new BitCodeAbbrev();
133   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
134   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
135   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
136                             Log2_32_Ceil(VE.getParamAttrs().size()+1)));
137   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
138   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
139                             Log2_32_Ceil(VE.getTypes().size()+1)));
140   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
141   
142   // Abbrev for TYPE_CODE_STRUCT.
143   Abbv = new BitCodeAbbrev();
144   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
145   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
146   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
147   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
148                             Log2_32_Ceil(VE.getTypes().size()+1)));
149   unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
150  
151   // Abbrev for TYPE_CODE_ARRAY.
152   Abbv = new BitCodeAbbrev();
153   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
154   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
155   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
156                             Log2_32_Ceil(VE.getTypes().size()+1)));
157   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
158   
159   // Emit an entry count so the reader can reserve space.
160   TypeVals.push_back(TypeList.size());
161   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
162   TypeVals.clear();
163   
164   // Loop over all of the types, emitting each in turn.
165   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
166     const Type *T = TypeList[i].first;
167     int AbbrevToUse = 0;
168     unsigned Code = 0;
169     
170     switch (T->getTypeID()) {
171     case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
172     default: assert(0 && "Unknown type!");
173     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
174     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
175     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
176     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
177     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
178     case Type::IntegerTyID:
179       // INTEGER: [width]
180       Code = bitc::TYPE_CODE_INTEGER;
181       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
182       break;
183     case Type::PointerTyID:
184       // POINTER: [pointee type]
185       Code = bitc::TYPE_CODE_POINTER;
186       TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
187       AbbrevToUse = PtrAbbrev;
188       break;
189
190     case Type::FunctionTyID: {
191       const FunctionType *FT = cast<FunctionType>(T);
192       // FUNCTION: [isvararg, attrid, retty, paramty x N]
193       Code = bitc::TYPE_CODE_FUNCTION;
194       TypeVals.push_back(FT->isVarArg());
195       TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs()));
196       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
197       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
198         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
199       AbbrevToUse = FunctionAbbrev;
200       break;
201     }
202     case Type::StructTyID: {
203       const StructType *ST = cast<StructType>(T);
204       // STRUCT: [ispacked, eltty x N]
205       Code = bitc::TYPE_CODE_STRUCT;
206       TypeVals.push_back(ST->isPacked());
207       // Output all of the element types.
208       for (StructType::element_iterator I = ST->element_begin(),
209            E = ST->element_end(); I != E; ++I)
210         TypeVals.push_back(VE.getTypeID(*I));
211       AbbrevToUse = StructAbbrev;
212       break;
213     }
214     case Type::ArrayTyID: {
215       const ArrayType *AT = cast<ArrayType>(T);
216       // ARRAY: [numelts, eltty]
217       Code = bitc::TYPE_CODE_ARRAY;
218       TypeVals.push_back(AT->getNumElements());
219       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
220       AbbrevToUse = ArrayAbbrev;
221       break;
222     }
223     case Type::VectorTyID: {
224       const VectorType *VT = cast<VectorType>(T);
225       // VECTOR [numelts, eltty]
226       Code = bitc::TYPE_CODE_VECTOR;
227       TypeVals.push_back(VT->getNumElements());
228       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
229       break;
230     }
231     }
232
233     // Emit the finished record.
234     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
235     TypeVals.clear();
236   }
237   
238   Stream.ExitBlock();
239 }
240
241 static unsigned getEncodedLinkage(const GlobalValue *GV) {
242   switch (GV->getLinkage()) {
243   default: assert(0 && "Invalid linkage!");
244   case GlobalValue::ExternalLinkage:     return 0;
245   case GlobalValue::WeakLinkage:         return 1;
246   case GlobalValue::AppendingLinkage:    return 2;
247   case GlobalValue::InternalLinkage:     return 3;
248   case GlobalValue::LinkOnceLinkage:     return 4;
249   case GlobalValue::DLLImportLinkage:    return 5;
250   case GlobalValue::DLLExportLinkage:    return 6;
251   case GlobalValue::ExternalWeakLinkage: return 7;
252   }
253 }
254
255 static unsigned getEncodedVisibility(const GlobalValue *GV) {
256   switch (GV->getVisibility()) {
257   default: assert(0 && "Invalid visibility!");
258   case GlobalValue::DefaultVisibility:   return 0;
259   case GlobalValue::HiddenVisibility:    return 1;
260   case GlobalValue::ProtectedVisibility: return 2;
261   }
262 }
263
264 // Emit top-level description of module, including target triple, inline asm,
265 // descriptors for global variables, and function prototype info.
266 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
267                             BitstreamWriter &Stream) {
268   // Emit the list of dependent libraries for the Module.
269   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
270     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
271
272   // Emit various pieces of data attached to a module.
273   if (!M->getTargetTriple().empty())
274     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
275                       0/*TODO*/, Stream);
276   if (!M->getDataLayout().empty())
277     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
278                       0/*TODO*/, Stream);
279   if (!M->getModuleInlineAsm().empty())
280     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
281                       0/*TODO*/, Stream);
282
283   // Emit information about sections, computing how many there are.  Also
284   // compute the maximum alignment value.
285   std::map<std::string, unsigned> SectionMap;
286   unsigned MaxAlignment = 0;
287   unsigned MaxGlobalType = 0;
288   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
289        GV != E; ++GV) {
290     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
291     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
292     
293     if (!GV->hasSection()) continue;
294     // Give section names unique ID's.
295     unsigned &Entry = SectionMap[GV->getSection()];
296     if (Entry != 0) continue;
297     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
298                       0/*TODO*/, Stream);
299     Entry = SectionMap.size();
300   }
301   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
302     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
303     if (!F->hasSection()) continue;
304     // Give section names unique ID's.
305     unsigned &Entry = SectionMap[F->getSection()];
306     if (Entry != 0) continue;
307     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
308                       0/*TODO*/, Stream);
309     Entry = SectionMap.size();
310   }
311   
312   // Emit abbrev for globals, now that we know # sections and max alignment.
313   unsigned SimpleGVarAbbrev = 0;
314   if (!M->global_empty()) { 
315     // Add an abbrev for common globals with no visibility or thread localness.
316     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
317     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
318     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
319                               Log2_32_Ceil(MaxGlobalType+1)));
320     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
321     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
322     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));      // Linkage.
323     if (MaxAlignment == 0)                                      // Alignment.
324       Abbv->Add(BitCodeAbbrevOp(0));
325     else {
326       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
327       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
328                                Log2_32_Ceil(MaxEncAlignment+1)));
329     }
330     if (SectionMap.empty())                                    // Section.
331       Abbv->Add(BitCodeAbbrevOp(0));
332     else
333       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
334                                Log2_32_Ceil(SectionMap.size()+1)));
335     // Don't bother emitting vis + thread local.
336     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
337   }
338   
339   // Emit the global variable information.
340   SmallVector<unsigned, 64> Vals;
341   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
342        GV != E; ++GV) {
343     unsigned AbbrevToUse = 0;
344
345     // GLOBALVAR: [type, isconst, initid, 
346     //             linkage, alignment, section, visibility, threadlocal]
347     Vals.push_back(VE.getTypeID(GV->getType()));
348     Vals.push_back(GV->isConstant());
349     Vals.push_back(GV->isDeclaration() ? 0 :
350                    (VE.getValueID(GV->getInitializer()) + 1));
351     Vals.push_back(getEncodedLinkage(GV));
352     Vals.push_back(Log2_32(GV->getAlignment())+1);
353     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
354     if (GV->isThreadLocal() || 
355         GV->getVisibility() != GlobalValue::DefaultVisibility) {
356       Vals.push_back(getEncodedVisibility(GV));
357       Vals.push_back(GV->isThreadLocal());
358     } else {
359       AbbrevToUse = SimpleGVarAbbrev;
360     }
361     
362     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
363     Vals.clear();
364   }
365
366   // Emit the function proto information.
367   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
368     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
369     //             visibility]
370     Vals.push_back(VE.getTypeID(F->getType()));
371     Vals.push_back(F->getCallingConv());
372     Vals.push_back(F->isDeclaration());
373     Vals.push_back(getEncodedLinkage(F));
374     Vals.push_back(Log2_32(F->getAlignment())+1);
375     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
376     Vals.push_back(getEncodedVisibility(F));
377     
378     unsigned AbbrevToUse = 0;
379     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
380     Vals.clear();
381   }
382   
383   
384   // Emit the alias information.
385   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
386        AI != E; ++AI) {
387     Vals.push_back(VE.getTypeID(AI->getType()));
388     Vals.push_back(VE.getValueID(AI->getAliasee()));
389     Vals.push_back(getEncodedLinkage(AI));
390     unsigned AbbrevToUse = 0;
391     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
392     Vals.clear();
393   }
394 }
395
396
397 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
398                            const ValueEnumerator &VE,
399                            BitstreamWriter &Stream) {
400   if (FirstVal == LastVal) return;
401   
402   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
403
404   // FIXME: Install and use abbrevs to reduce size.  Install them globally so
405   // they don't need to be reemitted for each function body.
406   
407   SmallVector<uint64_t, 64> Record;
408
409   const ValueEnumerator::ValueList &Vals = VE.getValues();
410   const Type *LastTy = 0;
411   for (unsigned i = FirstVal; i != LastVal; ++i) {
412     const Value *V = Vals[i].first;
413     // If we need to switch types, do so now.
414     if (V->getType() != LastTy) {
415       LastTy = V->getType();
416       Record.push_back(VE.getTypeID(LastTy));
417       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
418       Record.clear();
419     }
420     
421     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
422       assert(0 && IA && "FIXME: Inline asm writing unimp!");
423       continue;
424     }
425     const Constant *C = cast<Constant>(V);
426     unsigned Code = -1U;
427     unsigned AbbrevToUse = 0;
428     if (C->isNullValue()) {
429       Code = bitc::CST_CODE_NULL;
430     } else if (isa<UndefValue>(C)) {
431       Code = bitc::CST_CODE_UNDEF;
432     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
433       if (IV->getBitWidth() <= 64) {
434         int64_t V = IV->getSExtValue();
435         if (V >= 0)
436           Record.push_back(V << 1);
437         else
438           Record.push_back((-V << 1) | 1);
439         Code = bitc::CST_CODE_INTEGER;
440       } else {                             // Wide integers, > 64 bits in size.
441         // We have an arbitrary precision integer value to write whose 
442         // bit width is > 64. However, in canonical unsigned integer 
443         // format it is likely that the high bits are going to be zero.
444         // So, we only write the number of active words.
445         unsigned NWords = IV->getValue().getActiveWords(); 
446         const uint64_t *RawWords = IV->getValue().getRawData();
447         for (unsigned i = 0; i != NWords; ++i) {
448           int64_t V = RawWords[i];
449           if (V >= 0)
450             Record.push_back(V << 1);
451           else
452             Record.push_back((-V << 1) | 1);
453         }
454         Code = bitc::CST_CODE_WIDE_INTEGER;
455       }
456     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
457       Code = bitc::CST_CODE_FLOAT;
458       if (CFP->getType() == Type::FloatTy) {
459         Record.push_back(FloatToBits((float)CFP->getValue()));
460       } else {
461         assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
462         Record.push_back(DoubleToBits((double)CFP->getValue()));
463       }
464     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
465                isa<ConstantVector>(V)) {
466       Code = bitc::CST_CODE_AGGREGATE;
467       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
468         Record.push_back(VE.getValueID(C->getOperand(i)));
469     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
470       switch (CE->getOpcode()) {
471       default:
472         if (Instruction::isCast(CE->getOpcode())) {
473           Code = bitc::CST_CODE_CE_CAST;
474           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
475           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
476           Record.push_back(VE.getValueID(C->getOperand(0)));
477         } else {
478           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
479           Code = bitc::CST_CODE_CE_BINOP;
480           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
481           Record.push_back(VE.getValueID(C->getOperand(0)));
482           Record.push_back(VE.getValueID(C->getOperand(1)));
483         }
484         break;
485       case Instruction::GetElementPtr:
486         Code = bitc::CST_CODE_CE_GEP;
487         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
488           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
489           Record.push_back(VE.getValueID(C->getOperand(i)));
490         }
491         break;
492       case Instruction::Select:
493         Code = bitc::CST_CODE_CE_SELECT;
494         Record.push_back(VE.getValueID(C->getOperand(0)));
495         Record.push_back(VE.getValueID(C->getOperand(1)));
496         Record.push_back(VE.getValueID(C->getOperand(2)));
497         break;
498       case Instruction::ExtractElement:
499         Code = bitc::CST_CODE_CE_EXTRACTELT;
500         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
501         Record.push_back(VE.getValueID(C->getOperand(0)));
502         Record.push_back(VE.getValueID(C->getOperand(1)));
503         break;
504       case Instruction::InsertElement:
505         Code = bitc::CST_CODE_CE_INSERTELT;
506         Record.push_back(VE.getValueID(C->getOperand(0)));
507         Record.push_back(VE.getValueID(C->getOperand(1)));
508         Record.push_back(VE.getValueID(C->getOperand(2)));
509         break;
510       case Instruction::ShuffleVector:
511         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
512         Record.push_back(VE.getValueID(C->getOperand(0)));
513         Record.push_back(VE.getValueID(C->getOperand(1)));
514         Record.push_back(VE.getValueID(C->getOperand(2)));
515         break;
516       case Instruction::ICmp:
517       case Instruction::FCmp:
518         Code = bitc::CST_CODE_CE_CMP;
519         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
520         Record.push_back(VE.getValueID(C->getOperand(0)));
521         Record.push_back(VE.getValueID(C->getOperand(1)));
522         Record.push_back(CE->getPredicate());
523         break;
524       }
525     } else {
526       assert(0 && "Unknown constant!");
527     }
528     Stream.EmitRecord(Code, Record, AbbrevToUse);
529     Record.clear();
530   }
531
532   Stream.ExitBlock();
533 }
534
535 static void WriteModuleConstants(const ValueEnumerator &VE,
536                                  BitstreamWriter &Stream) {
537   const ValueEnumerator::ValueList &Vals = VE.getValues();
538   
539   // Find the first constant to emit, which is the first non-globalvalue value.
540   // We know globalvalues have been emitted by WriteModuleInfo.
541   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
542     if (!isa<GlobalValue>(Vals[i].first)) {
543       WriteConstants(i, Vals.size(), VE, Stream);
544       return;
545     }
546   }
547 }
548
549 /// WriteInstruction - Emit an instruction to the specified stream.
550 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE, 
551                              BitstreamWriter &Stream,
552                              SmallVector<unsigned, 64> &Vals) {
553   unsigned Code = 0;
554   unsigned AbbrevToUse = 0;
555   switch (I.getOpcode()) {
556   default:
557     if (Instruction::isCast(I.getOpcode())) {
558       Code = bitc::FUNC_CODE_INST_CAST;
559       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
560       Vals.push_back(VE.getTypeID(I.getType()));
561       Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
562       Vals.push_back(VE.getValueID(I.getOperand(0)));
563     } else {
564       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
565       Code = bitc::FUNC_CODE_INST_BINOP;
566       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
567       Vals.push_back(VE.getTypeID(I.getType()));
568       Vals.push_back(VE.getValueID(I.getOperand(0)));
569       Vals.push_back(VE.getValueID(I.getOperand(1)));
570     }
571     break;
572
573   case Instruction::GetElementPtr:
574     Code = bitc::FUNC_CODE_INST_GEP;
575     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
576       Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
577       Vals.push_back(VE.getValueID(I.getOperand(i)));
578     }
579     break;
580   case Instruction::Select:
581     Code = bitc::FUNC_CODE_INST_SELECT;
582     Vals.push_back(VE.getTypeID(I.getType()));
583     Vals.push_back(VE.getValueID(I.getOperand(0)));
584     Vals.push_back(VE.getValueID(I.getOperand(1)));
585     Vals.push_back(VE.getValueID(I.getOperand(2)));
586     break;
587   case Instruction::ExtractElement:
588     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
589     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
590     Vals.push_back(VE.getValueID(I.getOperand(0)));
591     Vals.push_back(VE.getValueID(I.getOperand(1)));
592     break;
593   case Instruction::InsertElement:
594     Code = bitc::FUNC_CODE_INST_INSERTELT;
595     Vals.push_back(VE.getTypeID(I.getType()));
596     Vals.push_back(VE.getValueID(I.getOperand(0)));
597     Vals.push_back(VE.getValueID(I.getOperand(1)));
598     Vals.push_back(VE.getValueID(I.getOperand(2)));
599     break;
600   case Instruction::ShuffleVector:
601     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
602     Vals.push_back(VE.getTypeID(I.getType()));
603     Vals.push_back(VE.getValueID(I.getOperand(0)));
604     Vals.push_back(VE.getValueID(I.getOperand(1)));
605     Vals.push_back(VE.getValueID(I.getOperand(2)));
606     break;
607   case Instruction::ICmp:
608   case Instruction::FCmp:
609     Code = bitc::FUNC_CODE_INST_CMP;
610     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
611     Vals.push_back(VE.getValueID(I.getOperand(0)));
612     Vals.push_back(VE.getValueID(I.getOperand(1)));
613     Vals.push_back(cast<CmpInst>(I).getPredicate());
614     break;
615
616   case Instruction::Ret:
617     Code = bitc::FUNC_CODE_INST_RET;
618     if (I.getNumOperands()) {
619       Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
620       Vals.push_back(VE.getValueID(I.getOperand(0)));
621     }
622     break;
623   case Instruction::Br:
624     Code = bitc::FUNC_CODE_INST_BR;
625     Vals.push_back(VE.getValueID(I.getOperand(0)));
626     if (cast<BranchInst>(I).isConditional()) {
627       Vals.push_back(VE.getValueID(I.getOperand(1)));
628       Vals.push_back(VE.getValueID(I.getOperand(2)));
629     }
630     break;
631   case Instruction::Switch:
632     Code = bitc::FUNC_CODE_INST_SWITCH;
633     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
634     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
635       Vals.push_back(VE.getValueID(I.getOperand(i)));
636     break;
637   case Instruction::Invoke: {
638     Code = bitc::FUNC_CODE_INST_INVOKE;
639     Vals.push_back(cast<InvokeInst>(I).getCallingConv());
640     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
641     Vals.push_back(VE.getValueID(I.getOperand(0)));  // callee
642     Vals.push_back(VE.getValueID(I.getOperand(1)));  // normal
643     Vals.push_back(VE.getValueID(I.getOperand(2)));  // unwind
644     
645     // Emit value #'s for the fixed parameters.
646     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
647     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
648     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
649       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
650
651     // Emit type/value pairs for varargs params.
652     if (FTy->isVarArg()) {
653       unsigned NumVarargs = I.getNumOperands()-3-FTy->getNumParams();
654       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
655            i != e; ++i) {
656         Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
657         Vals.push_back(VE.getValueID(I.getOperand(i)));
658       }
659     }
660     break;
661   }
662   case Instruction::Unwind:
663     Code = bitc::FUNC_CODE_INST_UNWIND;
664     break;
665   case Instruction::Unreachable:
666     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
667     break;
668   
669   case Instruction::PHI:
670     Code = bitc::FUNC_CODE_INST_PHI;
671     Vals.push_back(VE.getTypeID(I.getType()));
672     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
673       Vals.push_back(VE.getValueID(I.getOperand(i)));
674     break;
675     
676   case Instruction::Malloc:
677     Code = bitc::FUNC_CODE_INST_MALLOC;
678     Vals.push_back(VE.getTypeID(I.getType()));
679     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
680     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
681     break;
682     
683   case Instruction::Free:
684     Code = bitc::FUNC_CODE_INST_FREE;
685     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
686     Vals.push_back(VE.getValueID(I.getOperand(0)));
687     break;
688     
689   case Instruction::Alloca:
690     Code = bitc::FUNC_CODE_INST_ALLOCA;
691     Vals.push_back(VE.getTypeID(I.getType()));
692     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
693     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
694     break;
695     
696   case Instruction::Load:
697     Code = bitc::FUNC_CODE_INST_LOAD;
698     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
699     Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr.
700     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
701     Vals.push_back(cast<LoadInst>(I).isVolatile());
702     break;
703   case Instruction::Store:
704     Code = bitc::FUNC_CODE_INST_STORE;
705     Vals.push_back(VE.getTypeID(I.getOperand(1)->getType()));   // Pointer
706     Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
707     Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
708     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
709     Vals.push_back(cast<StoreInst>(I).isVolatile());
710     break;
711   case Instruction::Call: {
712     Code = bitc::FUNC_CODE_INST_CALL;
713     Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
714                    cast<CallInst>(I).isTailCall());
715     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
716     Vals.push_back(VE.getValueID(I.getOperand(0)));  // callee
717     
718     // Emit value #'s for the fixed parameters.
719     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
720     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
721     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
722       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
723       
724     // Emit type/value pairs for varargs params.
725     if (FTy->isVarArg()) {
726       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
727       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
728            i != e; ++i) {
729         Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
730         Vals.push_back(VE.getValueID(I.getOperand(i)));
731       }
732     }
733     break;
734   }
735   case Instruction::VAArg:
736     Code = bitc::FUNC_CODE_INST_VAARG;
737     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
738     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
739     Vals.push_back(VE.getTypeID(I.getType())); // restype.
740     break;
741   }
742   
743   Stream.EmitRecord(Code, Vals, AbbrevToUse);
744   Vals.clear();
745 }
746
747 // Emit names for globals/functions etc.
748 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
749                                   const ValueEnumerator &VE,
750                                   BitstreamWriter &Stream) {
751   if (VST.empty()) return;
752   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
753
754   // FIXME: Set up the abbrev, we know how many values there are!
755   // FIXME: We know if the type names can use 7-bit ascii.
756   SmallVector<unsigned, 64> NameVals;
757   
758   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
759        SI != SE; ++SI) {
760     
761     const ValueName &Name = *SI;
762     
763     // Figure out the encoding to use for the name.
764     bool is7Bit = true;
765     bool isChar6 = true;
766     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
767          C != E; ++C) {
768       if (isChar6) 
769         isChar6 = BitCodeAbbrevOp::isChar6(*C);
770       if ((unsigned char)*C & 128) {
771         is7Bit = false;
772         break;  // don't bother scanning the rest.
773       }
774     }
775     
776     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
777     
778     // VST_ENTRY:   [valueid, namechar x N]
779     // VST_BBENTRY: [bbid, namechar x N]
780     unsigned Code;
781     if (isa<BasicBlock>(SI->getValue())) {
782       Code = bitc::VST_CODE_BBENTRY;
783       if (isChar6)
784         AbbrevToUse = VST_BBENTRY_6_ABBREV;
785     } else {
786       Code = bitc::VST_CODE_ENTRY;
787       if (isChar6)
788         AbbrevToUse = VST_ENTRY_6_ABBREV;
789       else if (is7Bit)
790         AbbrevToUse = VST_ENTRY_7_ABBREV;
791     }
792     
793     NameVals.push_back(VE.getValueID(SI->getValue()));
794     for (const char *P = Name.getKeyData(),
795          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
796       NameVals.push_back((unsigned char)*P);
797     
798     // Emit the finished record.
799     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
800     NameVals.clear();
801   }
802   Stream.ExitBlock();
803 }
804
805 /// WriteFunction - Emit a function body to the module stream.
806 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
807                           BitstreamWriter &Stream) {
808   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
809   VE.incorporateFunction(F);
810
811   SmallVector<unsigned, 64> Vals;
812   
813   // Emit the number of basic blocks, so the reader can create them ahead of
814   // time.
815   Vals.push_back(VE.getBasicBlocks().size());
816   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
817   Vals.clear();
818   
819   // FIXME: Function attributes?
820   
821   // If there are function-local constants, emit them now.
822   unsigned CstStart, CstEnd;
823   VE.getFunctionConstantRange(CstStart, CstEnd);
824   WriteConstants(CstStart, CstEnd, VE, Stream);
825   
826   // Finally, emit all the instructions, in order.
827   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
828     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
829       WriteInstruction(*I, VE, Stream, Vals);
830   
831   // Emit names for all the instructions etc.
832   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
833     
834   VE.purgeFunction();
835   Stream.ExitBlock();
836 }
837
838 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
839 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
840                                  const ValueEnumerator &VE,
841                                  BitstreamWriter &Stream) {
842   if (TST.empty()) return;
843   
844   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
845   
846   // 7-bit fixed width VST_CODE_ENTRY strings.
847   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
848   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
849   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
850                             Log2_32_Ceil(VE.getTypes().size()+1)));
851   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
852   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
853   unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
854   
855   SmallVector<unsigned, 64> NameVals;
856   
857   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
858        TI != TE; ++TI) {
859     // TST_ENTRY: [typeid, namechar x N]
860     NameVals.push_back(VE.getTypeID(TI->second));
861     
862     const std::string &Str = TI->first;
863     bool is7Bit = true;
864     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
865       NameVals.push_back((unsigned char)Str[i]);
866       if (Str[i] & 128)
867         is7Bit = false;
868     }
869     
870     // Emit the finished record.
871     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
872     NameVals.clear();
873   }
874   
875   Stream.ExitBlock();
876 }
877
878
879 /// WriteModule - Emit the specified module to the bitstream.
880 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
881   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
882   
883   // Emit the version number if it is non-zero.
884   if (CurVersion) {
885     SmallVector<unsigned, 1> Vals;
886     Vals.push_back(CurVersion);
887     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
888   }
889   
890   // Analyze the module, enumerating globals, functions, etc.
891   ValueEnumerator VE(M);
892   
893   // Emit information about parameter attributes.
894   WriteParamAttrTable(VE, Stream);
895   
896   // Emit information describing all of the types in the module.
897   WriteTypeTable(VE, Stream);
898   
899   // Emit top-level description of module, including target triple, inline asm,
900   // descriptors for global variables, and function prototype info.
901   WriteModuleInfo(M, VE, Stream);
902   
903   // Emit constants.
904   WriteModuleConstants(VE, Stream);
905   
906   // If we have any aggregate values in the value table, purge them - these can
907   // only be used to initialize global variables.  Doing so makes the value
908   // namespace smaller for code in functions.
909   int NumNonAggregates = VE.PurgeAggregateValues();
910   if (NumNonAggregates != -1) {
911     SmallVector<unsigned, 1> Vals;
912     Vals.push_back(NumNonAggregates);
913     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
914   }
915   
916   // Emit function bodies.
917   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
918     if (!I->isDeclaration())
919       WriteFunction(*I, VE, Stream);
920   
921   // Emit the type symbol table information.
922   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
923   
924   // Emit names for globals/functions etc.
925   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
926   
927   Stream.ExitBlock();
928 }
929
930 // Emit blockinfo, which defines the standard abbreviations etc.
931 static void WriteBlockInfo(BitstreamWriter &Stream) {
932   // We only want to emit block info records for blocks that have multiple
933   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
934   // blocks can defined their abbrevs inline.
935   Stream.EnterBlockInfoBlock(2);
936   
937   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
938     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
939     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
940     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
941     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
942     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
943     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 
944                                    Abbv) != VST_ENTRY_8_ABBREV)
945       assert(0 && "Unexpected abbrev ordering!");
946   }
947   
948   { // 7-bit fixed width VST_ENTRY strings.
949     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
950     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
951     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
952     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
953     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
954     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
955                                    Abbv) != VST_ENTRY_7_ABBREV)
956       assert(0 && "Unexpected abbrev ordering!");
957   }
958   { // 6-bit char6 VST_ENTRY strings.
959     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
960     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
961     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
962     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
963     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
964     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
965                                    Abbv) != VST_ENTRY_6_ABBREV)
966       assert(0 && "Unexpected abbrev ordering!");
967   }
968   { // 6-bit char6 VST_BBENTRY strings.
969     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
970     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
971     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
972     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
973     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
974     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
975                                    Abbv) != VST_BBENTRY_6_ABBREV)
976       assert(0 && "Unexpected abbrev ordering!");
977   }
978   
979   Stream.ExitBlock();
980 }
981
982
983 /// WriteBitcodeToFile - Write the specified module to the specified output
984 /// stream.
985 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
986   std::vector<unsigned char> Buffer;
987   BitstreamWriter Stream(Buffer);
988   
989   Buffer.reserve(256*1024);
990   
991   // Emit the file header.
992   Stream.Emit((unsigned)'B', 8);
993   Stream.Emit((unsigned)'C', 8);
994   Stream.Emit(0x0, 4);
995   Stream.Emit(0xC, 4);
996   Stream.Emit(0xE, 4);
997   Stream.Emit(0xD, 4);
998
999   // Emit blockinfo, which defines the standard abbreviations etc.
1000   WriteBlockInfo(Stream);
1001   
1002   // Emit the module.
1003   WriteModule(M, Stream);
1004   
1005   // Write the generated bitstream to "Out".
1006   Out.write((char*)&Buffer.front(), Buffer.size());
1007 }