AsmWriter/Bitcode: MDObjCProperty
[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 "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/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/UseListOrder.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cctype>
34 #include <map>
35 using namespace llvm;
36
37 /// These are manifest constants used by the bitcode writer. They do not need to
38 /// be kept in sync with the reader, but need to be consistent within this file.
39 enum {
40   // VALUE_SYMTAB_BLOCK abbrev id's.
41   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
42   VST_ENTRY_7_ABBREV,
43   VST_ENTRY_6_ABBREV,
44   VST_BBENTRY_6_ABBREV,
45
46   // CONSTANTS_BLOCK abbrev id's.
47   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48   CONSTANTS_INTEGER_ABBREV,
49   CONSTANTS_CE_CAST_Abbrev,
50   CONSTANTS_NULL_Abbrev,
51
52   // FUNCTION_BLOCK abbrev id's.
53   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54   FUNCTION_INST_BINOP_ABBREV,
55   FUNCTION_INST_BINOP_FLAGS_ABBREV,
56   FUNCTION_INST_CAST_ABBREV,
57   FUNCTION_INST_RET_VOID_ABBREV,
58   FUNCTION_INST_RET_VAL_ABBREV,
59   FUNCTION_INST_UNREACHABLE_ABBREV
60 };
61
62 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
63   switch (Opcode) {
64   default: llvm_unreachable("Unknown cast instruction!");
65   case Instruction::Trunc   : return bitc::CAST_TRUNC;
66   case Instruction::ZExt    : return bitc::CAST_ZEXT;
67   case Instruction::SExt    : return bitc::CAST_SEXT;
68   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
69   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
70   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
71   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
72   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
73   case Instruction::FPExt   : return bitc::CAST_FPEXT;
74   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
75   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
76   case Instruction::BitCast : return bitc::CAST_BITCAST;
77   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
78   }
79 }
80
81 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
82   switch (Opcode) {
83   default: llvm_unreachable("Unknown binary instruction!");
84   case Instruction::Add:
85   case Instruction::FAdd: return bitc::BINOP_ADD;
86   case Instruction::Sub:
87   case Instruction::FSub: return bitc::BINOP_SUB;
88   case Instruction::Mul:
89   case Instruction::FMul: return bitc::BINOP_MUL;
90   case Instruction::UDiv: return bitc::BINOP_UDIV;
91   case Instruction::FDiv:
92   case Instruction::SDiv: return bitc::BINOP_SDIV;
93   case Instruction::URem: return bitc::BINOP_UREM;
94   case Instruction::FRem:
95   case Instruction::SRem: return bitc::BINOP_SREM;
96   case Instruction::Shl:  return bitc::BINOP_SHL;
97   case Instruction::LShr: return bitc::BINOP_LSHR;
98   case Instruction::AShr: return bitc::BINOP_ASHR;
99   case Instruction::And:  return bitc::BINOP_AND;
100   case Instruction::Or:   return bitc::BINOP_OR;
101   case Instruction::Xor:  return bitc::BINOP_XOR;
102   }
103 }
104
105 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
106   switch (Op) {
107   default: llvm_unreachable("Unknown RMW operation!");
108   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
109   case AtomicRMWInst::Add: return bitc::RMW_ADD;
110   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
111   case AtomicRMWInst::And: return bitc::RMW_AND;
112   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
113   case AtomicRMWInst::Or: return bitc::RMW_OR;
114   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
115   case AtomicRMWInst::Max: return bitc::RMW_MAX;
116   case AtomicRMWInst::Min: return bitc::RMW_MIN;
117   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
118   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
119   }
120 }
121
122 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
123   switch (Ordering) {
124   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
125   case Unordered: return bitc::ORDERING_UNORDERED;
126   case Monotonic: return bitc::ORDERING_MONOTONIC;
127   case Acquire: return bitc::ORDERING_ACQUIRE;
128   case Release: return bitc::ORDERING_RELEASE;
129   case AcquireRelease: return bitc::ORDERING_ACQREL;
130   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
131   }
132   llvm_unreachable("Invalid ordering");
133 }
134
135 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
136   switch (SynchScope) {
137   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
138   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
139   }
140   llvm_unreachable("Invalid synch scope");
141 }
142
143 static void WriteStringRecord(unsigned Code, StringRef Str,
144                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
145   SmallVector<unsigned, 64> Vals;
146
147   // Code: [strchar x N]
148   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
149     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
150       AbbrevToUse = 0;
151     Vals.push_back(Str[i]);
152   }
153
154   // Emit the finished record.
155   Stream.EmitRecord(Code, Vals, AbbrevToUse);
156 }
157
158 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
159   switch (Kind) {
160   case Attribute::Alignment:
161     return bitc::ATTR_KIND_ALIGNMENT;
162   case Attribute::AlwaysInline:
163     return bitc::ATTR_KIND_ALWAYS_INLINE;
164   case Attribute::Builtin:
165     return bitc::ATTR_KIND_BUILTIN;
166   case Attribute::ByVal:
167     return bitc::ATTR_KIND_BY_VAL;
168   case Attribute::InAlloca:
169     return bitc::ATTR_KIND_IN_ALLOCA;
170   case Attribute::Cold:
171     return bitc::ATTR_KIND_COLD;
172   case Attribute::InlineHint:
173     return bitc::ATTR_KIND_INLINE_HINT;
174   case Attribute::InReg:
175     return bitc::ATTR_KIND_IN_REG;
176   case Attribute::JumpTable:
177     return bitc::ATTR_KIND_JUMP_TABLE;
178   case Attribute::MinSize:
179     return bitc::ATTR_KIND_MIN_SIZE;
180   case Attribute::Naked:
181     return bitc::ATTR_KIND_NAKED;
182   case Attribute::Nest:
183     return bitc::ATTR_KIND_NEST;
184   case Attribute::NoAlias:
185     return bitc::ATTR_KIND_NO_ALIAS;
186   case Attribute::NoBuiltin:
187     return bitc::ATTR_KIND_NO_BUILTIN;
188   case Attribute::NoCapture:
189     return bitc::ATTR_KIND_NO_CAPTURE;
190   case Attribute::NoDuplicate:
191     return bitc::ATTR_KIND_NO_DUPLICATE;
192   case Attribute::NoImplicitFloat:
193     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
194   case Attribute::NoInline:
195     return bitc::ATTR_KIND_NO_INLINE;
196   case Attribute::NonLazyBind:
197     return bitc::ATTR_KIND_NON_LAZY_BIND;
198   case Attribute::NonNull:
199     return bitc::ATTR_KIND_NON_NULL;
200   case Attribute::Dereferenceable:
201     return bitc::ATTR_KIND_DEREFERENCEABLE;
202   case Attribute::NoRedZone:
203     return bitc::ATTR_KIND_NO_RED_ZONE;
204   case Attribute::NoReturn:
205     return bitc::ATTR_KIND_NO_RETURN;
206   case Attribute::NoUnwind:
207     return bitc::ATTR_KIND_NO_UNWIND;
208   case Attribute::OptimizeForSize:
209     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
210   case Attribute::OptimizeNone:
211     return bitc::ATTR_KIND_OPTIMIZE_NONE;
212   case Attribute::ReadNone:
213     return bitc::ATTR_KIND_READ_NONE;
214   case Attribute::ReadOnly:
215     return bitc::ATTR_KIND_READ_ONLY;
216   case Attribute::Returned:
217     return bitc::ATTR_KIND_RETURNED;
218   case Attribute::ReturnsTwice:
219     return bitc::ATTR_KIND_RETURNS_TWICE;
220   case Attribute::SExt:
221     return bitc::ATTR_KIND_S_EXT;
222   case Attribute::StackAlignment:
223     return bitc::ATTR_KIND_STACK_ALIGNMENT;
224   case Attribute::StackProtect:
225     return bitc::ATTR_KIND_STACK_PROTECT;
226   case Attribute::StackProtectReq:
227     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
228   case Attribute::StackProtectStrong:
229     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
230   case Attribute::StructRet:
231     return bitc::ATTR_KIND_STRUCT_RET;
232   case Attribute::SanitizeAddress:
233     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
234   case Attribute::SanitizeThread:
235     return bitc::ATTR_KIND_SANITIZE_THREAD;
236   case Attribute::SanitizeMemory:
237     return bitc::ATTR_KIND_SANITIZE_MEMORY;
238   case Attribute::UWTable:
239     return bitc::ATTR_KIND_UW_TABLE;
240   case Attribute::ZExt:
241     return bitc::ATTR_KIND_Z_EXT;
242   case Attribute::EndAttrKinds:
243     llvm_unreachable("Can not encode end-attribute kinds marker.");
244   case Attribute::None:
245     llvm_unreachable("Can not encode none-attribute.");
246   }
247
248   llvm_unreachable("Trying to encode unknown attribute");
249 }
250
251 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
252                                      BitstreamWriter &Stream) {
253   const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
254   if (AttrGrps.empty()) return;
255
256   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
257
258   SmallVector<uint64_t, 64> Record;
259   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
260     AttributeSet AS = AttrGrps[i];
261     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
262       AttributeSet A = AS.getSlotAttributes(i);
263
264       Record.push_back(VE.getAttributeGroupID(A));
265       Record.push_back(AS.getSlotIndex(i));
266
267       for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
268            I != E; ++I) {
269         Attribute Attr = *I;
270         if (Attr.isEnumAttribute()) {
271           Record.push_back(0);
272           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
273         } else if (Attr.isIntAttribute()) {
274           Record.push_back(1);
275           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
276           Record.push_back(Attr.getValueAsInt());
277         } else {
278           StringRef Kind = Attr.getKindAsString();
279           StringRef Val = Attr.getValueAsString();
280
281           Record.push_back(Val.empty() ? 3 : 4);
282           Record.append(Kind.begin(), Kind.end());
283           Record.push_back(0);
284           if (!Val.empty()) {
285             Record.append(Val.begin(), Val.end());
286             Record.push_back(0);
287           }
288         }
289       }
290
291       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
292       Record.clear();
293     }
294   }
295
296   Stream.ExitBlock();
297 }
298
299 static void WriteAttributeTable(const ValueEnumerator &VE,
300                                 BitstreamWriter &Stream) {
301   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
302   if (Attrs.empty()) return;
303
304   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
305
306   SmallVector<uint64_t, 64> Record;
307   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
308     const AttributeSet &A = Attrs[i];
309     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
310       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
311
312     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
313     Record.clear();
314   }
315
316   Stream.ExitBlock();
317 }
318
319 /// WriteTypeTable - Write out the type table for a module.
320 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
321   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
322
323   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
324   SmallVector<uint64_t, 64> TypeVals;
325
326   uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
327
328   // Abbrev for TYPE_CODE_POINTER.
329   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
330   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
331   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
332   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
333   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
334
335   // Abbrev for TYPE_CODE_FUNCTION.
336   Abbv = new BitCodeAbbrev();
337   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
338   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
339   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
340   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
341
342   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
343
344   // Abbrev for TYPE_CODE_STRUCT_ANON.
345   Abbv = new BitCodeAbbrev();
346   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
347   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
348   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
349   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
350
351   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
352
353   // Abbrev for TYPE_CODE_STRUCT_NAME.
354   Abbv = new BitCodeAbbrev();
355   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
356   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
357   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
358   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
359
360   // Abbrev for TYPE_CODE_STRUCT_NAMED.
361   Abbv = new BitCodeAbbrev();
362   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
363   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
364   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
365   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
366
367   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
368
369   // Abbrev for TYPE_CODE_ARRAY.
370   Abbv = new BitCodeAbbrev();
371   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
372   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
373   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
374
375   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
376
377   // Emit an entry count so the reader can reserve space.
378   TypeVals.push_back(TypeList.size());
379   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
380   TypeVals.clear();
381
382   // Loop over all of the types, emitting each in turn.
383   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
384     Type *T = TypeList[i];
385     int AbbrevToUse = 0;
386     unsigned Code = 0;
387
388     switch (T->getTypeID()) {
389     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
390     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
391     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
392     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
393     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
394     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
395     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
396     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
397     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
398     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
399     case Type::IntegerTyID:
400       // INTEGER: [width]
401       Code = bitc::TYPE_CODE_INTEGER;
402       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
403       break;
404     case Type::PointerTyID: {
405       PointerType *PTy = cast<PointerType>(T);
406       // POINTER: [pointee type, address space]
407       Code = bitc::TYPE_CODE_POINTER;
408       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
409       unsigned AddressSpace = PTy->getAddressSpace();
410       TypeVals.push_back(AddressSpace);
411       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
412       break;
413     }
414     case Type::FunctionTyID: {
415       FunctionType *FT = cast<FunctionType>(T);
416       // FUNCTION: [isvararg, retty, paramty x N]
417       Code = bitc::TYPE_CODE_FUNCTION;
418       TypeVals.push_back(FT->isVarArg());
419       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
420       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
421         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
422       AbbrevToUse = FunctionAbbrev;
423       break;
424     }
425     case Type::StructTyID: {
426       StructType *ST = cast<StructType>(T);
427       // STRUCT: [ispacked, eltty x N]
428       TypeVals.push_back(ST->isPacked());
429       // Output all of the element types.
430       for (StructType::element_iterator I = ST->element_begin(),
431            E = ST->element_end(); I != E; ++I)
432         TypeVals.push_back(VE.getTypeID(*I));
433
434       if (ST->isLiteral()) {
435         Code = bitc::TYPE_CODE_STRUCT_ANON;
436         AbbrevToUse = StructAnonAbbrev;
437       } else {
438         if (ST->isOpaque()) {
439           Code = bitc::TYPE_CODE_OPAQUE;
440         } else {
441           Code = bitc::TYPE_CODE_STRUCT_NAMED;
442           AbbrevToUse = StructNamedAbbrev;
443         }
444
445         // Emit the name if it is present.
446         if (!ST->getName().empty())
447           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
448                             StructNameAbbrev, Stream);
449       }
450       break;
451     }
452     case Type::ArrayTyID: {
453       ArrayType *AT = cast<ArrayType>(T);
454       // ARRAY: [numelts, eltty]
455       Code = bitc::TYPE_CODE_ARRAY;
456       TypeVals.push_back(AT->getNumElements());
457       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
458       AbbrevToUse = ArrayAbbrev;
459       break;
460     }
461     case Type::VectorTyID: {
462       VectorType *VT = cast<VectorType>(T);
463       // VECTOR [numelts, eltty]
464       Code = bitc::TYPE_CODE_VECTOR;
465       TypeVals.push_back(VT->getNumElements());
466       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
467       break;
468     }
469     }
470
471     // Emit the finished record.
472     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
473     TypeVals.clear();
474   }
475
476   Stream.ExitBlock();
477 }
478
479 static unsigned getEncodedLinkage(const GlobalValue &GV) {
480   switch (GV.getLinkage()) {
481   case GlobalValue::ExternalLinkage:
482     return 0;
483   case GlobalValue::WeakAnyLinkage:
484     return 16;
485   case GlobalValue::AppendingLinkage:
486     return 2;
487   case GlobalValue::InternalLinkage:
488     return 3;
489   case GlobalValue::LinkOnceAnyLinkage:
490     return 18;
491   case GlobalValue::ExternalWeakLinkage:
492     return 7;
493   case GlobalValue::CommonLinkage:
494     return 8;
495   case GlobalValue::PrivateLinkage:
496     return 9;
497   case GlobalValue::WeakODRLinkage:
498     return 17;
499   case GlobalValue::LinkOnceODRLinkage:
500     return 19;
501   case GlobalValue::AvailableExternallyLinkage:
502     return 12;
503   }
504   llvm_unreachable("Invalid linkage");
505 }
506
507 static unsigned getEncodedVisibility(const GlobalValue &GV) {
508   switch (GV.getVisibility()) {
509   case GlobalValue::DefaultVisibility:   return 0;
510   case GlobalValue::HiddenVisibility:    return 1;
511   case GlobalValue::ProtectedVisibility: return 2;
512   }
513   llvm_unreachable("Invalid visibility");
514 }
515
516 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
517   switch (GV.getDLLStorageClass()) {
518   case GlobalValue::DefaultStorageClass:   return 0;
519   case GlobalValue::DLLImportStorageClass: return 1;
520   case GlobalValue::DLLExportStorageClass: return 2;
521   }
522   llvm_unreachable("Invalid DLL storage class");
523 }
524
525 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
526   switch (GV.getThreadLocalMode()) {
527     case GlobalVariable::NotThreadLocal:         return 0;
528     case GlobalVariable::GeneralDynamicTLSModel: return 1;
529     case GlobalVariable::LocalDynamicTLSModel:   return 2;
530     case GlobalVariable::InitialExecTLSModel:    return 3;
531     case GlobalVariable::LocalExecTLSModel:      return 4;
532   }
533   llvm_unreachable("Invalid TLS model");
534 }
535
536 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
537   switch (C.getSelectionKind()) {
538   case Comdat::Any:
539     return bitc::COMDAT_SELECTION_KIND_ANY;
540   case Comdat::ExactMatch:
541     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
542   case Comdat::Largest:
543     return bitc::COMDAT_SELECTION_KIND_LARGEST;
544   case Comdat::NoDuplicates:
545     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
546   case Comdat::SameSize:
547     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
548   }
549   llvm_unreachable("Invalid selection kind");
550 }
551
552 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
553   SmallVector<uint16_t, 64> Vals;
554   for (const Comdat *C : VE.getComdats()) {
555     // COMDAT: [selection_kind, name]
556     Vals.push_back(getEncodedComdatSelectionKind(*C));
557     size_t Size = C->getName().size();
558     assert(isUInt<16>(Size));
559     Vals.push_back(Size);
560     for (char Chr : C->getName())
561       Vals.push_back((unsigned char)Chr);
562     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
563     Vals.clear();
564   }
565 }
566
567 // Emit top-level description of module, including target triple, inline asm,
568 // descriptors for global variables, and function prototype info.
569 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
570                             BitstreamWriter &Stream) {
571   // Emit various pieces of data attached to a module.
572   if (!M->getTargetTriple().empty())
573     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
574                       0/*TODO*/, Stream);
575   const std::string &DL = M->getDataLayoutStr();
576   if (!DL.empty())
577     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
578   if (!M->getModuleInlineAsm().empty())
579     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
580                       0/*TODO*/, Stream);
581
582   // Emit information about sections and GC, computing how many there are. Also
583   // compute the maximum alignment value.
584   std::map<std::string, unsigned> SectionMap;
585   std::map<std::string, unsigned> GCMap;
586   unsigned MaxAlignment = 0;
587   unsigned MaxGlobalType = 0;
588   for (const GlobalValue &GV : M->globals()) {
589     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
590     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
591     if (GV.hasSection()) {
592       // Give section names unique ID's.
593       unsigned &Entry = SectionMap[GV.getSection()];
594       if (!Entry) {
595         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
596                           0/*TODO*/, Stream);
597         Entry = SectionMap.size();
598       }
599     }
600   }
601   for (const Function &F : *M) {
602     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
603     if (F.hasSection()) {
604       // Give section names unique ID's.
605       unsigned &Entry = SectionMap[F.getSection()];
606       if (!Entry) {
607         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
608                           0/*TODO*/, Stream);
609         Entry = SectionMap.size();
610       }
611     }
612     if (F.hasGC()) {
613       // Same for GC names.
614       unsigned &Entry = GCMap[F.getGC()];
615       if (!Entry) {
616         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
617                           0/*TODO*/, Stream);
618         Entry = GCMap.size();
619       }
620     }
621   }
622
623   // Emit abbrev for globals, now that we know # sections and max alignment.
624   unsigned SimpleGVarAbbrev = 0;
625   if (!M->global_empty()) {
626     // Add an abbrev for common globals with no visibility or thread localness.
627     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
628     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
629     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
630                               Log2_32_Ceil(MaxGlobalType+1)));
631     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
632     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
633     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));      // Linkage.
634     if (MaxAlignment == 0)                                      // Alignment.
635       Abbv->Add(BitCodeAbbrevOp(0));
636     else {
637       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
638       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
639                                Log2_32_Ceil(MaxEncAlignment+1)));
640     }
641     if (SectionMap.empty())                                    // Section.
642       Abbv->Add(BitCodeAbbrevOp(0));
643     else
644       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
645                                Log2_32_Ceil(SectionMap.size()+1)));
646     // Don't bother emitting vis + thread local.
647     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
648   }
649
650   // Emit the global variable information.
651   SmallVector<unsigned, 64> Vals;
652   for (const GlobalVariable &GV : M->globals()) {
653     unsigned AbbrevToUse = 0;
654
655     // GLOBALVAR: [type, isconst, initid,
656     //             linkage, alignment, section, visibility, threadlocal,
657     //             unnamed_addr, externally_initialized, dllstorageclass,
658     //             comdat]
659     Vals.push_back(VE.getTypeID(GV.getType()));
660     Vals.push_back(GV.isConstant());
661     Vals.push_back(GV.isDeclaration() ? 0 :
662                    (VE.getValueID(GV.getInitializer()) + 1));
663     Vals.push_back(getEncodedLinkage(GV));
664     Vals.push_back(Log2_32(GV.getAlignment())+1);
665     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
666     if (GV.isThreadLocal() ||
667         GV.getVisibility() != GlobalValue::DefaultVisibility ||
668         GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
669         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
670         GV.hasComdat()) {
671       Vals.push_back(getEncodedVisibility(GV));
672       Vals.push_back(getEncodedThreadLocalMode(GV));
673       Vals.push_back(GV.hasUnnamedAddr());
674       Vals.push_back(GV.isExternallyInitialized());
675       Vals.push_back(getEncodedDLLStorageClass(GV));
676       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
677     } else {
678       AbbrevToUse = SimpleGVarAbbrev;
679     }
680
681     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
682     Vals.clear();
683   }
684
685   // Emit the function proto information.
686   for (const Function &F : *M) {
687     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
688     //             section, visibility, gc, unnamed_addr, prologuedata,
689     //             dllstorageclass, comdat, prefixdata]
690     Vals.push_back(VE.getTypeID(F.getType()));
691     Vals.push_back(F.getCallingConv());
692     Vals.push_back(F.isDeclaration());
693     Vals.push_back(getEncodedLinkage(F));
694     Vals.push_back(VE.getAttributeID(F.getAttributes()));
695     Vals.push_back(Log2_32(F.getAlignment())+1);
696     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
697     Vals.push_back(getEncodedVisibility(F));
698     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
699     Vals.push_back(F.hasUnnamedAddr());
700     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
701                                        : 0);
702     Vals.push_back(getEncodedDLLStorageClass(F));
703     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
704     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
705                                      : 0);
706
707     unsigned AbbrevToUse = 0;
708     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
709     Vals.clear();
710   }
711
712   // Emit the alias information.
713   for (const GlobalAlias &A : M->aliases()) {
714     // ALIAS: [alias type, aliasee val#, linkage, visibility]
715     Vals.push_back(VE.getTypeID(A.getType()));
716     Vals.push_back(VE.getValueID(A.getAliasee()));
717     Vals.push_back(getEncodedLinkage(A));
718     Vals.push_back(getEncodedVisibility(A));
719     Vals.push_back(getEncodedDLLStorageClass(A));
720     Vals.push_back(getEncodedThreadLocalMode(A));
721     Vals.push_back(A.hasUnnamedAddr());
722     unsigned AbbrevToUse = 0;
723     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
724     Vals.clear();
725   }
726 }
727
728 static uint64_t GetOptimizationFlags(const Value *V) {
729   uint64_t Flags = 0;
730
731   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
732     if (OBO->hasNoSignedWrap())
733       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
734     if (OBO->hasNoUnsignedWrap())
735       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
736   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
737     if (PEO->isExact())
738       Flags |= 1 << bitc::PEO_EXACT;
739   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
740     if (FPMO->hasUnsafeAlgebra())
741       Flags |= FastMathFlags::UnsafeAlgebra;
742     if (FPMO->hasNoNaNs())
743       Flags |= FastMathFlags::NoNaNs;
744     if (FPMO->hasNoInfs())
745       Flags |= FastMathFlags::NoInfs;
746     if (FPMO->hasNoSignedZeros())
747       Flags |= FastMathFlags::NoSignedZeros;
748     if (FPMO->hasAllowReciprocal())
749       Flags |= FastMathFlags::AllowReciprocal;
750   }
751
752   return Flags;
753 }
754
755 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
756                                  const ValueEnumerator &VE,
757                                  BitstreamWriter &Stream,
758                                  SmallVectorImpl<uint64_t> &Record) {
759   // Mimic an MDNode with a value as one operand.
760   Value *V = MD->getValue();
761   Record.push_back(VE.getTypeID(V->getType()));
762   Record.push_back(VE.getValueID(V));
763   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
764   Record.clear();
765 }
766
767 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
768                          BitstreamWriter &Stream,
769                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
770   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
771     Metadata *MD = N->getOperand(i);
772     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
773            "Unexpected function-local metadata");
774     Record.push_back(VE.getMetadataOrNullID(MD));
775   }
776   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
777                                     : bitc::METADATA_NODE,
778                     Record, Abbrev);
779   Record.clear();
780 }
781
782 static void WriteMDLocation(const MDLocation *N, const ValueEnumerator &VE,
783                             BitstreamWriter &Stream,
784                             SmallVectorImpl<uint64_t> &Record,
785                             unsigned Abbrev) {
786   Record.push_back(N->isDistinct());
787   Record.push_back(N->getLine());
788   Record.push_back(N->getColumn());
789   Record.push_back(VE.getMetadataID(N->getScope()));
790   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
791
792   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
793   Record.clear();
794 }
795
796 static void WriteGenericDebugNode(const GenericDebugNode *N,
797                                   const ValueEnumerator &VE,
798                                   BitstreamWriter &Stream,
799                                   SmallVectorImpl<uint64_t> &Record,
800                                   unsigned Abbrev) {
801   Record.push_back(N->isDistinct());
802   Record.push_back(N->getTag());
803   Record.push_back(0); // Per-tag version field; unused for now.
804
805   for (auto &I : N->operands())
806     Record.push_back(VE.getMetadataOrNullID(I));
807
808   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
809   Record.clear();
810 }
811
812 static uint64_t rotateSign(int64_t I) {
813   uint64_t U = I;
814   return I < 0 ? ~(U << 1) : U << 1;
815 }
816
817 static void WriteMDSubrange(const MDSubrange *N, const ValueEnumerator &,
818                             BitstreamWriter &Stream,
819                             SmallVectorImpl<uint64_t> &Record,
820                             unsigned Abbrev) {
821   Record.push_back(N->isDistinct());
822   Record.push_back(N->getCount());
823   Record.push_back(rotateSign(N->getLo()));
824
825   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
826   Record.clear();
827 }
828
829 static void WriteMDEnumerator(const MDEnumerator *N, const ValueEnumerator &VE,
830                               BitstreamWriter &Stream,
831                               SmallVectorImpl<uint64_t> &Record,
832                               unsigned Abbrev) {
833   Record.push_back(N->isDistinct());
834   Record.push_back(rotateSign(N->getValue()));
835   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
836
837   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
838   Record.clear();
839 }
840
841 static void WriteMDBasicType(const MDBasicType *N, const ValueEnumerator &VE,
842                              BitstreamWriter &Stream,
843                              SmallVectorImpl<uint64_t> &Record,
844                              unsigned Abbrev) {
845   Record.push_back(N->isDistinct());
846   Record.push_back(N->getTag());
847   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
848   Record.push_back(N->getSizeInBits());
849   Record.push_back(N->getAlignInBits());
850   Record.push_back(N->getEncoding());
851
852   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
853   Record.clear();
854 }
855
856 static void WriteMDDerivedType(const MDDerivedType *N,
857                                const ValueEnumerator &VE,
858                                BitstreamWriter &Stream,
859                                SmallVectorImpl<uint64_t> &Record,
860                                unsigned Abbrev) {
861   Record.push_back(N->isDistinct());
862   Record.push_back(N->getTag());
863   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
864   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
865   Record.push_back(N->getLine());
866   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
867   Record.push_back(VE.getMetadataID(N->getBaseType()));
868   Record.push_back(N->getSizeInBits());
869   Record.push_back(N->getAlignInBits());
870   Record.push_back(N->getOffsetInBits());
871   Record.push_back(N->getFlags());
872   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
873
874   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
875   Record.clear();
876 }
877
878 static void WriteMDCompositeType(const MDCompositeType *N,
879                                  const ValueEnumerator &VE,
880                                  BitstreamWriter &Stream,
881                                  SmallVectorImpl<uint64_t> &Record,
882                                  unsigned Abbrev) {
883   Record.push_back(N->isDistinct());
884   Record.push_back(N->getTag());
885   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
886   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
887   Record.push_back(N->getLine());
888   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
889   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
890   Record.push_back(N->getSizeInBits());
891   Record.push_back(N->getAlignInBits());
892   Record.push_back(N->getOffsetInBits());
893   Record.push_back(N->getFlags());
894   Record.push_back(VE.getMetadataOrNullID(N->getElements()));
895   Record.push_back(N->getRuntimeLang());
896   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
897   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
898   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
899
900   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
901   Record.clear();
902 }
903
904 static void WriteMDSubroutineType(const MDSubroutineType *N,
905                                   const ValueEnumerator &VE,
906                                   BitstreamWriter &Stream,
907                                   SmallVectorImpl<uint64_t> &Record,
908                                   unsigned Abbrev) {
909   Record.push_back(N->isDistinct());
910   Record.push_back(N->getFlags());
911   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray()));
912
913   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
914   Record.clear();
915 }
916
917 static void WriteMDFile(const MDFile *N, const ValueEnumerator &VE,
918                         BitstreamWriter &Stream,
919                         SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
920   Record.push_back(N->isDistinct());
921   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
922   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
923
924   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
925   Record.clear();
926 }
927
928 static void WriteMDCompileUnit(const MDCompileUnit *N,
929                                const ValueEnumerator &VE,
930                                BitstreamWriter &Stream,
931                                SmallVectorImpl<uint64_t> &Record,
932                                unsigned Abbrev) {
933   Record.push_back(N->isDistinct());
934   Record.push_back(N->getSourceLanguage());
935   Record.push_back(VE.getMetadataID(N->getFile()));
936   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
937   Record.push_back(N->isOptimized());
938   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
939   Record.push_back(N->getRuntimeVersion());
940   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
941   Record.push_back(N->getEmissionKind());
942   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes()));
943   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes()));
944   Record.push_back(VE.getMetadataOrNullID(N->getSubprograms()));
945   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables()));
946   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities()));
947
948   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
949   Record.clear();
950 }
951
952 static void WriteMDSubprogram(const MDSubprogram *N,
953                                const ValueEnumerator &VE,
954                                BitstreamWriter &Stream,
955                                SmallVectorImpl<uint64_t> &Record,
956                                unsigned Abbrev) {
957   Record.push_back(N->isDistinct());
958   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
959   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
960   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
961   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
962   Record.push_back(N->getLine());
963   Record.push_back(VE.getMetadataOrNullID(N->getType()));
964   Record.push_back(N->isLocalToUnit());
965   Record.push_back(N->isDefinition());
966   Record.push_back(N->getScopeLine());
967   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
968   Record.push_back(N->getVirtuality());
969   Record.push_back(N->getVirtualIndex());
970   Record.push_back(N->getFlags());
971   Record.push_back(N->isOptimized());
972   Record.push_back(VE.getMetadataOrNullID(N->getFunction()));
973   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
974   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
975   Record.push_back(VE.getMetadataOrNullID(N->getVariables()));
976
977   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
978   Record.clear();
979 }
980
981 static void WriteMDLexicalBlock(const MDLexicalBlock *N,
982                                const ValueEnumerator &VE,
983                                BitstreamWriter &Stream,
984                                SmallVectorImpl<uint64_t> &Record,
985                                unsigned Abbrev) {
986   Record.push_back(N->isDistinct());
987   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
988   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
989   Record.push_back(N->getLine());
990   Record.push_back(N->getColumn());
991
992   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
993   Record.clear();
994 }
995
996 static void WriteMDLexicalBlockFile(const MDLexicalBlockFile *N,
997                                     const ValueEnumerator &VE,
998                                     BitstreamWriter &Stream,
999                                     SmallVectorImpl<uint64_t> &Record,
1000                                     unsigned Abbrev) {
1001   Record.push_back(N->isDistinct());
1002   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1003   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1004   Record.push_back(N->getDiscriminator());
1005
1006   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1007   Record.clear();
1008 }
1009
1010 static void WriteMDNamespace(const MDNamespace *N, const ValueEnumerator &VE,
1011                              BitstreamWriter &Stream,
1012                              SmallVectorImpl<uint64_t> &Record,
1013                              unsigned Abbrev) {
1014   Record.push_back(N->isDistinct());
1015   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1016   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1017   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1018   Record.push_back(N->getLine());
1019
1020   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1021   Record.clear();
1022 }
1023
1024 static void WriteMDTemplateTypeParameter(const MDTemplateTypeParameter *N,
1025                                          const ValueEnumerator &VE,
1026                                          BitstreamWriter &Stream,
1027                                          SmallVectorImpl<uint64_t> &Record,
1028                                          unsigned Abbrev) {
1029   Record.push_back(N->isDistinct());
1030   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1031   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1032   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1033
1034   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1035   Record.clear();
1036 }
1037
1038 static void WriteMDTemplateValueParameter(const MDTemplateValueParameter *N,
1039                                           const ValueEnumerator &VE,
1040                                           BitstreamWriter &Stream,
1041                                           SmallVectorImpl<uint64_t> &Record,
1042                                           unsigned Abbrev) {
1043   Record.push_back(N->isDistinct());
1044   Record.push_back(N->getTag());
1045   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1046   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1047   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1048   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1049
1050   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1051   Record.clear();
1052 }
1053
1054 static void WriteMDGlobalVariable(const MDGlobalVariable *N,
1055                                   const ValueEnumerator &VE,
1056                                   BitstreamWriter &Stream,
1057                                   SmallVectorImpl<uint64_t> &Record,
1058                                   unsigned Abbrev) {
1059   Record.push_back(N->isDistinct());
1060   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1061   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1062   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1063   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1064   Record.push_back(N->getLine());
1065   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1066   Record.push_back(N->isLocalToUnit());
1067   Record.push_back(N->isDefinition());
1068   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1069   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1070
1071   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1072   Record.clear();
1073 }
1074
1075 static void WriteMDLocalVariable(const MDLocalVariable *N,
1076                                  const ValueEnumerator &VE,
1077                                  BitstreamWriter &Stream,
1078                                  SmallVectorImpl<uint64_t> &Record,
1079                                  unsigned Abbrev) {
1080   Record.push_back(N->isDistinct());
1081   Record.push_back(N->getTag());
1082   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1083   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1084   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1085   Record.push_back(N->getLine());
1086   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1087   Record.push_back(N->getArg());
1088   Record.push_back(N->getFlags());
1089   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1090
1091   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1092   Record.clear();
1093 }
1094
1095 static void WriteMDExpression(const MDExpression *N, const ValueEnumerator &,
1096                               BitstreamWriter &Stream,
1097                               SmallVectorImpl<uint64_t> &Record,
1098                               unsigned Abbrev) {
1099   Record.reserve(N->getElements().size() + 1);
1100
1101   Record.push_back(N->isDistinct());
1102   for (uint64_t I : N->getElements())
1103     Record.push_back(I);
1104
1105   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1106   Record.clear();
1107 }
1108
1109 static void WriteMDObjCProperty(const MDObjCProperty *N,
1110                                  const ValueEnumerator &VE,
1111                                  BitstreamWriter &Stream,
1112                                  SmallVectorImpl<uint64_t> &Record,
1113                                  unsigned Abbrev) {
1114   Record.push_back(N->isDistinct());
1115   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1116   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1117   Record.push_back(N->getLine());
1118   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1119   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1120   Record.push_back(N->getAttributes());
1121   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1122
1123   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1124   Record.clear();
1125 }
1126
1127 static void WriteMDImportedEntity(const MDImportedEntity *,
1128                                   const ValueEnumerator &, BitstreamWriter &,
1129                                   SmallVectorImpl<uint64_t> &, unsigned) {
1130   llvm_unreachable("write not implemented");
1131 }
1132
1133 static void WriteModuleMetadata(const Module *M,
1134                                 const ValueEnumerator &VE,
1135                                 BitstreamWriter &Stream) {
1136   const auto &MDs = VE.getMDs();
1137   if (MDs.empty() && M->named_metadata_empty())
1138     return;
1139
1140   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1141
1142   unsigned MDSAbbrev = 0;
1143   if (VE.hasMDString()) {
1144     // Abbrev for METADATA_STRING.
1145     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1146     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1147     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1148     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1149     MDSAbbrev = Stream.EmitAbbrev(Abbv);
1150   }
1151
1152   // Initialize MDNode abbreviations.
1153 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1154 #include "llvm/IR/Metadata.def"
1155
1156   if (VE.hasMDLocation()) {
1157     // Abbrev for METADATA_LOCATION.
1158     //
1159     // Assume the column is usually under 128, and always output the inlined-at
1160     // location (it's never more expensive than building an array size 1).
1161     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1162     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1163     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1164     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1165     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1166     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1167     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1168     MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
1169   }
1170
1171   if (VE.hasGenericDebugNode()) {
1172     // Abbrev for METADATA_GENERIC_DEBUG.
1173     //
1174     // Assume the column is usually under 128, and always output the inlined-at
1175     // location (it's never more expensive than building an array size 1).
1176     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1177     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1178     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1179     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1180     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1181     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1182     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1183     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1184     GenericDebugNodeAbbrev = Stream.EmitAbbrev(Abbv);
1185   }
1186
1187   unsigned NameAbbrev = 0;
1188   if (!M->named_metadata_empty()) {
1189     // Abbrev for METADATA_NAME.
1190     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1191     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1192     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1193     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1194     NameAbbrev = Stream.EmitAbbrev(Abbv);
1195   }
1196
1197   SmallVector<uint64_t, 64> Record;
1198   for (const Metadata *MD : MDs) {
1199     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1200       switch (N->getMetadataID()) {
1201       default:
1202         llvm_unreachable("Invalid MDNode subclass");
1203 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1204   case Metadata::CLASS##Kind:                                                  \
1205     Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
1206     continue;
1207 #include "llvm/IR/Metadata.def"
1208       }
1209     }
1210     if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1211       WriteValueAsMetadata(MDC, VE, Stream, Record);
1212       continue;
1213     }
1214     const MDString *MDS = cast<MDString>(MD);
1215     // Code: [strchar x N]
1216     Record.append(MDS->bytes_begin(), MDS->bytes_end());
1217
1218     // Emit the finished record.
1219     Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1220     Record.clear();
1221   }
1222
1223   // Write named metadata.
1224   for (const NamedMDNode &NMD : M->named_metadata()) {
1225     // Write name.
1226     StringRef Str = NMD.getName();
1227     Record.append(Str.bytes_begin(), Str.bytes_end());
1228     Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1229     Record.clear();
1230
1231     // Write named metadata operands.
1232     for (const MDNode *N : NMD.operands())
1233       Record.push_back(VE.getMetadataID(N));
1234     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1235     Record.clear();
1236   }
1237
1238   Stream.ExitBlock();
1239 }
1240
1241 static void WriteFunctionLocalMetadata(const Function &F,
1242                                        const ValueEnumerator &VE,
1243                                        BitstreamWriter &Stream) {
1244   bool StartedMetadataBlock = false;
1245   SmallVector<uint64_t, 64> Record;
1246   const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1247       VE.getFunctionLocalMDs();
1248   for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1249     assert(MDs[i] && "Expected valid function-local metadata");
1250     if (!StartedMetadataBlock) {
1251       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1252       StartedMetadataBlock = true;
1253     }
1254     WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1255   }
1256
1257   if (StartedMetadataBlock)
1258     Stream.ExitBlock();
1259 }
1260
1261 static void WriteMetadataAttachment(const Function &F,
1262                                     const ValueEnumerator &VE,
1263                                     BitstreamWriter &Stream) {
1264   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1265
1266   SmallVector<uint64_t, 64> Record;
1267
1268   // Write metadata attachments
1269   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1270   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1271
1272   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1273     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1274          I != E; ++I) {
1275       MDs.clear();
1276       I->getAllMetadataOtherThanDebugLoc(MDs);
1277
1278       // If no metadata, ignore instruction.
1279       if (MDs.empty()) continue;
1280
1281       Record.push_back(VE.getInstructionID(I));
1282
1283       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1284         Record.push_back(MDs[i].first);
1285         Record.push_back(VE.getMetadataID(MDs[i].second));
1286       }
1287       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1288       Record.clear();
1289     }
1290
1291   Stream.ExitBlock();
1292 }
1293
1294 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1295   SmallVector<uint64_t, 64> Record;
1296
1297   // Write metadata kinds
1298   // METADATA_KIND - [n x [id, name]]
1299   SmallVector<StringRef, 8> Names;
1300   M->getMDKindNames(Names);
1301
1302   if (Names.empty()) return;
1303
1304   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1305
1306   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1307     Record.push_back(MDKindID);
1308     StringRef KName = Names[MDKindID];
1309     Record.append(KName.begin(), KName.end());
1310
1311     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1312     Record.clear();
1313   }
1314
1315   Stream.ExitBlock();
1316 }
1317
1318 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1319   if ((int64_t)V >= 0)
1320     Vals.push_back(V << 1);
1321   else
1322     Vals.push_back((-V << 1) | 1);
1323 }
1324
1325 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1326                            const ValueEnumerator &VE,
1327                            BitstreamWriter &Stream, bool isGlobal) {
1328   if (FirstVal == LastVal) return;
1329
1330   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1331
1332   unsigned AggregateAbbrev = 0;
1333   unsigned String8Abbrev = 0;
1334   unsigned CString7Abbrev = 0;
1335   unsigned CString6Abbrev = 0;
1336   // If this is a constant pool for the module, emit module-specific abbrevs.
1337   if (isGlobal) {
1338     // Abbrev for CST_CODE_AGGREGATE.
1339     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1340     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1341     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1342     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1343     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1344
1345     // Abbrev for CST_CODE_STRING.
1346     Abbv = new BitCodeAbbrev();
1347     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1348     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1349     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1350     String8Abbrev = Stream.EmitAbbrev(Abbv);
1351     // Abbrev for CST_CODE_CSTRING.
1352     Abbv = new BitCodeAbbrev();
1353     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1354     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1355     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1356     CString7Abbrev = Stream.EmitAbbrev(Abbv);
1357     // Abbrev for CST_CODE_CSTRING.
1358     Abbv = new BitCodeAbbrev();
1359     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1360     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1361     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1362     CString6Abbrev = Stream.EmitAbbrev(Abbv);
1363   }
1364
1365   SmallVector<uint64_t, 64> Record;
1366
1367   const ValueEnumerator::ValueList &Vals = VE.getValues();
1368   Type *LastTy = nullptr;
1369   for (unsigned i = FirstVal; i != LastVal; ++i) {
1370     const Value *V = Vals[i].first;
1371     // If we need to switch types, do so now.
1372     if (V->getType() != LastTy) {
1373       LastTy = V->getType();
1374       Record.push_back(VE.getTypeID(LastTy));
1375       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1376                         CONSTANTS_SETTYPE_ABBREV);
1377       Record.clear();
1378     }
1379
1380     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1381       Record.push_back(unsigned(IA->hasSideEffects()) |
1382                        unsigned(IA->isAlignStack()) << 1 |
1383                        unsigned(IA->getDialect()&1) << 2);
1384
1385       // Add the asm string.
1386       const std::string &AsmStr = IA->getAsmString();
1387       Record.push_back(AsmStr.size());
1388       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
1389         Record.push_back(AsmStr[i]);
1390
1391       // Add the constraint string.
1392       const std::string &ConstraintStr = IA->getConstraintString();
1393       Record.push_back(ConstraintStr.size());
1394       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
1395         Record.push_back(ConstraintStr[i]);
1396       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1397       Record.clear();
1398       continue;
1399     }
1400     const Constant *C = cast<Constant>(V);
1401     unsigned Code = -1U;
1402     unsigned AbbrevToUse = 0;
1403     if (C->isNullValue()) {
1404       Code = bitc::CST_CODE_NULL;
1405     } else if (isa<UndefValue>(C)) {
1406       Code = bitc::CST_CODE_UNDEF;
1407     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1408       if (IV->getBitWidth() <= 64) {
1409         uint64_t V = IV->getSExtValue();
1410         emitSignedInt64(Record, V);
1411         Code = bitc::CST_CODE_INTEGER;
1412         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1413       } else {                             // Wide integers, > 64 bits in size.
1414         // We have an arbitrary precision integer value to write whose
1415         // bit width is > 64. However, in canonical unsigned integer
1416         // format it is likely that the high bits are going to be zero.
1417         // So, we only write the number of active words.
1418         unsigned NWords = IV->getValue().getActiveWords();
1419         const uint64_t *RawWords = IV->getValue().getRawData();
1420         for (unsigned i = 0; i != NWords; ++i) {
1421           emitSignedInt64(Record, RawWords[i]);
1422         }
1423         Code = bitc::CST_CODE_WIDE_INTEGER;
1424       }
1425     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1426       Code = bitc::CST_CODE_FLOAT;
1427       Type *Ty = CFP->getType();
1428       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1429         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1430       } else if (Ty->isX86_FP80Ty()) {
1431         // api needed to prevent premature destruction
1432         // bits are not in the same order as a normal i80 APInt, compensate.
1433         APInt api = CFP->getValueAPF().bitcastToAPInt();
1434         const uint64_t *p = api.getRawData();
1435         Record.push_back((p[1] << 48) | (p[0] >> 16));
1436         Record.push_back(p[0] & 0xffffLL);
1437       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1438         APInt api = CFP->getValueAPF().bitcastToAPInt();
1439         const uint64_t *p = api.getRawData();
1440         Record.push_back(p[0]);
1441         Record.push_back(p[1]);
1442       } else {
1443         assert (0 && "Unknown FP type!");
1444       }
1445     } else if (isa<ConstantDataSequential>(C) &&
1446                cast<ConstantDataSequential>(C)->isString()) {
1447       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1448       // Emit constant strings specially.
1449       unsigned NumElts = Str->getNumElements();
1450       // If this is a null-terminated string, use the denser CSTRING encoding.
1451       if (Str->isCString()) {
1452         Code = bitc::CST_CODE_CSTRING;
1453         --NumElts;  // Don't encode the null, which isn't allowed by char6.
1454       } else {
1455         Code = bitc::CST_CODE_STRING;
1456         AbbrevToUse = String8Abbrev;
1457       }
1458       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1459       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1460       for (unsigned i = 0; i != NumElts; ++i) {
1461         unsigned char V = Str->getElementAsInteger(i);
1462         Record.push_back(V);
1463         isCStr7 &= (V & 128) == 0;
1464         if (isCStrChar6)
1465           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1466       }
1467
1468       if (isCStrChar6)
1469         AbbrevToUse = CString6Abbrev;
1470       else if (isCStr7)
1471         AbbrevToUse = CString7Abbrev;
1472     } else if (const ConstantDataSequential *CDS =
1473                   dyn_cast<ConstantDataSequential>(C)) {
1474       Code = bitc::CST_CODE_DATA;
1475       Type *EltTy = CDS->getType()->getElementType();
1476       if (isa<IntegerType>(EltTy)) {
1477         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1478           Record.push_back(CDS->getElementAsInteger(i));
1479       } else if (EltTy->isFloatTy()) {
1480         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1481           union { float F; uint32_t I; };
1482           F = CDS->getElementAsFloat(i);
1483           Record.push_back(I);
1484         }
1485       } else {
1486         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1487         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1488           union { double F; uint64_t I; };
1489           F = CDS->getElementAsDouble(i);
1490           Record.push_back(I);
1491         }
1492       }
1493     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1494                isa<ConstantVector>(C)) {
1495       Code = bitc::CST_CODE_AGGREGATE;
1496       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1497         Record.push_back(VE.getValueID(C->getOperand(i)));
1498       AbbrevToUse = AggregateAbbrev;
1499     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1500       switch (CE->getOpcode()) {
1501       default:
1502         if (Instruction::isCast(CE->getOpcode())) {
1503           Code = bitc::CST_CODE_CE_CAST;
1504           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1505           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1506           Record.push_back(VE.getValueID(C->getOperand(0)));
1507           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1508         } else {
1509           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1510           Code = bitc::CST_CODE_CE_BINOP;
1511           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1512           Record.push_back(VE.getValueID(C->getOperand(0)));
1513           Record.push_back(VE.getValueID(C->getOperand(1)));
1514           uint64_t Flags = GetOptimizationFlags(CE);
1515           if (Flags != 0)
1516             Record.push_back(Flags);
1517         }
1518         break;
1519       case Instruction::GetElementPtr:
1520         Code = bitc::CST_CODE_CE_GEP;
1521         if (cast<GEPOperator>(C)->isInBounds())
1522           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1523         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1524           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1525           Record.push_back(VE.getValueID(C->getOperand(i)));
1526         }
1527         break;
1528       case Instruction::Select:
1529         Code = bitc::CST_CODE_CE_SELECT;
1530         Record.push_back(VE.getValueID(C->getOperand(0)));
1531         Record.push_back(VE.getValueID(C->getOperand(1)));
1532         Record.push_back(VE.getValueID(C->getOperand(2)));
1533         break;
1534       case Instruction::ExtractElement:
1535         Code = bitc::CST_CODE_CE_EXTRACTELT;
1536         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1537         Record.push_back(VE.getValueID(C->getOperand(0)));
1538         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1539         Record.push_back(VE.getValueID(C->getOperand(1)));
1540         break;
1541       case Instruction::InsertElement:
1542         Code = bitc::CST_CODE_CE_INSERTELT;
1543         Record.push_back(VE.getValueID(C->getOperand(0)));
1544         Record.push_back(VE.getValueID(C->getOperand(1)));
1545         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1546         Record.push_back(VE.getValueID(C->getOperand(2)));
1547         break;
1548       case Instruction::ShuffleVector:
1549         // If the return type and argument types are the same, this is a
1550         // standard shufflevector instruction.  If the types are different,
1551         // then the shuffle is widening or truncating the input vectors, and
1552         // the argument type must also be encoded.
1553         if (C->getType() == C->getOperand(0)->getType()) {
1554           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1555         } else {
1556           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1557           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1558         }
1559         Record.push_back(VE.getValueID(C->getOperand(0)));
1560         Record.push_back(VE.getValueID(C->getOperand(1)));
1561         Record.push_back(VE.getValueID(C->getOperand(2)));
1562         break;
1563       case Instruction::ICmp:
1564       case Instruction::FCmp:
1565         Code = bitc::CST_CODE_CE_CMP;
1566         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1567         Record.push_back(VE.getValueID(C->getOperand(0)));
1568         Record.push_back(VE.getValueID(C->getOperand(1)));
1569         Record.push_back(CE->getPredicate());
1570         break;
1571       }
1572     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1573       Code = bitc::CST_CODE_BLOCKADDRESS;
1574       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1575       Record.push_back(VE.getValueID(BA->getFunction()));
1576       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1577     } else {
1578 #ifndef NDEBUG
1579       C->dump();
1580 #endif
1581       llvm_unreachable("Unknown constant!");
1582     }
1583     Stream.EmitRecord(Code, Record, AbbrevToUse);
1584     Record.clear();
1585   }
1586
1587   Stream.ExitBlock();
1588 }
1589
1590 static void WriteModuleConstants(const ValueEnumerator &VE,
1591                                  BitstreamWriter &Stream) {
1592   const ValueEnumerator::ValueList &Vals = VE.getValues();
1593
1594   // Find the first constant to emit, which is the first non-globalvalue value.
1595   // We know globalvalues have been emitted by WriteModuleInfo.
1596   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1597     if (!isa<GlobalValue>(Vals[i].first)) {
1598       WriteConstants(i, Vals.size(), VE, Stream, true);
1599       return;
1600     }
1601   }
1602 }
1603
1604 /// PushValueAndType - The file has to encode both the value and type id for
1605 /// many values, because we need to know what type to create for forward
1606 /// references.  However, most operands are not forward references, so this type
1607 /// field is not needed.
1608 ///
1609 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1610 /// instruction ID, then it is a forward reference, and it also includes the
1611 /// type ID.  The value ID that is written is encoded relative to the InstID.
1612 static bool PushValueAndType(const Value *V, unsigned InstID,
1613                              SmallVectorImpl<unsigned> &Vals,
1614                              ValueEnumerator &VE) {
1615   unsigned ValID = VE.getValueID(V);
1616   // Make encoding relative to the InstID.
1617   Vals.push_back(InstID - ValID);
1618   if (ValID >= InstID) {
1619     Vals.push_back(VE.getTypeID(V->getType()));
1620     return true;
1621   }
1622   return false;
1623 }
1624
1625 /// pushValue - Like PushValueAndType, but where the type of the value is
1626 /// omitted (perhaps it was already encoded in an earlier operand).
1627 static void pushValue(const Value *V, unsigned InstID,
1628                       SmallVectorImpl<unsigned> &Vals,
1629                       ValueEnumerator &VE) {
1630   unsigned ValID = VE.getValueID(V);
1631   Vals.push_back(InstID - ValID);
1632 }
1633
1634 static void pushValueSigned(const Value *V, unsigned InstID,
1635                             SmallVectorImpl<uint64_t> &Vals,
1636                             ValueEnumerator &VE) {
1637   unsigned ValID = VE.getValueID(V);
1638   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1639   emitSignedInt64(Vals, diff);
1640 }
1641
1642 /// WriteInstruction - Emit an instruction to the specified stream.
1643 static void WriteInstruction(const Instruction &I, unsigned InstID,
1644                              ValueEnumerator &VE, BitstreamWriter &Stream,
1645                              SmallVectorImpl<unsigned> &Vals) {
1646   unsigned Code = 0;
1647   unsigned AbbrevToUse = 0;
1648   VE.setInstructionID(&I);
1649   switch (I.getOpcode()) {
1650   default:
1651     if (Instruction::isCast(I.getOpcode())) {
1652       Code = bitc::FUNC_CODE_INST_CAST;
1653       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1654         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1655       Vals.push_back(VE.getTypeID(I.getType()));
1656       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1657     } else {
1658       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1659       Code = bitc::FUNC_CODE_INST_BINOP;
1660       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1661         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1662       pushValue(I.getOperand(1), InstID, Vals, VE);
1663       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1664       uint64_t Flags = GetOptimizationFlags(&I);
1665       if (Flags != 0) {
1666         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1667           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1668         Vals.push_back(Flags);
1669       }
1670     }
1671     break;
1672
1673   case Instruction::GetElementPtr:
1674     Code = bitc::FUNC_CODE_INST_GEP;
1675     if (cast<GEPOperator>(&I)->isInBounds())
1676       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1677     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1678       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1679     break;
1680   case Instruction::ExtractValue: {
1681     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1682     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1683     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1684     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1685       Vals.push_back(*i);
1686     break;
1687   }
1688   case Instruction::InsertValue: {
1689     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1690     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1691     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1692     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1693     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1694       Vals.push_back(*i);
1695     break;
1696   }
1697   case Instruction::Select:
1698     Code = bitc::FUNC_CODE_INST_VSELECT;
1699     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1700     pushValue(I.getOperand(2), InstID, Vals, VE);
1701     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1702     break;
1703   case Instruction::ExtractElement:
1704     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1705     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1706     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1707     break;
1708   case Instruction::InsertElement:
1709     Code = bitc::FUNC_CODE_INST_INSERTELT;
1710     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1711     pushValue(I.getOperand(1), InstID, Vals, VE);
1712     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1713     break;
1714   case Instruction::ShuffleVector:
1715     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1716     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1717     pushValue(I.getOperand(1), InstID, Vals, VE);
1718     pushValue(I.getOperand(2), InstID, Vals, VE);
1719     break;
1720   case Instruction::ICmp:
1721   case Instruction::FCmp:
1722     // compare returning Int1Ty or vector of Int1Ty
1723     Code = bitc::FUNC_CODE_INST_CMP2;
1724     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1725     pushValue(I.getOperand(1), InstID, Vals, VE);
1726     Vals.push_back(cast<CmpInst>(I).getPredicate());
1727     break;
1728
1729   case Instruction::Ret:
1730     {
1731       Code = bitc::FUNC_CODE_INST_RET;
1732       unsigned NumOperands = I.getNumOperands();
1733       if (NumOperands == 0)
1734         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1735       else if (NumOperands == 1) {
1736         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1737           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1738       } else {
1739         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1740           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1741       }
1742     }
1743     break;
1744   case Instruction::Br:
1745     {
1746       Code = bitc::FUNC_CODE_INST_BR;
1747       const BranchInst &II = cast<BranchInst>(I);
1748       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1749       if (II.isConditional()) {
1750         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1751         pushValue(II.getCondition(), InstID, Vals, VE);
1752       }
1753     }
1754     break;
1755   case Instruction::Switch:
1756     {
1757       Code = bitc::FUNC_CODE_INST_SWITCH;
1758       const SwitchInst &SI = cast<SwitchInst>(I);
1759       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1760       pushValue(SI.getCondition(), InstID, Vals, VE);
1761       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1762       for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1763            i != e; ++i) {
1764         Vals.push_back(VE.getValueID(i.getCaseValue()));
1765         Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1766       }
1767     }
1768     break;
1769   case Instruction::IndirectBr:
1770     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1771     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1772     // Encode the address operand as relative, but not the basic blocks.
1773     pushValue(I.getOperand(0), InstID, Vals, VE);
1774     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1775       Vals.push_back(VE.getValueID(I.getOperand(i)));
1776     break;
1777
1778   case Instruction::Invoke: {
1779     const InvokeInst *II = cast<InvokeInst>(&I);
1780     const Value *Callee(II->getCalledValue());
1781     PointerType *PTy = cast<PointerType>(Callee->getType());
1782     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1783     Code = bitc::FUNC_CODE_INST_INVOKE;
1784
1785     Vals.push_back(VE.getAttributeID(II->getAttributes()));
1786     Vals.push_back(II->getCallingConv());
1787     Vals.push_back(VE.getValueID(II->getNormalDest()));
1788     Vals.push_back(VE.getValueID(II->getUnwindDest()));
1789     PushValueAndType(Callee, InstID, Vals, VE);
1790
1791     // Emit value #'s for the fixed parameters.
1792     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1793       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
1794
1795     // Emit type/value pairs for varargs params.
1796     if (FTy->isVarArg()) {
1797       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1798            i != e; ++i)
1799         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1800     }
1801     break;
1802   }
1803   case Instruction::Resume:
1804     Code = bitc::FUNC_CODE_INST_RESUME;
1805     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1806     break;
1807   case Instruction::Unreachable:
1808     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1809     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1810     break;
1811
1812   case Instruction::PHI: {
1813     const PHINode &PN = cast<PHINode>(I);
1814     Code = bitc::FUNC_CODE_INST_PHI;
1815     // With the newer instruction encoding, forward references could give
1816     // negative valued IDs.  This is most common for PHIs, so we use
1817     // signed VBRs.
1818     SmallVector<uint64_t, 128> Vals64;
1819     Vals64.push_back(VE.getTypeID(PN.getType()));
1820     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1821       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1822       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1823     }
1824     // Emit a Vals64 vector and exit.
1825     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1826     Vals64.clear();
1827     return;
1828   }
1829
1830   case Instruction::LandingPad: {
1831     const LandingPadInst &LP = cast<LandingPadInst>(I);
1832     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1833     Vals.push_back(VE.getTypeID(LP.getType()));
1834     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1835     Vals.push_back(LP.isCleanup());
1836     Vals.push_back(LP.getNumClauses());
1837     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1838       if (LP.isCatch(I))
1839         Vals.push_back(LandingPadInst::Catch);
1840       else
1841         Vals.push_back(LandingPadInst::Filter);
1842       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1843     }
1844     break;
1845   }
1846
1847   case Instruction::Alloca: {
1848     Code = bitc::FUNC_CODE_INST_ALLOCA;
1849     Vals.push_back(VE.getTypeID(I.getType()));
1850     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1851     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1852     const AllocaInst &AI = cast<AllocaInst>(I);
1853     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1854     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1855            "not enough bits for maximum alignment");
1856     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1857     AlignRecord |= AI.isUsedWithInAlloca() << 5;
1858     Vals.push_back(AlignRecord);
1859     break;
1860   }
1861
1862   case Instruction::Load:
1863     if (cast<LoadInst>(I).isAtomic()) {
1864       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1865       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1866     } else {
1867       Code = bitc::FUNC_CODE_INST_LOAD;
1868       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1869         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1870     }
1871     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1872     Vals.push_back(cast<LoadInst>(I).isVolatile());
1873     if (cast<LoadInst>(I).isAtomic()) {
1874       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1875       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1876     }
1877     break;
1878   case Instruction::Store:
1879     if (cast<StoreInst>(I).isAtomic())
1880       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1881     else
1882       Code = bitc::FUNC_CODE_INST_STORE;
1883     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1884     pushValue(I.getOperand(0), InstID, Vals, VE);         // val.
1885     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1886     Vals.push_back(cast<StoreInst>(I).isVolatile());
1887     if (cast<StoreInst>(I).isAtomic()) {
1888       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1889       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1890     }
1891     break;
1892   case Instruction::AtomicCmpXchg:
1893     Code = bitc::FUNC_CODE_INST_CMPXCHG;
1894     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1895     pushValue(I.getOperand(1), InstID, Vals, VE);         // cmp.
1896     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
1897     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1898     Vals.push_back(GetEncodedOrdering(
1899                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1900     Vals.push_back(GetEncodedSynchScope(
1901                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
1902     Vals.push_back(GetEncodedOrdering(
1903                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1904     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1905     break;
1906   case Instruction::AtomicRMW:
1907     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1908     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1909     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
1910     Vals.push_back(GetEncodedRMWOperation(
1911                      cast<AtomicRMWInst>(I).getOperation()));
1912     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1913     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1914     Vals.push_back(GetEncodedSynchScope(
1915                      cast<AtomicRMWInst>(I).getSynchScope()));
1916     break;
1917   case Instruction::Fence:
1918     Code = bitc::FUNC_CODE_INST_FENCE;
1919     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1920     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1921     break;
1922   case Instruction::Call: {
1923     const CallInst &CI = cast<CallInst>(I);
1924     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1925     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1926
1927     Code = bitc::FUNC_CODE_INST_CALL;
1928
1929     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1930     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1931                    unsigned(CI.isMustTailCall()) << 14);
1932     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
1933
1934     // Emit value #'s for the fixed parameters.
1935     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1936       // Check for labels (can happen with asm labels).
1937       if (FTy->getParamType(i)->isLabelTy())
1938         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1939       else
1940         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
1941     }
1942
1943     // Emit type/value pairs for varargs params.
1944     if (FTy->isVarArg()) {
1945       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1946            i != e; ++i)
1947         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
1948     }
1949     break;
1950   }
1951   case Instruction::VAArg:
1952     Code = bitc::FUNC_CODE_INST_VAARG;
1953     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
1954     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1955     Vals.push_back(VE.getTypeID(I.getType())); // restype.
1956     break;
1957   }
1958
1959   Stream.EmitRecord(Code, Vals, AbbrevToUse);
1960   Vals.clear();
1961 }
1962
1963 // Emit names for globals/functions etc.
1964 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1965                                   const ValueEnumerator &VE,
1966                                   BitstreamWriter &Stream) {
1967   if (VST.empty()) return;
1968   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1969
1970   // FIXME: Set up the abbrev, we know how many values there are!
1971   // FIXME: We know if the type names can use 7-bit ascii.
1972   SmallVector<unsigned, 64> NameVals;
1973
1974   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1975        SI != SE; ++SI) {
1976
1977     const ValueName &Name = *SI;
1978
1979     // Figure out the encoding to use for the name.
1980     bool is7Bit = true;
1981     bool isChar6 = true;
1982     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1983          C != E; ++C) {
1984       if (isChar6)
1985         isChar6 = BitCodeAbbrevOp::isChar6(*C);
1986       if ((unsigned char)*C & 128) {
1987         is7Bit = false;
1988         break;  // don't bother scanning the rest.
1989       }
1990     }
1991
1992     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1993
1994     // VST_ENTRY:   [valueid, namechar x N]
1995     // VST_BBENTRY: [bbid, namechar x N]
1996     unsigned Code;
1997     if (isa<BasicBlock>(SI->getValue())) {
1998       Code = bitc::VST_CODE_BBENTRY;
1999       if (isChar6)
2000         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2001     } else {
2002       Code = bitc::VST_CODE_ENTRY;
2003       if (isChar6)
2004         AbbrevToUse = VST_ENTRY_6_ABBREV;
2005       else if (is7Bit)
2006         AbbrevToUse = VST_ENTRY_7_ABBREV;
2007     }
2008
2009     NameVals.push_back(VE.getValueID(SI->getValue()));
2010     for (const char *P = Name.getKeyData(),
2011          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2012       NameVals.push_back((unsigned char)*P);
2013
2014     // Emit the finished record.
2015     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2016     NameVals.clear();
2017   }
2018   Stream.ExitBlock();
2019 }
2020
2021 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2022                          BitstreamWriter &Stream) {
2023   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2024   unsigned Code;
2025   if (isa<BasicBlock>(Order.V))
2026     Code = bitc::USELIST_CODE_BB;
2027   else
2028     Code = bitc::USELIST_CODE_DEFAULT;
2029
2030   SmallVector<uint64_t, 64> Record;
2031   for (unsigned I : Order.Shuffle)
2032     Record.push_back(I);
2033   Record.push_back(VE.getValueID(Order.V));
2034   Stream.EmitRecord(Code, Record);
2035 }
2036
2037 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2038                               BitstreamWriter &Stream) {
2039   auto hasMore = [&]() {
2040     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2041   };
2042   if (!hasMore())
2043     // Nothing to do.
2044     return;
2045
2046   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2047   while (hasMore()) {
2048     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2049     VE.UseListOrders.pop_back();
2050   }
2051   Stream.ExitBlock();
2052 }
2053
2054 /// WriteFunction - Emit a function body to the module stream.
2055 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2056                           BitstreamWriter &Stream) {
2057   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2058   VE.incorporateFunction(F);
2059
2060   SmallVector<unsigned, 64> Vals;
2061
2062   // Emit the number of basic blocks, so the reader can create them ahead of
2063   // time.
2064   Vals.push_back(VE.getBasicBlocks().size());
2065   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2066   Vals.clear();
2067
2068   // If there are function-local constants, emit them now.
2069   unsigned CstStart, CstEnd;
2070   VE.getFunctionConstantRange(CstStart, CstEnd);
2071   WriteConstants(CstStart, CstEnd, VE, Stream, false);
2072
2073   // If there is function-local metadata, emit it now.
2074   WriteFunctionLocalMetadata(F, VE, Stream);
2075
2076   // Keep a running idea of what the instruction ID is.
2077   unsigned InstID = CstEnd;
2078
2079   bool NeedsMetadataAttachment = false;
2080
2081   DebugLoc LastDL;
2082
2083   // Finally, emit all the instructions, in order.
2084   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2085     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2086          I != E; ++I) {
2087       WriteInstruction(*I, InstID, VE, Stream, Vals);
2088
2089       if (!I->getType()->isVoidTy())
2090         ++InstID;
2091
2092       // If the instruction has metadata, write a metadata attachment later.
2093       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2094
2095       // If the instruction has a debug location, emit it.
2096       DebugLoc DL = I->getDebugLoc();
2097       if (DL.isUnknown()) {
2098         // nothing todo.
2099       } else if (DL == LastDL) {
2100         // Just repeat the same debug loc as last time.
2101         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2102       } else {
2103         MDNode *Scope, *IA;
2104         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
2105         assert(Scope && "Expected valid scope");
2106
2107         Vals.push_back(DL.getLine());
2108         Vals.push_back(DL.getCol());
2109         Vals.push_back(VE.getMetadataOrNullID(Scope));
2110         Vals.push_back(VE.getMetadataOrNullID(IA));
2111         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2112         Vals.clear();
2113
2114         LastDL = DL;
2115       }
2116     }
2117
2118   // Emit names for all the instructions etc.
2119   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2120
2121   if (NeedsMetadataAttachment)
2122     WriteMetadataAttachment(F, VE, Stream);
2123   if (shouldPreserveBitcodeUseListOrder())
2124     WriteUseListBlock(&F, VE, Stream);
2125   VE.purgeFunction();
2126   Stream.ExitBlock();
2127 }
2128
2129 // Emit blockinfo, which defines the standard abbreviations etc.
2130 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2131   // We only want to emit block info records for blocks that have multiple
2132   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2133   // Other blocks can define their abbrevs inline.
2134   Stream.EnterBlockInfoBlock(2);
2135
2136   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2137     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2138     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2139     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2140     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2141     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2142     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2143                                    Abbv) != VST_ENTRY_8_ABBREV)
2144       llvm_unreachable("Unexpected abbrev ordering!");
2145   }
2146
2147   { // 7-bit fixed width VST_ENTRY strings.
2148     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2149     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2150     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2151     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2152     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2153     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2154                                    Abbv) != VST_ENTRY_7_ABBREV)
2155       llvm_unreachable("Unexpected abbrev ordering!");
2156   }
2157   { // 6-bit char6 VST_ENTRY strings.
2158     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2159     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2160     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2161     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2162     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2163     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2164                                    Abbv) != VST_ENTRY_6_ABBREV)
2165       llvm_unreachable("Unexpected abbrev ordering!");
2166   }
2167   { // 6-bit char6 VST_BBENTRY strings.
2168     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2169     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2170     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2171     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2172     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2173     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2174                                    Abbv) != VST_BBENTRY_6_ABBREV)
2175       llvm_unreachable("Unexpected abbrev ordering!");
2176   }
2177
2178
2179
2180   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2181     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2182     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2183     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2184                               Log2_32_Ceil(VE.getTypes().size()+1)));
2185     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2186                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
2187       llvm_unreachable("Unexpected abbrev ordering!");
2188   }
2189
2190   { // INTEGER abbrev for CONSTANTS_BLOCK.
2191     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2192     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2193     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2194     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2195                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
2196       llvm_unreachable("Unexpected abbrev ordering!");
2197   }
2198
2199   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2200     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2201     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2202     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
2203     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
2204                               Log2_32_Ceil(VE.getTypes().size()+1)));
2205     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
2206
2207     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2208                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
2209       llvm_unreachable("Unexpected abbrev ordering!");
2210   }
2211   { // NULL abbrev for CONSTANTS_BLOCK.
2212     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2213     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2214     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2215                                    Abbv) != CONSTANTS_NULL_Abbrev)
2216       llvm_unreachable("Unexpected abbrev ordering!");
2217   }
2218
2219   // FIXME: This should only use space for first class types!
2220
2221   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2222     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2223     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2224     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2225     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2226     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2227     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2228                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
2229       llvm_unreachable("Unexpected abbrev ordering!");
2230   }
2231   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2232     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2233     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2234     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2235     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2236     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2237     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2238                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
2239       llvm_unreachable("Unexpected abbrev ordering!");
2240   }
2241   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2242     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2243     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2244     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2245     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2246     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2247     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2248     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2249                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2250       llvm_unreachable("Unexpected abbrev ordering!");
2251   }
2252   { // INST_CAST abbrev for FUNCTION_BLOCK.
2253     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2254     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2255     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
2256     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
2257                               Log2_32_Ceil(VE.getTypes().size()+1)));
2258     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
2259     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2260                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
2261       llvm_unreachable("Unexpected abbrev ordering!");
2262   }
2263
2264   { // INST_RET abbrev for FUNCTION_BLOCK.
2265     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2266     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2267     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2268                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2269       llvm_unreachable("Unexpected abbrev ordering!");
2270   }
2271   { // INST_RET abbrev for FUNCTION_BLOCK.
2272     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2273     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2274     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2275     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2276                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2277       llvm_unreachable("Unexpected abbrev ordering!");
2278   }
2279   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2280     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2281     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2282     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2283                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2284       llvm_unreachable("Unexpected abbrev ordering!");
2285   }
2286
2287   Stream.ExitBlock();
2288 }
2289
2290 /// WriteModule - Emit the specified module to the bitstream.
2291 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
2292   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2293
2294   SmallVector<unsigned, 1> Vals;
2295   unsigned CurVersion = 1;
2296   Vals.push_back(CurVersion);
2297   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2298
2299   // Analyze the module, enumerating globals, functions, etc.
2300   ValueEnumerator VE(*M);
2301
2302   // Emit blockinfo, which defines the standard abbreviations etc.
2303   WriteBlockInfo(VE, Stream);
2304
2305   // Emit information about attribute groups.
2306   WriteAttributeGroupTable(VE, Stream);
2307
2308   // Emit information about parameter attributes.
2309   WriteAttributeTable(VE, Stream);
2310
2311   // Emit information describing all of the types in the module.
2312   WriteTypeTable(VE, Stream);
2313
2314   writeComdats(VE, Stream);
2315
2316   // Emit top-level description of module, including target triple, inline asm,
2317   // descriptors for global variables, and function prototype info.
2318   WriteModuleInfo(M, VE, Stream);
2319
2320   // Emit constants.
2321   WriteModuleConstants(VE, Stream);
2322
2323   // Emit metadata.
2324   WriteModuleMetadata(M, VE, Stream);
2325
2326   // Emit metadata.
2327   WriteModuleMetadataStore(M, Stream);
2328
2329   // Emit names for globals/functions etc.
2330   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2331
2332   // Emit module-level use-lists.
2333   if (shouldPreserveBitcodeUseListOrder())
2334     WriteUseListBlock(nullptr, VE, Stream);
2335
2336   // Emit function bodies.
2337   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2338     if (!F->isDeclaration())
2339       WriteFunction(*F, VE, Stream);
2340
2341   Stream.ExitBlock();
2342 }
2343
2344 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2345 /// header and trailer to make it compatible with the system archiver.  To do
2346 /// this we emit the following header, and then emit a trailer that pads the
2347 /// file out to be a multiple of 16 bytes.
2348 ///
2349 /// struct bc_header {
2350 ///   uint32_t Magic;         // 0x0B17C0DE
2351 ///   uint32_t Version;       // Version, currently always 0.
2352 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2353 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
2354 ///   uint32_t CPUType;       // CPU specifier.
2355 ///   ... potentially more later ...
2356 /// };
2357 enum {
2358   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2359   DarwinBCHeaderSize = 5*4
2360 };
2361
2362 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2363                                uint32_t &Position) {
2364   Buffer[Position + 0] = (unsigned char) (Value >>  0);
2365   Buffer[Position + 1] = (unsigned char) (Value >>  8);
2366   Buffer[Position + 2] = (unsigned char) (Value >> 16);
2367   Buffer[Position + 3] = (unsigned char) (Value >> 24);
2368   Position += 4;
2369 }
2370
2371 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2372                                          const Triple &TT) {
2373   unsigned CPUType = ~0U;
2374
2375   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2376   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2377   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
2378   // specific constants here because they are implicitly part of the Darwin ABI.
2379   enum {
2380     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
2381     DARWIN_CPU_TYPE_X86        = 7,
2382     DARWIN_CPU_TYPE_ARM        = 12,
2383     DARWIN_CPU_TYPE_POWERPC    = 18
2384   };
2385
2386   Triple::ArchType Arch = TT.getArch();
2387   if (Arch == Triple::x86_64)
2388     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2389   else if (Arch == Triple::x86)
2390     CPUType = DARWIN_CPU_TYPE_X86;
2391   else if (Arch == Triple::ppc)
2392     CPUType = DARWIN_CPU_TYPE_POWERPC;
2393   else if (Arch == Triple::ppc64)
2394     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2395   else if (Arch == Triple::arm || Arch == Triple::thumb)
2396     CPUType = DARWIN_CPU_TYPE_ARM;
2397
2398   // Traditional Bitcode starts after header.
2399   assert(Buffer.size() >= DarwinBCHeaderSize &&
2400          "Expected header size to be reserved");
2401   unsigned BCOffset = DarwinBCHeaderSize;
2402   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2403
2404   // Write the magic and version.
2405   unsigned Position = 0;
2406   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2407   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
2408   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
2409   WriteInt32ToBuffer(BCSize     , Buffer, Position);
2410   WriteInt32ToBuffer(CPUType    , Buffer, Position);
2411
2412   // If the file is not a multiple of 16 bytes, insert dummy padding.
2413   while (Buffer.size() & 15)
2414     Buffer.push_back(0);
2415 }
2416
2417 /// WriteBitcodeToFile - Write the specified module to the specified output
2418 /// stream.
2419 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2420   SmallVector<char, 0> Buffer;
2421   Buffer.reserve(256*1024);
2422
2423   // If this is darwin or another generic macho target, reserve space for the
2424   // header.
2425   Triple TT(M->getTargetTriple());
2426   if (TT.isOSDarwin())
2427     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2428
2429   // Emit the module into the buffer.
2430   {
2431     BitstreamWriter Stream(Buffer);
2432
2433     // Emit the file header.
2434     Stream.Emit((unsigned)'B', 8);
2435     Stream.Emit((unsigned)'C', 8);
2436     Stream.Emit(0x0, 4);
2437     Stream.Emit(0xC, 4);
2438     Stream.Emit(0xE, 4);
2439     Stream.Emit(0xD, 4);
2440
2441     // Emit the module.
2442     WriteModule(M, Stream);
2443   }
2444
2445   if (TT.isOSDarwin())
2446     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2447
2448   // Write the generated bitstream to "Out".
2449   Out.write((char*)&Buffer.front(), Buffer.size());
2450 }