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