Optimized usage of new SwitchInst case values (IntegersSubset type) in Local.cpp...
[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         unsigned Code, Abbrev; // will unused.
1162         
1163         if (CaseRanges.isSingleNumber()) {
1164           Vals64.push_back(1/*NumItems = 1*/);
1165           Vals64.push_back(true/*IsSingleNumber = true*/);
1166           EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
1167         } else {
1168           
1169           Vals64.push_back(CaseRanges.getNumItems());
1170           
1171           if (CaseRanges.isSingleNumbersOnly()) {
1172             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1173                  ri != rn; ++ri) {
1174               
1175               Vals64.push_back(true/*IsSingleNumber = true*/);
1176               
1177               EmitAPInt(Vals64, Code, Abbrev,
1178                         CaseRanges.getSingleNumber(ri), true);
1179             }
1180           } else
1181             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1182                  ri != rn; ++ri) {
1183               IntegersSubset::Range r = CaseRanges.getItem(ri);
1184               bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
1185     
1186               Vals64.push_back(IsSingleNumber);
1187               
1188               EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1189               if (!IsSingleNumber)
1190                 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1191             }
1192         }
1193         Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1194       }
1195       
1196       Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1197       
1198       // Also do expected action - clear external Vals collection:
1199       Vals.clear();
1200       return;
1201     }
1202     break;
1203   case Instruction::IndirectBr:
1204     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1205     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1206     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1207       Vals.push_back(VE.getValueID(I.getOperand(i)));
1208     break;
1209       
1210   case Instruction::Invoke: {
1211     const InvokeInst *II = cast<InvokeInst>(&I);
1212     const Value *Callee(II->getCalledValue());
1213     PointerType *PTy = cast<PointerType>(Callee->getType());
1214     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1215     Code = bitc::FUNC_CODE_INST_INVOKE;
1216
1217     Vals.push_back(VE.getAttributeID(II->getAttributes()));
1218     Vals.push_back(II->getCallingConv());
1219     Vals.push_back(VE.getValueID(II->getNormalDest()));
1220     Vals.push_back(VE.getValueID(II->getUnwindDest()));
1221     PushValueAndType(Callee, InstID, Vals, VE);
1222
1223     // Emit value #'s for the fixed parameters.
1224     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1225       Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
1226
1227     // Emit type/value pairs for varargs params.
1228     if (FTy->isVarArg()) {
1229       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1230            i != e; ++i)
1231         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1232     }
1233     break;
1234   }
1235   case Instruction::Resume:
1236     Code = bitc::FUNC_CODE_INST_RESUME;
1237     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1238     break;
1239   case Instruction::Unreachable:
1240     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1241     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1242     break;
1243
1244   case Instruction::PHI: {
1245     const PHINode &PN = cast<PHINode>(I);
1246     Code = bitc::FUNC_CODE_INST_PHI;
1247     Vals.push_back(VE.getTypeID(PN.getType()));
1248     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1249       Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1250       Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1251     }
1252     break;
1253   }
1254
1255   case Instruction::LandingPad: {
1256     const LandingPadInst &LP = cast<LandingPadInst>(I);
1257     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1258     Vals.push_back(VE.getTypeID(LP.getType()));
1259     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1260     Vals.push_back(LP.isCleanup());
1261     Vals.push_back(LP.getNumClauses());
1262     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1263       if (LP.isCatch(I))
1264         Vals.push_back(LandingPadInst::Catch);
1265       else
1266         Vals.push_back(LandingPadInst::Filter);
1267       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1268     }
1269     break;
1270   }
1271
1272   case Instruction::Alloca:
1273     Code = bitc::FUNC_CODE_INST_ALLOCA;
1274     Vals.push_back(VE.getTypeID(I.getType()));
1275     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1276     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1277     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1278     break;
1279
1280   case Instruction::Load:
1281     if (cast<LoadInst>(I).isAtomic()) {
1282       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1283       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1284     } else {
1285       Code = bitc::FUNC_CODE_INST_LOAD;
1286       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1287         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1288     }
1289     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1290     Vals.push_back(cast<LoadInst>(I).isVolatile());
1291     if (cast<LoadInst>(I).isAtomic()) {
1292       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1293       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1294     }
1295     break;
1296   case Instruction::Store:
1297     if (cast<StoreInst>(I).isAtomic())
1298       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1299     else
1300       Code = bitc::FUNC_CODE_INST_STORE;
1301     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1302     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
1303     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1304     Vals.push_back(cast<StoreInst>(I).isVolatile());
1305     if (cast<StoreInst>(I).isAtomic()) {
1306       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1307       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1308     }
1309     break;
1310   case Instruction::AtomicCmpXchg:
1311     Code = bitc::FUNC_CODE_INST_CMPXCHG;
1312     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1313     Vals.push_back(VE.getValueID(I.getOperand(1)));       // cmp.
1314     Vals.push_back(VE.getValueID(I.getOperand(2)));       // newval.
1315     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1316     Vals.push_back(GetEncodedOrdering(
1317                      cast<AtomicCmpXchgInst>(I).getOrdering()));
1318     Vals.push_back(GetEncodedSynchScope(
1319                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
1320     break;
1321   case Instruction::AtomicRMW:
1322     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1323     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1324     Vals.push_back(VE.getValueID(I.getOperand(1)));       // val.
1325     Vals.push_back(GetEncodedRMWOperation(
1326                      cast<AtomicRMWInst>(I).getOperation()));
1327     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1328     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1329     Vals.push_back(GetEncodedSynchScope(
1330                      cast<AtomicRMWInst>(I).getSynchScope()));
1331     break;
1332   case Instruction::Fence:
1333     Code = bitc::FUNC_CODE_INST_FENCE;
1334     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1335     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1336     break;
1337   case Instruction::Call: {
1338     const CallInst &CI = cast<CallInst>(I);
1339     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1340     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1341
1342     Code = bitc::FUNC_CODE_INST_CALL;
1343
1344     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1345     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1346     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
1347
1348     // Emit value #'s for the fixed parameters.
1349     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1350       Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
1351
1352     // Emit type/value pairs for varargs params.
1353     if (FTy->isVarArg()) {
1354       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1355            i != e; ++i)
1356         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
1357     }
1358     break;
1359   }
1360   case Instruction::VAArg:
1361     Code = bitc::FUNC_CODE_INST_VAARG;
1362     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
1363     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1364     Vals.push_back(VE.getTypeID(I.getType())); // restype.
1365     break;
1366   }
1367
1368   Stream.EmitRecord(Code, Vals, AbbrevToUse);
1369   Vals.clear();
1370 }
1371
1372 // Emit names for globals/functions etc.
1373 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1374                                   const ValueEnumerator &VE,
1375                                   BitstreamWriter &Stream) {
1376   if (VST.empty()) return;
1377   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1378
1379   // FIXME: Set up the abbrev, we know how many values there are!
1380   // FIXME: We know if the type names can use 7-bit ascii.
1381   SmallVector<unsigned, 64> NameVals;
1382
1383   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1384        SI != SE; ++SI) {
1385
1386     const ValueName &Name = *SI;
1387
1388     // Figure out the encoding to use for the name.
1389     bool is7Bit = true;
1390     bool isChar6 = true;
1391     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1392          C != E; ++C) {
1393       if (isChar6)
1394         isChar6 = BitCodeAbbrevOp::isChar6(*C);
1395       if ((unsigned char)*C & 128) {
1396         is7Bit = false;
1397         break;  // don't bother scanning the rest.
1398       }
1399     }
1400
1401     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1402
1403     // VST_ENTRY:   [valueid, namechar x N]
1404     // VST_BBENTRY: [bbid, namechar x N]
1405     unsigned Code;
1406     if (isa<BasicBlock>(SI->getValue())) {
1407       Code = bitc::VST_CODE_BBENTRY;
1408       if (isChar6)
1409         AbbrevToUse = VST_BBENTRY_6_ABBREV;
1410     } else {
1411       Code = bitc::VST_CODE_ENTRY;
1412       if (isChar6)
1413         AbbrevToUse = VST_ENTRY_6_ABBREV;
1414       else if (is7Bit)
1415         AbbrevToUse = VST_ENTRY_7_ABBREV;
1416     }
1417
1418     NameVals.push_back(VE.getValueID(SI->getValue()));
1419     for (const char *P = Name.getKeyData(),
1420          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1421       NameVals.push_back((unsigned char)*P);
1422
1423     // Emit the finished record.
1424     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1425     NameVals.clear();
1426   }
1427   Stream.ExitBlock();
1428 }
1429
1430 /// WriteFunction - Emit a function body to the module stream.
1431 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1432                           BitstreamWriter &Stream) {
1433   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1434   VE.incorporateFunction(F);
1435
1436   SmallVector<unsigned, 64> Vals;
1437
1438   // Emit the number of basic blocks, so the reader can create them ahead of
1439   // time.
1440   Vals.push_back(VE.getBasicBlocks().size());
1441   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1442   Vals.clear();
1443
1444   // If there are function-local constants, emit them now.
1445   unsigned CstStart, CstEnd;
1446   VE.getFunctionConstantRange(CstStart, CstEnd);
1447   WriteConstants(CstStart, CstEnd, VE, Stream, false);
1448
1449   // If there is function-local metadata, emit it now.
1450   WriteFunctionLocalMetadata(F, VE, Stream);
1451
1452   // Keep a running idea of what the instruction ID is.
1453   unsigned InstID = CstEnd;
1454
1455   bool NeedsMetadataAttachment = false;
1456   
1457   DebugLoc LastDL;
1458   
1459   // Finally, emit all the instructions, in order.
1460   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1461     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1462          I != E; ++I) {
1463       WriteInstruction(*I, InstID, VE, Stream, Vals);
1464       
1465       if (!I->getType()->isVoidTy())
1466         ++InstID;
1467       
1468       // If the instruction has metadata, write a metadata attachment later.
1469       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1470       
1471       // If the instruction has a debug location, emit it.
1472       DebugLoc DL = I->getDebugLoc();
1473       if (DL.isUnknown()) {
1474         // nothing todo.
1475       } else if (DL == LastDL) {
1476         // Just repeat the same debug loc as last time.
1477         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1478       } else {
1479         MDNode *Scope, *IA;
1480         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1481         
1482         Vals.push_back(DL.getLine());
1483         Vals.push_back(DL.getCol());
1484         Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1485         Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1486         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1487         Vals.clear();
1488         
1489         LastDL = DL;
1490       }
1491     }
1492
1493   // Emit names for all the instructions etc.
1494   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1495
1496   if (NeedsMetadataAttachment)
1497     WriteMetadataAttachment(F, VE, Stream);
1498   VE.purgeFunction();
1499   Stream.ExitBlock();
1500 }
1501
1502 // Emit blockinfo, which defines the standard abbreviations etc.
1503 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1504   // We only want to emit block info records for blocks that have multiple
1505   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1506   // blocks can defined their abbrevs inline.
1507   Stream.EnterBlockInfoBlock(2);
1508
1509   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1510     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1511     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1512     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1513     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1514     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1515     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1516                                    Abbv) != VST_ENTRY_8_ABBREV)
1517       llvm_unreachable("Unexpected abbrev ordering!");
1518   }
1519
1520   { // 7-bit fixed width VST_ENTRY strings.
1521     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1522     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1523     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1524     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1525     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1526     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1527                                    Abbv) != VST_ENTRY_7_ABBREV)
1528       llvm_unreachable("Unexpected abbrev ordering!");
1529   }
1530   { // 6-bit char6 VST_ENTRY strings.
1531     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1532     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1533     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1534     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1535     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1536     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1537                                    Abbv) != VST_ENTRY_6_ABBREV)
1538       llvm_unreachable("Unexpected abbrev ordering!");
1539   }
1540   { // 6-bit char6 VST_BBENTRY strings.
1541     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1542     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1543     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1544     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1545     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1546     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1547                                    Abbv) != VST_BBENTRY_6_ABBREV)
1548       llvm_unreachable("Unexpected abbrev ordering!");
1549   }
1550
1551
1552
1553   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1554     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1555     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1556     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1557                               Log2_32_Ceil(VE.getTypes().size()+1)));
1558     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1559                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1560       llvm_unreachable("Unexpected abbrev ordering!");
1561   }
1562
1563   { // INTEGER abbrev for CONSTANTS_BLOCK.
1564     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1565     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1566     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1567     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1568                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1569       llvm_unreachable("Unexpected abbrev ordering!");
1570   }
1571
1572   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1573     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1574     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1575     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1576     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1577                               Log2_32_Ceil(VE.getTypes().size()+1)));
1578     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1579
1580     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1581                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1582       llvm_unreachable("Unexpected abbrev ordering!");
1583   }
1584   { // NULL abbrev for CONSTANTS_BLOCK.
1585     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1586     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1587     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1588                                    Abbv) != CONSTANTS_NULL_Abbrev)
1589       llvm_unreachable("Unexpected abbrev ordering!");
1590   }
1591
1592   // FIXME: This should only use space for first class types!
1593
1594   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1595     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1596     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1597     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1598     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1599     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1600     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1601                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1602       llvm_unreachable("Unexpected abbrev ordering!");
1603   }
1604   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1605     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1606     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1607     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1608     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1609     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1610     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1611                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1612       llvm_unreachable("Unexpected abbrev ordering!");
1613   }
1614   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1615     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1616     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1617     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1618     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1619     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1620     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1621     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1622                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1623       llvm_unreachable("Unexpected abbrev ordering!");
1624   }
1625   { // INST_CAST abbrev for FUNCTION_BLOCK.
1626     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1627     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1628     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1629     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1630                               Log2_32_Ceil(VE.getTypes().size()+1)));
1631     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1632     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1633                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1634       llvm_unreachable("Unexpected abbrev ordering!");
1635   }
1636
1637   { // INST_RET abbrev for FUNCTION_BLOCK.
1638     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1639     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1640     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1641                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1642       llvm_unreachable("Unexpected abbrev ordering!");
1643   }
1644   { // INST_RET abbrev for FUNCTION_BLOCK.
1645     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1646     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1647     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1648     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1649                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1650       llvm_unreachable("Unexpected abbrev ordering!");
1651   }
1652   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1653     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1654     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1655     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1656                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1657       llvm_unreachable("Unexpected abbrev ordering!");
1658   }
1659
1660   Stream.ExitBlock();
1661 }
1662
1663 // Sort the Users based on the order in which the reader parses the bitcode 
1664 // file.
1665 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1666   // TODO: Implement.
1667   return true;
1668 }
1669
1670 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1671                          BitstreamWriter &Stream) {
1672
1673   // One or zero uses can't get out of order.
1674   if (V->use_empty() || V->hasNUses(1))
1675     return;
1676
1677   // Make a copy of the in-memory use-list for sorting.
1678   unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1679   SmallVector<const User*, 8> UseList;
1680   UseList.reserve(UseListSize);
1681   for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1682        I != E; ++I) {
1683     const User *U = *I;
1684     UseList.push_back(U);
1685   }
1686
1687   // Sort the copy based on the order read by the BitcodeReader.
1688   std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1689
1690   // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1691   // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1692
1693   // TODO: Emit the USELIST_CODE_ENTRYs.
1694 }
1695
1696 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1697                                  BitstreamWriter &Stream) {
1698   VE.incorporateFunction(*F);
1699
1700   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1701        AI != AE; ++AI)
1702     WriteUseList(AI, VE, Stream);
1703   for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1704        ++BB) {
1705     WriteUseList(BB, VE, Stream);
1706     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1707          ++II) {
1708       WriteUseList(II, VE, Stream);
1709       for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1710            OI != E; ++OI) {
1711         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1712             isa<InlineAsm>(*OI))
1713           WriteUseList(*OI, VE, Stream);
1714       }
1715     }
1716   }
1717   VE.purgeFunction();
1718 }
1719
1720 // Emit use-lists.
1721 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1722                                 BitstreamWriter &Stream) {
1723   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1724
1725   // XXX: this modifies the module, but in a way that should never change the
1726   // behavior of any pass or codegen in LLVM. The problem is that GVs may
1727   // contain entries in the use_list that do not exist in the Module and are
1728   // not stored in the .bc file.
1729   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1730        I != E; ++I)
1731     I->removeDeadConstantUsers();
1732   
1733   // Write the global variables.
1734   for (Module::const_global_iterator GI = M->global_begin(), 
1735          GE = M->global_end(); GI != GE; ++GI) {
1736     WriteUseList(GI, VE, Stream);
1737
1738     // Write the global variable initializers.
1739     if (GI->hasInitializer())
1740       WriteUseList(GI->getInitializer(), VE, Stream);
1741   }
1742
1743   // Write the functions.
1744   for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1745     WriteUseList(FI, VE, Stream);
1746     if (!FI->isDeclaration())
1747       WriteFunctionUseList(FI, VE, Stream);
1748   }
1749
1750   // Write the aliases.
1751   for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1752        AI != AE; ++AI) {
1753     WriteUseList(AI, VE, Stream);
1754     WriteUseList(AI->getAliasee(), VE, Stream);
1755   }
1756
1757   Stream.ExitBlock();
1758 }
1759
1760 /// WriteModule - Emit the specified module to the bitstream.
1761 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1762   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1763
1764   // Emit the version number if it is non-zero.
1765   if (CurVersion) {
1766     SmallVector<unsigned, 1> Vals;
1767     Vals.push_back(CurVersion);
1768     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1769   }
1770
1771   // Analyze the module, enumerating globals, functions, etc.
1772   ValueEnumerator VE(M);
1773
1774   // Emit blockinfo, which defines the standard abbreviations etc.
1775   WriteBlockInfo(VE, Stream);
1776
1777   // Emit information about parameter attributes.
1778   WriteAttributeTable(VE, Stream);
1779
1780   // Emit information describing all of the types in the module.
1781   WriteTypeTable(VE, Stream);
1782
1783   // Emit top-level description of module, including target triple, inline asm,
1784   // descriptors for global variables, and function prototype info.
1785   WriteModuleInfo(M, VE, Stream);
1786
1787   // Emit constants.
1788   WriteModuleConstants(VE, Stream);
1789
1790   // Emit metadata.
1791   WriteModuleMetadata(M, VE, Stream);
1792
1793   // Emit metadata.
1794   WriteModuleMetadataStore(M, Stream);
1795
1796   // Emit names for globals/functions etc.
1797   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1798
1799   // Emit use-lists.
1800   if (EnablePreserveUseListOrdering)
1801     WriteModuleUseLists(M, VE, Stream);
1802
1803   // Emit function bodies.
1804   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1805     if (!F->isDeclaration())
1806       WriteFunction(*F, VE, Stream);
1807
1808   Stream.ExitBlock();
1809 }
1810
1811 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1812 /// header and trailer to make it compatible with the system archiver.  To do
1813 /// this we emit the following header, and then emit a trailer that pads the
1814 /// file out to be a multiple of 16 bytes.
1815 ///
1816 /// struct bc_header {
1817 ///   uint32_t Magic;         // 0x0B17C0DE
1818 ///   uint32_t Version;       // Version, currently always 0.
1819 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1820 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1821 ///   uint32_t CPUType;       // CPU specifier.
1822 ///   ... potentially more later ...
1823 /// };
1824 enum {
1825   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1826   DarwinBCHeaderSize = 5*4
1827 };
1828
1829 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1830                                uint32_t &Position) {
1831   Buffer[Position + 0] = (unsigned char) (Value >>  0);
1832   Buffer[Position + 1] = (unsigned char) (Value >>  8);
1833   Buffer[Position + 2] = (unsigned char) (Value >> 16);
1834   Buffer[Position + 3] = (unsigned char) (Value >> 24);
1835   Position += 4;
1836 }
1837
1838 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1839                                          const Triple &TT) {
1840   unsigned CPUType = ~0U;
1841
1842   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1843   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1844   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
1845   // specific constants here because they are implicitly part of the Darwin ABI.
1846   enum {
1847     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
1848     DARWIN_CPU_TYPE_X86        = 7,
1849     DARWIN_CPU_TYPE_ARM        = 12,
1850     DARWIN_CPU_TYPE_POWERPC    = 18
1851   };
1852
1853   Triple::ArchType Arch = TT.getArch();
1854   if (Arch == Triple::x86_64)
1855     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1856   else if (Arch == Triple::x86)
1857     CPUType = DARWIN_CPU_TYPE_X86;
1858   else if (Arch == Triple::ppc)
1859     CPUType = DARWIN_CPU_TYPE_POWERPC;
1860   else if (Arch == Triple::ppc64)
1861     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1862   else if (Arch == Triple::arm || Arch == Triple::thumb)
1863     CPUType = DARWIN_CPU_TYPE_ARM;
1864
1865   // Traditional Bitcode starts after header.
1866   assert(Buffer.size() >= DarwinBCHeaderSize &&
1867          "Expected header size to be reserved");
1868   unsigned BCOffset = DarwinBCHeaderSize;
1869   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1870
1871   // Write the magic and version.
1872   unsigned Position = 0;
1873   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1874   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
1875   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
1876   WriteInt32ToBuffer(BCSize     , Buffer, Position);
1877   WriteInt32ToBuffer(CPUType    , Buffer, Position);
1878
1879   // If the file is not a multiple of 16 bytes, insert dummy padding.
1880   while (Buffer.size() & 15)
1881     Buffer.push_back(0);
1882 }
1883
1884 /// WriteBitcodeToFile - Write the specified module to the specified output
1885 /// stream.
1886 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1887   SmallVector<char, 1024> Buffer;
1888   Buffer.reserve(256*1024);
1889
1890   // If this is darwin or another generic macho target, reserve space for the
1891   // header.
1892   Triple TT(M->getTargetTriple());
1893   if (TT.isOSDarwin())
1894     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1895
1896   // Emit the module into the buffer.
1897   {
1898     BitstreamWriter Stream(Buffer);
1899
1900     // Emit the file header.
1901     Stream.Emit((unsigned)'B', 8);
1902     Stream.Emit((unsigned)'C', 8);
1903     Stream.Emit(0x0, 4);
1904     Stream.Emit(0xC, 4);
1905     Stream.Emit(0xE, 4);
1906     Stream.Emit(0xD, 4);
1907
1908     // Emit the module.
1909     WriteModule(M, Stream);
1910   }
1911
1912   if (TT.isOSDarwin())
1913     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1914
1915   // Write the generated bitstream to "Out".
1916   Out.write((char*)&Buffer.front(), Buffer.size());
1917 }