xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 12b79aa0f1b7aa6e792a0b65d219a969f4ea8f0b)
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 "ValueEnumerator.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/BlockFrequencyInfo.h"
18 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
19 #include "llvm/Analysis/BranchProbabilityInfo.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Bitcode/BitstreamWriter.h"
22 #include "llvm/Bitcode/LLVMBitCodes.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/UseListOrder.h"
36 #include "llvm/IR/ValueSymbolTable.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <cctype>
43 #include <map>
44 using namespace llvm;
45 
46 /// These are manifest constants used by the bitcode writer. They do not need to
47 /// be kept in sync with the reader, but need to be consistent within this file.
48 enum {
49   // VALUE_SYMTAB_BLOCK abbrev id's.
50   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51   VST_ENTRY_7_ABBREV,
52   VST_ENTRY_6_ABBREV,
53   VST_BBENTRY_6_ABBREV,
54 
55   // CONSTANTS_BLOCK abbrev id's.
56   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
57   CONSTANTS_INTEGER_ABBREV,
58   CONSTANTS_CE_CAST_Abbrev,
59   CONSTANTS_NULL_Abbrev,
60 
61   // FUNCTION_BLOCK abbrev id's.
62   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
63   FUNCTION_INST_BINOP_ABBREV,
64   FUNCTION_INST_BINOP_FLAGS_ABBREV,
65   FUNCTION_INST_CAST_ABBREV,
66   FUNCTION_INST_RET_VOID_ABBREV,
67   FUNCTION_INST_RET_VAL_ABBREV,
68   FUNCTION_INST_UNREACHABLE_ABBREV,
69   FUNCTION_INST_GEP_ABBREV,
70 };
71 
72 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
73   switch (Opcode) {
74   default: llvm_unreachable("Unknown cast instruction!");
75   case Instruction::Trunc   : return bitc::CAST_TRUNC;
76   case Instruction::ZExt    : return bitc::CAST_ZEXT;
77   case Instruction::SExt    : return bitc::CAST_SEXT;
78   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
79   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
80   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
81   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
82   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
83   case Instruction::FPExt   : return bitc::CAST_FPEXT;
84   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
85   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
86   case Instruction::BitCast : return bitc::CAST_BITCAST;
87   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
88   }
89 }
90 
91 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
92   switch (Opcode) {
93   default: llvm_unreachable("Unknown binary instruction!");
94   case Instruction::Add:
95   case Instruction::FAdd: return bitc::BINOP_ADD;
96   case Instruction::Sub:
97   case Instruction::FSub: return bitc::BINOP_SUB;
98   case Instruction::Mul:
99   case Instruction::FMul: return bitc::BINOP_MUL;
100   case Instruction::UDiv: return bitc::BINOP_UDIV;
101   case Instruction::FDiv:
102   case Instruction::SDiv: return bitc::BINOP_SDIV;
103   case Instruction::URem: return bitc::BINOP_UREM;
104   case Instruction::FRem:
105   case Instruction::SRem: return bitc::BINOP_SREM;
106   case Instruction::Shl:  return bitc::BINOP_SHL;
107   case Instruction::LShr: return bitc::BINOP_LSHR;
108   case Instruction::AShr: return bitc::BINOP_ASHR;
109   case Instruction::And:  return bitc::BINOP_AND;
110   case Instruction::Or:   return bitc::BINOP_OR;
111   case Instruction::Xor:  return bitc::BINOP_XOR;
112   }
113 }
114 
115 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
116   switch (Op) {
117   default: llvm_unreachable("Unknown RMW operation!");
118   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
119   case AtomicRMWInst::Add: return bitc::RMW_ADD;
120   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
121   case AtomicRMWInst::And: return bitc::RMW_AND;
122   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
123   case AtomicRMWInst::Or: return bitc::RMW_OR;
124   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
125   case AtomicRMWInst::Max: return bitc::RMW_MAX;
126   case AtomicRMWInst::Min: return bitc::RMW_MIN;
127   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
128   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
129   }
130 }
131 
132 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
133   switch (Ordering) {
134   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
135   case Unordered: return bitc::ORDERING_UNORDERED;
136   case Monotonic: return bitc::ORDERING_MONOTONIC;
137   case Acquire: return bitc::ORDERING_ACQUIRE;
138   case Release: return bitc::ORDERING_RELEASE;
139   case AcquireRelease: return bitc::ORDERING_ACQREL;
140   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
141   }
142   llvm_unreachable("Invalid ordering");
143 }
144 
145 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
146   switch (SynchScope) {
147   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
148   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
149   }
150   llvm_unreachable("Invalid synch scope");
151 }
152 
153 static void WriteStringRecord(unsigned Code, StringRef Str,
154                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
155   SmallVector<unsigned, 64> Vals;
156 
157   // Code: [strchar x N]
158   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
159     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
160       AbbrevToUse = 0;
161     Vals.push_back(Str[i]);
162   }
163 
164   // Emit the finished record.
165   Stream.EmitRecord(Code, Vals, AbbrevToUse);
166 }
167 
168 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
169   switch (Kind) {
170   case Attribute::Alignment:
171     return bitc::ATTR_KIND_ALIGNMENT;
172   case Attribute::AlwaysInline:
173     return bitc::ATTR_KIND_ALWAYS_INLINE;
174   case Attribute::ArgMemOnly:
175     return bitc::ATTR_KIND_ARGMEMONLY;
176   case Attribute::Builtin:
177     return bitc::ATTR_KIND_BUILTIN;
178   case Attribute::ByVal:
179     return bitc::ATTR_KIND_BY_VAL;
180   case Attribute::Convergent:
181     return bitc::ATTR_KIND_CONVERGENT;
182   case Attribute::InAlloca:
183     return bitc::ATTR_KIND_IN_ALLOCA;
184   case Attribute::Cold:
185     return bitc::ATTR_KIND_COLD;
186   case Attribute::InaccessibleMemOnly:
187     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
188   case Attribute::InaccessibleMemOrArgMemOnly:
189     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
190   case Attribute::InlineHint:
191     return bitc::ATTR_KIND_INLINE_HINT;
192   case Attribute::InReg:
193     return bitc::ATTR_KIND_IN_REG;
194   case Attribute::JumpTable:
195     return bitc::ATTR_KIND_JUMP_TABLE;
196   case Attribute::MinSize:
197     return bitc::ATTR_KIND_MIN_SIZE;
198   case Attribute::Naked:
199     return bitc::ATTR_KIND_NAKED;
200   case Attribute::Nest:
201     return bitc::ATTR_KIND_NEST;
202   case Attribute::NoAlias:
203     return bitc::ATTR_KIND_NO_ALIAS;
204   case Attribute::NoBuiltin:
205     return bitc::ATTR_KIND_NO_BUILTIN;
206   case Attribute::NoCapture:
207     return bitc::ATTR_KIND_NO_CAPTURE;
208   case Attribute::NoDuplicate:
209     return bitc::ATTR_KIND_NO_DUPLICATE;
210   case Attribute::NoImplicitFloat:
211     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
212   case Attribute::NoInline:
213     return bitc::ATTR_KIND_NO_INLINE;
214   case Attribute::NoRecurse:
215     return bitc::ATTR_KIND_NO_RECURSE;
216   case Attribute::NonLazyBind:
217     return bitc::ATTR_KIND_NON_LAZY_BIND;
218   case Attribute::NonNull:
219     return bitc::ATTR_KIND_NON_NULL;
220   case Attribute::Dereferenceable:
221     return bitc::ATTR_KIND_DEREFERENCEABLE;
222   case Attribute::DereferenceableOrNull:
223     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
224   case Attribute::NoRedZone:
225     return bitc::ATTR_KIND_NO_RED_ZONE;
226   case Attribute::NoReturn:
227     return bitc::ATTR_KIND_NO_RETURN;
228   case Attribute::NoUnwind:
229     return bitc::ATTR_KIND_NO_UNWIND;
230   case Attribute::OptimizeForSize:
231     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
232   case Attribute::OptimizeNone:
233     return bitc::ATTR_KIND_OPTIMIZE_NONE;
234   case Attribute::ReadNone:
235     return bitc::ATTR_KIND_READ_NONE;
236   case Attribute::ReadOnly:
237     return bitc::ATTR_KIND_READ_ONLY;
238   case Attribute::Returned:
239     return bitc::ATTR_KIND_RETURNED;
240   case Attribute::ReturnsTwice:
241     return bitc::ATTR_KIND_RETURNS_TWICE;
242   case Attribute::SExt:
243     return bitc::ATTR_KIND_S_EXT;
244   case Attribute::StackAlignment:
245     return bitc::ATTR_KIND_STACK_ALIGNMENT;
246   case Attribute::StackProtect:
247     return bitc::ATTR_KIND_STACK_PROTECT;
248   case Attribute::StackProtectReq:
249     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
250   case Attribute::StackProtectStrong:
251     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
252   case Attribute::SafeStack:
253     return bitc::ATTR_KIND_SAFESTACK;
254   case Attribute::StructRet:
255     return bitc::ATTR_KIND_STRUCT_RET;
256   case Attribute::SanitizeAddress:
257     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
258   case Attribute::SanitizeThread:
259     return bitc::ATTR_KIND_SANITIZE_THREAD;
260   case Attribute::SanitizeMemory:
261     return bitc::ATTR_KIND_SANITIZE_MEMORY;
262   case Attribute::UWTable:
263     return bitc::ATTR_KIND_UW_TABLE;
264   case Attribute::ZExt:
265     return bitc::ATTR_KIND_Z_EXT;
266   case Attribute::EndAttrKinds:
267     llvm_unreachable("Can not encode end-attribute kinds marker.");
268   case Attribute::None:
269     llvm_unreachable("Can not encode none-attribute.");
270   }
271 
272   llvm_unreachable("Trying to encode unknown attribute");
273 }
274 
275 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
276                                      BitstreamWriter &Stream) {
277   const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
278   if (AttrGrps.empty()) return;
279 
280   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
281 
282   SmallVector<uint64_t, 64> Record;
283   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
284     AttributeSet AS = AttrGrps[i];
285     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
286       AttributeSet A = AS.getSlotAttributes(i);
287 
288       Record.push_back(VE.getAttributeGroupID(A));
289       Record.push_back(AS.getSlotIndex(i));
290 
291       for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
292            I != E; ++I) {
293         Attribute Attr = *I;
294         if (Attr.isEnumAttribute()) {
295           Record.push_back(0);
296           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
297         } else if (Attr.isIntAttribute()) {
298           Record.push_back(1);
299           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
300           Record.push_back(Attr.getValueAsInt());
301         } else {
302           StringRef Kind = Attr.getKindAsString();
303           StringRef Val = Attr.getValueAsString();
304 
305           Record.push_back(Val.empty() ? 3 : 4);
306           Record.append(Kind.begin(), Kind.end());
307           Record.push_back(0);
308           if (!Val.empty()) {
309             Record.append(Val.begin(), Val.end());
310             Record.push_back(0);
311           }
312         }
313       }
314 
315       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
316       Record.clear();
317     }
318   }
319 
320   Stream.ExitBlock();
321 }
322 
323 static void WriteAttributeTable(const ValueEnumerator &VE,
324                                 BitstreamWriter &Stream) {
325   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
326   if (Attrs.empty()) return;
327 
328   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
329 
330   SmallVector<uint64_t, 64> Record;
331   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
332     const AttributeSet &A = Attrs[i];
333     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
334       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
335 
336     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
337     Record.clear();
338   }
339 
340   Stream.ExitBlock();
341 }
342 
343 /// WriteTypeTable - Write out the type table for a module.
344 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
345   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
346 
347   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
348   SmallVector<uint64_t, 64> TypeVals;
349 
350   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
351 
352   // Abbrev for TYPE_CODE_POINTER.
353   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
354   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
355   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
356   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
357   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
358 
359   // Abbrev for TYPE_CODE_FUNCTION.
360   Abbv = new BitCodeAbbrev();
361   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
362   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
363   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
364   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
365 
366   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
367 
368   // Abbrev for TYPE_CODE_STRUCT_ANON.
369   Abbv = new BitCodeAbbrev();
370   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
371   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
372   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
373   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
374 
375   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
376 
377   // Abbrev for TYPE_CODE_STRUCT_NAME.
378   Abbv = new BitCodeAbbrev();
379   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
380   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
381   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
382   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
383 
384   // Abbrev for TYPE_CODE_STRUCT_NAMED.
385   Abbv = new BitCodeAbbrev();
386   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
387   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
388   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
389   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
390 
391   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
392 
393   // Abbrev for TYPE_CODE_ARRAY.
394   Abbv = new BitCodeAbbrev();
395   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
396   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
397   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
398 
399   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
400 
401   // Emit an entry count so the reader can reserve space.
402   TypeVals.push_back(TypeList.size());
403   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
404   TypeVals.clear();
405 
406   // Loop over all of the types, emitting each in turn.
407   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
408     Type *T = TypeList[i];
409     int AbbrevToUse = 0;
410     unsigned Code = 0;
411 
412     switch (T->getTypeID()) {
413     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
414     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
415     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
416     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
417     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
418     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
419     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
420     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
421     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
422     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
423     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
424     case Type::IntegerTyID:
425       // INTEGER: [width]
426       Code = bitc::TYPE_CODE_INTEGER;
427       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
428       break;
429     case Type::PointerTyID: {
430       PointerType *PTy = cast<PointerType>(T);
431       // POINTER: [pointee type, address space]
432       Code = bitc::TYPE_CODE_POINTER;
433       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
434       unsigned AddressSpace = PTy->getAddressSpace();
435       TypeVals.push_back(AddressSpace);
436       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
437       break;
438     }
439     case Type::FunctionTyID: {
440       FunctionType *FT = cast<FunctionType>(T);
441       // FUNCTION: [isvararg, retty, paramty x N]
442       Code = bitc::TYPE_CODE_FUNCTION;
443       TypeVals.push_back(FT->isVarArg());
444       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
445       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
446         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
447       AbbrevToUse = FunctionAbbrev;
448       break;
449     }
450     case Type::StructTyID: {
451       StructType *ST = cast<StructType>(T);
452       // STRUCT: [ispacked, eltty x N]
453       TypeVals.push_back(ST->isPacked());
454       // Output all of the element types.
455       for (StructType::element_iterator I = ST->element_begin(),
456            E = ST->element_end(); I != E; ++I)
457         TypeVals.push_back(VE.getTypeID(*I));
458 
459       if (ST->isLiteral()) {
460         Code = bitc::TYPE_CODE_STRUCT_ANON;
461         AbbrevToUse = StructAnonAbbrev;
462       } else {
463         if (ST->isOpaque()) {
464           Code = bitc::TYPE_CODE_OPAQUE;
465         } else {
466           Code = bitc::TYPE_CODE_STRUCT_NAMED;
467           AbbrevToUse = StructNamedAbbrev;
468         }
469 
470         // Emit the name if it is present.
471         if (!ST->getName().empty())
472           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
473                             StructNameAbbrev, Stream);
474       }
475       break;
476     }
477     case Type::ArrayTyID: {
478       ArrayType *AT = cast<ArrayType>(T);
479       // ARRAY: [numelts, eltty]
480       Code = bitc::TYPE_CODE_ARRAY;
481       TypeVals.push_back(AT->getNumElements());
482       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
483       AbbrevToUse = ArrayAbbrev;
484       break;
485     }
486     case Type::VectorTyID: {
487       VectorType *VT = cast<VectorType>(T);
488       // VECTOR [numelts, eltty]
489       Code = bitc::TYPE_CODE_VECTOR;
490       TypeVals.push_back(VT->getNumElements());
491       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
492       break;
493     }
494     }
495 
496     // Emit the finished record.
497     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
498     TypeVals.clear();
499   }
500 
501   Stream.ExitBlock();
502 }
503 
504 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
505   switch (Linkage) {
506   case GlobalValue::ExternalLinkage:
507     return 0;
508   case GlobalValue::WeakAnyLinkage:
509     return 16;
510   case GlobalValue::AppendingLinkage:
511     return 2;
512   case GlobalValue::InternalLinkage:
513     return 3;
514   case GlobalValue::LinkOnceAnyLinkage:
515     return 18;
516   case GlobalValue::ExternalWeakLinkage:
517     return 7;
518   case GlobalValue::CommonLinkage:
519     return 8;
520   case GlobalValue::PrivateLinkage:
521     return 9;
522   case GlobalValue::WeakODRLinkage:
523     return 17;
524   case GlobalValue::LinkOnceODRLinkage:
525     return 19;
526   case GlobalValue::AvailableExternallyLinkage:
527     return 12;
528   }
529   llvm_unreachable("Invalid linkage");
530 }
531 
532 static unsigned getEncodedLinkage(const GlobalValue &GV) {
533   return getEncodedLinkage(GV.getLinkage());
534 }
535 
536 static unsigned getEncodedVisibility(const GlobalValue &GV) {
537   switch (GV.getVisibility()) {
538   case GlobalValue::DefaultVisibility:   return 0;
539   case GlobalValue::HiddenVisibility:    return 1;
540   case GlobalValue::ProtectedVisibility: return 2;
541   }
542   llvm_unreachable("Invalid visibility");
543 }
544 
545 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
546   switch (GV.getDLLStorageClass()) {
547   case GlobalValue::DefaultStorageClass:   return 0;
548   case GlobalValue::DLLImportStorageClass: return 1;
549   case GlobalValue::DLLExportStorageClass: return 2;
550   }
551   llvm_unreachable("Invalid DLL storage class");
552 }
553 
554 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
555   switch (GV.getThreadLocalMode()) {
556     case GlobalVariable::NotThreadLocal:         return 0;
557     case GlobalVariable::GeneralDynamicTLSModel: return 1;
558     case GlobalVariable::LocalDynamicTLSModel:   return 2;
559     case GlobalVariable::InitialExecTLSModel:    return 3;
560     case GlobalVariable::LocalExecTLSModel:      return 4;
561   }
562   llvm_unreachable("Invalid TLS model");
563 }
564 
565 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
566   switch (C.getSelectionKind()) {
567   case Comdat::Any:
568     return bitc::COMDAT_SELECTION_KIND_ANY;
569   case Comdat::ExactMatch:
570     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
571   case Comdat::Largest:
572     return bitc::COMDAT_SELECTION_KIND_LARGEST;
573   case Comdat::NoDuplicates:
574     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
575   case Comdat::SameSize:
576     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
577   }
578   llvm_unreachable("Invalid selection kind");
579 }
580 
581 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
582   SmallVector<unsigned, 64> Vals;
583   for (const Comdat *C : VE.getComdats()) {
584     // COMDAT: [selection_kind, name]
585     Vals.push_back(getEncodedComdatSelectionKind(*C));
586     size_t Size = C->getName().size();
587     assert(isUInt<32>(Size));
588     Vals.push_back(Size);
589     for (char Chr : C->getName())
590       Vals.push_back((unsigned char)Chr);
591     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
592     Vals.clear();
593   }
594 }
595 
596 /// Write a record that will eventually hold the word offset of the
597 /// module-level VST. For now the offset is 0, which will be backpatched
598 /// after the real VST is written. Returns the bit offset to backpatch.
599 static uint64_t WriteValueSymbolTableForwardDecl(BitstreamWriter &Stream) {
600   // Write a placeholder value in for the offset of the real VST,
601   // which is written after the function blocks so that it can include
602   // the offset of each function. The placeholder offset will be
603   // updated when the real VST is written.
604   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
605   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
606   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
607   // hold the real VST offset. Must use fixed instead of VBR as we don't
608   // know how many VBR chunks to reserve ahead of time.
609   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
610   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
611 
612   // Emit the placeholder
613   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
614   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
615 
616   // Compute and return the bit offset to the placeholder, which will be
617   // patched when the real VST is written. We can simply subtract the 32-bit
618   // fixed size from the current bit number to get the location to backpatch.
619   return Stream.GetCurrentBitNo() - 32;
620 }
621 
622 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
623 
624 /// Determine the encoding to use for the given string name and length.
625 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
626   bool isChar6 = true;
627   for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
628     if (isChar6)
629       isChar6 = BitCodeAbbrevOp::isChar6(*C);
630     if ((unsigned char)*C & 128)
631       // don't bother scanning the rest.
632       return SE_Fixed8;
633   }
634   if (isChar6)
635     return SE_Char6;
636   else
637     return SE_Fixed7;
638 }
639 
640 /// Emit top-level description of module, including target triple, inline asm,
641 /// descriptors for global variables, and function prototype info.
642 /// Returns the bit offset to backpatch with the location of the real VST.
643 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
644                                 BitstreamWriter &Stream) {
645   // Emit various pieces of data attached to a module.
646   if (!M->getTargetTriple().empty())
647     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
648                       0/*TODO*/, Stream);
649   const std::string &DL = M->getDataLayoutStr();
650   if (!DL.empty())
651     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
652   if (!M->getModuleInlineAsm().empty())
653     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
654                       0/*TODO*/, Stream);
655 
656   // Emit information about sections and GC, computing how many there are. Also
657   // compute the maximum alignment value.
658   std::map<std::string, unsigned> SectionMap;
659   std::map<std::string, unsigned> GCMap;
660   unsigned MaxAlignment = 0;
661   unsigned MaxGlobalType = 0;
662   for (const GlobalValue &GV : M->globals()) {
663     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
664     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
665     if (GV.hasSection()) {
666       // Give section names unique ID's.
667       unsigned &Entry = SectionMap[GV.getSection()];
668       if (!Entry) {
669         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
670                           0/*TODO*/, Stream);
671         Entry = SectionMap.size();
672       }
673     }
674   }
675   for (const Function &F : *M) {
676     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
677     if (F.hasSection()) {
678       // Give section names unique ID's.
679       unsigned &Entry = SectionMap[F.getSection()];
680       if (!Entry) {
681         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
682                           0/*TODO*/, Stream);
683         Entry = SectionMap.size();
684       }
685     }
686     if (F.hasGC()) {
687       // Same for GC names.
688       unsigned &Entry = GCMap[F.getGC()];
689       if (!Entry) {
690         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
691                           0/*TODO*/, Stream);
692         Entry = GCMap.size();
693       }
694     }
695   }
696 
697   // Emit abbrev for globals, now that we know # sections and max alignment.
698   unsigned SimpleGVarAbbrev = 0;
699   if (!M->global_empty()) {
700     // Add an abbrev for common globals with no visibility or thread localness.
701     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
702     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
703     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
704                               Log2_32_Ceil(MaxGlobalType+1)));
705     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
706                                                            //| explicitType << 1
707                                                            //| constant
708     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
709     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
710     if (MaxAlignment == 0)                                 // Alignment.
711       Abbv->Add(BitCodeAbbrevOp(0));
712     else {
713       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
714       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
715                                Log2_32_Ceil(MaxEncAlignment+1)));
716     }
717     if (SectionMap.empty())                                    // Section.
718       Abbv->Add(BitCodeAbbrevOp(0));
719     else
720       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
721                                Log2_32_Ceil(SectionMap.size()+1)));
722     // Don't bother emitting vis + thread local.
723     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
724   }
725 
726   // Emit the global variable information.
727   SmallVector<unsigned, 64> Vals;
728   for (const GlobalVariable &GV : M->globals()) {
729     unsigned AbbrevToUse = 0;
730 
731     // GLOBALVAR: [type, isconst, initid,
732     //             linkage, alignment, section, visibility, threadlocal,
733     //             unnamed_addr, externally_initialized, dllstorageclass,
734     //             comdat]
735     Vals.push_back(VE.getTypeID(GV.getValueType()));
736     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
737     Vals.push_back(GV.isDeclaration() ? 0 :
738                    (VE.getValueID(GV.getInitializer()) + 1));
739     Vals.push_back(getEncodedLinkage(GV));
740     Vals.push_back(Log2_32(GV.getAlignment())+1);
741     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
742     if (GV.isThreadLocal() ||
743         GV.getVisibility() != GlobalValue::DefaultVisibility ||
744         GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
745         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
746         GV.hasComdat()) {
747       Vals.push_back(getEncodedVisibility(GV));
748       Vals.push_back(getEncodedThreadLocalMode(GV));
749       Vals.push_back(GV.hasUnnamedAddr());
750       Vals.push_back(GV.isExternallyInitialized());
751       Vals.push_back(getEncodedDLLStorageClass(GV));
752       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
753     } else {
754       AbbrevToUse = SimpleGVarAbbrev;
755     }
756 
757     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
758     Vals.clear();
759   }
760 
761   // Emit the function proto information.
762   for (const Function &F : *M) {
763     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
764     //             section, visibility, gc, unnamed_addr, prologuedata,
765     //             dllstorageclass, comdat, prefixdata, personalityfn]
766     Vals.push_back(VE.getTypeID(F.getFunctionType()));
767     Vals.push_back(F.getCallingConv());
768     Vals.push_back(F.isDeclaration());
769     Vals.push_back(getEncodedLinkage(F));
770     Vals.push_back(VE.getAttributeID(F.getAttributes()));
771     Vals.push_back(Log2_32(F.getAlignment())+1);
772     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
773     Vals.push_back(getEncodedVisibility(F));
774     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
775     Vals.push_back(F.hasUnnamedAddr());
776     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
777                                        : 0);
778     Vals.push_back(getEncodedDLLStorageClass(F));
779     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
780     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
781                                      : 0);
782     Vals.push_back(
783         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
784 
785     unsigned AbbrevToUse = 0;
786     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
787     Vals.clear();
788   }
789 
790   // Emit the alias information.
791   for (const GlobalAlias &A : M->aliases()) {
792     // ALIAS: [alias type, aliasee val#, linkage, visibility]
793     Vals.push_back(VE.getTypeID(A.getValueType()));
794     Vals.push_back(A.getType()->getAddressSpace());
795     Vals.push_back(VE.getValueID(A.getAliasee()));
796     Vals.push_back(getEncodedLinkage(A));
797     Vals.push_back(getEncodedVisibility(A));
798     Vals.push_back(getEncodedDLLStorageClass(A));
799     Vals.push_back(getEncodedThreadLocalMode(A));
800     Vals.push_back(A.hasUnnamedAddr());
801     unsigned AbbrevToUse = 0;
802     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
803     Vals.clear();
804   }
805 
806   // Write a record indicating the number of module-level metadata IDs
807   // This is needed because the ids of metadata are assigned implicitly
808   // based on their ordering in the bitcode, with the function-level
809   // metadata ids starting after the module-level metadata ids. For
810   // function importing where we lazy load the metadata as a postpass,
811   // we want to avoid parsing the module-level metadata before parsing
812   // the imported functions.
813   {
814     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
815     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_METADATA_VALUES));
816     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
817     unsigned MDValsAbbrev = Stream.EmitAbbrev(Abbv);
818     Vals.push_back(VE.numMDs());
819     Stream.EmitRecord(bitc::MODULE_CODE_METADATA_VALUES, Vals, MDValsAbbrev);
820     Vals.clear();
821   }
822 
823   // Emit the module's source file name.
824   {
825     StringEncoding Bits = getStringEncoding(M->getSourceFileName().data(),
826                                             M->getSourceFileName().size());
827     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
828     if (Bits == SE_Char6)
829       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
830     else if (Bits == SE_Fixed7)
831       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
832 
833     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
834     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
835     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
836     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
837     Abbv->Add(AbbrevOpToUse);
838     unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv);
839 
840     for (const auto P : M->getSourceFileName())
841       Vals.push_back((unsigned char)P);
842 
843     // Emit the finished record.
844     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
845     Vals.clear();
846   }
847 
848   // If we have a VST, write the VSTOFFSET record placeholder and return
849   // its offset.
850   if (M->getValueSymbolTable().empty())
851     return 0;
852   return WriteValueSymbolTableForwardDecl(Stream);
853 }
854 
855 static uint64_t GetOptimizationFlags(const Value *V) {
856   uint64_t Flags = 0;
857 
858   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
859     if (OBO->hasNoSignedWrap())
860       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
861     if (OBO->hasNoUnsignedWrap())
862       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
863   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
864     if (PEO->isExact())
865       Flags |= 1 << bitc::PEO_EXACT;
866   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
867     if (FPMO->hasUnsafeAlgebra())
868       Flags |= FastMathFlags::UnsafeAlgebra;
869     if (FPMO->hasNoNaNs())
870       Flags |= FastMathFlags::NoNaNs;
871     if (FPMO->hasNoInfs())
872       Flags |= FastMathFlags::NoInfs;
873     if (FPMO->hasNoSignedZeros())
874       Flags |= FastMathFlags::NoSignedZeros;
875     if (FPMO->hasAllowReciprocal())
876       Flags |= FastMathFlags::AllowReciprocal;
877   }
878 
879   return Flags;
880 }
881 
882 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
883                                  const ValueEnumerator &VE,
884                                  BitstreamWriter &Stream,
885                                  SmallVectorImpl<uint64_t> &Record) {
886   // Mimic an MDNode with a value as one operand.
887   Value *V = MD->getValue();
888   Record.push_back(VE.getTypeID(V->getType()));
889   Record.push_back(VE.getValueID(V));
890   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
891   Record.clear();
892 }
893 
894 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
895                          BitstreamWriter &Stream,
896                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
897   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
898     Metadata *MD = N->getOperand(i);
899     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
900            "Unexpected function-local metadata");
901     Record.push_back(VE.getMetadataOrNullID(MD));
902   }
903   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
904                                     : bitc::METADATA_NODE,
905                     Record, Abbrev);
906   Record.clear();
907 }
908 
909 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
910                             BitstreamWriter &Stream,
911                             SmallVectorImpl<uint64_t> &Record,
912                             unsigned Abbrev) {
913   Record.push_back(N->isDistinct());
914   Record.push_back(N->getLine());
915   Record.push_back(N->getColumn());
916   Record.push_back(VE.getMetadataID(N->getScope()));
917   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
918 
919   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
920   Record.clear();
921 }
922 
923 static void WriteGenericDINode(const GenericDINode *N,
924                                const ValueEnumerator &VE,
925                                BitstreamWriter &Stream,
926                                SmallVectorImpl<uint64_t> &Record,
927                                unsigned Abbrev) {
928   Record.push_back(N->isDistinct());
929   Record.push_back(N->getTag());
930   Record.push_back(0); // Per-tag version field; unused for now.
931 
932   for (auto &I : N->operands())
933     Record.push_back(VE.getMetadataOrNullID(I));
934 
935   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
936   Record.clear();
937 }
938 
939 static uint64_t rotateSign(int64_t I) {
940   uint64_t U = I;
941   return I < 0 ? ~(U << 1) : U << 1;
942 }
943 
944 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
945                             BitstreamWriter &Stream,
946                             SmallVectorImpl<uint64_t> &Record,
947                             unsigned Abbrev) {
948   Record.push_back(N->isDistinct());
949   Record.push_back(N->getCount());
950   Record.push_back(rotateSign(N->getLowerBound()));
951 
952   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
953   Record.clear();
954 }
955 
956 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
957                               BitstreamWriter &Stream,
958                               SmallVectorImpl<uint64_t> &Record,
959                               unsigned Abbrev) {
960   Record.push_back(N->isDistinct());
961   Record.push_back(rotateSign(N->getValue()));
962   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
963 
964   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
965   Record.clear();
966 }
967 
968 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
969                              BitstreamWriter &Stream,
970                              SmallVectorImpl<uint64_t> &Record,
971                              unsigned Abbrev) {
972   Record.push_back(N->isDistinct());
973   Record.push_back(N->getTag());
974   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
975   Record.push_back(N->getSizeInBits());
976   Record.push_back(N->getAlignInBits());
977   Record.push_back(N->getEncoding());
978 
979   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
980   Record.clear();
981 }
982 
983 static void WriteDIDerivedType(const DIDerivedType *N,
984                                const ValueEnumerator &VE,
985                                BitstreamWriter &Stream,
986                                SmallVectorImpl<uint64_t> &Record,
987                                unsigned Abbrev) {
988   Record.push_back(N->isDistinct());
989   Record.push_back(N->getTag());
990   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
991   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
992   Record.push_back(N->getLine());
993   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
994   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
995   Record.push_back(N->getSizeInBits());
996   Record.push_back(N->getAlignInBits());
997   Record.push_back(N->getOffsetInBits());
998   Record.push_back(N->getFlags());
999   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1000 
1001   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1002   Record.clear();
1003 }
1004 
1005 static void WriteDICompositeType(const DICompositeType *N,
1006                                  const ValueEnumerator &VE,
1007                                  BitstreamWriter &Stream,
1008                                  SmallVectorImpl<uint64_t> &Record,
1009                                  unsigned Abbrev) {
1010   Record.push_back(N->isDistinct());
1011   Record.push_back(N->getTag());
1012   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1013   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1014   Record.push_back(N->getLine());
1015   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1016   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1017   Record.push_back(N->getSizeInBits());
1018   Record.push_back(N->getAlignInBits());
1019   Record.push_back(N->getOffsetInBits());
1020   Record.push_back(N->getFlags());
1021   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1022   Record.push_back(N->getRuntimeLang());
1023   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1024   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1025   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1026 
1027   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1028   Record.clear();
1029 }
1030 
1031 static void WriteDISubroutineType(const DISubroutineType *N,
1032                                   const ValueEnumerator &VE,
1033                                   BitstreamWriter &Stream,
1034                                   SmallVectorImpl<uint64_t> &Record,
1035                                   unsigned Abbrev) {
1036   Record.push_back(N->isDistinct());
1037   Record.push_back(N->getFlags());
1038   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1039 
1040   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1041   Record.clear();
1042 }
1043 
1044 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
1045                         BitstreamWriter &Stream,
1046                         SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1047   Record.push_back(N->isDistinct());
1048   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1049   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1050 
1051   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1052   Record.clear();
1053 }
1054 
1055 static void WriteDICompileUnit(const DICompileUnit *N,
1056                                const ValueEnumerator &VE,
1057                                BitstreamWriter &Stream,
1058                                SmallVectorImpl<uint64_t> &Record,
1059                                unsigned Abbrev) {
1060   assert(N->isDistinct() && "Expected distinct compile units");
1061   Record.push_back(/* IsDistinct */ true);
1062   Record.push_back(N->getSourceLanguage());
1063   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1064   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1065   Record.push_back(N->isOptimized());
1066   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1067   Record.push_back(N->getRuntimeVersion());
1068   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1069   Record.push_back(N->getEmissionKind());
1070   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1071   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1072   Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
1073   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1074   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1075   Record.push_back(N->getDWOId());
1076   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1077 
1078   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1079   Record.clear();
1080 }
1081 
1082 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
1083                               BitstreamWriter &Stream,
1084                               SmallVectorImpl<uint64_t> &Record,
1085                               unsigned Abbrev) {
1086   Record.push_back(N->isDistinct());
1087   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1088   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1089   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1090   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1091   Record.push_back(N->getLine());
1092   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1093   Record.push_back(N->isLocalToUnit());
1094   Record.push_back(N->isDefinition());
1095   Record.push_back(N->getScopeLine());
1096   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1097   Record.push_back(N->getVirtuality());
1098   Record.push_back(N->getVirtualIndex());
1099   Record.push_back(N->getFlags());
1100   Record.push_back(N->isOptimized());
1101   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1102   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1103   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1104 
1105   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1106   Record.clear();
1107 }
1108 
1109 static void WriteDILexicalBlock(const DILexicalBlock *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->getScope()));
1116   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1117   Record.push_back(N->getLine());
1118   Record.push_back(N->getColumn());
1119 
1120   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1121   Record.clear();
1122 }
1123 
1124 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
1125                                     const ValueEnumerator &VE,
1126                                     BitstreamWriter &Stream,
1127                                     SmallVectorImpl<uint64_t> &Record,
1128                                     unsigned Abbrev) {
1129   Record.push_back(N->isDistinct());
1130   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1131   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1132   Record.push_back(N->getDiscriminator());
1133 
1134   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1135   Record.clear();
1136 }
1137 
1138 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1139                              BitstreamWriter &Stream,
1140                              SmallVectorImpl<uint64_t> &Record,
1141                              unsigned Abbrev) {
1142   Record.push_back(N->isDistinct());
1143   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1144   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1145   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1146   Record.push_back(N->getLine());
1147 
1148   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1149   Record.clear();
1150 }
1151 
1152 static void WriteDIMacro(const DIMacro *N, const ValueEnumerator &VE,
1153                          BitstreamWriter &Stream,
1154                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1155   Record.push_back(N->isDistinct());
1156   Record.push_back(N->getMacinfoType());
1157   Record.push_back(N->getLine());
1158   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1159   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1160 
1161   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1162   Record.clear();
1163 }
1164 
1165 static void WriteDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE,
1166                              BitstreamWriter &Stream,
1167                              SmallVectorImpl<uint64_t> &Record,
1168                              unsigned Abbrev) {
1169   Record.push_back(N->isDistinct());
1170   Record.push_back(N->getMacinfoType());
1171   Record.push_back(N->getLine());
1172   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1173   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1174 
1175   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1176   Record.clear();
1177 }
1178 
1179 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1180                           BitstreamWriter &Stream,
1181                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1182   Record.push_back(N->isDistinct());
1183   for (auto &I : N->operands())
1184     Record.push_back(VE.getMetadataOrNullID(I));
1185 
1186   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1187   Record.clear();
1188 }
1189 
1190 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
1191                                          const ValueEnumerator &VE,
1192                                          BitstreamWriter &Stream,
1193                                          SmallVectorImpl<uint64_t> &Record,
1194                                          unsigned Abbrev) {
1195   Record.push_back(N->isDistinct());
1196   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1197   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1198 
1199   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1200   Record.clear();
1201 }
1202 
1203 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
1204                                           const ValueEnumerator &VE,
1205                                           BitstreamWriter &Stream,
1206                                           SmallVectorImpl<uint64_t> &Record,
1207                                           unsigned Abbrev) {
1208   Record.push_back(N->isDistinct());
1209   Record.push_back(N->getTag());
1210   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1211   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1212   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1213 
1214   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1215   Record.clear();
1216 }
1217 
1218 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
1219                                   const ValueEnumerator &VE,
1220                                   BitstreamWriter &Stream,
1221                                   SmallVectorImpl<uint64_t> &Record,
1222                                   unsigned Abbrev) {
1223   Record.push_back(N->isDistinct());
1224   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1225   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1226   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1227   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1228   Record.push_back(N->getLine());
1229   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1230   Record.push_back(N->isLocalToUnit());
1231   Record.push_back(N->isDefinition());
1232   Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1233   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1234 
1235   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1236   Record.clear();
1237 }
1238 
1239 static void WriteDILocalVariable(const DILocalVariable *N,
1240                                  const ValueEnumerator &VE,
1241                                  BitstreamWriter &Stream,
1242                                  SmallVectorImpl<uint64_t> &Record,
1243                                  unsigned Abbrev) {
1244   Record.push_back(N->isDistinct());
1245   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1246   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1247   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1248   Record.push_back(N->getLine());
1249   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1250   Record.push_back(N->getArg());
1251   Record.push_back(N->getFlags());
1252 
1253   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1254   Record.clear();
1255 }
1256 
1257 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1258                               BitstreamWriter &Stream,
1259                               SmallVectorImpl<uint64_t> &Record,
1260                               unsigned Abbrev) {
1261   Record.reserve(N->getElements().size() + 1);
1262 
1263   Record.push_back(N->isDistinct());
1264   Record.append(N->elements_begin(), N->elements_end());
1265 
1266   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1267   Record.clear();
1268 }
1269 
1270 static void WriteDIObjCProperty(const DIObjCProperty *N,
1271                                 const ValueEnumerator &VE,
1272                                 BitstreamWriter &Stream,
1273                                 SmallVectorImpl<uint64_t> &Record,
1274                                 unsigned Abbrev) {
1275   Record.push_back(N->isDistinct());
1276   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1277   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1278   Record.push_back(N->getLine());
1279   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1280   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1281   Record.push_back(N->getAttributes());
1282   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1283 
1284   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1285   Record.clear();
1286 }
1287 
1288 static void WriteDIImportedEntity(const DIImportedEntity *N,
1289                                   const ValueEnumerator &VE,
1290                                   BitstreamWriter &Stream,
1291                                   SmallVectorImpl<uint64_t> &Record,
1292                                   unsigned Abbrev) {
1293   Record.push_back(N->isDistinct());
1294   Record.push_back(N->getTag());
1295   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1296   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1297   Record.push_back(N->getLine());
1298   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1299 
1300   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1301   Record.clear();
1302 }
1303 
1304 static void WriteModuleMetadata(const Module *M,
1305                                 const ValueEnumerator &VE,
1306                                 BitstreamWriter &Stream) {
1307   const auto &MDs = VE.getMDs();
1308   if (MDs.empty() && M->named_metadata_empty())
1309     return;
1310 
1311   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1312 
1313   unsigned MDSAbbrev = 0;
1314   if (VE.hasMDString()) {
1315     // Abbrev for METADATA_STRING.
1316     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1317     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1318     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1319     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1320     MDSAbbrev = Stream.EmitAbbrev(Abbv);
1321   }
1322 
1323   // Initialize MDNode abbreviations.
1324 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1325 #include "llvm/IR/Metadata.def"
1326 
1327   if (VE.hasDILocation()) {
1328     // Abbrev for METADATA_LOCATION.
1329     //
1330     // Assume the column is usually under 128, and always output the inlined-at
1331     // location (it's never more expensive than building an array size 1).
1332     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1333     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1334     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1335     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1336     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1337     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1338     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1339     DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1340   }
1341 
1342   if (VE.hasGenericDINode()) {
1343     // Abbrev for METADATA_GENERIC_DEBUG.
1344     //
1345     // Assume the column is usually under 128, and always output the inlined-at
1346     // location (it's never more expensive than building an array size 1).
1347     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1348     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1349     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1350     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1351     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1352     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1353     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1354     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1355     GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1356   }
1357 
1358   unsigned NameAbbrev = 0;
1359   if (!M->named_metadata_empty()) {
1360     // Abbrev for METADATA_NAME.
1361     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1362     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1363     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1364     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1365     NameAbbrev = Stream.EmitAbbrev(Abbv);
1366   }
1367 
1368   SmallVector<uint64_t, 64> Record;
1369   for (const Metadata *MD : MDs) {
1370     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1371       assert(N->isResolved() && "Expected forward references to be resolved");
1372 
1373       switch (N->getMetadataID()) {
1374       default:
1375         llvm_unreachable("Invalid MDNode subclass");
1376 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1377   case Metadata::CLASS##Kind:                                                  \
1378     Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
1379     continue;
1380 #include "llvm/IR/Metadata.def"
1381       }
1382     }
1383     if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1384       WriteValueAsMetadata(MDC, VE, Stream, Record);
1385       continue;
1386     }
1387     const MDString *MDS = cast<MDString>(MD);
1388     // Code: [strchar x N]
1389     Record.append(MDS->bytes_begin(), MDS->bytes_end());
1390 
1391     // Emit the finished record.
1392     Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1393     Record.clear();
1394   }
1395 
1396   // Write named metadata.
1397   for (const NamedMDNode &NMD : M->named_metadata()) {
1398     // Write name.
1399     StringRef Str = NMD.getName();
1400     Record.append(Str.bytes_begin(), Str.bytes_end());
1401     Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1402     Record.clear();
1403 
1404     // Write named metadata operands.
1405     for (const MDNode *N : NMD.operands())
1406       Record.push_back(VE.getMetadataID(N));
1407     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1408     Record.clear();
1409   }
1410 
1411   Stream.ExitBlock();
1412 }
1413 
1414 static void WriteFunctionLocalMetadata(const Function &F,
1415                                        const ValueEnumerator &VE,
1416                                        BitstreamWriter &Stream) {
1417   bool StartedMetadataBlock = false;
1418   SmallVector<uint64_t, 64> Record;
1419   const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1420       VE.getFunctionLocalMDs();
1421   for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1422     assert(MDs[i] && "Expected valid function-local metadata");
1423     if (!StartedMetadataBlock) {
1424       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1425       StartedMetadataBlock = true;
1426     }
1427     WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1428   }
1429 
1430   if (StartedMetadataBlock)
1431     Stream.ExitBlock();
1432 }
1433 
1434 static void WriteMetadataAttachment(const Function &F,
1435                                     const ValueEnumerator &VE,
1436                                     BitstreamWriter &Stream) {
1437   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1438 
1439   SmallVector<uint64_t, 64> Record;
1440 
1441   // Write metadata attachments
1442   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1443   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1444   F.getAllMetadata(MDs);
1445   if (!MDs.empty()) {
1446     for (const auto &I : MDs) {
1447       Record.push_back(I.first);
1448       Record.push_back(VE.getMetadataID(I.second));
1449     }
1450     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1451     Record.clear();
1452   }
1453 
1454   for (const BasicBlock &BB : F)
1455     for (const Instruction &I : BB) {
1456       MDs.clear();
1457       I.getAllMetadataOtherThanDebugLoc(MDs);
1458 
1459       // If no metadata, ignore instruction.
1460       if (MDs.empty()) continue;
1461 
1462       Record.push_back(VE.getInstructionID(&I));
1463 
1464       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1465         Record.push_back(MDs[i].first);
1466         Record.push_back(VE.getMetadataID(MDs[i].second));
1467       }
1468       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1469       Record.clear();
1470     }
1471 
1472   Stream.ExitBlock();
1473 }
1474 
1475 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1476   SmallVector<uint64_t, 64> Record;
1477 
1478   // Write metadata kinds
1479   // METADATA_KIND - [n x [id, name]]
1480   SmallVector<StringRef, 8> Names;
1481   M->getMDKindNames(Names);
1482 
1483   if (Names.empty()) return;
1484 
1485   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1486 
1487   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1488     Record.push_back(MDKindID);
1489     StringRef KName = Names[MDKindID];
1490     Record.append(KName.begin(), KName.end());
1491 
1492     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1493     Record.clear();
1494   }
1495 
1496   Stream.ExitBlock();
1497 }
1498 
1499 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
1500   // Write metadata kinds
1501   //
1502   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1503   //
1504   // OPERAND_BUNDLE_TAG - [strchr x N]
1505 
1506   SmallVector<StringRef, 8> Tags;
1507   M->getOperandBundleTags(Tags);
1508 
1509   if (Tags.empty())
1510     return;
1511 
1512   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
1513 
1514   SmallVector<uint64_t, 64> Record;
1515 
1516   for (auto Tag : Tags) {
1517     Record.append(Tag.begin(), Tag.end());
1518 
1519     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
1520     Record.clear();
1521   }
1522 
1523   Stream.ExitBlock();
1524 }
1525 
1526 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1527   if ((int64_t)V >= 0)
1528     Vals.push_back(V << 1);
1529   else
1530     Vals.push_back((-V << 1) | 1);
1531 }
1532 
1533 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1534                            const ValueEnumerator &VE,
1535                            BitstreamWriter &Stream, bool isGlobal) {
1536   if (FirstVal == LastVal) return;
1537 
1538   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1539 
1540   unsigned AggregateAbbrev = 0;
1541   unsigned String8Abbrev = 0;
1542   unsigned CString7Abbrev = 0;
1543   unsigned CString6Abbrev = 0;
1544   // If this is a constant pool for the module, emit module-specific abbrevs.
1545   if (isGlobal) {
1546     // Abbrev for CST_CODE_AGGREGATE.
1547     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1548     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1549     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1550     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1551     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1552 
1553     // Abbrev for CST_CODE_STRING.
1554     Abbv = new BitCodeAbbrev();
1555     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1556     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1557     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1558     String8Abbrev = Stream.EmitAbbrev(Abbv);
1559     // Abbrev for CST_CODE_CSTRING.
1560     Abbv = new BitCodeAbbrev();
1561     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1562     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1563     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1564     CString7Abbrev = Stream.EmitAbbrev(Abbv);
1565     // Abbrev for CST_CODE_CSTRING.
1566     Abbv = new BitCodeAbbrev();
1567     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1568     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1569     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1570     CString6Abbrev = Stream.EmitAbbrev(Abbv);
1571   }
1572 
1573   SmallVector<uint64_t, 64> Record;
1574 
1575   const ValueEnumerator::ValueList &Vals = VE.getValues();
1576   Type *LastTy = nullptr;
1577   for (unsigned i = FirstVal; i != LastVal; ++i) {
1578     const Value *V = Vals[i].first;
1579     // If we need to switch types, do so now.
1580     if (V->getType() != LastTy) {
1581       LastTy = V->getType();
1582       Record.push_back(VE.getTypeID(LastTy));
1583       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1584                         CONSTANTS_SETTYPE_ABBREV);
1585       Record.clear();
1586     }
1587 
1588     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1589       Record.push_back(unsigned(IA->hasSideEffects()) |
1590                        unsigned(IA->isAlignStack()) << 1 |
1591                        unsigned(IA->getDialect()&1) << 2);
1592 
1593       // Add the asm string.
1594       const std::string &AsmStr = IA->getAsmString();
1595       Record.push_back(AsmStr.size());
1596       Record.append(AsmStr.begin(), AsmStr.end());
1597 
1598       // Add the constraint string.
1599       const std::string &ConstraintStr = IA->getConstraintString();
1600       Record.push_back(ConstraintStr.size());
1601       Record.append(ConstraintStr.begin(), ConstraintStr.end());
1602       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1603       Record.clear();
1604       continue;
1605     }
1606     const Constant *C = cast<Constant>(V);
1607     unsigned Code = -1U;
1608     unsigned AbbrevToUse = 0;
1609     if (C->isNullValue()) {
1610       Code = bitc::CST_CODE_NULL;
1611     } else if (isa<UndefValue>(C)) {
1612       Code = bitc::CST_CODE_UNDEF;
1613     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1614       if (IV->getBitWidth() <= 64) {
1615         uint64_t V = IV->getSExtValue();
1616         emitSignedInt64(Record, V);
1617         Code = bitc::CST_CODE_INTEGER;
1618         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1619       } else {                             // Wide integers, > 64 bits in size.
1620         // We have an arbitrary precision integer value to write whose
1621         // bit width is > 64. However, in canonical unsigned integer
1622         // format it is likely that the high bits are going to be zero.
1623         // So, we only write the number of active words.
1624         unsigned NWords = IV->getValue().getActiveWords();
1625         const uint64_t *RawWords = IV->getValue().getRawData();
1626         for (unsigned i = 0; i != NWords; ++i) {
1627           emitSignedInt64(Record, RawWords[i]);
1628         }
1629         Code = bitc::CST_CODE_WIDE_INTEGER;
1630       }
1631     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1632       Code = bitc::CST_CODE_FLOAT;
1633       Type *Ty = CFP->getType();
1634       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1635         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1636       } else if (Ty->isX86_FP80Ty()) {
1637         // api needed to prevent premature destruction
1638         // bits are not in the same order as a normal i80 APInt, compensate.
1639         APInt api = CFP->getValueAPF().bitcastToAPInt();
1640         const uint64_t *p = api.getRawData();
1641         Record.push_back((p[1] << 48) | (p[0] >> 16));
1642         Record.push_back(p[0] & 0xffffLL);
1643       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1644         APInt api = CFP->getValueAPF().bitcastToAPInt();
1645         const uint64_t *p = api.getRawData();
1646         Record.push_back(p[0]);
1647         Record.push_back(p[1]);
1648       } else {
1649         assert (0 && "Unknown FP type!");
1650       }
1651     } else if (isa<ConstantDataSequential>(C) &&
1652                cast<ConstantDataSequential>(C)->isString()) {
1653       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1654       // Emit constant strings specially.
1655       unsigned NumElts = Str->getNumElements();
1656       // If this is a null-terminated string, use the denser CSTRING encoding.
1657       if (Str->isCString()) {
1658         Code = bitc::CST_CODE_CSTRING;
1659         --NumElts;  // Don't encode the null, which isn't allowed by char6.
1660       } else {
1661         Code = bitc::CST_CODE_STRING;
1662         AbbrevToUse = String8Abbrev;
1663       }
1664       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1665       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1666       for (unsigned i = 0; i != NumElts; ++i) {
1667         unsigned char V = Str->getElementAsInteger(i);
1668         Record.push_back(V);
1669         isCStr7 &= (V & 128) == 0;
1670         if (isCStrChar6)
1671           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1672       }
1673 
1674       if (isCStrChar6)
1675         AbbrevToUse = CString6Abbrev;
1676       else if (isCStr7)
1677         AbbrevToUse = CString7Abbrev;
1678     } else if (const ConstantDataSequential *CDS =
1679                   dyn_cast<ConstantDataSequential>(C)) {
1680       Code = bitc::CST_CODE_DATA;
1681       Type *EltTy = CDS->getType()->getElementType();
1682       if (isa<IntegerType>(EltTy)) {
1683         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1684           Record.push_back(CDS->getElementAsInteger(i));
1685       } else {
1686         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1687           Record.push_back(
1688               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
1689       }
1690     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1691                isa<ConstantVector>(C)) {
1692       Code = bitc::CST_CODE_AGGREGATE;
1693       for (const Value *Op : C->operands())
1694         Record.push_back(VE.getValueID(Op));
1695       AbbrevToUse = AggregateAbbrev;
1696     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1697       switch (CE->getOpcode()) {
1698       default:
1699         if (Instruction::isCast(CE->getOpcode())) {
1700           Code = bitc::CST_CODE_CE_CAST;
1701           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1702           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1703           Record.push_back(VE.getValueID(C->getOperand(0)));
1704           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1705         } else {
1706           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1707           Code = bitc::CST_CODE_CE_BINOP;
1708           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1709           Record.push_back(VE.getValueID(C->getOperand(0)));
1710           Record.push_back(VE.getValueID(C->getOperand(1)));
1711           uint64_t Flags = GetOptimizationFlags(CE);
1712           if (Flags != 0)
1713             Record.push_back(Flags);
1714         }
1715         break;
1716       case Instruction::GetElementPtr: {
1717         Code = bitc::CST_CODE_CE_GEP;
1718         const auto *GO = cast<GEPOperator>(C);
1719         if (GO->isInBounds())
1720           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1721         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1722         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1723           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1724           Record.push_back(VE.getValueID(C->getOperand(i)));
1725         }
1726         break;
1727       }
1728       case Instruction::Select:
1729         Code = bitc::CST_CODE_CE_SELECT;
1730         Record.push_back(VE.getValueID(C->getOperand(0)));
1731         Record.push_back(VE.getValueID(C->getOperand(1)));
1732         Record.push_back(VE.getValueID(C->getOperand(2)));
1733         break;
1734       case Instruction::ExtractElement:
1735         Code = bitc::CST_CODE_CE_EXTRACTELT;
1736         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1737         Record.push_back(VE.getValueID(C->getOperand(0)));
1738         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1739         Record.push_back(VE.getValueID(C->getOperand(1)));
1740         break;
1741       case Instruction::InsertElement:
1742         Code = bitc::CST_CODE_CE_INSERTELT;
1743         Record.push_back(VE.getValueID(C->getOperand(0)));
1744         Record.push_back(VE.getValueID(C->getOperand(1)));
1745         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1746         Record.push_back(VE.getValueID(C->getOperand(2)));
1747         break;
1748       case Instruction::ShuffleVector:
1749         // If the return type and argument types are the same, this is a
1750         // standard shufflevector instruction.  If the types are different,
1751         // then the shuffle is widening or truncating the input vectors, and
1752         // the argument type must also be encoded.
1753         if (C->getType() == C->getOperand(0)->getType()) {
1754           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1755         } else {
1756           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1757           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1758         }
1759         Record.push_back(VE.getValueID(C->getOperand(0)));
1760         Record.push_back(VE.getValueID(C->getOperand(1)));
1761         Record.push_back(VE.getValueID(C->getOperand(2)));
1762         break;
1763       case Instruction::ICmp:
1764       case Instruction::FCmp:
1765         Code = bitc::CST_CODE_CE_CMP;
1766         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1767         Record.push_back(VE.getValueID(C->getOperand(0)));
1768         Record.push_back(VE.getValueID(C->getOperand(1)));
1769         Record.push_back(CE->getPredicate());
1770         break;
1771       }
1772     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1773       Code = bitc::CST_CODE_BLOCKADDRESS;
1774       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1775       Record.push_back(VE.getValueID(BA->getFunction()));
1776       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1777     } else {
1778 #ifndef NDEBUG
1779       C->dump();
1780 #endif
1781       llvm_unreachable("Unknown constant!");
1782     }
1783     Stream.EmitRecord(Code, Record, AbbrevToUse);
1784     Record.clear();
1785   }
1786 
1787   Stream.ExitBlock();
1788 }
1789 
1790 static void WriteModuleConstants(const ValueEnumerator &VE,
1791                                  BitstreamWriter &Stream) {
1792   const ValueEnumerator::ValueList &Vals = VE.getValues();
1793 
1794   // Find the first constant to emit, which is the first non-globalvalue value.
1795   // We know globalvalues have been emitted by WriteModuleInfo.
1796   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1797     if (!isa<GlobalValue>(Vals[i].first)) {
1798       WriteConstants(i, Vals.size(), VE, Stream, true);
1799       return;
1800     }
1801   }
1802 }
1803 
1804 /// PushValueAndType - The file has to encode both the value and type id for
1805 /// many values, because we need to know what type to create for forward
1806 /// references.  However, most operands are not forward references, so this type
1807 /// field is not needed.
1808 ///
1809 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1810 /// instruction ID, then it is a forward reference, and it also includes the
1811 /// type ID.  The value ID that is written is encoded relative to the InstID.
1812 static bool PushValueAndType(const Value *V, unsigned InstID,
1813                              SmallVectorImpl<unsigned> &Vals,
1814                              ValueEnumerator &VE) {
1815   unsigned ValID = VE.getValueID(V);
1816   // Make encoding relative to the InstID.
1817   Vals.push_back(InstID - ValID);
1818   if (ValID >= InstID) {
1819     Vals.push_back(VE.getTypeID(V->getType()));
1820     return true;
1821   }
1822   return false;
1823 }
1824 
1825 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
1826                                 unsigned InstID, ValueEnumerator &VE) {
1827   SmallVector<unsigned, 64> Record;
1828   LLVMContext &C = CS.getInstruction()->getContext();
1829 
1830   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1831     const auto &Bundle = CS.getOperandBundleAt(i);
1832     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
1833 
1834     for (auto &Input : Bundle.Inputs)
1835       PushValueAndType(Input, InstID, Record, VE);
1836 
1837     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
1838     Record.clear();
1839   }
1840 }
1841 
1842 /// pushValue - Like PushValueAndType, but where the type of the value is
1843 /// omitted (perhaps it was already encoded in an earlier operand).
1844 static void pushValue(const Value *V, unsigned InstID,
1845                       SmallVectorImpl<unsigned> &Vals,
1846                       ValueEnumerator &VE) {
1847   unsigned ValID = VE.getValueID(V);
1848   Vals.push_back(InstID - ValID);
1849 }
1850 
1851 static void pushValueSigned(const Value *V, unsigned InstID,
1852                             SmallVectorImpl<uint64_t> &Vals,
1853                             ValueEnumerator &VE) {
1854   unsigned ValID = VE.getValueID(V);
1855   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1856   emitSignedInt64(Vals, diff);
1857 }
1858 
1859 /// WriteInstruction - Emit an instruction to the specified stream.
1860 static void WriteInstruction(const Instruction &I, unsigned InstID,
1861                              ValueEnumerator &VE, BitstreamWriter &Stream,
1862                              SmallVectorImpl<unsigned> &Vals) {
1863   unsigned Code = 0;
1864   unsigned AbbrevToUse = 0;
1865   VE.setInstructionID(&I);
1866   switch (I.getOpcode()) {
1867   default:
1868     if (Instruction::isCast(I.getOpcode())) {
1869       Code = bitc::FUNC_CODE_INST_CAST;
1870       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1871         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1872       Vals.push_back(VE.getTypeID(I.getType()));
1873       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1874     } else {
1875       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1876       Code = bitc::FUNC_CODE_INST_BINOP;
1877       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1878         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1879       pushValue(I.getOperand(1), InstID, Vals, VE);
1880       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1881       uint64_t Flags = GetOptimizationFlags(&I);
1882       if (Flags != 0) {
1883         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1884           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1885         Vals.push_back(Flags);
1886       }
1887     }
1888     break;
1889 
1890   case Instruction::GetElementPtr: {
1891     Code = bitc::FUNC_CODE_INST_GEP;
1892     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1893     auto &GEPInst = cast<GetElementPtrInst>(I);
1894     Vals.push_back(GEPInst.isInBounds());
1895     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1896     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1897       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1898     break;
1899   }
1900   case Instruction::ExtractValue: {
1901     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1902     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1903     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1904     Vals.append(EVI->idx_begin(), EVI->idx_end());
1905     break;
1906   }
1907   case Instruction::InsertValue: {
1908     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1909     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1910     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1911     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1912     Vals.append(IVI->idx_begin(), IVI->idx_end());
1913     break;
1914   }
1915   case Instruction::Select:
1916     Code = bitc::FUNC_CODE_INST_VSELECT;
1917     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1918     pushValue(I.getOperand(2), InstID, Vals, VE);
1919     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1920     break;
1921   case Instruction::ExtractElement:
1922     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1923     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1924     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1925     break;
1926   case Instruction::InsertElement:
1927     Code = bitc::FUNC_CODE_INST_INSERTELT;
1928     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1929     pushValue(I.getOperand(1), InstID, Vals, VE);
1930     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1931     break;
1932   case Instruction::ShuffleVector:
1933     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1934     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1935     pushValue(I.getOperand(1), InstID, Vals, VE);
1936     pushValue(I.getOperand(2), InstID, Vals, VE);
1937     break;
1938   case Instruction::ICmp:
1939   case Instruction::FCmp: {
1940     // compare returning Int1Ty or vector of Int1Ty
1941     Code = bitc::FUNC_CODE_INST_CMP2;
1942     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1943     pushValue(I.getOperand(1), InstID, Vals, VE);
1944     Vals.push_back(cast<CmpInst>(I).getPredicate());
1945     uint64_t Flags = GetOptimizationFlags(&I);
1946     if (Flags != 0)
1947       Vals.push_back(Flags);
1948     break;
1949   }
1950 
1951   case Instruction::Ret:
1952     {
1953       Code = bitc::FUNC_CODE_INST_RET;
1954       unsigned NumOperands = I.getNumOperands();
1955       if (NumOperands == 0)
1956         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1957       else if (NumOperands == 1) {
1958         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1959           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1960       } else {
1961         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1962           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1963       }
1964     }
1965     break;
1966   case Instruction::Br:
1967     {
1968       Code = bitc::FUNC_CODE_INST_BR;
1969       const BranchInst &II = cast<BranchInst>(I);
1970       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1971       if (II.isConditional()) {
1972         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1973         pushValue(II.getCondition(), InstID, Vals, VE);
1974       }
1975     }
1976     break;
1977   case Instruction::Switch:
1978     {
1979       Code = bitc::FUNC_CODE_INST_SWITCH;
1980       const SwitchInst &SI = cast<SwitchInst>(I);
1981       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1982       pushValue(SI.getCondition(), InstID, Vals, VE);
1983       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1984       for (SwitchInst::ConstCaseIt Case : SI.cases()) {
1985         Vals.push_back(VE.getValueID(Case.getCaseValue()));
1986         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
1987       }
1988     }
1989     break;
1990   case Instruction::IndirectBr:
1991     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1992     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1993     // Encode the address operand as relative, but not the basic blocks.
1994     pushValue(I.getOperand(0), InstID, Vals, VE);
1995     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1996       Vals.push_back(VE.getValueID(I.getOperand(i)));
1997     break;
1998 
1999   case Instruction::Invoke: {
2000     const InvokeInst *II = cast<InvokeInst>(&I);
2001     const Value *Callee = II->getCalledValue();
2002     FunctionType *FTy = II->getFunctionType();
2003 
2004     if (II->hasOperandBundles())
2005       WriteOperandBundles(Stream, II, InstID, VE);
2006 
2007     Code = bitc::FUNC_CODE_INST_INVOKE;
2008 
2009     Vals.push_back(VE.getAttributeID(II->getAttributes()));
2010     Vals.push_back(II->getCallingConv() | 1 << 13);
2011     Vals.push_back(VE.getValueID(II->getNormalDest()));
2012     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2013     Vals.push_back(VE.getTypeID(FTy));
2014     PushValueAndType(Callee, InstID, Vals, VE);
2015 
2016     // Emit value #'s for the fixed parameters.
2017     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2018       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
2019 
2020     // Emit type/value pairs for varargs params.
2021     if (FTy->isVarArg()) {
2022       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
2023            i != e; ++i)
2024         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
2025     }
2026     break;
2027   }
2028   case Instruction::Resume:
2029     Code = bitc::FUNC_CODE_INST_RESUME;
2030     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2031     break;
2032   case Instruction::CleanupRet: {
2033     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2034     const auto &CRI = cast<CleanupReturnInst>(I);
2035     pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
2036     if (CRI.hasUnwindDest())
2037       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2038     break;
2039   }
2040   case Instruction::CatchRet: {
2041     Code = bitc::FUNC_CODE_INST_CATCHRET;
2042     const auto &CRI = cast<CatchReturnInst>(I);
2043     pushValue(CRI.getCatchPad(), InstID, Vals, VE);
2044     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2045     break;
2046   }
2047   case Instruction::CleanupPad:
2048   case Instruction::CatchPad: {
2049     const auto &FuncletPad = cast<FuncletPadInst>(I);
2050     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2051                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2052     pushValue(FuncletPad.getParentPad(), InstID, Vals, VE);
2053 
2054     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2055     Vals.push_back(NumArgOperands);
2056     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2057       PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE);
2058     break;
2059   }
2060   case Instruction::CatchSwitch: {
2061     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2062     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2063 
2064     pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE);
2065 
2066     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2067     Vals.push_back(NumHandlers);
2068     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2069       Vals.push_back(VE.getValueID(CatchPadBB));
2070 
2071     if (CatchSwitch.hasUnwindDest())
2072       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2073     break;
2074   }
2075   case Instruction::Unreachable:
2076     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2077     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2078     break;
2079 
2080   case Instruction::PHI: {
2081     const PHINode &PN = cast<PHINode>(I);
2082     Code = bitc::FUNC_CODE_INST_PHI;
2083     // With the newer instruction encoding, forward references could give
2084     // negative valued IDs.  This is most common for PHIs, so we use
2085     // signed VBRs.
2086     SmallVector<uint64_t, 128> Vals64;
2087     Vals64.push_back(VE.getTypeID(PN.getType()));
2088     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2089       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
2090       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2091     }
2092     // Emit a Vals64 vector and exit.
2093     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2094     Vals64.clear();
2095     return;
2096   }
2097 
2098   case Instruction::LandingPad: {
2099     const LandingPadInst &LP = cast<LandingPadInst>(I);
2100     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2101     Vals.push_back(VE.getTypeID(LP.getType()));
2102     Vals.push_back(LP.isCleanup());
2103     Vals.push_back(LP.getNumClauses());
2104     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2105       if (LP.isCatch(I))
2106         Vals.push_back(LandingPadInst::Catch);
2107       else
2108         Vals.push_back(LandingPadInst::Filter);
2109       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
2110     }
2111     break;
2112   }
2113 
2114   case Instruction::Alloca: {
2115     Code = bitc::FUNC_CODE_INST_ALLOCA;
2116     const AllocaInst &AI = cast<AllocaInst>(I);
2117     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2118     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2119     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2120     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2121     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2122            "not enough bits for maximum alignment");
2123     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2124     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2125     AlignRecord |= 1 << 6;
2126     // Reserve bit 7 for SwiftError flag.
2127     // AlignRecord |= AI.isSwiftError() << 7;
2128     Vals.push_back(AlignRecord);
2129     break;
2130   }
2131 
2132   case Instruction::Load:
2133     if (cast<LoadInst>(I).isAtomic()) {
2134       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2135       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2136     } else {
2137       Code = bitc::FUNC_CODE_INST_LOAD;
2138       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
2139         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2140     }
2141     Vals.push_back(VE.getTypeID(I.getType()));
2142     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2143     Vals.push_back(cast<LoadInst>(I).isVolatile());
2144     if (cast<LoadInst>(I).isAtomic()) {
2145       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2146       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2147     }
2148     break;
2149   case Instruction::Store:
2150     if (cast<StoreInst>(I).isAtomic())
2151       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2152     else
2153       Code = bitc::FUNC_CODE_INST_STORE;
2154     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
2155     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // valty + val
2156     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2157     Vals.push_back(cast<StoreInst>(I).isVolatile());
2158     if (cast<StoreInst>(I).isAtomic()) {
2159       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2160       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2161     }
2162     break;
2163   case Instruction::AtomicCmpXchg:
2164     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2165     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2166     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // cmp.
2167     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
2168     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2169     Vals.push_back(GetEncodedOrdering(
2170                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2171     Vals.push_back(GetEncodedSynchScope(
2172                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
2173     Vals.push_back(GetEncodedOrdering(
2174                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2175     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2176     break;
2177   case Instruction::AtomicRMW:
2178     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2179     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2180     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
2181     Vals.push_back(GetEncodedRMWOperation(
2182                      cast<AtomicRMWInst>(I).getOperation()));
2183     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2184     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2185     Vals.push_back(GetEncodedSynchScope(
2186                      cast<AtomicRMWInst>(I).getSynchScope()));
2187     break;
2188   case Instruction::Fence:
2189     Code = bitc::FUNC_CODE_INST_FENCE;
2190     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2191     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2192     break;
2193   case Instruction::Call: {
2194     const CallInst &CI = cast<CallInst>(I);
2195     FunctionType *FTy = CI.getFunctionType();
2196 
2197     if (CI.hasOperandBundles())
2198       WriteOperandBundles(Stream, &CI, InstID, VE);
2199 
2200     Code = bitc::FUNC_CODE_INST_CALL;
2201 
2202     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2203 
2204     unsigned Flags = GetOptimizationFlags(&I);
2205     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2206                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2207                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2208                    1 << bitc::CALL_EXPLICIT_TYPE |
2209                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2210                    unsigned(Flags != 0) << bitc::CALL_FMF);
2211     if (Flags != 0)
2212       Vals.push_back(Flags);
2213 
2214     Vals.push_back(VE.getTypeID(FTy));
2215     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
2216 
2217     // Emit value #'s for the fixed parameters.
2218     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2219       // Check for labels (can happen with asm labels).
2220       if (FTy->getParamType(i)->isLabelTy())
2221         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2222       else
2223         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
2224     }
2225 
2226     // Emit type/value pairs for varargs params.
2227     if (FTy->isVarArg()) {
2228       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2229            i != e; ++i)
2230         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
2231     }
2232     break;
2233   }
2234   case Instruction::VAArg:
2235     Code = bitc::FUNC_CODE_INST_VAARG;
2236     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
2237     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2238     Vals.push_back(VE.getTypeID(I.getType())); // restype.
2239     break;
2240   }
2241 
2242   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2243   Vals.clear();
2244 }
2245 
2246 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2247 /// BitcodeStartBit and ModuleSummaryIndex are only passed for the module-level
2248 /// VST, where we are including a function bitcode index and need to
2249 /// backpatch the VST forward declaration record.
2250 static void WriteValueSymbolTable(
2251     const ValueSymbolTable &VST, const ValueEnumerator &VE,
2252     BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2253     uint64_t BitcodeStartBit = 0,
2254     DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>>
2255         *FunctionIndex = nullptr) {
2256   if (VST.empty()) {
2257     // WriteValueSymbolTableForwardDecl should have returned early as
2258     // well. Ensure this handling remains in sync by asserting that
2259     // the placeholder offset is not set.
2260     assert(VSTOffsetPlaceholder == 0);
2261     return;
2262   }
2263 
2264   if (VSTOffsetPlaceholder > 0) {
2265     // Get the offset of the VST we are writing, and backpatch it into
2266     // the VST forward declaration record.
2267     uint64_t VSTOffset = Stream.GetCurrentBitNo();
2268     // The BitcodeStartBit was the stream offset of the actual bitcode
2269     // (e.g. excluding any initial darwin header).
2270     VSTOffset -= BitcodeStartBit;
2271     assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2272     Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2273   }
2274 
2275   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2276 
2277   // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2278   // records, which are not used in the per-function VSTs.
2279   unsigned FnEntry8BitAbbrev;
2280   unsigned FnEntry7BitAbbrev;
2281   unsigned FnEntry6BitAbbrev;
2282   if (VSTOffsetPlaceholder > 0) {
2283     // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2284     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2285     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2286     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2287     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2288     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2289     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2290     FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2291 
2292     // 7-bit fixed width VST_CODE_FNENTRY function strings.
2293     Abbv = new BitCodeAbbrev();
2294     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2295     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2296     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2297     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2298     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2299     FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2300 
2301     // 6-bit char6 VST_CODE_FNENTRY function strings.
2302     Abbv = new BitCodeAbbrev();
2303     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2304     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2305     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2306     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2307     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2308     FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2309   }
2310 
2311   // FIXME: Set up the abbrev, we know how many values there are!
2312   // FIXME: We know if the type names can use 7-bit ascii.
2313   SmallVector<unsigned, 64> NameVals;
2314 
2315   for (const ValueName &Name : VST) {
2316     // Figure out the encoding to use for the name.
2317     StringEncoding Bits =
2318         getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2319 
2320     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2321     NameVals.push_back(VE.getValueID(Name.getValue()));
2322 
2323     Function *F = dyn_cast<Function>(Name.getValue());
2324     if (!F) {
2325       // If value is an alias, need to get the aliased base object to
2326       // see if it is a function.
2327       auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2328       if (GA && GA->getBaseObject())
2329         F = dyn_cast<Function>(GA->getBaseObject());
2330     }
2331 
2332     // VST_CODE_ENTRY:   [valueid, namechar x N]
2333     // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2334     // VST_CODE_BBENTRY: [bbid, namechar x N]
2335     unsigned Code;
2336     if (isa<BasicBlock>(Name.getValue())) {
2337       Code = bitc::VST_CODE_BBENTRY;
2338       if (Bits == SE_Char6)
2339         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2340     } else if (F && !F->isDeclaration()) {
2341       // Must be the module-level VST, where we pass in the Index and
2342       // have a VSTOffsetPlaceholder. The function-level VST should not
2343       // contain any Function symbols.
2344       assert(FunctionIndex);
2345       assert(VSTOffsetPlaceholder > 0);
2346 
2347       // Save the word offset of the function (from the start of the
2348       // actual bitcode written to the stream).
2349       uint64_t BitcodeIndex =
2350           (*FunctionIndex)[F]->bitcodeIndex() - BitcodeStartBit;
2351       assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2352       NameVals.push_back(BitcodeIndex / 32);
2353 
2354       Code = bitc::VST_CODE_FNENTRY;
2355       AbbrevToUse = FnEntry8BitAbbrev;
2356       if (Bits == SE_Char6)
2357         AbbrevToUse = FnEntry6BitAbbrev;
2358       else if (Bits == SE_Fixed7)
2359         AbbrevToUse = FnEntry7BitAbbrev;
2360     } else {
2361       Code = bitc::VST_CODE_ENTRY;
2362       if (Bits == SE_Char6)
2363         AbbrevToUse = VST_ENTRY_6_ABBREV;
2364       else if (Bits == SE_Fixed7)
2365         AbbrevToUse = VST_ENTRY_7_ABBREV;
2366     }
2367 
2368     for (const auto P : Name.getKey())
2369       NameVals.push_back((unsigned char)P);
2370 
2371     // Emit the finished record.
2372     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2373     NameVals.clear();
2374   }
2375   Stream.ExitBlock();
2376 }
2377 
2378 /// Emit function names and summary offsets for the combined index
2379 /// used by ThinLTO.
2380 static void
2381 WriteCombinedValueSymbolTable(const ModuleSummaryIndex &Index,
2382                               BitstreamWriter &Stream,
2383                               std::map<uint64_t, unsigned> &GUIDToValueIdMap,
2384                               uint64_t VSTOffsetPlaceholder) {
2385   assert(VSTOffsetPlaceholder > 0 && "Expected non-zero VSTOffsetPlaceholder");
2386   // Get the offset of the VST we are writing, and backpatch it into
2387   // the VST forward declaration record.
2388   uint64_t VSTOffset = Stream.GetCurrentBitNo();
2389   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2390   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2391 
2392   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2393 
2394   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2395   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_GVDEFENTRY));
2396   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2397   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // sumoffset
2398   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // guid
2399   unsigned DefEntryAbbrev = Stream.EmitAbbrev(Abbv);
2400 
2401   Abbv = new BitCodeAbbrev();
2402   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2403   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2404   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2405   unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
2406 
2407   SmallVector<uint64_t, 64> NameVals;
2408 
2409   for (const auto &FII : Index) {
2410     uint64_t FuncGUID = FII.first;
2411     const auto &VMI = GUIDToValueIdMap.find(FuncGUID);
2412     assert(VMI != GUIDToValueIdMap.end());
2413 
2414     for (const auto &FI : FII.second) {
2415       // VST_CODE_COMBINED_GVDEFENTRY: [valueid, sumoffset, guid]
2416       NameVals.push_back(VMI->second);
2417       NameVals.push_back(FI->bitcodeIndex());
2418       NameVals.push_back(FuncGUID);
2419 
2420       // Emit the finished record.
2421       Stream.EmitRecord(bitc::VST_CODE_COMBINED_GVDEFENTRY, NameVals,
2422                         DefEntryAbbrev);
2423       NameVals.clear();
2424     }
2425     GUIDToValueIdMap.erase(VMI);
2426   }
2427   for (const auto &GVI : GUIDToValueIdMap) {
2428     // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2429     NameVals.push_back(GVI.second);
2430     NameVals.push_back(GVI.first);
2431 
2432     // Emit the finished record.
2433     Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
2434     NameVals.clear();
2435   }
2436   Stream.ExitBlock();
2437 }
2438 
2439 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2440                          BitstreamWriter &Stream) {
2441   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2442   unsigned Code;
2443   if (isa<BasicBlock>(Order.V))
2444     Code = bitc::USELIST_CODE_BB;
2445   else
2446     Code = bitc::USELIST_CODE_DEFAULT;
2447 
2448   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2449   Record.push_back(VE.getValueID(Order.V));
2450   Stream.EmitRecord(Code, Record);
2451 }
2452 
2453 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2454                               BitstreamWriter &Stream) {
2455   assert(VE.shouldPreserveUseListOrder() &&
2456          "Expected to be preserving use-list order");
2457 
2458   auto hasMore = [&]() {
2459     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2460   };
2461   if (!hasMore())
2462     // Nothing to do.
2463     return;
2464 
2465   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2466   while (hasMore()) {
2467     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2468     VE.UseListOrders.pop_back();
2469   }
2470   Stream.ExitBlock();
2471 }
2472 
2473 // Walk through the operands of a given User via worklist iteration and populate
2474 // the set of GlobalValue references encountered. Invoked either on an
2475 // Instruction or a GlobalVariable (which walks its initializer).
2476 static void findRefEdges(const User *CurUser, const ValueEnumerator &VE,
2477                          DenseSet<unsigned> &RefEdges,
2478                          SmallPtrSet<const User *, 8> &Visited) {
2479   SmallVector<const User *, 32> Worklist;
2480   Worklist.push_back(CurUser);
2481 
2482   while (!Worklist.empty()) {
2483     const User *U = Worklist.pop_back_val();
2484 
2485     if (!Visited.insert(U).second)
2486       continue;
2487 
2488     ImmutableCallSite CS(U);
2489 
2490     for (const auto &OI : U->operands()) {
2491       const User *Operand = dyn_cast<User>(OI);
2492       if (!Operand)
2493         continue;
2494       if (isa<BlockAddress>(Operand))
2495         continue;
2496       if (isa<GlobalValue>(Operand)) {
2497         // We have a reference to a global value. This should be added to
2498         // the reference set unless it is a callee. Callees are handled
2499         // specially by WriteFunction and are added to a separate list.
2500         if (!(CS && CS.isCallee(&OI)))
2501           RefEdges.insert(VE.getValueID(Operand));
2502         continue;
2503       }
2504       Worklist.push_back(Operand);
2505     }
2506   }
2507 }
2508 
2509 /// Emit a function body to the module stream.
2510 static void WriteFunction(
2511     const Function &F, const Module *M, ValueEnumerator &VE,
2512     BitstreamWriter &Stream,
2513     DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex,
2514     bool EmitSummaryIndex) {
2515   // Save the bitcode index of the start of this function block for recording
2516   // in the VST.
2517   uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
2518 
2519   bool HasProfileData = F.getEntryCount().hasValue();
2520   std::unique_ptr<BlockFrequencyInfo> BFI;
2521   if (EmitSummaryIndex && HasProfileData) {
2522     Function &Func = const_cast<Function &>(F);
2523     LoopInfo LI{DominatorTree(Func)};
2524     BranchProbabilityInfo BPI{Func, LI};
2525     BFI = llvm::make_unique<BlockFrequencyInfo>(Func, BPI, LI);
2526   }
2527 
2528   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2529   VE.incorporateFunction(F);
2530 
2531   SmallVector<unsigned, 64> Vals;
2532 
2533   // Emit the number of basic blocks, so the reader can create them ahead of
2534   // time.
2535   Vals.push_back(VE.getBasicBlocks().size());
2536   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2537   Vals.clear();
2538 
2539   // If there are function-local constants, emit them now.
2540   unsigned CstStart, CstEnd;
2541   VE.getFunctionConstantRange(CstStart, CstEnd);
2542   WriteConstants(CstStart, CstEnd, VE, Stream, false);
2543 
2544   // If there is function-local metadata, emit it now.
2545   WriteFunctionLocalMetadata(F, VE, Stream);
2546 
2547   // Keep a running idea of what the instruction ID is.
2548   unsigned InstID = CstEnd;
2549 
2550   bool NeedsMetadataAttachment = F.hasMetadata();
2551 
2552   DILocation *LastDL = nullptr;
2553   unsigned NumInsts = 0;
2554   // Map from callee ValueId to profile count. Used to accumulate profile
2555   // counts for all static calls to a given callee.
2556   DenseMap<unsigned, CalleeInfo> CallGraphEdges;
2557   DenseSet<unsigned> RefEdges;
2558 
2559   SmallPtrSet<const User *, 8> Visited;
2560   // Finally, emit all the instructions, in order.
2561   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2562     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2563          I != E; ++I) {
2564       WriteInstruction(*I, InstID, VE, Stream, Vals);
2565 
2566       if (!isa<DbgInfoIntrinsic>(I))
2567         ++NumInsts;
2568 
2569       if (!I->getType()->isVoidTy())
2570         ++InstID;
2571 
2572       if (EmitSummaryIndex) {
2573         if (auto CS = ImmutableCallSite(&*I)) {
2574           auto *CalledFunction = CS.getCalledFunction();
2575           if (CalledFunction && CalledFunction->hasName() &&
2576               !CalledFunction->isIntrinsic()) {
2577             auto ScaledCount = BFI ? BFI->getBlockProfileCount(&*BB) : None;
2578             unsigned CalleeId = VE.getValueID(
2579                 M->getValueSymbolTable().lookup(CalledFunction->getName()));
2580             CallGraphEdges[CalleeId] +=
2581                 (ScaledCount ? ScaledCount.getValue() : 0);
2582           }
2583         }
2584         findRefEdges(&*I, VE, RefEdges, Visited);
2585       }
2586 
2587       // If the instruction has metadata, write a metadata attachment later.
2588       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2589 
2590       // If the instruction has a debug location, emit it.
2591       DILocation *DL = I->getDebugLoc();
2592       if (!DL)
2593         continue;
2594 
2595       if (DL == LastDL) {
2596         // Just repeat the same debug loc as last time.
2597         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2598         continue;
2599       }
2600 
2601       Vals.push_back(DL->getLine());
2602       Vals.push_back(DL->getColumn());
2603       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2604       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2605       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2606       Vals.clear();
2607 
2608       LastDL = DL;
2609     }
2610 
2611   std::unique_ptr<FunctionSummary> FuncSummary;
2612   if (EmitSummaryIndex) {
2613     FuncSummary = llvm::make_unique<FunctionSummary>(F.getLinkage(), NumInsts);
2614     FuncSummary->addCallGraphEdges(CallGraphEdges);
2615     FuncSummary->addRefEdges(RefEdges);
2616   }
2617   FunctionIndex[&F] =
2618       llvm::make_unique<GlobalValueInfo>(BitcodeIndex, std::move(FuncSummary));
2619 
2620   // Emit names for all the instructions etc.
2621   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2622 
2623   if (NeedsMetadataAttachment)
2624     WriteMetadataAttachment(F, VE, Stream);
2625   if (VE.shouldPreserveUseListOrder())
2626     WriteUseListBlock(&F, VE, Stream);
2627   VE.purgeFunction();
2628   Stream.ExitBlock();
2629 }
2630 
2631 // Emit blockinfo, which defines the standard abbreviations etc.
2632 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2633   // We only want to emit block info records for blocks that have multiple
2634   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2635   // Other blocks can define their abbrevs inline.
2636   Stream.EnterBlockInfoBlock(2);
2637 
2638   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
2639     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2640     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2641     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2642     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2643     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2644     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2645                                    Abbv) != VST_ENTRY_8_ABBREV)
2646       llvm_unreachable("Unexpected abbrev ordering!");
2647   }
2648 
2649   { // 7-bit fixed width VST_CODE_ENTRY strings.
2650     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2651     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2652     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2653     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2654     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2655     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2656                                    Abbv) != VST_ENTRY_7_ABBREV)
2657       llvm_unreachable("Unexpected abbrev ordering!");
2658   }
2659   { // 6-bit char6 VST_CODE_ENTRY strings.
2660     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2661     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2662     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2663     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2664     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2665     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2666                                    Abbv) != VST_ENTRY_6_ABBREV)
2667       llvm_unreachable("Unexpected abbrev ordering!");
2668   }
2669   { // 6-bit char6 VST_CODE_BBENTRY strings.
2670     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2671     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2672     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2673     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2674     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2675     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2676                                    Abbv) != VST_BBENTRY_6_ABBREV)
2677       llvm_unreachable("Unexpected abbrev ordering!");
2678   }
2679 
2680 
2681 
2682   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2683     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2684     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2685     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2686                               VE.computeBitsRequiredForTypeIndicies()));
2687     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2688                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
2689       llvm_unreachable("Unexpected abbrev ordering!");
2690   }
2691 
2692   { // INTEGER abbrev for CONSTANTS_BLOCK.
2693     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2694     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2695     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2696     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2697                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
2698       llvm_unreachable("Unexpected abbrev ordering!");
2699   }
2700 
2701   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2702     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2703     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2704     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
2705     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
2706                               VE.computeBitsRequiredForTypeIndicies()));
2707     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
2708 
2709     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2710                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
2711       llvm_unreachable("Unexpected abbrev ordering!");
2712   }
2713   { // NULL abbrev for CONSTANTS_BLOCK.
2714     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2715     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2716     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2717                                    Abbv) != CONSTANTS_NULL_Abbrev)
2718       llvm_unreachable("Unexpected abbrev ordering!");
2719   }
2720 
2721   // FIXME: This should only use space for first class types!
2722 
2723   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2724     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2725     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2726     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2727     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2728                               VE.computeBitsRequiredForTypeIndicies()));
2729     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2730     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2731     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2732                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
2733       llvm_unreachable("Unexpected abbrev ordering!");
2734   }
2735   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2736     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2737     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2738     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2739     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2740     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2741     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2742                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
2743       llvm_unreachable("Unexpected abbrev ordering!");
2744   }
2745   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2746     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2747     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2748     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2749     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2750     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2751     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2752     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2753                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2754       llvm_unreachable("Unexpected abbrev ordering!");
2755   }
2756   { // INST_CAST abbrev for FUNCTION_BLOCK.
2757     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2758     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2759     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
2760     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
2761                               VE.computeBitsRequiredForTypeIndicies()));
2762     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
2763     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2764                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
2765       llvm_unreachable("Unexpected abbrev ordering!");
2766   }
2767 
2768   { // INST_RET abbrev for FUNCTION_BLOCK.
2769     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2770     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2771     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2772                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2773       llvm_unreachable("Unexpected abbrev ordering!");
2774   }
2775   { // INST_RET abbrev for FUNCTION_BLOCK.
2776     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2777     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2778     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2779     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2780                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2781       llvm_unreachable("Unexpected abbrev ordering!");
2782   }
2783   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2784     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2785     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2786     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2787                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2788       llvm_unreachable("Unexpected abbrev ordering!");
2789   }
2790   {
2791     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2792     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2793     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2794     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2795                               Log2_32_Ceil(VE.getTypes().size() + 1)));
2796     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2797     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2798     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2799         FUNCTION_INST_GEP_ABBREV)
2800       llvm_unreachable("Unexpected abbrev ordering!");
2801   }
2802 
2803   Stream.ExitBlock();
2804 }
2805 
2806 /// Write the module path strings, currently only used when generating
2807 /// a combined index file.
2808 static void WriteModStrings(const ModuleSummaryIndex &I,
2809                             BitstreamWriter &Stream) {
2810   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
2811 
2812   // TODO: See which abbrev sizes we actually need to emit
2813 
2814   // 8-bit fixed-width MST_ENTRY strings.
2815   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2816   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2817   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2818   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2819   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2820   unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
2821 
2822   // 7-bit fixed width MST_ENTRY strings.
2823   Abbv = new BitCodeAbbrev();
2824   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2825   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2826   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2827   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2828   unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
2829 
2830   // 6-bit char6 MST_ENTRY strings.
2831   Abbv = new BitCodeAbbrev();
2832   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2833   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2834   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2835   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2836   unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
2837 
2838   SmallVector<unsigned, 64> NameVals;
2839   for (const StringMapEntry<uint64_t> &MPSE : I.modPathStringEntries()) {
2840     StringEncoding Bits =
2841         getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
2842     unsigned AbbrevToUse = Abbrev8Bit;
2843     if (Bits == SE_Char6)
2844       AbbrevToUse = Abbrev6Bit;
2845     else if (Bits == SE_Fixed7)
2846       AbbrevToUse = Abbrev7Bit;
2847 
2848     NameVals.push_back(MPSE.getValue());
2849 
2850     for (const auto P : MPSE.getKey())
2851       NameVals.push_back((unsigned char)P);
2852 
2853     // Emit the finished record.
2854     Stream.EmitRecord(bitc::MST_CODE_ENTRY, NameVals, AbbrevToUse);
2855     NameVals.clear();
2856   }
2857   Stream.ExitBlock();
2858 }
2859 
2860 // Helper to emit a single function summary record.
2861 static void WritePerModuleFunctionSummaryRecord(
2862     SmallVector<uint64_t, 64> &NameVals, FunctionSummary *FS, unsigned ValueID,
2863     unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
2864     BitstreamWriter &Stream, const Function &F) {
2865   assert(FS);
2866   NameVals.push_back(ValueID);
2867   NameVals.push_back(getEncodedLinkage(FS->linkage()));
2868   NameVals.push_back(FS->instCount());
2869   NameVals.push_back(FS->refs().size());
2870 
2871   for (auto &RI : FS->refs())
2872     NameVals.push_back(RI);
2873 
2874   bool HasProfileData = F.getEntryCount().hasValue();
2875   for (auto &ECI : FS->edges()) {
2876     NameVals.push_back(ECI.first);
2877     assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite");
2878     NameVals.push_back(ECI.second.CallsiteCount);
2879     if (HasProfileData)
2880       NameVals.push_back(ECI.second.ProfileCount);
2881   }
2882 
2883   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
2884   unsigned Code =
2885       (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
2886 
2887   // Emit the finished record.
2888   Stream.EmitRecord(Code, NameVals, FSAbbrev);
2889   NameVals.clear();
2890 }
2891 
2892 // Collect the global value references in the given variable's initializer,
2893 // and emit them in a summary record.
2894 static void WriteModuleLevelReferences(const GlobalVariable &V,
2895                                        const ValueEnumerator &VE,
2896                                        SmallVector<uint64_t, 64> &NameVals,
2897                                        unsigned FSModRefsAbbrev,
2898                                        BitstreamWriter &Stream) {
2899   // Only interested in recording variable defs in the summary.
2900   if (V.isDeclaration())
2901     return;
2902   DenseSet<unsigned> RefEdges;
2903   SmallPtrSet<const User *, 8> Visited;
2904   findRefEdges(&V, VE, RefEdges, Visited);
2905   NameVals.push_back(VE.getValueID(&V));
2906   NameVals.push_back(getEncodedLinkage(V.getLinkage()));
2907   for (auto RefId : RefEdges) {
2908     NameVals.push_back(RefId);
2909   }
2910   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
2911                     FSModRefsAbbrev);
2912   NameVals.clear();
2913 }
2914 
2915 /// Emit the per-module summary section alongside the rest of
2916 /// the module's bitcode.
2917 static void WritePerModuleGlobalValueSummary(
2918     DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex,
2919     const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream) {
2920   if (M->empty())
2921     return;
2922 
2923   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
2924 
2925   // Abbrev for FS_PERMODULE.
2926   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2927   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
2928   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2929   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2930   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2931   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2932   // numrefs x valueid, n x (valueid, callsitecount)
2933   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2934   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2935   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
2936 
2937   // Abbrev for FS_PERMODULE_PROFILE.
2938   Abbv = new BitCodeAbbrev();
2939   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
2940   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2941   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2942   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2943   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2944   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
2945   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2946   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2947   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
2948 
2949   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
2950   Abbv = new BitCodeAbbrev();
2951   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
2952   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2953   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2954   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
2955   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2956   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
2957 
2958   SmallVector<uint64_t, 64> NameVals;
2959   // Iterate over the list of functions instead of the FunctionIndex map to
2960   // ensure the ordering is stable.
2961   for (const Function &F : *M) {
2962     if (F.isDeclaration())
2963       continue;
2964     // Skip anonymous functions. We will emit a function summary for
2965     // any aliases below.
2966     if (!F.hasName())
2967       continue;
2968 
2969     assert(FunctionIndex.count(&F) == 1);
2970 
2971     WritePerModuleFunctionSummaryRecord(
2972         NameVals, cast<FunctionSummary>(FunctionIndex[&F]->summary()),
2973         VE.getValueID(M->getValueSymbolTable().lookup(F.getName())),
2974         FSCallsAbbrev, FSCallsProfileAbbrev, Stream, F);
2975   }
2976 
2977   for (const GlobalAlias &A : M->aliases()) {
2978     if (!A.getBaseObject())
2979       continue;
2980     const Function *F = dyn_cast<Function>(A.getBaseObject());
2981     if (!F || F->isDeclaration())
2982       continue;
2983 
2984     assert(FunctionIndex.count(F) == 1);
2985     FunctionSummary *FS =
2986         cast<FunctionSummary>(FunctionIndex[F]->summary());
2987     // Add the alias to the reference list of aliasee function.
2988     FS->addRefEdge(
2989         VE.getValueID(M->getValueSymbolTable().lookup(A.getName())));
2990     WritePerModuleFunctionSummaryRecord(
2991         NameVals, FS,
2992         VE.getValueID(M->getValueSymbolTable().lookup(A.getName())),
2993         FSCallsAbbrev, FSCallsProfileAbbrev, Stream, *F);
2994   }
2995 
2996   // Capture references from GlobalVariable initializers, which are outside
2997   // of a function scope.
2998   for (const GlobalVariable &G : M->globals())
2999     WriteModuleLevelReferences(G, VE, NameVals, FSModRefsAbbrev, Stream);
3000   for (const GlobalAlias &A : M->aliases())
3001     if (auto *GV = dyn_cast<GlobalVariable>(A.getBaseObject()))
3002       WriteModuleLevelReferences(*GV, VE, NameVals, FSModRefsAbbrev, Stream);
3003 
3004   Stream.ExitBlock();
3005 }
3006 
3007 /// Emit the combined summary section into the combined index file.
3008 static void WriteCombinedGlobalValueSummary(
3009     const ModuleSummaryIndex &I, BitstreamWriter &Stream,
3010     std::map<uint64_t, unsigned> &GUIDToValueIdMap, unsigned GlobalValueId) {
3011   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3012 
3013   // Abbrev for FS_COMBINED.
3014   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3015   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3016   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3017   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3018   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3019   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3020   // numrefs x valueid, n x (valueid, callsitecount)
3021   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3022   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3023   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
3024 
3025   // Abbrev for FS_COMBINED_PROFILE.
3026   Abbv = new BitCodeAbbrev();
3027   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3028   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3029   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3030   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3031   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3032   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
3033   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3034   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3035   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
3036 
3037   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3038   Abbv = new BitCodeAbbrev();
3039   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3040   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3041   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3042   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
3043   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3044   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
3045 
3046   SmallVector<uint64_t, 64> NameVals;
3047   for (const auto &FII : I) {
3048     for (auto &FI : FII.second) {
3049       GlobalValueSummary *S = FI->summary();
3050       assert(S);
3051 
3052       if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3053         NameVals.push_back(I.getModuleId(VS->modulePath()));
3054         NameVals.push_back(getEncodedLinkage(VS->linkage()));
3055         for (auto &RI : VS->refs()) {
3056           const auto &VMI = GUIDToValueIdMap.find(RI);
3057           unsigned RefId;
3058           // If this GUID doesn't have an entry, assign one.
3059           if (VMI == GUIDToValueIdMap.end()) {
3060             GUIDToValueIdMap[RI] = ++GlobalValueId;
3061             RefId = GlobalValueId;
3062           } else {
3063             RefId = VMI->second;
3064           }
3065           NameVals.push_back(RefId);
3066         }
3067 
3068         // Record the starting offset of this summary entry for use
3069         // in the VST entry. Add the current code size since the
3070         // reader will invoke readRecord after the abbrev id read.
3071         FI->setBitcodeIndex(Stream.GetCurrentBitNo() +
3072                             Stream.GetAbbrevIDWidth());
3073 
3074         // Emit the finished record.
3075         Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3076                           FSModRefsAbbrev);
3077         NameVals.clear();
3078         continue;
3079       }
3080 
3081       auto *FS = cast<FunctionSummary>(S);
3082       NameVals.push_back(I.getModuleId(FS->modulePath()));
3083       NameVals.push_back(getEncodedLinkage(FS->linkage()));
3084       NameVals.push_back(FS->instCount());
3085       NameVals.push_back(FS->refs().size());
3086 
3087       for (auto &RI : FS->refs()) {
3088         const auto &VMI = GUIDToValueIdMap.find(RI);
3089         unsigned RefId;
3090         // If this GUID doesn't have an entry, assign one.
3091         if (VMI == GUIDToValueIdMap.end()) {
3092           GUIDToValueIdMap[RI] = ++GlobalValueId;
3093           RefId = GlobalValueId;
3094         } else {
3095           RefId = VMI->second;
3096         }
3097         NameVals.push_back(RefId);
3098       }
3099 
3100       bool HasProfileData = false;
3101       for (auto &EI : FS->edges()) {
3102         HasProfileData |= EI.second.ProfileCount != 0;
3103         if (HasProfileData)
3104           break;
3105       }
3106 
3107       for (auto &EI : FS->edges()) {
3108         const auto &VMI = GUIDToValueIdMap.find(EI.first);
3109         // If this GUID doesn't have an entry, it doesn't have a function
3110         // summary and we don't need to record any calls to it.
3111         if (VMI == GUIDToValueIdMap.end())
3112           continue;
3113         NameVals.push_back(VMI->second);
3114         assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite");
3115         NameVals.push_back(EI.second.CallsiteCount);
3116         if (HasProfileData)
3117           NameVals.push_back(EI.second.ProfileCount);
3118       }
3119 
3120       // Record the starting offset of this summary entry for use
3121       // in the VST entry. Add the current code size since the
3122       // reader will invoke readRecord after the abbrev id read.
3123       FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
3124 
3125       unsigned FSAbbrev =
3126           (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3127       unsigned Code =
3128           (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3129 
3130       // Emit the finished record.
3131       Stream.EmitRecord(Code, NameVals, FSAbbrev);
3132       NameVals.clear();
3133     }
3134   }
3135 
3136   Stream.ExitBlock();
3137 }
3138 
3139 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3140 // current llvm version, and a record for the epoch number.
3141 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
3142   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3143 
3144   // Write the "user readable" string identifying the bitcode producer
3145   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3146   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3147   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3148   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3149   auto StringAbbrev = Stream.EmitAbbrev(Abbv);
3150   WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
3151                     "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
3152 
3153   // Write the epoch version
3154   Abbv = new BitCodeAbbrev();
3155   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3156   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3157   auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
3158   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3159   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3160   Stream.ExitBlock();
3161 }
3162 
3163 /// WriteModule - Emit the specified module to the bitstream.
3164 static void WriteModule(const Module *M, BitstreamWriter &Stream,
3165                         bool ShouldPreserveUseListOrder,
3166                         uint64_t BitcodeStartBit, bool EmitSummaryIndex) {
3167   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3168 
3169   SmallVector<unsigned, 1> Vals;
3170   unsigned CurVersion = 1;
3171   Vals.push_back(CurVersion);
3172   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3173 
3174   // Analyze the module, enumerating globals, functions, etc.
3175   ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
3176 
3177   // Emit blockinfo, which defines the standard abbreviations etc.
3178   WriteBlockInfo(VE, Stream);
3179 
3180   // Emit information about attribute groups.
3181   WriteAttributeGroupTable(VE, Stream);
3182 
3183   // Emit information about parameter attributes.
3184   WriteAttributeTable(VE, Stream);
3185 
3186   // Emit information describing all of the types in the module.
3187   WriteTypeTable(VE, Stream);
3188 
3189   writeComdats(VE, Stream);
3190 
3191   // Emit top-level description of module, including target triple, inline asm,
3192   // descriptors for global variables, and function prototype info.
3193   uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
3194 
3195   // Emit constants.
3196   WriteModuleConstants(VE, Stream);
3197 
3198   // Emit metadata.
3199   WriteModuleMetadata(M, VE, Stream);
3200 
3201   // Emit metadata.
3202   WriteModuleMetadataStore(M, Stream);
3203 
3204   // Emit module-level use-lists.
3205   if (VE.shouldPreserveUseListOrder())
3206     WriteUseListBlock(nullptr, VE, Stream);
3207 
3208   WriteOperandBundleTags(M, Stream);
3209 
3210   // Emit function bodies.
3211   DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> FunctionIndex;
3212   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
3213     if (!F->isDeclaration())
3214       WriteFunction(*F, M, VE, Stream, FunctionIndex, EmitSummaryIndex);
3215 
3216   // Need to write after the above call to WriteFunction which populates
3217   // the summary information in the index.
3218   if (EmitSummaryIndex)
3219     WritePerModuleGlobalValueSummary(FunctionIndex, M, VE, Stream);
3220 
3221   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
3222                         VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
3223 
3224   Stream.ExitBlock();
3225 }
3226 
3227 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
3228 /// header and trailer to make it compatible with the system archiver.  To do
3229 /// this we emit the following header, and then emit a trailer that pads the
3230 /// file out to be a multiple of 16 bytes.
3231 ///
3232 /// struct bc_header {
3233 ///   uint32_t Magic;         // 0x0B17C0DE
3234 ///   uint32_t Version;       // Version, currently always 0.
3235 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3236 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
3237 ///   uint32_t CPUType;       // CPU specifier.
3238 ///   ... potentially more later ...
3239 /// };
3240 
3241 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3242                                uint32_t &Position) {
3243   support::endian::write32le(&Buffer[Position], Value);
3244   Position += 4;
3245 }
3246 
3247 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3248                                          const Triple &TT) {
3249   unsigned CPUType = ~0U;
3250 
3251   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3252   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3253   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
3254   // specific constants here because they are implicitly part of the Darwin ABI.
3255   enum {
3256     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
3257     DARWIN_CPU_TYPE_X86        = 7,
3258     DARWIN_CPU_TYPE_ARM        = 12,
3259     DARWIN_CPU_TYPE_POWERPC    = 18
3260   };
3261 
3262   Triple::ArchType Arch = TT.getArch();
3263   if (Arch == Triple::x86_64)
3264     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3265   else if (Arch == Triple::x86)
3266     CPUType = DARWIN_CPU_TYPE_X86;
3267   else if (Arch == Triple::ppc)
3268     CPUType = DARWIN_CPU_TYPE_POWERPC;
3269   else if (Arch == Triple::ppc64)
3270     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3271   else if (Arch == Triple::arm || Arch == Triple::thumb)
3272     CPUType = DARWIN_CPU_TYPE_ARM;
3273 
3274   // Traditional Bitcode starts after header.
3275   assert(Buffer.size() >= BWH_HeaderSize &&
3276          "Expected header size to be reserved");
3277   unsigned BCOffset = BWH_HeaderSize;
3278   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3279 
3280   // Write the magic and version.
3281   unsigned Position = 0;
3282   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
3283   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
3284   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
3285   WriteInt32ToBuffer(BCSize     , Buffer, Position);
3286   WriteInt32ToBuffer(CPUType    , Buffer, Position);
3287 
3288   // If the file is not a multiple of 16 bytes, insert dummy padding.
3289   while (Buffer.size() & 15)
3290     Buffer.push_back(0);
3291 }
3292 
3293 /// Helper to write the header common to all bitcode files.
3294 static void WriteBitcodeHeader(BitstreamWriter &Stream) {
3295   // Emit the file header.
3296   Stream.Emit((unsigned)'B', 8);
3297   Stream.Emit((unsigned)'C', 8);
3298   Stream.Emit(0x0, 4);
3299   Stream.Emit(0xC, 4);
3300   Stream.Emit(0xE, 4);
3301   Stream.Emit(0xD, 4);
3302 }
3303 
3304 /// WriteBitcodeToFile - Write the specified module to the specified output
3305 /// stream.
3306 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3307                               bool ShouldPreserveUseListOrder,
3308                               bool EmitSummaryIndex) {
3309   SmallVector<char, 0> Buffer;
3310   Buffer.reserve(256*1024);
3311 
3312   // If this is darwin or another generic macho target, reserve space for the
3313   // header.
3314   Triple TT(M->getTargetTriple());
3315   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3316     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3317 
3318   // Emit the module into the buffer.
3319   {
3320     BitstreamWriter Stream(Buffer);
3321     // Save the start bit of the actual bitcode, in case there is space
3322     // saved at the start for the darwin header above. The reader stream
3323     // will start at the bitcode, and we need the offset of the VST
3324     // to line up.
3325     uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
3326 
3327     // Emit the file header.
3328     WriteBitcodeHeader(Stream);
3329 
3330     WriteIdentificationBlock(M, Stream);
3331 
3332     // Emit the module.
3333     WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit,
3334                 EmitSummaryIndex);
3335   }
3336 
3337   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3338     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
3339 
3340   // Write the generated bitstream to "Out".
3341   Out.write((char*)&Buffer.front(), Buffer.size());
3342 }
3343 
3344 // Write the specified module summary index to the given raw output stream,
3345 // where it will be written in a new bitcode block. This is used when
3346 // writing the combined index file for ThinLTO.
3347 void llvm::WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out) {
3348   SmallVector<char, 0> Buffer;
3349   Buffer.reserve(256 * 1024);
3350 
3351   BitstreamWriter Stream(Buffer);
3352 
3353   // Emit the bitcode header.
3354   WriteBitcodeHeader(Stream);
3355 
3356   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3357 
3358   SmallVector<unsigned, 1> Vals;
3359   unsigned CurVersion = 1;
3360   Vals.push_back(CurVersion);
3361   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3362 
3363   // If we have a VST, write the VSTOFFSET record placeholder and record
3364   // its offset.
3365   uint64_t VSTOffsetPlaceholder = WriteValueSymbolTableForwardDecl(Stream);
3366 
3367   // Write the module paths in the combined index.
3368   WriteModStrings(Index, Stream);
3369 
3370   // Assign unique value ids to all functions in the index for use
3371   // in writing out the call graph edges. Save the mapping from GUID
3372   // to the new global value id to use when writing those edges, which
3373   // are currently saved in the index in terms of GUID.
3374   std::map<uint64_t, unsigned> GUIDToValueIdMap;
3375   unsigned GlobalValueId = 0;
3376   for (auto &II : Index)
3377     GUIDToValueIdMap[II.first] = ++GlobalValueId;
3378 
3379   // Write the summary combined index records.
3380   WriteCombinedGlobalValueSummary(Index, Stream, GUIDToValueIdMap,
3381                                   GlobalValueId);
3382 
3383   // Need a special VST writer for the combined index (we don't have a
3384   // real VST and real values when this is invoked).
3385   WriteCombinedValueSymbolTable(Index, Stream, GUIDToValueIdMap,
3386                                 VSTOffsetPlaceholder);
3387 
3388   Stream.ExitBlock();
3389 
3390   Out.write((char *)&Buffer.front(), Buffer.size());
3391 }
3392