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