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