5b1725f5508c125027326a604f866f066916cc07
[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/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/Program.h"
31 #include <cctype>
32 #include <map>
33 using namespace llvm;
34
35 static cl::opt<bool>
36 EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
37                               cl::desc("Turn on experimental support for "
38                                        "use-list order preservation."),
39                               cl::init(false), cl::Hidden);
40
41 /// These are manifest constants used by the bitcode writer. They do not need to
42 /// be kept in sync with the reader, but need to be consistent within this file.
43 enum {
44   CurVersion = 0,
45
46   // VALUE_SYMTAB_BLOCK abbrev id's.
47   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48   VST_ENTRY_7_ABBREV,
49   VST_ENTRY_6_ABBREV,
50   VST_BBENTRY_6_ABBREV,
51
52   // CONSTANTS_BLOCK abbrev id's.
53   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54   CONSTANTS_INTEGER_ABBREV,
55   CONSTANTS_CE_CAST_Abbrev,
56   CONSTANTS_NULL_Abbrev,
57
58   // FUNCTION_BLOCK abbrev id's.
59   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
60   FUNCTION_INST_BINOP_ABBREV,
61   FUNCTION_INST_BINOP_FLAGS_ABBREV,
62   FUNCTION_INST_CAST_ABBREV,
63   FUNCTION_INST_RET_VOID_ABBREV,
64   FUNCTION_INST_RET_VAL_ABBREV,
65   FUNCTION_INST_UNREACHABLE_ABBREV,
66   
67   // SwitchInst Magic
68   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
69 };
70
71 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
72   switch (Opcode) {
73   default: llvm_unreachable("Unknown cast instruction!");
74   case Instruction::Trunc   : return bitc::CAST_TRUNC;
75   case Instruction::ZExt    : return bitc::CAST_ZEXT;
76   case Instruction::SExt    : return bitc::CAST_SEXT;
77   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
78   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
79   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
80   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
81   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
82   case Instruction::FPExt   : return bitc::CAST_FPEXT;
83   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
84   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
85   case Instruction::BitCast : return bitc::CAST_BITCAST;
86   }
87 }
88
89 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
90   switch (Opcode) {
91   default: llvm_unreachable("Unknown binary instruction!");
92   case Instruction::Add:
93   case Instruction::FAdd: return bitc::BINOP_ADD;
94   case Instruction::Sub:
95   case Instruction::FSub: return bitc::BINOP_SUB;
96   case Instruction::Mul:
97   case Instruction::FMul: return bitc::BINOP_MUL;
98   case Instruction::UDiv: return bitc::BINOP_UDIV;
99   case Instruction::FDiv:
100   case Instruction::SDiv: return bitc::BINOP_SDIV;
101   case Instruction::URem: return bitc::BINOP_UREM;
102   case Instruction::FRem:
103   case Instruction::SRem: return bitc::BINOP_SREM;
104   case Instruction::Shl:  return bitc::BINOP_SHL;
105   case Instruction::LShr: return bitc::BINOP_LSHR;
106   case Instruction::AShr: return bitc::BINOP_ASHR;
107   case Instruction::And:  return bitc::BINOP_AND;
108   case Instruction::Or:   return bitc::BINOP_OR;
109   case Instruction::Xor:  return bitc::BINOP_XOR;
110   }
111 }
112
113 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
114   switch (Op) {
115   default: llvm_unreachable("Unknown RMW operation!");
116   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
117   case AtomicRMWInst::Add: return bitc::RMW_ADD;
118   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
119   case AtomicRMWInst::And: return bitc::RMW_AND;
120   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
121   case AtomicRMWInst::Or: return bitc::RMW_OR;
122   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
123   case AtomicRMWInst::Max: return bitc::RMW_MAX;
124   case AtomicRMWInst::Min: return bitc::RMW_MIN;
125   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
126   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
127   }
128 }
129
130 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
131   switch (Ordering) {
132   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
133   case Unordered: return bitc::ORDERING_UNORDERED;
134   case Monotonic: return bitc::ORDERING_MONOTONIC;
135   case Acquire: return bitc::ORDERING_ACQUIRE;
136   case Release: return bitc::ORDERING_RELEASE;
137   case AcquireRelease: return bitc::ORDERING_ACQREL;
138   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
139   }
140   llvm_unreachable("Invalid ordering");
141 }
142
143 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
144   switch (SynchScope) {
145   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
146   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
147   }
148   llvm_unreachable("Invalid synch scope");
149 }
150
151 static void WriteStringRecord(unsigned Code, StringRef Str,
152                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
153   SmallVector<unsigned, 64> Vals;
154
155   // Code: [strchar x N]
156   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
157     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
158       AbbrevToUse = 0;
159     Vals.push_back(Str[i]);
160   }
161
162   // Emit the finished record.
163   Stream.EmitRecord(Code, Vals, AbbrevToUse);
164 }
165
166 // Emit information about parameter attributes.
167 static void WriteAttributeTable(const ValueEnumerator &VE,
168                                 BitstreamWriter &Stream) {
169   const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
170   if (Attrs.empty()) return;
171
172   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
173
174   SmallVector<uint64_t, 64> Record;
175   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
176     const AttrListPtr &A = Attrs[i];
177     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
178       const AttributeWithIndex &PAWI = A.getSlot(i);
179       Record.push_back(PAWI.Index);
180       Record.push_back(Attribute::encodeLLVMAttributesForBitcode(PAWI.Attrs));
181     }
182
183     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
184     Record.clear();
185   }
186
187   Stream.ExitBlock();
188 }
189
190 /// WriteTypeTable - Write out the type table for a module.
191 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
192   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
193
194   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
195   SmallVector<uint64_t, 64> TypeVals;
196
197   uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
198
199   // Abbrev for TYPE_CODE_POINTER.
200   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
201   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
202   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
203   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
204   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
205
206   // Abbrev for TYPE_CODE_FUNCTION.
207   Abbv = new BitCodeAbbrev();
208   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
209   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
210   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
211   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
212
213   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
214
215   // Abbrev for TYPE_CODE_STRUCT_ANON.
216   Abbv = new BitCodeAbbrev();
217   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
218   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
219   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
220   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
221
222   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
223
224   // Abbrev for TYPE_CODE_STRUCT_NAME.
225   Abbv = new BitCodeAbbrev();
226   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
227   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
228   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
229   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
230
231   // Abbrev for TYPE_CODE_STRUCT_NAMED.
232   Abbv = new BitCodeAbbrev();
233   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
234   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
235   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
236   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
237
238   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
239   
240   // Abbrev for TYPE_CODE_ARRAY.
241   Abbv = new BitCodeAbbrev();
242   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
243   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
244   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
245
246   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
247
248   // Emit an entry count so the reader can reserve space.
249   TypeVals.push_back(TypeList.size());
250   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
251   TypeVals.clear();
252
253   // Loop over all of the types, emitting each in turn.
254   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
255     Type *T = TypeList[i];
256     int AbbrevToUse = 0;
257     unsigned Code = 0;
258
259     switch (T->getTypeID()) {
260     default: llvm_unreachable("Unknown type!");
261     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;   break;
262     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;   break;
263     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;  break;
264     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE; break;
265     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80; break;
266     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128; break;
267     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
268     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;  break;
269     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA; break;
270     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX; break;
271     case Type::IntegerTyID:
272       // INTEGER: [width]
273       Code = bitc::TYPE_CODE_INTEGER;
274       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
275       break;
276     case Type::PointerTyID: {
277       PointerType *PTy = cast<PointerType>(T);
278       // POINTER: [pointee type, address space]
279       Code = bitc::TYPE_CODE_POINTER;
280       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
281       unsigned AddressSpace = PTy->getAddressSpace();
282       TypeVals.push_back(AddressSpace);
283       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
284       break;
285     }
286     case Type::FunctionTyID: {
287       FunctionType *FT = cast<FunctionType>(T);
288       // FUNCTION: [isvararg, retty, paramty x N]
289       Code = bitc::TYPE_CODE_FUNCTION;
290       TypeVals.push_back(FT->isVarArg());
291       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
292       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
293         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
294       AbbrevToUse = FunctionAbbrev;
295       break;
296     }
297     case Type::StructTyID: {
298       StructType *ST = cast<StructType>(T);
299       // STRUCT: [ispacked, eltty x N]
300       TypeVals.push_back(ST->isPacked());
301       // Output all of the element types.
302       for (StructType::element_iterator I = ST->element_begin(),
303            E = ST->element_end(); I != E; ++I)
304         TypeVals.push_back(VE.getTypeID(*I));
305       
306       if (ST->isLiteral()) {
307         Code = bitc::TYPE_CODE_STRUCT_ANON;
308         AbbrevToUse = StructAnonAbbrev;
309       } else {
310         if (ST->isOpaque()) {
311           Code = bitc::TYPE_CODE_OPAQUE;
312         } else {
313           Code = bitc::TYPE_CODE_STRUCT_NAMED;
314           AbbrevToUse = StructNamedAbbrev;
315         }
316
317         // Emit the name if it is present.
318         if (!ST->getName().empty())
319           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
320                             StructNameAbbrev, Stream);
321       }
322       break;
323     }
324     case Type::ArrayTyID: {
325       ArrayType *AT = cast<ArrayType>(T);
326       // ARRAY: [numelts, eltty]
327       Code = bitc::TYPE_CODE_ARRAY;
328       TypeVals.push_back(AT->getNumElements());
329       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
330       AbbrevToUse = ArrayAbbrev;
331       break;
332     }
333     case Type::VectorTyID: {
334       VectorType *VT = cast<VectorType>(T);
335       // VECTOR [numelts, eltty]
336       Code = bitc::TYPE_CODE_VECTOR;
337       TypeVals.push_back(VT->getNumElements());
338       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
339       break;
340     }
341     }
342
343     // Emit the finished record.
344     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
345     TypeVals.clear();
346   }
347
348   Stream.ExitBlock();
349 }
350
351 static unsigned getEncodedLinkage(const GlobalValue *GV) {
352   switch (GV->getLinkage()) {
353   case GlobalValue::ExternalLinkage:                 return 0;
354   case GlobalValue::WeakAnyLinkage:                  return 1;
355   case GlobalValue::AppendingLinkage:                return 2;
356   case GlobalValue::InternalLinkage:                 return 3;
357   case GlobalValue::LinkOnceAnyLinkage:              return 4;
358   case GlobalValue::DLLImportLinkage:                return 5;
359   case GlobalValue::DLLExportLinkage:                return 6;
360   case GlobalValue::ExternalWeakLinkage:             return 7;
361   case GlobalValue::CommonLinkage:                   return 8;
362   case GlobalValue::PrivateLinkage:                  return 9;
363   case GlobalValue::WeakODRLinkage:                  return 10;
364   case GlobalValue::LinkOnceODRLinkage:              return 11;
365   case GlobalValue::AvailableExternallyLinkage:      return 12;
366   case GlobalValue::LinkerPrivateLinkage:            return 13;
367   case GlobalValue::LinkerPrivateWeakLinkage:        return 14;
368   case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
369   }
370   llvm_unreachable("Invalid linkage");
371 }
372
373 static unsigned getEncodedVisibility(const GlobalValue *GV) {
374   switch (GV->getVisibility()) {
375   case GlobalValue::DefaultVisibility:   return 0;
376   case GlobalValue::HiddenVisibility:    return 1;
377   case GlobalValue::ProtectedVisibility: return 2;
378   }
379   llvm_unreachable("Invalid visibility");
380 }
381
382 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
383   switch (GV->getThreadLocalMode()) {
384     case GlobalVariable::NotThreadLocal:         return 0;
385     case GlobalVariable::GeneralDynamicTLSModel: return 1;
386     case GlobalVariable::LocalDynamicTLSModel:   return 2;
387     case GlobalVariable::InitialExecTLSModel:    return 3;
388     case GlobalVariable::LocalExecTLSModel:      return 4;
389   }
390   llvm_unreachable("Invalid TLS model");
391 }
392
393 // Emit top-level description of module, including target triple, inline asm,
394 // descriptors for global variables, and function prototype info.
395 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
396                             BitstreamWriter &Stream) {
397   // Emit the list of dependent libraries for the Module.
398   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
399     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
400
401   // Emit various pieces of data attached to a module.
402   if (!M->getTargetTriple().empty())
403     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
404                       0/*TODO*/, Stream);
405   if (!M->getDataLayout().empty())
406     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
407                       0/*TODO*/, Stream);
408   if (!M->getModuleInlineAsm().empty())
409     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
410                       0/*TODO*/, Stream);
411
412   // Emit information about sections and GC, computing how many there are. Also
413   // compute the maximum alignment value.
414   std::map<std::string, unsigned> SectionMap;
415   std::map<std::string, unsigned> GCMap;
416   unsigned MaxAlignment = 0;
417   unsigned MaxGlobalType = 0;
418   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
419        GV != E; ++GV) {
420     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
421     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
422     if (GV->hasSection()) {
423       // Give section names unique ID's.
424       unsigned &Entry = SectionMap[GV->getSection()];
425       if (!Entry) {
426         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
427                           0/*TODO*/, Stream);
428         Entry = SectionMap.size();
429       }
430     }
431   }
432   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
433     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
434     if (F->hasSection()) {
435       // Give section names unique ID's.
436       unsigned &Entry = SectionMap[F->getSection()];
437       if (!Entry) {
438         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
439                           0/*TODO*/, Stream);
440         Entry = SectionMap.size();
441       }
442     }
443     if (F->hasGC()) {
444       // Same for GC names.
445       unsigned &Entry = GCMap[F->getGC()];
446       if (!Entry) {
447         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
448                           0/*TODO*/, Stream);
449         Entry = GCMap.size();
450       }
451     }
452   }
453
454   // Emit abbrev for globals, now that we know # sections and max alignment.
455   unsigned SimpleGVarAbbrev = 0;
456   if (!M->global_empty()) {
457     // Add an abbrev for common globals with no visibility or thread localness.
458     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
459     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
460     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
461                               Log2_32_Ceil(MaxGlobalType+1)));
462     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
463     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
464     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
465     if (MaxAlignment == 0)                                      // Alignment.
466       Abbv->Add(BitCodeAbbrevOp(0));
467     else {
468       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
469       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
470                                Log2_32_Ceil(MaxEncAlignment+1)));
471     }
472     if (SectionMap.empty())                                    // Section.
473       Abbv->Add(BitCodeAbbrevOp(0));
474     else
475       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
476                                Log2_32_Ceil(SectionMap.size()+1)));
477     // Don't bother emitting vis + thread local.
478     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
479   }
480
481   // Emit the global variable information.
482   SmallVector<unsigned, 64> Vals;
483   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
484        GV != E; ++GV) {
485     unsigned AbbrevToUse = 0;
486
487     // GLOBALVAR: [type, isconst, initid,
488     //             linkage, alignment, section, visibility, threadlocal,
489     //             unnamed_addr]
490     Vals.push_back(VE.getTypeID(GV->getType()));
491     Vals.push_back(GV->isConstant());
492     Vals.push_back(GV->isDeclaration() ? 0 :
493                    (VE.getValueID(GV->getInitializer()) + 1));
494     Vals.push_back(getEncodedLinkage(GV));
495     Vals.push_back(Log2_32(GV->getAlignment())+1);
496     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
497     if (GV->isThreadLocal() ||
498         GV->getVisibility() != GlobalValue::DefaultVisibility ||
499         GV->hasUnnamedAddr()) {
500       Vals.push_back(getEncodedVisibility(GV));
501       Vals.push_back(getEncodedThreadLocalMode(GV));
502       Vals.push_back(GV->hasUnnamedAddr());
503     } else {
504       AbbrevToUse = SimpleGVarAbbrev;
505     }
506
507     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
508     Vals.clear();
509   }
510
511   // Emit the function proto information.
512   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
513     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
514     //             section, visibility, gc, unnamed_addr]
515     Vals.push_back(VE.getTypeID(F->getType()));
516     Vals.push_back(F->getCallingConv());
517     Vals.push_back(F->isDeclaration());
518     Vals.push_back(getEncodedLinkage(F));
519     Vals.push_back(VE.getAttributeID(F->getAttributes()));
520     Vals.push_back(Log2_32(F->getAlignment())+1);
521     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
522     Vals.push_back(getEncodedVisibility(F));
523     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
524     Vals.push_back(F->hasUnnamedAddr());
525
526     unsigned AbbrevToUse = 0;
527     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
528     Vals.clear();
529   }
530
531   // Emit the alias information.
532   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
533        AI != E; ++AI) {
534     // ALIAS: [alias type, aliasee val#, linkage, visibility]
535     Vals.push_back(VE.getTypeID(AI->getType()));
536     Vals.push_back(VE.getValueID(AI->getAliasee()));
537     Vals.push_back(getEncodedLinkage(AI));
538     Vals.push_back(getEncodedVisibility(AI));
539     unsigned AbbrevToUse = 0;
540     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
541     Vals.clear();
542   }
543 }
544
545 static uint64_t GetOptimizationFlags(const Value *V) {
546   uint64_t Flags = 0;
547
548   if (const OverflowingBinaryOperator *OBO =
549         dyn_cast<OverflowingBinaryOperator>(V)) {
550     if (OBO->hasNoSignedWrap())
551       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
552     if (OBO->hasNoUnsignedWrap())
553       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
554   } else if (const PossiblyExactOperator *PEO =
555                dyn_cast<PossiblyExactOperator>(V)) {
556     if (PEO->isExact())
557       Flags |= 1 << bitc::PEO_EXACT;
558   }
559
560   return Flags;
561 }
562
563 static void WriteMDNode(const MDNode *N,
564                         const ValueEnumerator &VE,
565                         BitstreamWriter &Stream,
566                         SmallVector<uint64_t, 64> &Record) {
567   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
568     if (N->getOperand(i)) {
569       Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
570       Record.push_back(VE.getValueID(N->getOperand(i)));
571     } else {
572       Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
573       Record.push_back(0);
574     }
575   }
576   unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
577                                            bitc::METADATA_NODE;
578   Stream.EmitRecord(MDCode, Record, 0);
579   Record.clear();
580 }
581
582 static void WriteModuleMetadata(const Module *M,
583                                 const ValueEnumerator &VE,
584                                 BitstreamWriter &Stream) {
585   const ValueEnumerator::ValueList &Vals = VE.getMDValues();
586   bool StartedMetadataBlock = false;
587   unsigned MDSAbbrev = 0;
588   SmallVector<uint64_t, 64> Record;
589   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
590
591     if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
592       if (!N->isFunctionLocal() || !N->getFunction()) {
593         if (!StartedMetadataBlock) {
594           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
595           StartedMetadataBlock = true;
596         }
597         WriteMDNode(N, VE, Stream, Record);
598       }
599     } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
600       if (!StartedMetadataBlock)  {
601         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
602
603         // Abbrev for METADATA_STRING.
604         BitCodeAbbrev *Abbv = new BitCodeAbbrev();
605         Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
606         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
607         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
608         MDSAbbrev = Stream.EmitAbbrev(Abbv);
609         StartedMetadataBlock = true;
610       }
611
612       // Code: [strchar x N]
613       Record.append(MDS->begin(), MDS->end());
614
615       // Emit the finished record.
616       Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
617       Record.clear();
618     }
619   }
620
621   // Write named metadata.
622   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
623        E = M->named_metadata_end(); I != E; ++I) {
624     const NamedMDNode *NMD = I;
625     if (!StartedMetadataBlock)  {
626       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
627       StartedMetadataBlock = true;
628     }
629
630     // Write name.
631     StringRef Str = NMD->getName();
632     for (unsigned i = 0, e = Str.size(); i != e; ++i)
633       Record.push_back(Str[i]);
634     Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
635     Record.clear();
636
637     // Write named metadata operands.
638     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
639       Record.push_back(VE.getValueID(NMD->getOperand(i)));
640     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
641     Record.clear();
642   }
643
644   if (StartedMetadataBlock)
645     Stream.ExitBlock();
646 }
647
648 static void WriteFunctionLocalMetadata(const Function &F,
649                                        const ValueEnumerator &VE,
650                                        BitstreamWriter &Stream) {
651   bool StartedMetadataBlock = false;
652   SmallVector<uint64_t, 64> Record;
653   const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
654   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
655     if (const MDNode *N = Vals[i])
656       if (N->isFunctionLocal() && N->getFunction() == &F) {
657         if (!StartedMetadataBlock) {
658           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
659           StartedMetadataBlock = true;
660         }
661         WriteMDNode(N, VE, Stream, Record);
662       }
663       
664   if (StartedMetadataBlock)
665     Stream.ExitBlock();
666 }
667
668 static void WriteMetadataAttachment(const Function &F,
669                                     const ValueEnumerator &VE,
670                                     BitstreamWriter &Stream) {
671   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
672
673   SmallVector<uint64_t, 64> Record;
674
675   // Write metadata attachments
676   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
677   SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
678   
679   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
680     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
681          I != E; ++I) {
682       MDs.clear();
683       I->getAllMetadataOtherThanDebugLoc(MDs);
684       
685       // If no metadata, ignore instruction.
686       if (MDs.empty()) continue;
687
688       Record.push_back(VE.getInstructionID(I));
689       
690       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
691         Record.push_back(MDs[i].first);
692         Record.push_back(VE.getValueID(MDs[i].second));
693       }
694       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
695       Record.clear();
696     }
697
698   Stream.ExitBlock();
699 }
700
701 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
702   SmallVector<uint64_t, 64> Record;
703
704   // Write metadata kinds
705   // METADATA_KIND - [n x [id, name]]
706   SmallVector<StringRef, 4> Names;
707   M->getMDKindNames(Names);
708   
709   if (Names.empty()) return;
710
711   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
712   
713   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
714     Record.push_back(MDKindID);
715     StringRef KName = Names[MDKindID];
716     Record.append(KName.begin(), KName.end());
717     
718     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
719     Record.clear();
720   }
721
722   Stream.ExitBlock();
723 }
724
725 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
726                       unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
727                       bool EmitSizeForWideNumbers = false
728                       ) {
729   if (Val.getBitWidth() <= 64) {
730     uint64_t V = Val.getSExtValue();
731     if ((int64_t)V >= 0)
732       Vals.push_back(V << 1);
733     else
734       Vals.push_back((-V << 1) | 1);
735     Code = bitc::CST_CODE_INTEGER;
736     AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
737   } else {
738     // Wide integers, > 64 bits in size.
739     // We have an arbitrary precision integer value to write whose
740     // bit width is > 64. However, in canonical unsigned integer
741     // format it is likely that the high bits are going to be zero.
742     // So, we only write the number of active words.
743     unsigned NWords = Val.getActiveWords();
744     
745     if (EmitSizeForWideNumbers)
746       Vals.push_back(NWords);
747     
748     const uint64_t *RawWords = Val.getRawData();
749     for (unsigned i = 0; i != NWords; ++i) {
750       int64_t V = RawWords[i];
751       if (V >= 0)
752         Vals.push_back(V << 1);
753       else
754         Vals.push_back((-V << 1) | 1);
755     }
756     Code = bitc::CST_CODE_WIDE_INTEGER;
757   }
758 }
759
760 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
761                            const ValueEnumerator &VE,
762                            BitstreamWriter &Stream, bool isGlobal) {
763   if (FirstVal == LastVal) return;
764
765   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
766
767   unsigned AggregateAbbrev = 0;
768   unsigned String8Abbrev = 0;
769   unsigned CString7Abbrev = 0;
770   unsigned CString6Abbrev = 0;
771   // If this is a constant pool for the module, emit module-specific abbrevs.
772   if (isGlobal) {
773     // Abbrev for CST_CODE_AGGREGATE.
774     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
775     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
776     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
777     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
778     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
779
780     // Abbrev for CST_CODE_STRING.
781     Abbv = new BitCodeAbbrev();
782     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
783     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
784     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
785     String8Abbrev = Stream.EmitAbbrev(Abbv);
786     // Abbrev for CST_CODE_CSTRING.
787     Abbv = new BitCodeAbbrev();
788     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
789     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
790     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
791     CString7Abbrev = Stream.EmitAbbrev(Abbv);
792     // Abbrev for CST_CODE_CSTRING.
793     Abbv = new BitCodeAbbrev();
794     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
795     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
796     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
797     CString6Abbrev = Stream.EmitAbbrev(Abbv);
798   }
799
800   SmallVector<uint64_t, 64> Record;
801
802   const ValueEnumerator::ValueList &Vals = VE.getValues();
803   Type *LastTy = 0;
804   for (unsigned i = FirstVal; i != LastVal; ++i) {
805     const Value *V = Vals[i].first;
806     // If we need to switch types, do so now.
807     if (V->getType() != LastTy) {
808       LastTy = V->getType();
809       Record.push_back(VE.getTypeID(LastTy));
810       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
811                         CONSTANTS_SETTYPE_ABBREV);
812       Record.clear();
813     }
814
815     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
816       Record.push_back(unsigned(IA->hasSideEffects()) |
817                        unsigned(IA->isAlignStack()) << 1);
818
819       // Add the asm string.
820       const std::string &AsmStr = IA->getAsmString();
821       Record.push_back(AsmStr.size());
822       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
823         Record.push_back(AsmStr[i]);
824
825       // Add the constraint string.
826       const std::string &ConstraintStr = IA->getConstraintString();
827       Record.push_back(ConstraintStr.size());
828       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
829         Record.push_back(ConstraintStr[i]);
830       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
831       Record.clear();
832       continue;
833     }
834     const Constant *C = cast<Constant>(V);
835     unsigned Code = -1U;
836     unsigned AbbrevToUse = 0;
837     if (C->isNullValue()) {
838       Code = bitc::CST_CODE_NULL;
839     } else if (isa<UndefValue>(C)) {
840       Code = bitc::CST_CODE_UNDEF;
841     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
842       EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
843     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
844       Code = bitc::CST_CODE_FLOAT;
845       Type *Ty = CFP->getType();
846       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
847         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
848       } else if (Ty->isX86_FP80Ty()) {
849         // api needed to prevent premature destruction
850         // bits are not in the same order as a normal i80 APInt, compensate.
851         APInt api = CFP->getValueAPF().bitcastToAPInt();
852         const uint64_t *p = api.getRawData();
853         Record.push_back((p[1] << 48) | (p[0] >> 16));
854         Record.push_back(p[0] & 0xffffLL);
855       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
856         APInt api = CFP->getValueAPF().bitcastToAPInt();
857         const uint64_t *p = api.getRawData();
858         Record.push_back(p[0]);
859         Record.push_back(p[1]);
860       } else {
861         assert (0 && "Unknown FP type!");
862       }
863     } else if (isa<ConstantDataSequential>(C) &&
864                cast<ConstantDataSequential>(C)->isString()) {
865       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
866       // Emit constant strings specially.
867       unsigned NumElts = Str->getNumElements();
868       // If this is a null-terminated string, use the denser CSTRING encoding.
869       if (Str->isCString()) {
870         Code = bitc::CST_CODE_CSTRING;
871         --NumElts;  // Don't encode the null, which isn't allowed by char6.
872       } else {
873         Code = bitc::CST_CODE_STRING;
874         AbbrevToUse = String8Abbrev;
875       }
876       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
877       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
878       for (unsigned i = 0; i != NumElts; ++i) {
879         unsigned char V = Str->getElementAsInteger(i);
880         Record.push_back(V);
881         isCStr7 &= (V & 128) == 0;
882         if (isCStrChar6)
883           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
884       }
885       
886       if (isCStrChar6)
887         AbbrevToUse = CString6Abbrev;
888       else if (isCStr7)
889         AbbrevToUse = CString7Abbrev;
890     } else if (const ConstantDataSequential *CDS = 
891                   dyn_cast<ConstantDataSequential>(C)) {
892       Code = bitc::CST_CODE_DATA;
893       Type *EltTy = CDS->getType()->getElementType();
894       if (isa<IntegerType>(EltTy)) {
895         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
896           Record.push_back(CDS->getElementAsInteger(i));
897       } else if (EltTy->isFloatTy()) {
898         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
899           union { float F; uint32_t I; };
900           F = CDS->getElementAsFloat(i);
901           Record.push_back(I);
902         }
903       } else {
904         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
905         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
906           union { double F; uint64_t I; };
907           F = CDS->getElementAsDouble(i);
908           Record.push_back(I);
909         }
910       }
911     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
912                isa<ConstantVector>(C)) {
913       Code = bitc::CST_CODE_AGGREGATE;
914       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
915         Record.push_back(VE.getValueID(C->getOperand(i)));
916       AbbrevToUse = AggregateAbbrev;
917     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
918       switch (CE->getOpcode()) {
919       default:
920         if (Instruction::isCast(CE->getOpcode())) {
921           Code = bitc::CST_CODE_CE_CAST;
922           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
923           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
924           Record.push_back(VE.getValueID(C->getOperand(0)));
925           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
926         } else {
927           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
928           Code = bitc::CST_CODE_CE_BINOP;
929           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
930           Record.push_back(VE.getValueID(C->getOperand(0)));
931           Record.push_back(VE.getValueID(C->getOperand(1)));
932           uint64_t Flags = GetOptimizationFlags(CE);
933           if (Flags != 0)
934             Record.push_back(Flags);
935         }
936         break;
937       case Instruction::GetElementPtr:
938         Code = bitc::CST_CODE_CE_GEP;
939         if (cast<GEPOperator>(C)->isInBounds())
940           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
941         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
942           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
943           Record.push_back(VE.getValueID(C->getOperand(i)));
944         }
945         break;
946       case Instruction::Select:
947         Code = bitc::CST_CODE_CE_SELECT;
948         Record.push_back(VE.getValueID(C->getOperand(0)));
949         Record.push_back(VE.getValueID(C->getOperand(1)));
950         Record.push_back(VE.getValueID(C->getOperand(2)));
951         break;
952       case Instruction::ExtractElement:
953         Code = bitc::CST_CODE_CE_EXTRACTELT;
954         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
955         Record.push_back(VE.getValueID(C->getOperand(0)));
956         Record.push_back(VE.getValueID(C->getOperand(1)));
957         break;
958       case Instruction::InsertElement:
959         Code = bitc::CST_CODE_CE_INSERTELT;
960         Record.push_back(VE.getValueID(C->getOperand(0)));
961         Record.push_back(VE.getValueID(C->getOperand(1)));
962         Record.push_back(VE.getValueID(C->getOperand(2)));
963         break;
964       case Instruction::ShuffleVector:
965         // If the return type and argument types are the same, this is a
966         // standard shufflevector instruction.  If the types are different,
967         // then the shuffle is widening or truncating the input vectors, and
968         // the argument type must also be encoded.
969         if (C->getType() == C->getOperand(0)->getType()) {
970           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
971         } else {
972           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
973           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
974         }
975         Record.push_back(VE.getValueID(C->getOperand(0)));
976         Record.push_back(VE.getValueID(C->getOperand(1)));
977         Record.push_back(VE.getValueID(C->getOperand(2)));
978         break;
979       case Instruction::ICmp:
980       case Instruction::FCmp:
981         Code = bitc::CST_CODE_CE_CMP;
982         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
983         Record.push_back(VE.getValueID(C->getOperand(0)));
984         Record.push_back(VE.getValueID(C->getOperand(1)));
985         Record.push_back(CE->getPredicate());
986         break;
987       }
988     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
989       Code = bitc::CST_CODE_BLOCKADDRESS;
990       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
991       Record.push_back(VE.getValueID(BA->getFunction()));
992       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
993     } else {
994 #ifndef NDEBUG
995       C->dump();
996 #endif
997       llvm_unreachable("Unknown constant!");
998     }
999     Stream.EmitRecord(Code, Record, AbbrevToUse);
1000     Record.clear();
1001   }
1002
1003   Stream.ExitBlock();
1004 }
1005
1006 static void WriteModuleConstants(const ValueEnumerator &VE,
1007                                  BitstreamWriter &Stream) {
1008   const ValueEnumerator::ValueList &Vals = VE.getValues();
1009
1010   // Find the first constant to emit, which is the first non-globalvalue value.
1011   // We know globalvalues have been emitted by WriteModuleInfo.
1012   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1013     if (!isa<GlobalValue>(Vals[i].first)) {
1014       WriteConstants(i, Vals.size(), VE, Stream, true);
1015       return;
1016     }
1017   }
1018 }
1019
1020 /// PushValueAndType - The file has to encode both the value and type id for
1021 /// many values, because we need to know what type to create for forward
1022 /// references.  However, most operands are not forward references, so this type
1023 /// field is not needed.
1024 ///
1025 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1026 /// instruction ID, then it is a forward reference, and it also includes the
1027 /// type ID.
1028 static bool PushValueAndType(const Value *V, unsigned InstID,
1029                              SmallVector<unsigned, 64> &Vals,
1030                              ValueEnumerator &VE) {
1031   unsigned ValID = VE.getValueID(V);
1032   Vals.push_back(ValID);
1033   if (ValID >= InstID) {
1034     Vals.push_back(VE.getTypeID(V->getType()));
1035     return true;
1036   }
1037   return false;
1038 }
1039
1040 /// WriteInstruction - Emit an instruction to the specified stream.
1041 static void WriteInstruction(const Instruction &I, unsigned InstID,
1042                              ValueEnumerator &VE, BitstreamWriter &Stream,
1043                              SmallVector<unsigned, 64> &Vals) {
1044   unsigned Code = 0;
1045   unsigned AbbrevToUse = 0;
1046   VE.setInstructionID(&I);
1047   switch (I.getOpcode()) {
1048   default:
1049     if (Instruction::isCast(I.getOpcode())) {
1050       Code = bitc::FUNC_CODE_INST_CAST;
1051       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1052         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1053       Vals.push_back(VE.getTypeID(I.getType()));
1054       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1055     } else {
1056       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1057       Code = bitc::FUNC_CODE_INST_BINOP;
1058       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1059         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1060       Vals.push_back(VE.getValueID(I.getOperand(1)));
1061       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1062       uint64_t Flags = GetOptimizationFlags(&I);
1063       if (Flags != 0) {
1064         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1065           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1066         Vals.push_back(Flags);
1067       }
1068     }
1069     break;
1070
1071   case Instruction::GetElementPtr:
1072     Code = bitc::FUNC_CODE_INST_GEP;
1073     if (cast<GEPOperator>(&I)->isInBounds())
1074       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1075     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1076       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1077     break;
1078   case Instruction::ExtractValue: {
1079     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1080     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1081     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1082     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1083       Vals.push_back(*i);
1084     break;
1085   }
1086   case Instruction::InsertValue: {
1087     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1088     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1089     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1090     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1091     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1092       Vals.push_back(*i);
1093     break;
1094   }
1095   case Instruction::Select:
1096     Code = bitc::FUNC_CODE_INST_VSELECT;
1097     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1098     Vals.push_back(VE.getValueID(I.getOperand(2)));
1099     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1100     break;
1101   case Instruction::ExtractElement:
1102     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1103     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1104     Vals.push_back(VE.getValueID(I.getOperand(1)));
1105     break;
1106   case Instruction::InsertElement:
1107     Code = bitc::FUNC_CODE_INST_INSERTELT;
1108     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1109     Vals.push_back(VE.getValueID(I.getOperand(1)));
1110     Vals.push_back(VE.getValueID(I.getOperand(2)));
1111     break;
1112   case Instruction::ShuffleVector:
1113     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1114     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1115     Vals.push_back(VE.getValueID(I.getOperand(1)));
1116     Vals.push_back(VE.getValueID(I.getOperand(2)));
1117     break;
1118   case Instruction::ICmp:
1119   case Instruction::FCmp:
1120     // compare returning Int1Ty or vector of Int1Ty
1121     Code = bitc::FUNC_CODE_INST_CMP2;
1122     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1123     Vals.push_back(VE.getValueID(I.getOperand(1)));
1124     Vals.push_back(cast<CmpInst>(I).getPredicate());
1125     break;
1126
1127   case Instruction::Ret:
1128     {
1129       Code = bitc::FUNC_CODE_INST_RET;
1130       unsigned NumOperands = I.getNumOperands();
1131       if (NumOperands == 0)
1132         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1133       else if (NumOperands == 1) {
1134         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1135           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1136       } else {
1137         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1138           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1139       }
1140     }
1141     break;
1142   case Instruction::Br:
1143     {
1144       Code = bitc::FUNC_CODE_INST_BR;
1145       BranchInst &II = cast<BranchInst>(I);
1146       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1147       if (II.isConditional()) {
1148         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1149         Vals.push_back(VE.getValueID(II.getCondition()));
1150       }
1151     }
1152     break;
1153   case Instruction::Switch:
1154     {
1155       // Redefine Vals, since here we need to use 64 bit values
1156       // explicitly to store large APInt numbers.
1157       SmallVector<uint64_t, 128> Vals64;
1158       
1159       Code = bitc::FUNC_CODE_INST_SWITCH;
1160       SwitchInst &SI = cast<SwitchInst>(I);
1161       
1162       uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16); 
1163       Vals64.push_back(SwitchRecordHeader);      
1164       
1165       Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
1166       Vals64.push_back(VE.getValueID(SI.getCondition()));
1167       Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
1168       Vals64.push_back(SI.getNumCases());
1169       for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1170            i != e; ++i) {
1171         IntegersSubset& CaseRanges = i.getCaseValueEx();
1172         unsigned Code, Abbrev; // will unused.
1173         
1174         if (CaseRanges.isSingleNumber()) {
1175           Vals64.push_back(1/*NumItems = 1*/);
1176           Vals64.push_back(true/*IsSingleNumber = true*/);
1177           EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
1178         } else {
1179           
1180           Vals64.push_back(CaseRanges.getNumItems());
1181           
1182           if (CaseRanges.isSingleNumbersOnly()) {
1183             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1184                  ri != rn; ++ri) {
1185               
1186               Vals64.push_back(true/*IsSingleNumber = true*/);
1187               
1188               EmitAPInt(Vals64, Code, Abbrev,
1189                         CaseRanges.getSingleNumber(ri), true);
1190             }
1191           } else
1192             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1193                  ri != rn; ++ri) {
1194               IntegersSubset::Range r = CaseRanges.getItem(ri);
1195               bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
1196     
1197               Vals64.push_back(IsSingleNumber);
1198               
1199               EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1200               if (!IsSingleNumber)
1201                 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1202             }
1203         }
1204         Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1205       }
1206       
1207       Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1208       
1209       // Also do expected action - clear external Vals collection:
1210       Vals.clear();
1211       return;
1212     }
1213     break;
1214   case Instruction::IndirectBr:
1215     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1216     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1217     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1218       Vals.push_back(VE.getValueID(I.getOperand(i)));
1219     break;
1220       
1221   case Instruction::Invoke: {
1222     const InvokeInst *II = cast<InvokeInst>(&I);
1223     const Value *Callee(II->getCalledValue());
1224     PointerType *PTy = cast<PointerType>(Callee->getType());
1225     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1226     Code = bitc::FUNC_CODE_INST_INVOKE;
1227
1228     Vals.push_back(VE.getAttributeID(II->getAttributes()));
1229     Vals.push_back(II->getCallingConv());
1230     Vals.push_back(VE.getValueID(II->getNormalDest()));
1231     Vals.push_back(VE.getValueID(II->getUnwindDest()));
1232     PushValueAndType(Callee, InstID, Vals, VE);
1233
1234     // Emit value #'s for the fixed parameters.
1235     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1236       Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
1237
1238     // Emit type/value pairs for varargs params.
1239     if (FTy->isVarArg()) {
1240       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1241            i != e; ++i)
1242         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1243     }
1244     break;
1245   }
1246   case Instruction::Resume:
1247     Code = bitc::FUNC_CODE_INST_RESUME;
1248     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1249     break;
1250   case Instruction::Unreachable:
1251     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1252     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1253     break;
1254
1255   case Instruction::PHI: {
1256     const PHINode &PN = cast<PHINode>(I);
1257     Code = bitc::FUNC_CODE_INST_PHI;
1258     Vals.push_back(VE.getTypeID(PN.getType()));
1259     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1260       Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1261       Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1262     }
1263     break;
1264   }
1265
1266   case Instruction::LandingPad: {
1267     const LandingPadInst &LP = cast<LandingPadInst>(I);
1268     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1269     Vals.push_back(VE.getTypeID(LP.getType()));
1270     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1271     Vals.push_back(LP.isCleanup());
1272     Vals.push_back(LP.getNumClauses());
1273     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1274       if (LP.isCatch(I))
1275         Vals.push_back(LandingPadInst::Catch);
1276       else
1277         Vals.push_back(LandingPadInst::Filter);
1278       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1279     }
1280     break;
1281   }
1282
1283   case Instruction::Alloca:
1284     Code = bitc::FUNC_CODE_INST_ALLOCA;
1285     Vals.push_back(VE.getTypeID(I.getType()));
1286     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1287     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1288     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1289     break;
1290
1291   case Instruction::Load:
1292     if (cast<LoadInst>(I).isAtomic()) {
1293       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1294       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1295     } else {
1296       Code = bitc::FUNC_CODE_INST_LOAD;
1297       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1298         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1299     }
1300     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1301     Vals.push_back(cast<LoadInst>(I).isVolatile());
1302     if (cast<LoadInst>(I).isAtomic()) {
1303       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1304       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1305     }
1306     break;
1307   case Instruction::Store:
1308     if (cast<StoreInst>(I).isAtomic())
1309       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1310     else
1311       Code = bitc::FUNC_CODE_INST_STORE;
1312     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1313     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
1314     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1315     Vals.push_back(cast<StoreInst>(I).isVolatile());
1316     if (cast<StoreInst>(I).isAtomic()) {
1317       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1318       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1319     }
1320     break;
1321   case Instruction::AtomicCmpXchg:
1322     Code = bitc::FUNC_CODE_INST_CMPXCHG;
1323     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1324     Vals.push_back(VE.getValueID(I.getOperand(1)));       // cmp.
1325     Vals.push_back(VE.getValueID(I.getOperand(2)));       // newval.
1326     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1327     Vals.push_back(GetEncodedOrdering(
1328                      cast<AtomicCmpXchgInst>(I).getOrdering()));
1329     Vals.push_back(GetEncodedSynchScope(
1330                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
1331     break;
1332   case Instruction::AtomicRMW:
1333     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1334     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1335     Vals.push_back(VE.getValueID(I.getOperand(1)));       // val.
1336     Vals.push_back(GetEncodedRMWOperation(
1337                      cast<AtomicRMWInst>(I).getOperation()));
1338     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1339     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1340     Vals.push_back(GetEncodedSynchScope(
1341                      cast<AtomicRMWInst>(I).getSynchScope()));
1342     break;
1343   case Instruction::Fence:
1344     Code = bitc::FUNC_CODE_INST_FENCE;
1345     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1346     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1347     break;
1348   case Instruction::Call: {
1349     const CallInst &CI = cast<CallInst>(I);
1350     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1351     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1352
1353     Code = bitc::FUNC_CODE_INST_CALL;
1354
1355     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1356     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1357     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
1358
1359     // Emit value #'s for the fixed parameters.
1360     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1361       Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
1362
1363     // Emit type/value pairs for varargs params.
1364     if (FTy->isVarArg()) {
1365       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1366            i != e; ++i)
1367         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
1368     }
1369     break;
1370   }
1371   case Instruction::VAArg:
1372     Code = bitc::FUNC_CODE_INST_VAARG;
1373     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
1374     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1375     Vals.push_back(VE.getTypeID(I.getType())); // restype.
1376     break;
1377   }
1378
1379   Stream.EmitRecord(Code, Vals, AbbrevToUse);
1380   Vals.clear();
1381 }
1382
1383 // Emit names for globals/functions etc.
1384 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1385                                   const ValueEnumerator &VE,
1386                                   BitstreamWriter &Stream) {
1387   if (VST.empty()) return;
1388   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1389
1390   // FIXME: Set up the abbrev, we know how many values there are!
1391   // FIXME: We know if the type names can use 7-bit ascii.
1392   SmallVector<unsigned, 64> NameVals;
1393
1394   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1395        SI != SE; ++SI) {
1396
1397     const ValueName &Name = *SI;
1398
1399     // Figure out the encoding to use for the name.
1400     bool is7Bit = true;
1401     bool isChar6 = true;
1402     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1403          C != E; ++C) {
1404       if (isChar6)
1405         isChar6 = BitCodeAbbrevOp::isChar6(*C);
1406       if ((unsigned char)*C & 128) {
1407         is7Bit = false;
1408         break;  // don't bother scanning the rest.
1409       }
1410     }
1411
1412     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1413
1414     // VST_ENTRY:   [valueid, namechar x N]
1415     // VST_BBENTRY: [bbid, namechar x N]
1416     unsigned Code;
1417     if (isa<BasicBlock>(SI->getValue())) {
1418       Code = bitc::VST_CODE_BBENTRY;
1419       if (isChar6)
1420         AbbrevToUse = VST_BBENTRY_6_ABBREV;
1421     } else {
1422       Code = bitc::VST_CODE_ENTRY;
1423       if (isChar6)
1424         AbbrevToUse = VST_ENTRY_6_ABBREV;
1425       else if (is7Bit)
1426         AbbrevToUse = VST_ENTRY_7_ABBREV;
1427     }
1428
1429     NameVals.push_back(VE.getValueID(SI->getValue()));
1430     for (const char *P = Name.getKeyData(),
1431          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1432       NameVals.push_back((unsigned char)*P);
1433
1434     // Emit the finished record.
1435     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1436     NameVals.clear();
1437   }
1438   Stream.ExitBlock();
1439 }
1440
1441 /// WriteFunction - Emit a function body to the module stream.
1442 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1443                           BitstreamWriter &Stream) {
1444   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1445   VE.incorporateFunction(F);
1446
1447   SmallVector<unsigned, 64> Vals;
1448
1449   // Emit the number of basic blocks, so the reader can create them ahead of
1450   // time.
1451   Vals.push_back(VE.getBasicBlocks().size());
1452   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1453   Vals.clear();
1454
1455   // If there are function-local constants, emit them now.
1456   unsigned CstStart, CstEnd;
1457   VE.getFunctionConstantRange(CstStart, CstEnd);
1458   WriteConstants(CstStart, CstEnd, VE, Stream, false);
1459
1460   // If there is function-local metadata, emit it now.
1461   WriteFunctionLocalMetadata(F, VE, Stream);
1462
1463   // Keep a running idea of what the instruction ID is.
1464   unsigned InstID = CstEnd;
1465
1466   bool NeedsMetadataAttachment = false;
1467   
1468   DebugLoc LastDL;
1469   
1470   // Finally, emit all the instructions, in order.
1471   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1472     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1473          I != E; ++I) {
1474       WriteInstruction(*I, InstID, VE, Stream, Vals);
1475       
1476       if (!I->getType()->isVoidTy())
1477         ++InstID;
1478       
1479       // If the instruction has metadata, write a metadata attachment later.
1480       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1481       
1482       // If the instruction has a debug location, emit it.
1483       DebugLoc DL = I->getDebugLoc();
1484       if (DL.isUnknown()) {
1485         // nothing todo.
1486       } else if (DL == LastDL) {
1487         // Just repeat the same debug loc as last time.
1488         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1489       } else {
1490         MDNode *Scope, *IA;
1491         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1492         
1493         Vals.push_back(DL.getLine());
1494         Vals.push_back(DL.getCol());
1495         Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1496         Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1497         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1498         Vals.clear();
1499         
1500         LastDL = DL;
1501       }
1502     }
1503
1504   // Emit names for all the instructions etc.
1505   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1506
1507   if (NeedsMetadataAttachment)
1508     WriteMetadataAttachment(F, VE, Stream);
1509   VE.purgeFunction();
1510   Stream.ExitBlock();
1511 }
1512
1513 // Emit blockinfo, which defines the standard abbreviations etc.
1514 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1515   // We only want to emit block info records for blocks that have multiple
1516   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1517   // blocks can defined their abbrevs inline.
1518   Stream.EnterBlockInfoBlock(2);
1519
1520   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1521     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1522     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1523     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1524     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1525     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1526     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1527                                    Abbv) != VST_ENTRY_8_ABBREV)
1528       llvm_unreachable("Unexpected abbrev ordering!");
1529   }
1530
1531   { // 7-bit fixed width VST_ENTRY strings.
1532     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1533     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1534     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1535     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1536     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1537     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1538                                    Abbv) != VST_ENTRY_7_ABBREV)
1539       llvm_unreachable("Unexpected abbrev ordering!");
1540   }
1541   { // 6-bit char6 VST_ENTRY strings.
1542     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1543     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1544     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1545     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1546     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1547     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1548                                    Abbv) != VST_ENTRY_6_ABBREV)
1549       llvm_unreachable("Unexpected abbrev ordering!");
1550   }
1551   { // 6-bit char6 VST_BBENTRY strings.
1552     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1553     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1554     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1555     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1556     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1557     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1558                                    Abbv) != VST_BBENTRY_6_ABBREV)
1559       llvm_unreachable("Unexpected abbrev ordering!");
1560   }
1561
1562
1563
1564   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1565     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1566     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1567     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1568                               Log2_32_Ceil(VE.getTypes().size()+1)));
1569     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1570                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1571       llvm_unreachable("Unexpected abbrev ordering!");
1572   }
1573
1574   { // INTEGER abbrev for CONSTANTS_BLOCK.
1575     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1576     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1577     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1578     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1579                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1580       llvm_unreachable("Unexpected abbrev ordering!");
1581   }
1582
1583   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1584     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1585     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1586     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1587     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1588                               Log2_32_Ceil(VE.getTypes().size()+1)));
1589     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1590
1591     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1592                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1593       llvm_unreachable("Unexpected abbrev ordering!");
1594   }
1595   { // NULL abbrev for CONSTANTS_BLOCK.
1596     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1597     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1598     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1599                                    Abbv) != CONSTANTS_NULL_Abbrev)
1600       llvm_unreachable("Unexpected abbrev ordering!");
1601   }
1602
1603   // FIXME: This should only use space for first class types!
1604
1605   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1606     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1607     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1608     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1609     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1610     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1611     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1612                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1613       llvm_unreachable("Unexpected abbrev ordering!");
1614   }
1615   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1616     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1617     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1618     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1619     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1620     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1621     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1622                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1623       llvm_unreachable("Unexpected abbrev ordering!");
1624   }
1625   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1626     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1627     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1628     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1629     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1630     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1631     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1632     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1633                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1634       llvm_unreachable("Unexpected abbrev ordering!");
1635   }
1636   { // INST_CAST abbrev for FUNCTION_BLOCK.
1637     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1638     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1639     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1640     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1641                               Log2_32_Ceil(VE.getTypes().size()+1)));
1642     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1643     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1644                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1645       llvm_unreachable("Unexpected abbrev ordering!");
1646   }
1647
1648   { // INST_RET abbrev for FUNCTION_BLOCK.
1649     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1650     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1651     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1652                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1653       llvm_unreachable("Unexpected abbrev ordering!");
1654   }
1655   { // INST_RET abbrev for FUNCTION_BLOCK.
1656     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1657     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1658     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1659     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1660                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1661       llvm_unreachable("Unexpected abbrev ordering!");
1662   }
1663   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1664     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1665     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1666     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1667                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1668       llvm_unreachable("Unexpected abbrev ordering!");
1669   }
1670
1671   Stream.ExitBlock();
1672 }
1673
1674 // Sort the Users based on the order in which the reader parses the bitcode 
1675 // file.
1676 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1677   // TODO: Implement.
1678   return true;
1679 }
1680
1681 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1682                          BitstreamWriter &Stream) {
1683
1684   // One or zero uses can't get out of order.
1685   if (V->use_empty() || V->hasNUses(1))
1686     return;
1687
1688   // Make a copy of the in-memory use-list for sorting.
1689   unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1690   SmallVector<const User*, 8> UseList;
1691   UseList.reserve(UseListSize);
1692   for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1693        I != E; ++I) {
1694     const User *U = *I;
1695     UseList.push_back(U);
1696   }
1697
1698   // Sort the copy based on the order read by the BitcodeReader.
1699   std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1700
1701   // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1702   // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1703
1704   // TODO: Emit the USELIST_CODE_ENTRYs.
1705 }
1706
1707 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1708                                  BitstreamWriter &Stream) {
1709   VE.incorporateFunction(*F);
1710
1711   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1712        AI != AE; ++AI)
1713     WriteUseList(AI, VE, Stream);
1714   for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1715        ++BB) {
1716     WriteUseList(BB, VE, Stream);
1717     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1718          ++II) {
1719       WriteUseList(II, VE, Stream);
1720       for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1721            OI != E; ++OI) {
1722         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1723             isa<InlineAsm>(*OI))
1724           WriteUseList(*OI, VE, Stream);
1725       }
1726     }
1727   }
1728   VE.purgeFunction();
1729 }
1730
1731 // Emit use-lists.
1732 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1733                                 BitstreamWriter &Stream) {
1734   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1735
1736   // XXX: this modifies the module, but in a way that should never change the
1737   // behavior of any pass or codegen in LLVM. The problem is that GVs may
1738   // contain entries in the use_list that do not exist in the Module and are
1739   // not stored in the .bc file.
1740   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1741        I != E; ++I)
1742     I->removeDeadConstantUsers();
1743   
1744   // Write the global variables.
1745   for (Module::const_global_iterator GI = M->global_begin(), 
1746          GE = M->global_end(); GI != GE; ++GI) {
1747     WriteUseList(GI, VE, Stream);
1748
1749     // Write the global variable initializers.
1750     if (GI->hasInitializer())
1751       WriteUseList(GI->getInitializer(), VE, Stream);
1752   }
1753
1754   // Write the functions.
1755   for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1756     WriteUseList(FI, VE, Stream);
1757     if (!FI->isDeclaration())
1758       WriteFunctionUseList(FI, VE, Stream);
1759   }
1760
1761   // Write the aliases.
1762   for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1763        AI != AE; ++AI) {
1764     WriteUseList(AI, VE, Stream);
1765     WriteUseList(AI->getAliasee(), VE, Stream);
1766   }
1767
1768   Stream.ExitBlock();
1769 }
1770
1771 /// WriteModule - Emit the specified module to the bitstream.
1772 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1773   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1774
1775   // Emit the version number if it is non-zero.
1776   if (CurVersion) {
1777     SmallVector<unsigned, 1> Vals;
1778     Vals.push_back(CurVersion);
1779     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1780   }
1781
1782   // Analyze the module, enumerating globals, functions, etc.
1783   ValueEnumerator VE(M);
1784
1785   // Emit blockinfo, which defines the standard abbreviations etc.
1786   WriteBlockInfo(VE, Stream);
1787
1788   // Emit information about parameter attributes.
1789   WriteAttributeTable(VE, Stream);
1790
1791   // Emit information describing all of the types in the module.
1792   WriteTypeTable(VE, Stream);
1793
1794   // Emit top-level description of module, including target triple, inline asm,
1795   // descriptors for global variables, and function prototype info.
1796   WriteModuleInfo(M, VE, Stream);
1797
1798   // Emit constants.
1799   WriteModuleConstants(VE, Stream);
1800
1801   // Emit metadata.
1802   WriteModuleMetadata(M, VE, Stream);
1803
1804   // Emit metadata.
1805   WriteModuleMetadataStore(M, Stream);
1806
1807   // Emit names for globals/functions etc.
1808   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1809
1810   // Emit use-lists.
1811   if (EnablePreserveUseListOrdering)
1812     WriteModuleUseLists(M, VE, Stream);
1813
1814   // Emit function bodies.
1815   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1816     if (!F->isDeclaration())
1817       WriteFunction(*F, VE, Stream);
1818
1819   Stream.ExitBlock();
1820 }
1821
1822 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1823 /// header and trailer to make it compatible with the system archiver.  To do
1824 /// this we emit the following header, and then emit a trailer that pads the
1825 /// file out to be a multiple of 16 bytes.
1826 ///
1827 /// struct bc_header {
1828 ///   uint32_t Magic;         // 0x0B17C0DE
1829 ///   uint32_t Version;       // Version, currently always 0.
1830 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1831 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1832 ///   uint32_t CPUType;       // CPU specifier.
1833 ///   ... potentially more later ...
1834 /// };
1835 enum {
1836   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1837   DarwinBCHeaderSize = 5*4
1838 };
1839
1840 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1841                                uint32_t &Position) {
1842   Buffer[Position + 0] = (unsigned char) (Value >>  0);
1843   Buffer[Position + 1] = (unsigned char) (Value >>  8);
1844   Buffer[Position + 2] = (unsigned char) (Value >> 16);
1845   Buffer[Position + 3] = (unsigned char) (Value >> 24);
1846   Position += 4;
1847 }
1848
1849 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1850                                          const Triple &TT) {
1851   unsigned CPUType = ~0U;
1852
1853   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1854   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1855   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
1856   // specific constants here because they are implicitly part of the Darwin ABI.
1857   enum {
1858     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
1859     DARWIN_CPU_TYPE_X86        = 7,
1860     DARWIN_CPU_TYPE_ARM        = 12,
1861     DARWIN_CPU_TYPE_POWERPC    = 18
1862   };
1863
1864   Triple::ArchType Arch = TT.getArch();
1865   if (Arch == Triple::x86_64)
1866     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1867   else if (Arch == Triple::x86)
1868     CPUType = DARWIN_CPU_TYPE_X86;
1869   else if (Arch == Triple::ppc)
1870     CPUType = DARWIN_CPU_TYPE_POWERPC;
1871   else if (Arch == Triple::ppc64)
1872     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1873   else if (Arch == Triple::arm || Arch == Triple::thumb)
1874     CPUType = DARWIN_CPU_TYPE_ARM;
1875
1876   // Traditional Bitcode starts after header.
1877   assert(Buffer.size() >= DarwinBCHeaderSize &&
1878          "Expected header size to be reserved");
1879   unsigned BCOffset = DarwinBCHeaderSize;
1880   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1881
1882   // Write the magic and version.
1883   unsigned Position = 0;
1884   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1885   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
1886   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
1887   WriteInt32ToBuffer(BCSize     , Buffer, Position);
1888   WriteInt32ToBuffer(CPUType    , Buffer, Position);
1889
1890   // If the file is not a multiple of 16 bytes, insert dummy padding.
1891   while (Buffer.size() & 15)
1892     Buffer.push_back(0);
1893 }
1894
1895 /// WriteBitcodeToFile - Write the specified module to the specified output
1896 /// stream.
1897 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1898   SmallVector<char, 1024> Buffer;
1899   Buffer.reserve(256*1024);
1900
1901   // If this is darwin or another generic macho target, reserve space for the
1902   // header.
1903   Triple TT(M->getTargetTriple());
1904   if (TT.isOSDarwin())
1905     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1906
1907   // Emit the module into the buffer.
1908   {
1909     BitstreamWriter Stream(Buffer);
1910
1911     // Emit the file header.
1912     Stream.Emit((unsigned)'B', 8);
1913     Stream.Emit((unsigned)'C', 8);
1914     Stream.Emit(0x0, 4);
1915     Stream.Emit(0xC, 4);
1916     Stream.Emit(0xE, 4);
1917     Stream.Emit(0xD, 4);
1918
1919     // Emit the module.
1920     WriteModule(M, Stream);
1921   }
1922
1923   if (TT.isOSDarwin())
1924     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1925
1926   // Write the generated bitstream to "Out".
1927   Out.write((char*)&Buffer.front(), Buffer.size());
1928 }