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