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