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