OSDN Git Service

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