Give embedded metadata its own type instead of relying on EmptyStructTy.
[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 is distributed under the University of Illinois Open Source
6 // 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/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Program.h"
30 using namespace llvm;
31
32 /// These are manifest constants used by the bitcode writer. They do not need to
33 /// be kept in sync with the reader, but need to be consistent within this file.
34 enum {
35   CurVersion = 0,
36   
37   // VALUE_SYMTAB_BLOCK abbrev id's.
38   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
39   VST_ENTRY_7_ABBREV,
40   VST_ENTRY_6_ABBREV,
41   VST_BBENTRY_6_ABBREV,
42   
43   // CONSTANTS_BLOCK abbrev id's.
44   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
45   CONSTANTS_INTEGER_ABBREV,
46   CONSTANTS_CE_CAST_Abbrev,
47   CONSTANTS_NULL_Abbrev,
48   
49   // FUNCTION_BLOCK abbrev id's.
50   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51   FUNCTION_INST_BINOP_ABBREV,
52   FUNCTION_INST_CAST_ABBREV,
53   FUNCTION_INST_RET_VOID_ABBREV,
54   FUNCTION_INST_RET_VAL_ABBREV,
55   FUNCTION_INST_UNREACHABLE_ABBREV
56 };
57
58
59 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
60   switch (Opcode) {
61   default: assert(0 && "Unknown cast instruction!");
62   case Instruction::Trunc   : return bitc::CAST_TRUNC;
63   case Instruction::ZExt    : return bitc::CAST_ZEXT;
64   case Instruction::SExt    : return bitc::CAST_SEXT;
65   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
66   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
67   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
68   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
69   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
70   case Instruction::FPExt   : return bitc::CAST_FPEXT;
71   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
72   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
73   case Instruction::BitCast : return bitc::CAST_BITCAST;
74   }
75 }
76
77 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
78   switch (Opcode) {
79   default: assert(0 && "Unknown binary instruction!");
80   case Instruction::Add:  return bitc::BINOP_ADD;
81   case Instruction::Sub:  return bitc::BINOP_SUB;
82   case Instruction::Mul:  return bitc::BINOP_MUL;
83   case Instruction::UDiv: return bitc::BINOP_UDIV;
84   case Instruction::FDiv:
85   case Instruction::SDiv: return bitc::BINOP_SDIV;
86   case Instruction::URem: return bitc::BINOP_UREM;
87   case Instruction::FRem:
88   case Instruction::SRem: return bitc::BINOP_SREM;
89   case Instruction::Shl:  return bitc::BINOP_SHL;
90   case Instruction::LShr: return bitc::BINOP_LSHR;
91   case Instruction::AShr: return bitc::BINOP_ASHR;
92   case Instruction::And:  return bitc::BINOP_AND;
93   case Instruction::Or:   return bitc::BINOP_OR;
94   case Instruction::Xor:  return bitc::BINOP_XOR;
95   }
96 }
97
98
99
100 static void WriteStringRecord(unsigned Code, const std::string &Str, 
101                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
102   SmallVector<unsigned, 64> Vals;
103   
104   // Code: [strchar x N]
105   for (unsigned i = 0, e = Str.size(); i != e; ++i)
106     Vals.push_back(Str[i]);
107     
108   // Emit the finished record.
109   Stream.EmitRecord(Code, Vals, AbbrevToUse);
110 }
111
112 // Emit information about parameter attributes.
113 static void WriteAttributeTable(const ValueEnumerator &VE, 
114                                 BitstreamWriter &Stream) {
115   const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
116   if (Attrs.empty()) return;
117   
118   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
119
120   SmallVector<uint64_t, 64> Record;
121   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
122     const AttrListPtr &A = Attrs[i];
123     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
124       const AttributeWithIndex &PAWI = A.getSlot(i);
125       Record.push_back(PAWI.Index);
126
127       // FIXME: remove in LLVM 3.0
128       // Store the alignment in the bitcode as a 16-bit raw value instead of a
129       // 5-bit log2 encoded value. Shift the bits above the alignment up by
130       // 11 bits.
131       uint64_t FauxAttr = PAWI.Attrs & 0xffff;
132       if (PAWI.Attrs & Attribute::Alignment)
133         FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
134       FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
135
136       Record.push_back(FauxAttr);
137     }
138     
139     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
140     Record.clear();
141   }
142   
143   Stream.ExitBlock();
144 }
145
146 /// WriteTypeTable - Write out the type table for a module.
147 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
148   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
149   
150   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
151   SmallVector<uint64_t, 64> TypeVals;
152   
153   // Abbrev for TYPE_CODE_POINTER.
154   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
155   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
156   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
157                             Log2_32_Ceil(VE.getTypes().size()+1)));
158   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
159   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
160   
161   // Abbrev for TYPE_CODE_FUNCTION.
162   Abbv = new BitCodeAbbrev();
163   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
164   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
165   Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
166   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
167   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
168                             Log2_32_Ceil(VE.getTypes().size()+1)));
169   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
170   
171   // Abbrev for TYPE_CODE_STRUCT.
172   Abbv = new BitCodeAbbrev();
173   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
174   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
175   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
176   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
177                             Log2_32_Ceil(VE.getTypes().size()+1)));
178   unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
179  
180   // Abbrev for TYPE_CODE_ARRAY.
181   Abbv = new BitCodeAbbrev();
182   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
183   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
184   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
185                             Log2_32_Ceil(VE.getTypes().size()+1)));
186   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
187   
188   // Emit an entry count so the reader can reserve space.
189   TypeVals.push_back(TypeList.size());
190   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
191   TypeVals.clear();
192   
193   // Loop over all of the types, emitting each in turn.
194   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
195     const Type *T = TypeList[i].first;
196     int AbbrevToUse = 0;
197     unsigned Code = 0;
198     
199     switch (T->getTypeID()) {
200     default: assert(0 && "Unknown type!");
201     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
202     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
203     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
204     case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
205     case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
206     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
207     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
208     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
209     case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
210     case Type::IntegerTyID:
211       // INTEGER: [width]
212       Code = bitc::TYPE_CODE_INTEGER;
213       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
214       break;
215     case Type::PointerTyID: {
216       const PointerType *PTy = cast<PointerType>(T);
217       // POINTER: [pointee type, address space]
218       Code = bitc::TYPE_CODE_POINTER;
219       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
220       unsigned AddressSpace = PTy->getAddressSpace();
221       TypeVals.push_back(AddressSpace);
222       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
223       break;
224     }
225     case Type::FunctionTyID: {
226       const FunctionType *FT = cast<FunctionType>(T);
227       // FUNCTION: [isvararg, attrid, retty, paramty x N]
228       Code = bitc::TYPE_CODE_FUNCTION;
229       TypeVals.push_back(FT->isVarArg());
230       TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
231       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
232       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
233         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
234       AbbrevToUse = FunctionAbbrev;
235       break;
236     }
237     case Type::StructTyID: {
238       const StructType *ST = cast<StructType>(T);
239       // STRUCT: [ispacked, eltty x N]
240       Code = bitc::TYPE_CODE_STRUCT;
241       TypeVals.push_back(ST->isPacked());
242       // Output all of the element types.
243       for (StructType::element_iterator I = ST->element_begin(),
244            E = ST->element_end(); I != E; ++I)
245         TypeVals.push_back(VE.getTypeID(*I));
246       AbbrevToUse = StructAbbrev;
247       break;
248     }
249     case Type::ArrayTyID: {
250       const ArrayType *AT = cast<ArrayType>(T);
251       // ARRAY: [numelts, eltty]
252       Code = bitc::TYPE_CODE_ARRAY;
253       TypeVals.push_back(AT->getNumElements());
254       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
255       AbbrevToUse = ArrayAbbrev;
256       break;
257     }
258     case Type::VectorTyID: {
259       const VectorType *VT = cast<VectorType>(T);
260       // VECTOR [numelts, eltty]
261       Code = bitc::TYPE_CODE_VECTOR;
262       TypeVals.push_back(VT->getNumElements());
263       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
264       break;
265     }
266     }
267
268     // Emit the finished record.
269     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
270     TypeVals.clear();
271   }
272   
273   Stream.ExitBlock();
274 }
275
276 static unsigned getEncodedLinkage(const GlobalValue *GV) {
277   switch (GV->getLinkage()) {
278   default: assert(0 && "Invalid linkage!");
279   case GlobalValue::GhostLinkage:  // Map ghost linkage onto external.
280   case GlobalValue::ExternalLinkage:     return 0;
281   case GlobalValue::WeakAnyLinkage:      return 1;
282   case GlobalValue::AppendingLinkage:    return 2;
283   case GlobalValue::InternalLinkage:     return 3;
284   case GlobalValue::LinkOnceAnyLinkage:  return 4;
285   case GlobalValue::DLLImportLinkage:    return 5;
286   case GlobalValue::DLLExportLinkage:    return 6;
287   case GlobalValue::ExternalWeakLinkage: return 7;
288   case GlobalValue::CommonLinkage:       return 8;
289   case GlobalValue::PrivateLinkage:      return 9;
290   case GlobalValue::WeakODRLinkage:      return 10;
291   case GlobalValue::LinkOnceODRLinkage:  return 11;
292   case GlobalValue::AvailableExternallyLinkage:  return 12;
293   }
294 }
295
296 static unsigned getEncodedVisibility(const GlobalValue *GV) {
297   switch (GV->getVisibility()) {
298   default: assert(0 && "Invalid visibility!");
299   case GlobalValue::DefaultVisibility:   return 0;
300   case GlobalValue::HiddenVisibility:    return 1;
301   case GlobalValue::ProtectedVisibility: return 2;
302   }
303 }
304
305 // Emit top-level description of module, including target triple, inline asm,
306 // descriptors for global variables, and function prototype info.
307 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
308                             BitstreamWriter &Stream) {
309   // Emit the list of dependent libraries for the Module.
310   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
311     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
312
313   // Emit various pieces of data attached to a module.
314   if (!M->getTargetTriple().empty())
315     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
316                       0/*TODO*/, Stream);
317   if (!M->getDataLayout().empty())
318     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
319                       0/*TODO*/, Stream);
320   if (!M->getModuleInlineAsm().empty())
321     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
322                       0/*TODO*/, Stream);
323
324   // Emit information about sections and GC, computing how many there are. Also
325   // compute the maximum alignment value.
326   std::map<std::string, unsigned> SectionMap;
327   std::map<std::string, unsigned> GCMap;
328   unsigned MaxAlignment = 0;
329   unsigned MaxGlobalType = 0;
330   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
331        GV != E; ++GV) {
332     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
333     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
334     
335     if (!GV->hasSection()) continue;
336     // Give section names unique ID's.
337     unsigned &Entry = SectionMap[GV->getSection()];
338     if (Entry != 0) continue;
339     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
340                       0/*TODO*/, Stream);
341     Entry = SectionMap.size();
342   }
343   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
344     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
345     if (F->hasSection()) {
346       // Give section names unique ID's.
347       unsigned &Entry = SectionMap[F->getSection()];
348       if (!Entry) {
349         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
350                           0/*TODO*/, Stream);
351         Entry = SectionMap.size();
352       }
353     }
354     if (F->hasGC()) {
355       // Same for GC names.
356       unsigned &Entry = GCMap[F->getGC()];
357       if (!Entry) {
358         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
359                           0/*TODO*/, Stream);
360         Entry = GCMap.size();
361       }
362     }
363   }
364   
365   // Emit abbrev for globals, now that we know # sections and max alignment.
366   unsigned SimpleGVarAbbrev = 0;
367   if (!M->global_empty()) { 
368     // Add an abbrev for common globals with no visibility or thread localness.
369     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
370     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
371     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
372                               Log2_32_Ceil(MaxGlobalType+1)));
373     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
374     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
375     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
376     if (MaxAlignment == 0)                                      // Alignment.
377       Abbv->Add(BitCodeAbbrevOp(0));
378     else {
379       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
380       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
381                                Log2_32_Ceil(MaxEncAlignment+1)));
382     }
383     if (SectionMap.empty())                                    // Section.
384       Abbv->Add(BitCodeAbbrevOp(0));
385     else
386       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
387                                Log2_32_Ceil(SectionMap.size()+1)));
388     // Don't bother emitting vis + thread local.
389     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
390   }
391   
392   // Emit the global variable information.
393   SmallVector<unsigned, 64> Vals;
394   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
395        GV != E; ++GV) {
396     unsigned AbbrevToUse = 0;
397
398     // GLOBALVAR: [type, isconst, initid, 
399     //             linkage, alignment, section, visibility, threadlocal]
400     Vals.push_back(VE.getTypeID(GV->getType()));
401     Vals.push_back(GV->isConstant());
402     Vals.push_back(GV->isDeclaration() ? 0 :
403                    (VE.getValueID(GV->getInitializer()) + 1));
404     Vals.push_back(getEncodedLinkage(GV));
405     Vals.push_back(Log2_32(GV->getAlignment())+1);
406     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
407     if (GV->isThreadLocal() || 
408         GV->getVisibility() != GlobalValue::DefaultVisibility) {
409       Vals.push_back(getEncodedVisibility(GV));
410       Vals.push_back(GV->isThreadLocal());
411     } else {
412       AbbrevToUse = SimpleGVarAbbrev;
413     }
414     
415     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
416     Vals.clear();
417   }
418
419   // Emit the function proto information.
420   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
421     // FUNCTION:  [type, callingconv, isproto, paramattr,
422     //             linkage, alignment, section, visibility, gc]
423     Vals.push_back(VE.getTypeID(F->getType()));
424     Vals.push_back(F->getCallingConv());
425     Vals.push_back(F->isDeclaration());
426     Vals.push_back(getEncodedLinkage(F));
427     Vals.push_back(VE.getAttributeID(F->getAttributes()));
428     Vals.push_back(Log2_32(F->getAlignment())+1);
429     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
430     Vals.push_back(getEncodedVisibility(F));
431     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
432     
433     unsigned AbbrevToUse = 0;
434     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
435     Vals.clear();
436   }
437   
438   
439   // Emit the alias information.
440   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
441        AI != E; ++AI) {
442     Vals.push_back(VE.getTypeID(AI->getType()));
443     Vals.push_back(VE.getValueID(AI->getAliasee()));
444     Vals.push_back(getEncodedLinkage(AI));
445     Vals.push_back(getEncodedVisibility(AI));
446     unsigned AbbrevToUse = 0;
447     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
448     Vals.clear();
449   }
450 }
451
452
453 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
454                            const ValueEnumerator &VE,
455                            BitstreamWriter &Stream, bool isGlobal) {
456   if (FirstVal == LastVal) return;
457   
458   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
459
460   unsigned AggregateAbbrev = 0;
461   unsigned String8Abbrev = 0;
462   unsigned CString7Abbrev = 0;
463   unsigned CString6Abbrev = 0;
464   unsigned MDString8Abbrev = 0;
465   unsigned MDString6Abbrev = 0;
466   // If this is a constant pool for the module, emit module-specific abbrevs.
467   if (isGlobal) {
468     // Abbrev for CST_CODE_AGGREGATE.
469     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
470     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
471     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
472     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
473     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
474
475     // Abbrev for CST_CODE_STRING.
476     Abbv = new BitCodeAbbrev();
477     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
478     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
479     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
480     String8Abbrev = Stream.EmitAbbrev(Abbv);
481     // Abbrev for CST_CODE_CSTRING.
482     Abbv = new BitCodeAbbrev();
483     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
484     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
485     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
486     CString7Abbrev = Stream.EmitAbbrev(Abbv);
487     // Abbrev for CST_CODE_CSTRING.
488     Abbv = new BitCodeAbbrev();
489     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
490     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
491     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
492     CString6Abbrev = Stream.EmitAbbrev(Abbv);
493
494     // Abbrev for CST_CODE_MDSTRING.
495     Abbv = new BitCodeAbbrev();
496     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
497     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
498     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
499     MDString8Abbrev = Stream.EmitAbbrev(Abbv);
500     // Abbrev for CST_CODE_MDSTRING.
501     Abbv = new BitCodeAbbrev();
502     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
503     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
504     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
505     MDString6Abbrev = Stream.EmitAbbrev(Abbv);
506   }  
507   
508   SmallVector<uint64_t, 64> Record;
509
510   const ValueEnumerator::ValueList &Vals = VE.getValues();
511   const Type *LastTy = 0;
512   for (unsigned i = FirstVal; i != LastVal; ++i) {
513     const Value *V = Vals[i].first;
514     // If we need to switch types, do so now.
515     if (V->getType() != LastTy) {
516       LastTy = V->getType();
517       Record.push_back(VE.getTypeID(LastTy));
518       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
519                         CONSTANTS_SETTYPE_ABBREV);
520       Record.clear();
521     }
522     
523     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
524       Record.push_back(unsigned(IA->hasSideEffects()));
525       
526       // Add the asm string.
527       const std::string &AsmStr = IA->getAsmString();
528       Record.push_back(AsmStr.size());
529       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
530         Record.push_back(AsmStr[i]);
531       
532       // Add the constraint string.
533       const std::string &ConstraintStr = IA->getConstraintString();
534       Record.push_back(ConstraintStr.size());
535       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
536         Record.push_back(ConstraintStr[i]);
537       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
538       Record.clear();
539       continue;
540     }
541     const Constant *C = cast<Constant>(V);
542     unsigned Code = -1U;
543     unsigned AbbrevToUse = 0;
544     if (C->isNullValue()) {
545       Code = bitc::CST_CODE_NULL;
546     } else if (isa<UndefValue>(C)) {
547       Code = bitc::CST_CODE_UNDEF;
548     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
549       if (IV->getBitWidth() <= 64) {
550         int64_t V = IV->getSExtValue();
551         if (V >= 0)
552           Record.push_back(V << 1);
553         else
554           Record.push_back((-V << 1) | 1);
555         Code = bitc::CST_CODE_INTEGER;
556         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
557       } else {                             // Wide integers, > 64 bits in size.
558         // We have an arbitrary precision integer value to write whose 
559         // bit width is > 64. However, in canonical unsigned integer 
560         // format it is likely that the high bits are going to be zero.
561         // So, we only write the number of active words.
562         unsigned NWords = IV->getValue().getActiveWords(); 
563         const uint64_t *RawWords = IV->getValue().getRawData();
564         for (unsigned i = 0; i != NWords; ++i) {
565           int64_t V = RawWords[i];
566           if (V >= 0)
567             Record.push_back(V << 1);
568           else
569             Record.push_back((-V << 1) | 1);
570         }
571         Code = bitc::CST_CODE_WIDE_INTEGER;
572       }
573     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
574       Code = bitc::CST_CODE_FLOAT;
575       const Type *Ty = CFP->getType();
576       if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
577         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
578       } else if (Ty == Type::X86_FP80Ty) {
579         // api needed to prevent premature destruction
580         // bits are not in the same order as a normal i80 APInt, compensate.
581         APInt api = CFP->getValueAPF().bitcastToAPInt();
582         const uint64_t *p = api.getRawData();
583         Record.push_back((p[1] << 48) | (p[0] >> 16));
584         Record.push_back(p[0] & 0xffffLL);
585       } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
586         APInt api = CFP->getValueAPF().bitcastToAPInt();
587         const uint64_t *p = api.getRawData();
588         Record.push_back(p[0]);
589         Record.push_back(p[1]);
590       } else {
591         assert (0 && "Unknown FP type!");
592       }
593     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
594       // Emit constant strings specially.
595       unsigned NumOps = C->getNumOperands();
596       // If this is a null-terminated string, use the denser CSTRING encoding.
597       if (C->getOperand(NumOps-1)->isNullValue()) {
598         Code = bitc::CST_CODE_CSTRING;
599         --NumOps;  // Don't encode the null, which isn't allowed by char6.
600       } else {
601         Code = bitc::CST_CODE_STRING;
602         AbbrevToUse = String8Abbrev;
603       }
604       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
605       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
606       for (unsigned i = 0; i != NumOps; ++i) {
607         unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
608         Record.push_back(V);
609         isCStr7 &= (V & 128) == 0;
610         if (isCStrChar6) 
611           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
612       }
613       
614       if (isCStrChar6)
615         AbbrevToUse = CString6Abbrev;
616       else if (isCStr7)
617         AbbrevToUse = CString7Abbrev;
618     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
619                isa<ConstantVector>(V)) {
620       Code = bitc::CST_CODE_AGGREGATE;
621       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
622         Record.push_back(VE.getValueID(C->getOperand(i)));
623       AbbrevToUse = AggregateAbbrev;
624     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
625       switch (CE->getOpcode()) {
626       default:
627         if (Instruction::isCast(CE->getOpcode())) {
628           Code = bitc::CST_CODE_CE_CAST;
629           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
630           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
631           Record.push_back(VE.getValueID(C->getOperand(0)));
632           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
633         } else {
634           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
635           Code = bitc::CST_CODE_CE_BINOP;
636           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
637           Record.push_back(VE.getValueID(C->getOperand(0)));
638           Record.push_back(VE.getValueID(C->getOperand(1)));
639         }
640         break;
641       case Instruction::GetElementPtr:
642         Code = bitc::CST_CODE_CE_GEP;
643         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
644           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
645           Record.push_back(VE.getValueID(C->getOperand(i)));
646         }
647         break;
648       case Instruction::Select:
649         Code = bitc::CST_CODE_CE_SELECT;
650         Record.push_back(VE.getValueID(C->getOperand(0)));
651         Record.push_back(VE.getValueID(C->getOperand(1)));
652         Record.push_back(VE.getValueID(C->getOperand(2)));
653         break;
654       case Instruction::ExtractElement:
655         Code = bitc::CST_CODE_CE_EXTRACTELT;
656         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
657         Record.push_back(VE.getValueID(C->getOperand(0)));
658         Record.push_back(VE.getValueID(C->getOperand(1)));
659         break;
660       case Instruction::InsertElement:
661         Code = bitc::CST_CODE_CE_INSERTELT;
662         Record.push_back(VE.getValueID(C->getOperand(0)));
663         Record.push_back(VE.getValueID(C->getOperand(1)));
664         Record.push_back(VE.getValueID(C->getOperand(2)));
665         break;
666       case Instruction::ShuffleVector:
667         // If the return type and argument types are the same, this is a
668         // standard shufflevector instruction.  If the types are different,
669         // then the shuffle is widening or truncating the input vectors, and
670         // the argument type must also be encoded.
671         if (C->getType() == C->getOperand(0)->getType()) {
672           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
673         } else {
674           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
675           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
676         }
677         Record.push_back(VE.getValueID(C->getOperand(0)));
678         Record.push_back(VE.getValueID(C->getOperand(1)));
679         Record.push_back(VE.getValueID(C->getOperand(2)));
680         break;
681       case Instruction::ICmp:
682       case Instruction::FCmp:
683       case Instruction::VICmp:
684       case Instruction::VFCmp:
685         if (isa<VectorType>(C->getOperand(0)->getType())
686             && (CE->getOpcode() == Instruction::ICmp
687                 || CE->getOpcode() == Instruction::FCmp)) {
688           // compare returning vector of Int1Ty
689           assert(0 && "Unsupported constant!");
690         } else {
691           Code = bitc::CST_CODE_CE_CMP;
692         }
693         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
694         Record.push_back(VE.getValueID(C->getOperand(0)));
695         Record.push_back(VE.getValueID(C->getOperand(1)));
696         Record.push_back(CE->getPredicate());
697         break;
698       }
699     } else if (const MDString *S = dyn_cast<MDString>(C)) {
700       Code = bitc::CST_CODE_MDSTRING;
701       AbbrevToUse = MDString6Abbrev;
702       for (unsigned i = 0, e = S->size(); i != e; ++i) {
703         char V = S->begin()[i];
704         Record.push_back(V);
705
706         if (!BitCodeAbbrevOp::isChar6(V))
707           AbbrevToUse = MDString8Abbrev;
708       }
709     } else if (const MDNode *N = dyn_cast<MDNode>(C)) {
710       Code = bitc::CST_CODE_MDNODE;
711       for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
712         if (N->getElement(i)) {
713           Record.push_back(VE.getTypeID(N->getElement(i)->getType()));
714           Record.push_back(VE.getValueID(N->getElement(i)));
715         } else {
716           Record.push_back(VE.getTypeID(Type::VoidTy));
717           Record.push_back(0);
718         }
719       }
720     } else {
721       assert(0 && "Unknown constant!");
722     }
723     Stream.EmitRecord(Code, Record, AbbrevToUse);
724     Record.clear();
725   }
726
727   Stream.ExitBlock();
728 }
729
730 static void WriteModuleConstants(const ValueEnumerator &VE,
731                                  BitstreamWriter &Stream) {
732   const ValueEnumerator::ValueList &Vals = VE.getValues();
733   
734   // Find the first constant to emit, which is the first non-globalvalue value.
735   // We know globalvalues have been emitted by WriteModuleInfo.
736   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
737     if (!isa<GlobalValue>(Vals[i].first)) {
738       WriteConstants(i, Vals.size(), VE, Stream, true);
739       return;
740     }
741   }
742 }
743
744 /// PushValueAndType - The file has to encode both the value and type id for
745 /// many values, because we need to know what type to create for forward
746 /// references.  However, most operands are not forward references, so this type
747 /// field is not needed.
748 ///
749 /// This function adds V's value ID to Vals.  If the value ID is higher than the
750 /// instruction ID, then it is a forward reference, and it also includes the
751 /// type ID.
752 static bool PushValueAndType(const Value *V, unsigned InstID,
753                              SmallVector<unsigned, 64> &Vals, 
754                              ValueEnumerator &VE) {
755   unsigned ValID = VE.getValueID(V);
756   Vals.push_back(ValID);
757   if (ValID >= InstID) {
758     Vals.push_back(VE.getTypeID(V->getType()));
759     return true;
760   }
761   return false;
762 }
763
764 /// WriteInstruction - Emit an instruction to the specified stream.
765 static void WriteInstruction(const Instruction &I, unsigned InstID,
766                              ValueEnumerator &VE, BitstreamWriter &Stream,
767                              SmallVector<unsigned, 64> &Vals) {
768   unsigned Code = 0;
769   unsigned AbbrevToUse = 0;
770   switch (I.getOpcode()) {
771   default:
772     if (Instruction::isCast(I.getOpcode())) {
773       Code = bitc::FUNC_CODE_INST_CAST;
774       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
775         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
776       Vals.push_back(VE.getTypeID(I.getType()));
777       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
778     } else {
779       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
780       Code = bitc::FUNC_CODE_INST_BINOP;
781       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
782         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
783       Vals.push_back(VE.getValueID(I.getOperand(1)));
784       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
785     }
786     break;
787
788   case Instruction::GetElementPtr:
789     Code = bitc::FUNC_CODE_INST_GEP;
790     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
791       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
792     break;
793   case Instruction::ExtractValue: {
794     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
795     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
796     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
797     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
798       Vals.push_back(*i);
799     break;
800   }
801   case Instruction::InsertValue: {
802     Code = bitc::FUNC_CODE_INST_INSERTVAL;
803     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
804     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
805     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
806     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
807       Vals.push_back(*i);
808     break;
809   }
810   case Instruction::Select:
811     Code = bitc::FUNC_CODE_INST_VSELECT;
812     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
813     Vals.push_back(VE.getValueID(I.getOperand(2)));
814     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
815     break;
816   case Instruction::ExtractElement:
817     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
818     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
819     Vals.push_back(VE.getValueID(I.getOperand(1)));
820     break;
821   case Instruction::InsertElement:
822     Code = bitc::FUNC_CODE_INST_INSERTELT;
823     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
824     Vals.push_back(VE.getValueID(I.getOperand(1)));
825     Vals.push_back(VE.getValueID(I.getOperand(2)));
826     break;
827   case Instruction::ShuffleVector:
828     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
829     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
830     Vals.push_back(VE.getValueID(I.getOperand(1)));
831     Vals.push_back(VE.getValueID(I.getOperand(2)));
832     break;
833   case Instruction::ICmp:
834   case Instruction::FCmp:
835   case Instruction::VICmp:
836   case Instruction::VFCmp:
837     if (I.getOpcode() == Instruction::ICmp
838         || I.getOpcode() == Instruction::FCmp) {
839       // compare returning Int1Ty or vector of Int1Ty
840       Code = bitc::FUNC_CODE_INST_CMP2;
841     } else {
842       Code = bitc::FUNC_CODE_INST_CMP;
843     }
844     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
845     Vals.push_back(VE.getValueID(I.getOperand(1)));
846     Vals.push_back(cast<CmpInst>(I).getPredicate());
847     break;
848
849   case Instruction::Ret: 
850     {
851       Code = bitc::FUNC_CODE_INST_RET;
852       unsigned NumOperands = I.getNumOperands();
853       if (NumOperands == 0)
854         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
855       else if (NumOperands == 1) {
856         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
857           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
858       } else {
859         for (unsigned i = 0, e = NumOperands; i != e; ++i)
860           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
861       }
862     }
863     break;
864   case Instruction::Br:
865     {
866       Code = bitc::FUNC_CODE_INST_BR;
867       BranchInst &II(cast<BranchInst>(I));
868       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
869       if (II.isConditional()) {
870         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
871         Vals.push_back(VE.getValueID(II.getCondition()));
872       }
873     }
874     break;
875   case Instruction::Switch:
876     Code = bitc::FUNC_CODE_INST_SWITCH;
877     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
878     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
879       Vals.push_back(VE.getValueID(I.getOperand(i)));
880     break;
881   case Instruction::Invoke: {
882     const InvokeInst *II = cast<InvokeInst>(&I);
883     const Value *Callee(II->getCalledValue());
884     const PointerType *PTy = cast<PointerType>(Callee->getType());
885     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
886     Code = bitc::FUNC_CODE_INST_INVOKE;
887     
888     Vals.push_back(VE.getAttributeID(II->getAttributes()));
889     Vals.push_back(II->getCallingConv());
890     Vals.push_back(VE.getValueID(II->getNormalDest()));
891     Vals.push_back(VE.getValueID(II->getUnwindDest()));
892     PushValueAndType(Callee, InstID, Vals, VE);
893     
894     // Emit value #'s for the fixed parameters.
895     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
896       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
897
898     // Emit type/value pairs for varargs params.
899     if (FTy->isVarArg()) {
900       for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
901            i != e; ++i)
902         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
903     }
904     break;
905   }
906   case Instruction::Unwind:
907     Code = bitc::FUNC_CODE_INST_UNWIND;
908     break;
909   case Instruction::Unreachable:
910     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
911     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
912     break;
913   
914   case Instruction::PHI:
915     Code = bitc::FUNC_CODE_INST_PHI;
916     Vals.push_back(VE.getTypeID(I.getType()));
917     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
918       Vals.push_back(VE.getValueID(I.getOperand(i)));
919     break;
920     
921   case Instruction::Malloc:
922     Code = bitc::FUNC_CODE_INST_MALLOC;
923     Vals.push_back(VE.getTypeID(I.getType()));
924     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
925     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
926     break;
927     
928   case Instruction::Free:
929     Code = bitc::FUNC_CODE_INST_FREE;
930     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
931     break;
932     
933   case Instruction::Alloca:
934     Code = bitc::FUNC_CODE_INST_ALLOCA;
935     Vals.push_back(VE.getTypeID(I.getType()));
936     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
937     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
938     break;
939     
940   case Instruction::Load:
941     Code = bitc::FUNC_CODE_INST_LOAD;
942     if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
943       AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
944       
945     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
946     Vals.push_back(cast<LoadInst>(I).isVolatile());
947     break;
948   case Instruction::Store:
949     Code = bitc::FUNC_CODE_INST_STORE2;
950     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
951     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
952     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
953     Vals.push_back(cast<StoreInst>(I).isVolatile());
954     break;
955   case Instruction::Call: {
956     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
957     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
958
959     Code = bitc::FUNC_CODE_INST_CALL;
960     
961     const CallInst *CI = cast<CallInst>(&I);
962     Vals.push_back(VE.getAttributeID(CI->getAttributes()));
963     Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
964     PushValueAndType(CI->getOperand(0), InstID, Vals, VE);  // Callee
965     
966     // Emit value #'s for the fixed parameters.
967     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
968       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
969       
970     // Emit type/value pairs for varargs params.
971     if (FTy->isVarArg()) {
972       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
973       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
974            i != e; ++i)
975         PushValueAndType(I.getOperand(i), InstID, Vals, VE);  // varargs
976     }
977     break;
978   }
979   case Instruction::VAArg:
980     Code = bitc::FUNC_CODE_INST_VAARG;
981     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
982     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
983     Vals.push_back(VE.getTypeID(I.getType())); // restype.
984     break;
985   }
986   
987   Stream.EmitRecord(Code, Vals, AbbrevToUse);
988   Vals.clear();
989 }
990
991 // Emit names for globals/functions etc.
992 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
993                                   const ValueEnumerator &VE,
994                                   BitstreamWriter &Stream) {
995   if (VST.empty()) return;
996   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
997
998   // FIXME: Set up the abbrev, we know how many values there are!
999   // FIXME: We know if the type names can use 7-bit ascii.
1000   SmallVector<unsigned, 64> NameVals;
1001   
1002   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1003        SI != SE; ++SI) {
1004     
1005     const ValueName &Name = *SI;
1006     
1007     // Figure out the encoding to use for the name.
1008     bool is7Bit = true;
1009     bool isChar6 = true;
1010     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1011          C != E; ++C) {
1012       if (isChar6) 
1013         isChar6 = BitCodeAbbrevOp::isChar6(*C);
1014       if ((unsigned char)*C & 128) {
1015         is7Bit = false;
1016         break;  // don't bother scanning the rest.
1017       }
1018     }
1019     
1020     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1021     
1022     // VST_ENTRY:   [valueid, namechar x N]
1023     // VST_BBENTRY: [bbid, namechar x N]
1024     unsigned Code;
1025     if (isa<BasicBlock>(SI->getValue())) {
1026       Code = bitc::VST_CODE_BBENTRY;
1027       if (isChar6)
1028         AbbrevToUse = VST_BBENTRY_6_ABBREV;
1029     } else {
1030       Code = bitc::VST_CODE_ENTRY;
1031       if (isChar6)
1032         AbbrevToUse = VST_ENTRY_6_ABBREV;
1033       else if (is7Bit)
1034         AbbrevToUse = VST_ENTRY_7_ABBREV;
1035     }
1036     
1037     NameVals.push_back(VE.getValueID(SI->getValue()));
1038     for (const char *P = Name.getKeyData(),
1039          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1040       NameVals.push_back((unsigned char)*P);
1041     
1042     // Emit the finished record.
1043     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1044     NameVals.clear();
1045   }
1046   Stream.ExitBlock();
1047 }
1048
1049 /// WriteFunction - Emit a function body to the module stream.
1050 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
1051                           BitstreamWriter &Stream) {
1052   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1053   VE.incorporateFunction(F);
1054
1055   SmallVector<unsigned, 64> Vals;
1056   
1057   // Emit the number of basic blocks, so the reader can create them ahead of
1058   // time.
1059   Vals.push_back(VE.getBasicBlocks().size());
1060   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1061   Vals.clear();
1062   
1063   // If there are function-local constants, emit them now.
1064   unsigned CstStart, CstEnd;
1065   VE.getFunctionConstantRange(CstStart, CstEnd);
1066   WriteConstants(CstStart, CstEnd, VE, Stream, false);
1067   
1068   // Keep a running idea of what the instruction ID is. 
1069   unsigned InstID = CstEnd;
1070   
1071   // Finally, emit all the instructions, in order.
1072   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1073     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1074          I != E; ++I) {
1075       WriteInstruction(*I, InstID, VE, Stream, Vals);
1076       if (I->getType() != Type::VoidTy)
1077         ++InstID;
1078     }
1079   
1080   // Emit names for all the instructions etc.
1081   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1082     
1083   VE.purgeFunction();
1084   Stream.ExitBlock();
1085 }
1086
1087 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1088 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1089                                  const ValueEnumerator &VE,
1090                                  BitstreamWriter &Stream) {
1091   if (TST.empty()) return;
1092   
1093   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1094   
1095   // 7-bit fixed width VST_CODE_ENTRY strings.
1096   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1097   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1098   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1099                             Log2_32_Ceil(VE.getTypes().size()+1)));
1100   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1101   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1102   unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1103   
1104   SmallVector<unsigned, 64> NameVals;
1105   
1106   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
1107        TI != TE; ++TI) {
1108     // TST_ENTRY: [typeid, namechar x N]
1109     NameVals.push_back(VE.getTypeID(TI->second));
1110     
1111     const std::string &Str = TI->first;
1112     bool is7Bit = true;
1113     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1114       NameVals.push_back((unsigned char)Str[i]);
1115       if (Str[i] & 128)
1116         is7Bit = false;
1117     }
1118     
1119     // Emit the finished record.
1120     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1121     NameVals.clear();
1122   }
1123   
1124   Stream.ExitBlock();
1125 }
1126
1127 // Emit blockinfo, which defines the standard abbreviations etc.
1128 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1129   // We only want to emit block info records for blocks that have multiple
1130   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1131   // blocks can defined their abbrevs inline.
1132   Stream.EnterBlockInfoBlock(2);
1133   
1134   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1135     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1136     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1137     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1138     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1139     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1140     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 
1141                                    Abbv) != VST_ENTRY_8_ABBREV)
1142       assert(0 && "Unexpected abbrev ordering!");
1143   }
1144   
1145   { // 7-bit fixed width VST_ENTRY strings.
1146     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1147     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1148     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1149     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1150     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1151     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1152                                    Abbv) != VST_ENTRY_7_ABBREV)
1153       assert(0 && "Unexpected abbrev ordering!");
1154   }
1155   { // 6-bit char6 VST_ENTRY strings.
1156     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1157     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1158     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1159     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1160     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1161     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1162                                    Abbv) != VST_ENTRY_6_ABBREV)
1163       assert(0 && "Unexpected abbrev ordering!");
1164   }
1165   { // 6-bit char6 VST_BBENTRY strings.
1166     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1167     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1168     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1169     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1170     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1171     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1172                                    Abbv) != VST_BBENTRY_6_ABBREV)
1173       assert(0 && "Unexpected abbrev ordering!");
1174   }
1175   
1176   
1177   
1178   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1179     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1180     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1181     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1182                               Log2_32_Ceil(VE.getTypes().size()+1)));
1183     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1184                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1185       assert(0 && "Unexpected abbrev ordering!");
1186   }
1187   
1188   { // INTEGER abbrev for CONSTANTS_BLOCK.
1189     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1190     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1191     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1192     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1193                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1194       assert(0 && "Unexpected abbrev ordering!");
1195   }
1196   
1197   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1198     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1199     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1200     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1201     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1202                               Log2_32_Ceil(VE.getTypes().size()+1)));
1203     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1204
1205     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1206                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1207       assert(0 && "Unexpected abbrev ordering!");
1208   }
1209   { // NULL abbrev for CONSTANTS_BLOCK.
1210     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1211     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1212     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1213                                    Abbv) != CONSTANTS_NULL_Abbrev)
1214       assert(0 && "Unexpected abbrev ordering!");
1215   }
1216   
1217   // FIXME: This should only use space for first class types!
1218  
1219   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1220     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1221     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1222     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1223     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1224     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1225     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1226                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1227       assert(0 && "Unexpected abbrev ordering!");
1228   }
1229   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1230     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1231     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1232     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1233     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1234     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1235     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1236                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1237       assert(0 && "Unexpected abbrev ordering!");
1238   }
1239   { // INST_CAST abbrev for FUNCTION_BLOCK.
1240     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1241     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1242     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1243     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1244                               Log2_32_Ceil(VE.getTypes().size()+1)));
1245     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1246     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1247                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1248       assert(0 && "Unexpected abbrev ordering!");
1249   }
1250   
1251   { // INST_RET abbrev for FUNCTION_BLOCK.
1252     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1253     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1254     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1255                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1256       assert(0 && "Unexpected abbrev ordering!");
1257   }
1258   { // INST_RET abbrev for FUNCTION_BLOCK.
1259     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1260     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1261     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1262     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1263                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1264       assert(0 && "Unexpected abbrev ordering!");
1265   }
1266   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1267     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1268     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1269     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1270                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1271       assert(0 && "Unexpected abbrev ordering!");
1272   }
1273   
1274   Stream.ExitBlock();
1275 }
1276
1277
1278 /// WriteModule - Emit the specified module to the bitstream.
1279 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1280   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1281   
1282   // Emit the version number if it is non-zero.
1283   if (CurVersion) {
1284     SmallVector<unsigned, 1> Vals;
1285     Vals.push_back(CurVersion);
1286     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1287   }
1288   
1289   // Analyze the module, enumerating globals, functions, etc.
1290   ValueEnumerator VE(M);
1291
1292   // Emit blockinfo, which defines the standard abbreviations etc.
1293   WriteBlockInfo(VE, Stream);
1294   
1295   // Emit information about parameter attributes.
1296   WriteAttributeTable(VE, Stream);
1297   
1298   // Emit information describing all of the types in the module.
1299   WriteTypeTable(VE, Stream);
1300   
1301   // Emit top-level description of module, including target triple, inline asm,
1302   // descriptors for global variables, and function prototype info.
1303   WriteModuleInfo(M, VE, Stream);
1304   
1305   // Emit constants.
1306   WriteModuleConstants(VE, Stream);
1307   
1308   // If we have any aggregate values in the value table, purge them - these can
1309   // only be used to initialize global variables.  Doing so makes the value
1310   // namespace smaller for code in functions.
1311   int NumNonAggregates = VE.PurgeAggregateValues();
1312   if (NumNonAggregates != -1) {
1313     SmallVector<unsigned, 1> Vals;
1314     Vals.push_back(NumNonAggregates);
1315     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1316   }
1317   
1318   // Emit function bodies.
1319   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1320     if (!I->isDeclaration())
1321       WriteFunction(*I, VE, Stream);
1322   
1323   // Emit the type symbol table information.
1324   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1325   
1326   // Emit names for globals/functions etc.
1327   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1328   
1329   Stream.ExitBlock();
1330 }
1331
1332 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1333 /// header and trailer to make it compatible with the system archiver.  To do
1334 /// this we emit the following header, and then emit a trailer that pads the
1335 /// file out to be a multiple of 16 bytes.
1336 /// 
1337 /// struct bc_header {
1338 ///   uint32_t Magic;         // 0x0B17C0DE
1339 ///   uint32_t Version;       // Version, currently always 0.
1340 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1341 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1342 ///   uint32_t CPUType;       // CPU specifier.
1343 ///   ... potentially more later ...
1344 /// };
1345 enum {
1346   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1347   DarwinBCHeaderSize = 5*4
1348 };
1349
1350 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1351                                const std::string &TT) {
1352   unsigned CPUType = ~0U;
1353   
1354   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*.  The CPUType is a
1355   // magic number from /usr/include/mach/machine.h.  It is ok to reproduce the
1356   // specific constants here because they are implicitly part of the Darwin ABI.
1357   enum {
1358     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
1359     DARWIN_CPU_TYPE_X86        = 7,
1360     DARWIN_CPU_TYPE_POWERPC    = 18
1361   };
1362   
1363   if (TT.find("x86_64-") == 0)
1364     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1365   else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1366            TT[4] == '-' && TT[1] - '3' < 6)
1367     CPUType = DARWIN_CPU_TYPE_X86;
1368   else if (TT.find("powerpc-") == 0)
1369     CPUType = DARWIN_CPU_TYPE_POWERPC;
1370   else if (TT.find("powerpc64-") == 0)
1371     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1372   
1373   // Traditional Bitcode starts after header.
1374   unsigned BCOffset = DarwinBCHeaderSize;
1375   
1376   Stream.Emit(0x0B17C0DE, 32);
1377   Stream.Emit(0         , 32);  // Version.
1378   Stream.Emit(BCOffset  , 32);
1379   Stream.Emit(0         , 32);  // Filled in later.
1380   Stream.Emit(CPUType   , 32);
1381 }
1382
1383 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1384 /// finalize the header.
1385 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1386   // Update the size field in the header.
1387   Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1388   
1389   // If the file is not a multiple of 16 bytes, insert dummy padding.
1390   while (BufferSize & 15) {
1391     Stream.Emit(0, 8);
1392     ++BufferSize;
1393   }
1394 }
1395
1396
1397 /// WriteBitcodeToFile - Write the specified module to the specified output
1398 /// stream.
1399 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1400   raw_os_ostream RawOut(Out);
1401   // If writing to stdout, set binary mode.
1402   if (llvm::cout == Out)
1403     sys::Program::ChangeStdoutToBinary();
1404   WriteBitcodeToFile(M, RawOut);
1405 }
1406
1407 /// WriteBitcodeToFile - Write the specified module to the specified output
1408 /// stream.
1409 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1410   std::vector<unsigned char> Buffer;
1411   BitstreamWriter Stream(Buffer);
1412   
1413   Buffer.reserve(256*1024);
1414
1415   WriteBitcodeToStream( M, Stream );
1416   
1417   // If writing to stdout, set binary mode.
1418   if (&llvm::outs() == &Out)
1419     sys::Program::ChangeStdoutToBinary();
1420
1421   // Write the generated bitstream to "Out".
1422   Out.write((char*)&Buffer.front(), Buffer.size());
1423   
1424   // Make sure it hits disk now.
1425   Out.flush();
1426 }
1427
1428 /// WriteBitcodeToStream - Write the specified module to the specified output
1429 /// stream.
1430 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1431   // If this is darwin, emit a file header and trailer if needed.
1432   bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1433   if (isDarwin)
1434     EmitDarwinBCHeader(Stream, M->getTargetTriple());
1435   
1436   // Emit the file header.
1437   Stream.Emit((unsigned)'B', 8);
1438   Stream.Emit((unsigned)'C', 8);
1439   Stream.Emit(0x0, 4);
1440   Stream.Emit(0xC, 4);
1441   Stream.Emit(0xE, 4);
1442   Stream.Emit(0xD, 4);
1443
1444   // Emit the module.
1445   WriteModule(M, Stream);
1446
1447   if (isDarwin)
1448     EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
1449 }