xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision b35cc691ea93d9408f76736170359fd7ce604b53)
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/StringExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/BitstreamWriter.h"
18 #include "llvm/Bitcode/LLVMBitCodes.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/UseListOrder.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/SHA1.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cctype>
37 #include <map>
38 using namespace llvm;
39 
40 /// These are manifest constants used by the bitcode writer. They do not need to
41 /// be kept in sync with the reader, but need to be consistent within this file.
42 enum {
43   // VALUE_SYMTAB_BLOCK abbrev id's.
44   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
45   VST_ENTRY_7_ABBREV,
46   VST_ENTRY_6_ABBREV,
47   VST_BBENTRY_6_ABBREV,
48 
49   // CONSTANTS_BLOCK abbrev id's.
50   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51   CONSTANTS_INTEGER_ABBREV,
52   CONSTANTS_CE_CAST_Abbrev,
53   CONSTANTS_NULL_Abbrev,
54 
55   // FUNCTION_BLOCK abbrev id's.
56   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
57   FUNCTION_INST_BINOP_ABBREV,
58   FUNCTION_INST_BINOP_FLAGS_ABBREV,
59   FUNCTION_INST_CAST_ABBREV,
60   FUNCTION_INST_RET_VOID_ABBREV,
61   FUNCTION_INST_RET_VAL_ABBREV,
62   FUNCTION_INST_UNREACHABLE_ABBREV,
63   FUNCTION_INST_GEP_ABBREV,
64 };
65 
66 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
67   switch (Opcode) {
68   default: llvm_unreachable("Unknown cast instruction!");
69   case Instruction::Trunc   : return bitc::CAST_TRUNC;
70   case Instruction::ZExt    : return bitc::CAST_ZEXT;
71   case Instruction::SExt    : return bitc::CAST_SEXT;
72   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
73   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
74   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
75   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
76   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
77   case Instruction::FPExt   : return bitc::CAST_FPEXT;
78   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
79   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
80   case Instruction::BitCast : return bitc::CAST_BITCAST;
81   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
82   }
83 }
84 
85 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
86   switch (Opcode) {
87   default: llvm_unreachable("Unknown binary instruction!");
88   case Instruction::Add:
89   case Instruction::FAdd: return bitc::BINOP_ADD;
90   case Instruction::Sub:
91   case Instruction::FSub: return bitc::BINOP_SUB;
92   case Instruction::Mul:
93   case Instruction::FMul: return bitc::BINOP_MUL;
94   case Instruction::UDiv: return bitc::BINOP_UDIV;
95   case Instruction::FDiv:
96   case Instruction::SDiv: return bitc::BINOP_SDIV;
97   case Instruction::URem: return bitc::BINOP_UREM;
98   case Instruction::FRem:
99   case Instruction::SRem: return bitc::BINOP_SREM;
100   case Instruction::Shl:  return bitc::BINOP_SHL;
101   case Instruction::LShr: return bitc::BINOP_LSHR;
102   case Instruction::AShr: return bitc::BINOP_ASHR;
103   case Instruction::And:  return bitc::BINOP_AND;
104   case Instruction::Or:   return bitc::BINOP_OR;
105   case Instruction::Xor:  return bitc::BINOP_XOR;
106   }
107 }
108 
109 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
110   switch (Op) {
111   default: llvm_unreachable("Unknown RMW operation!");
112   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
113   case AtomicRMWInst::Add: return bitc::RMW_ADD;
114   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
115   case AtomicRMWInst::And: return bitc::RMW_AND;
116   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
117   case AtomicRMWInst::Or: return bitc::RMW_OR;
118   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
119   case AtomicRMWInst::Max: return bitc::RMW_MAX;
120   case AtomicRMWInst::Min: return bitc::RMW_MIN;
121   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
122   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
123   }
124 }
125 
126 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
127   switch (Ordering) {
128   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
129   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
130   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
131   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
132   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
133   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
134   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
135   }
136   llvm_unreachable("Invalid ordering");
137 }
138 
139 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
140   switch (SynchScope) {
141   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
142   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
143   }
144   llvm_unreachable("Invalid synch scope");
145 }
146 
147 static void WriteStringRecord(unsigned Code, StringRef Str,
148                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
149   SmallVector<unsigned, 64> Vals;
150 
151   // Code: [strchar x N]
152   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
153     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
154       AbbrevToUse = 0;
155     Vals.push_back(Str[i]);
156   }
157 
158   // Emit the finished record.
159   Stream.EmitRecord(Code, Vals, AbbrevToUse);
160 }
161 
162 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
163   switch (Kind) {
164   case Attribute::Alignment:
165     return bitc::ATTR_KIND_ALIGNMENT;
166   case Attribute::AllocSize:
167     return bitc::ATTR_KIND_ALLOC_SIZE;
168   case Attribute::AlwaysInline:
169     return bitc::ATTR_KIND_ALWAYS_INLINE;
170   case Attribute::ArgMemOnly:
171     return bitc::ATTR_KIND_ARGMEMONLY;
172   case Attribute::Builtin:
173     return bitc::ATTR_KIND_BUILTIN;
174   case Attribute::ByVal:
175     return bitc::ATTR_KIND_BY_VAL;
176   case Attribute::Convergent:
177     return bitc::ATTR_KIND_CONVERGENT;
178   case Attribute::InAlloca:
179     return bitc::ATTR_KIND_IN_ALLOCA;
180   case Attribute::Cold:
181     return bitc::ATTR_KIND_COLD;
182   case Attribute::InaccessibleMemOnly:
183     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
184   case Attribute::InaccessibleMemOrArgMemOnly:
185     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
186   case Attribute::InlineHint:
187     return bitc::ATTR_KIND_INLINE_HINT;
188   case Attribute::InReg:
189     return bitc::ATTR_KIND_IN_REG;
190   case Attribute::JumpTable:
191     return bitc::ATTR_KIND_JUMP_TABLE;
192   case Attribute::MinSize:
193     return bitc::ATTR_KIND_MIN_SIZE;
194   case Attribute::Naked:
195     return bitc::ATTR_KIND_NAKED;
196   case Attribute::Nest:
197     return bitc::ATTR_KIND_NEST;
198   case Attribute::NoAlias:
199     return bitc::ATTR_KIND_NO_ALIAS;
200   case Attribute::NoBuiltin:
201     return bitc::ATTR_KIND_NO_BUILTIN;
202   case Attribute::NoCapture:
203     return bitc::ATTR_KIND_NO_CAPTURE;
204   case Attribute::NoDuplicate:
205     return bitc::ATTR_KIND_NO_DUPLICATE;
206   case Attribute::NoImplicitFloat:
207     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
208   case Attribute::NoInline:
209     return bitc::ATTR_KIND_NO_INLINE;
210   case Attribute::NoRecurse:
211     return bitc::ATTR_KIND_NO_RECURSE;
212   case Attribute::NonLazyBind:
213     return bitc::ATTR_KIND_NON_LAZY_BIND;
214   case Attribute::NonNull:
215     return bitc::ATTR_KIND_NON_NULL;
216   case Attribute::Dereferenceable:
217     return bitc::ATTR_KIND_DEREFERENCEABLE;
218   case Attribute::DereferenceableOrNull:
219     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
220   case Attribute::NoRedZone:
221     return bitc::ATTR_KIND_NO_RED_ZONE;
222   case Attribute::NoReturn:
223     return bitc::ATTR_KIND_NO_RETURN;
224   case Attribute::NoUnwind:
225     return bitc::ATTR_KIND_NO_UNWIND;
226   case Attribute::OptimizeForSize:
227     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
228   case Attribute::OptimizeNone:
229     return bitc::ATTR_KIND_OPTIMIZE_NONE;
230   case Attribute::ReadNone:
231     return bitc::ATTR_KIND_READ_NONE;
232   case Attribute::ReadOnly:
233     return bitc::ATTR_KIND_READ_ONLY;
234   case Attribute::Returned:
235     return bitc::ATTR_KIND_RETURNED;
236   case Attribute::ReturnsTwice:
237     return bitc::ATTR_KIND_RETURNS_TWICE;
238   case Attribute::SExt:
239     return bitc::ATTR_KIND_S_EXT;
240   case Attribute::StackAlignment:
241     return bitc::ATTR_KIND_STACK_ALIGNMENT;
242   case Attribute::StackProtect:
243     return bitc::ATTR_KIND_STACK_PROTECT;
244   case Attribute::StackProtectReq:
245     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
246   case Attribute::StackProtectStrong:
247     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
248   case Attribute::SafeStack:
249     return bitc::ATTR_KIND_SAFESTACK;
250   case Attribute::StructRet:
251     return bitc::ATTR_KIND_STRUCT_RET;
252   case Attribute::SanitizeAddress:
253     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
254   case Attribute::SanitizeThread:
255     return bitc::ATTR_KIND_SANITIZE_THREAD;
256   case Attribute::SanitizeMemory:
257     return bitc::ATTR_KIND_SANITIZE_MEMORY;
258   case Attribute::SwiftError:
259     return bitc::ATTR_KIND_SWIFT_ERROR;
260   case Attribute::SwiftSelf:
261     return bitc::ATTR_KIND_SWIFT_SELF;
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   // Emit the ifunc information.
807   for (const GlobalIFunc &I : M->ifuncs()) {
808     // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility]
809     Vals.push_back(VE.getTypeID(I.getValueType()));
810     Vals.push_back(I.getType()->getAddressSpace());
811     Vals.push_back(VE.getValueID(I.getResolver()));
812     Vals.push_back(getEncodedLinkage(I));
813     Vals.push_back(getEncodedVisibility(I));
814     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
815     Vals.clear();
816   }
817 
818   // Emit the module's source file name.
819   {
820     StringEncoding Bits = getStringEncoding(M->getSourceFileName().data(),
821                                             M->getSourceFileName().size());
822     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
823     if (Bits == SE_Char6)
824       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
825     else if (Bits == SE_Fixed7)
826       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
827 
828     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
829     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
830     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
831     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
832     Abbv->Add(AbbrevOpToUse);
833     unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv);
834 
835     for (const auto P : M->getSourceFileName())
836       Vals.push_back((unsigned char)P);
837 
838     // Emit the finished record.
839     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
840     Vals.clear();
841   }
842 
843   // If we have a VST, write the VSTOFFSET record placeholder and return
844   // its offset.
845   if (M->getValueSymbolTable().empty())
846     return 0;
847   return WriteValueSymbolTableForwardDecl(Stream);
848 }
849 
850 static uint64_t GetOptimizationFlags(const Value *V) {
851   uint64_t Flags = 0;
852 
853   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
854     if (OBO->hasNoSignedWrap())
855       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
856     if (OBO->hasNoUnsignedWrap())
857       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
858   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
859     if (PEO->isExact())
860       Flags |= 1 << bitc::PEO_EXACT;
861   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
862     if (FPMO->hasUnsafeAlgebra())
863       Flags |= FastMathFlags::UnsafeAlgebra;
864     if (FPMO->hasNoNaNs())
865       Flags |= FastMathFlags::NoNaNs;
866     if (FPMO->hasNoInfs())
867       Flags |= FastMathFlags::NoInfs;
868     if (FPMO->hasNoSignedZeros())
869       Flags |= FastMathFlags::NoSignedZeros;
870     if (FPMO->hasAllowReciprocal())
871       Flags |= FastMathFlags::AllowReciprocal;
872   }
873 
874   return Flags;
875 }
876 
877 static void writeValueAsMetadata(const ValueAsMetadata *MD,
878                                  const ValueEnumerator &VE,
879                                  BitstreamWriter &Stream,
880                                  SmallVectorImpl<uint64_t> &Record) {
881   // Mimic an MDNode with a value as one operand.
882   Value *V = MD->getValue();
883   Record.push_back(VE.getTypeID(V->getType()));
884   Record.push_back(VE.getValueID(V));
885   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
886   Record.clear();
887 }
888 
889 static void writeMDTuple(const MDTuple *N, const ValueEnumerator &VE,
890                          BitstreamWriter &Stream,
891                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
892   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
893     Metadata *MD = N->getOperand(i);
894     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
895            "Unexpected function-local metadata");
896     Record.push_back(VE.getMetadataOrNullID(MD));
897   }
898   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
899                                     : bitc::METADATA_NODE,
900                     Record, Abbrev);
901   Record.clear();
902 }
903 
904 static unsigned createDILocationAbbrev(BitstreamWriter &Stream) {
905   // Assume the column is usually under 128, and always output the inlined-at
906   // location (it's never more expensive than building an array size 1).
907   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
908   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
909   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
910   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
911   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
912   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
913   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
914   return Stream.EmitAbbrev(Abbv);
915 }
916 
917 static void writeDILocation(const DILocation *N, const ValueEnumerator &VE,
918                             BitstreamWriter &Stream,
919                             SmallVectorImpl<uint64_t> &Record,
920                             unsigned &Abbrev) {
921   if (!Abbrev)
922     Abbrev = createDILocationAbbrev(Stream);
923 
924   Record.push_back(N->isDistinct());
925   Record.push_back(N->getLine());
926   Record.push_back(N->getColumn());
927   Record.push_back(VE.getMetadataID(N->getScope()));
928   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
929 
930   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
931   Record.clear();
932 }
933 
934 static unsigned createGenericDINodeAbbrev(BitstreamWriter &Stream) {
935   // Assume the column is usually under 128, and always output the inlined-at
936   // location (it's never more expensive than building an array size 1).
937   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
938   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
939   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
940   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
941   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
942   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
943   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
944   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
945   return Stream.EmitAbbrev(Abbv);
946 }
947 
948 static void writeGenericDINode(const GenericDINode *N,
949                                const ValueEnumerator &VE,
950                                BitstreamWriter &Stream,
951                                SmallVectorImpl<uint64_t> &Record,
952                                unsigned &Abbrev) {
953   if (!Abbrev)
954     Abbrev = createGenericDINodeAbbrev(Stream);
955 
956   Record.push_back(N->isDistinct());
957   Record.push_back(N->getTag());
958   Record.push_back(0); // Per-tag version field; unused for now.
959 
960   for (auto &I : N->operands())
961     Record.push_back(VE.getMetadataOrNullID(I));
962 
963   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
964   Record.clear();
965 }
966 
967 static uint64_t rotateSign(int64_t I) {
968   uint64_t U = I;
969   return I < 0 ? ~(U << 1) : U << 1;
970 }
971 
972 static void writeDISubrange(const DISubrange *N, const ValueEnumerator &,
973                             BitstreamWriter &Stream,
974                             SmallVectorImpl<uint64_t> &Record,
975                             unsigned Abbrev) {
976   Record.push_back(N->isDistinct());
977   Record.push_back(N->getCount());
978   Record.push_back(rotateSign(N->getLowerBound()));
979 
980   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
981   Record.clear();
982 }
983 
984 static void writeDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
985                               BitstreamWriter &Stream,
986                               SmallVectorImpl<uint64_t> &Record,
987                               unsigned Abbrev) {
988   Record.push_back(N->isDistinct());
989   Record.push_back(rotateSign(N->getValue()));
990   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
991 
992   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
993   Record.clear();
994 }
995 
996 static void writeDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
997                              BitstreamWriter &Stream,
998                              SmallVectorImpl<uint64_t> &Record,
999                              unsigned Abbrev) {
1000   Record.push_back(N->isDistinct());
1001   Record.push_back(N->getTag());
1002   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1003   Record.push_back(N->getSizeInBits());
1004   Record.push_back(N->getAlignInBits());
1005   Record.push_back(N->getEncoding());
1006 
1007   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1008   Record.clear();
1009 }
1010 
1011 static void writeDIDerivedType(const DIDerivedType *N,
1012                                const ValueEnumerator &VE,
1013                                BitstreamWriter &Stream,
1014                                SmallVectorImpl<uint64_t> &Record,
1015                                unsigned Abbrev) {
1016   Record.push_back(N->isDistinct());
1017   Record.push_back(N->getTag());
1018   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1019   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1020   Record.push_back(N->getLine());
1021   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1022   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1023   Record.push_back(N->getSizeInBits());
1024   Record.push_back(N->getAlignInBits());
1025   Record.push_back(N->getOffsetInBits());
1026   Record.push_back(N->getFlags());
1027   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1028 
1029   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1030   Record.clear();
1031 }
1032 
1033 static void writeDICompositeType(const DICompositeType *N,
1034                                  const ValueEnumerator &VE,
1035                                  BitstreamWriter &Stream,
1036                                  SmallVectorImpl<uint64_t> &Record,
1037                                  unsigned Abbrev) {
1038   Record.push_back(N->isDistinct());
1039   Record.push_back(N->getTag());
1040   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1041   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1042   Record.push_back(N->getLine());
1043   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1044   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1045   Record.push_back(N->getSizeInBits());
1046   Record.push_back(N->getAlignInBits());
1047   Record.push_back(N->getOffsetInBits());
1048   Record.push_back(N->getFlags());
1049   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1050   Record.push_back(N->getRuntimeLang());
1051   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1052   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1053   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1054 
1055   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1056   Record.clear();
1057 }
1058 
1059 static void writeDISubroutineType(const DISubroutineType *N,
1060                                   const ValueEnumerator &VE,
1061                                   BitstreamWriter &Stream,
1062                                   SmallVectorImpl<uint64_t> &Record,
1063                                   unsigned Abbrev) {
1064   Record.push_back(N->isDistinct());
1065   Record.push_back(N->getFlags());
1066   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1067 
1068   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1069   Record.clear();
1070 }
1071 
1072 static void writeDIFile(const DIFile *N, const ValueEnumerator &VE,
1073                         BitstreamWriter &Stream,
1074                         SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1075   Record.push_back(N->isDistinct());
1076   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1077   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1078 
1079   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1080   Record.clear();
1081 }
1082 
1083 static void writeDICompileUnit(const DICompileUnit *N,
1084                                const ValueEnumerator &VE,
1085                                BitstreamWriter &Stream,
1086                                SmallVectorImpl<uint64_t> &Record,
1087                                unsigned Abbrev) {
1088   assert(N->isDistinct() && "Expected distinct compile units");
1089   Record.push_back(/* IsDistinct */ true);
1090   Record.push_back(N->getSourceLanguage());
1091   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1092   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1093   Record.push_back(N->isOptimized());
1094   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1095   Record.push_back(N->getRuntimeVersion());
1096   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1097   Record.push_back(N->getEmissionKind());
1098   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1099   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1100   Record.push_back(/* subprograms */ 0);
1101   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1102   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1103   Record.push_back(N->getDWOId());
1104   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1105 
1106   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1107   Record.clear();
1108 }
1109 
1110 static void writeDISubprogram(const DISubprogram *N, 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->getRawName()));
1117   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1118   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1119   Record.push_back(N->getLine());
1120   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1121   Record.push_back(N->isLocalToUnit());
1122   Record.push_back(N->isDefinition());
1123   Record.push_back(N->getScopeLine());
1124   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1125   Record.push_back(N->getVirtuality());
1126   Record.push_back(N->getVirtualIndex());
1127   Record.push_back(N->getFlags());
1128   Record.push_back(N->isOptimized());
1129   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1130   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1131   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1132   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1133 
1134   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1135   Record.clear();
1136 }
1137 
1138 static void writeDILexicalBlock(const DILexicalBlock *N,
1139                                 const ValueEnumerator &VE,
1140                                 BitstreamWriter &Stream,
1141                                 SmallVectorImpl<uint64_t> &Record,
1142                                 unsigned Abbrev) {
1143   Record.push_back(N->isDistinct());
1144   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1145   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1146   Record.push_back(N->getLine());
1147   Record.push_back(N->getColumn());
1148 
1149   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1150   Record.clear();
1151 }
1152 
1153 static void writeDILexicalBlockFile(const DILexicalBlockFile *N,
1154                                     const ValueEnumerator &VE,
1155                                     BitstreamWriter &Stream,
1156                                     SmallVectorImpl<uint64_t> &Record,
1157                                     unsigned Abbrev) {
1158   Record.push_back(N->isDistinct());
1159   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1160   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1161   Record.push_back(N->getDiscriminator());
1162 
1163   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1164   Record.clear();
1165 }
1166 
1167 static void writeDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1168                              BitstreamWriter &Stream,
1169                              SmallVectorImpl<uint64_t> &Record,
1170                              unsigned Abbrev) {
1171   Record.push_back(N->isDistinct());
1172   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1173   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1174   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1175   Record.push_back(N->getLine());
1176 
1177   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1178   Record.clear();
1179 }
1180 
1181 static void writeDIMacro(const DIMacro *N, const ValueEnumerator &VE,
1182                          BitstreamWriter &Stream,
1183                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1184   Record.push_back(N->isDistinct());
1185   Record.push_back(N->getMacinfoType());
1186   Record.push_back(N->getLine());
1187   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1188   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1189 
1190   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1191   Record.clear();
1192 }
1193 
1194 static void writeDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE,
1195                              BitstreamWriter &Stream,
1196                              SmallVectorImpl<uint64_t> &Record,
1197                              unsigned Abbrev) {
1198   Record.push_back(N->isDistinct());
1199   Record.push_back(N->getMacinfoType());
1200   Record.push_back(N->getLine());
1201   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1202   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1203 
1204   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1205   Record.clear();
1206 }
1207 
1208 static void writeDIModule(const DIModule *N, const ValueEnumerator &VE,
1209                           BitstreamWriter &Stream,
1210                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1211   Record.push_back(N->isDistinct());
1212   for (auto &I : N->operands())
1213     Record.push_back(VE.getMetadataOrNullID(I));
1214 
1215   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1216   Record.clear();
1217 }
1218 
1219 static void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
1220                                          const ValueEnumerator &VE,
1221                                          BitstreamWriter &Stream,
1222                                          SmallVectorImpl<uint64_t> &Record,
1223                                          unsigned Abbrev) {
1224   Record.push_back(N->isDistinct());
1225   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1226   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1227 
1228   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1229   Record.clear();
1230 }
1231 
1232 static void writeDITemplateValueParameter(const DITemplateValueParameter *N,
1233                                           const ValueEnumerator &VE,
1234                                           BitstreamWriter &Stream,
1235                                           SmallVectorImpl<uint64_t> &Record,
1236                                           unsigned Abbrev) {
1237   Record.push_back(N->isDistinct());
1238   Record.push_back(N->getTag());
1239   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1240   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1241   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1242 
1243   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1244   Record.clear();
1245 }
1246 
1247 static void writeDIGlobalVariable(const DIGlobalVariable *N,
1248                                   const ValueEnumerator &VE,
1249                                   BitstreamWriter &Stream,
1250                                   SmallVectorImpl<uint64_t> &Record,
1251                                   unsigned Abbrev) {
1252   Record.push_back(N->isDistinct());
1253   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1254   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1255   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1256   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1257   Record.push_back(N->getLine());
1258   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1259   Record.push_back(N->isLocalToUnit());
1260   Record.push_back(N->isDefinition());
1261   Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1262   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1263 
1264   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1265   Record.clear();
1266 }
1267 
1268 static void writeDILocalVariable(const DILocalVariable *N,
1269                                  const ValueEnumerator &VE,
1270                                  BitstreamWriter &Stream,
1271                                  SmallVectorImpl<uint64_t> &Record,
1272                                  unsigned Abbrev) {
1273   Record.push_back(N->isDistinct());
1274   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1275   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1276   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1277   Record.push_back(N->getLine());
1278   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1279   Record.push_back(N->getArg());
1280   Record.push_back(N->getFlags());
1281 
1282   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1283   Record.clear();
1284 }
1285 
1286 static void writeDIExpression(const DIExpression *N, const ValueEnumerator &,
1287                               BitstreamWriter &Stream,
1288                               SmallVectorImpl<uint64_t> &Record,
1289                               unsigned Abbrev) {
1290   Record.reserve(N->getElements().size() + 1);
1291 
1292   Record.push_back(N->isDistinct());
1293   Record.append(N->elements_begin(), N->elements_end());
1294 
1295   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1296   Record.clear();
1297 }
1298 
1299 static void writeDIObjCProperty(const DIObjCProperty *N,
1300                                 const ValueEnumerator &VE,
1301                                 BitstreamWriter &Stream,
1302                                 SmallVectorImpl<uint64_t> &Record,
1303                                 unsigned Abbrev) {
1304   Record.push_back(N->isDistinct());
1305   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1306   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1307   Record.push_back(N->getLine());
1308   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1309   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1310   Record.push_back(N->getAttributes());
1311   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1312 
1313   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1314   Record.clear();
1315 }
1316 
1317 static void writeDIImportedEntity(const DIImportedEntity *N,
1318                                   const ValueEnumerator &VE,
1319                                   BitstreamWriter &Stream,
1320                                   SmallVectorImpl<uint64_t> &Record,
1321                                   unsigned Abbrev) {
1322   Record.push_back(N->isDistinct());
1323   Record.push_back(N->getTag());
1324   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1325   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1326   Record.push_back(N->getLine());
1327   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1328 
1329   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1330   Record.clear();
1331 }
1332 
1333 static unsigned createNamedMetadataAbbrev(BitstreamWriter &Stream) {
1334   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1335   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1336   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1337   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1338   return Stream.EmitAbbrev(Abbv);
1339 }
1340 
1341 static void writeNamedMetadata(const Module &M, const ValueEnumerator &VE,
1342                                BitstreamWriter &Stream,
1343                                SmallVectorImpl<uint64_t> &Record) {
1344   if (M.named_metadata_empty())
1345     return;
1346 
1347   unsigned Abbrev = createNamedMetadataAbbrev(Stream);
1348   for (const NamedMDNode &NMD : M.named_metadata()) {
1349     // Write name.
1350     StringRef Str = NMD.getName();
1351     Record.append(Str.bytes_begin(), Str.bytes_end());
1352     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1353     Record.clear();
1354 
1355     // Write named metadata operands.
1356     for (const MDNode *N : NMD.operands())
1357       Record.push_back(VE.getMetadataID(N));
1358     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1359     Record.clear();
1360   }
1361 }
1362 
1363 static unsigned createMetadataStringsAbbrev(BitstreamWriter &Stream) {
1364   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1365   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1366   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1367   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1368   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1369   return Stream.EmitAbbrev(Abbv);
1370 }
1371 
1372 /// Write out a record for MDString.
1373 ///
1374 /// All the metadata strings in a metadata block are emitted in a single
1375 /// record.  The sizes and strings themselves are shoved into a blob.
1376 static void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
1377                                  BitstreamWriter &Stream,
1378                                  SmallVectorImpl<uint64_t> &Record) {
1379   if (Strings.empty())
1380     return;
1381 
1382   // Start the record with the number of strings.
1383   Record.push_back(bitc::METADATA_STRINGS);
1384   Record.push_back(Strings.size());
1385 
1386   // Emit the sizes of the strings in the blob.
1387   SmallString<256> Blob;
1388   {
1389     BitstreamWriter W(Blob);
1390     for (const Metadata *MD : Strings)
1391       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1392     W.FlushToWord();
1393   }
1394 
1395   // Add the offset to the strings to the record.
1396   Record.push_back(Blob.size());
1397 
1398   // Add the strings to the blob.
1399   for (const Metadata *MD : Strings)
1400     Blob.append(cast<MDString>(MD)->getString());
1401 
1402   // Emit the final record.
1403   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(Stream), Record, Blob);
1404   Record.clear();
1405 }
1406 
1407 static void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
1408                                  const ValueEnumerator &VE,
1409                                  BitstreamWriter &Stream,
1410                                  SmallVectorImpl<uint64_t> &Record) {
1411   if (MDs.empty())
1412     return;
1413 
1414   // Initialize MDNode abbreviations.
1415 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1416 #include "llvm/IR/Metadata.def"
1417 
1418   for (const Metadata *MD : MDs) {
1419     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1420       assert(N->isResolved() && "Expected forward references to be resolved");
1421 
1422       switch (N->getMetadataID()) {
1423       default:
1424         llvm_unreachable("Invalid MDNode subclass");
1425 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1426   case Metadata::CLASS##Kind:                                                  \
1427     write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
1428     continue;
1429 #include "llvm/IR/Metadata.def"
1430       }
1431     }
1432     writeValueAsMetadata(cast<ValueAsMetadata>(MD), VE, Stream, Record);
1433   }
1434 }
1435 
1436 static void writeModuleMetadata(const Module &M,
1437                                 const ValueEnumerator &VE,
1438                                 BitstreamWriter &Stream) {
1439   if (!VE.hasMDs() && M.named_metadata_empty())
1440     return;
1441 
1442   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1443   SmallVector<uint64_t, 64> Record;
1444   writeMetadataStrings(VE.getMDStrings(), Stream, Record);
1445   writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record);
1446   writeNamedMetadata(M, VE, Stream, Record);
1447   Stream.ExitBlock();
1448 }
1449 
1450 static void writeFunctionMetadata(const Function &F, const ValueEnumerator &VE,
1451                                   BitstreamWriter &Stream) {
1452   if (!VE.hasMDs())
1453     return;
1454 
1455   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1456   SmallVector<uint64_t, 64> Record;
1457   writeMetadataStrings(VE.getMDStrings(), Stream, Record);
1458   writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record);
1459   Stream.ExitBlock();
1460 }
1461 
1462 static void WriteMetadataAttachment(const Function &F,
1463                                     const ValueEnumerator &VE,
1464                                     BitstreamWriter &Stream) {
1465   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1466 
1467   SmallVector<uint64_t, 64> Record;
1468 
1469   // Write metadata attachments
1470   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1471   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1472   F.getAllMetadata(MDs);
1473   if (!MDs.empty()) {
1474     for (const auto &I : MDs) {
1475       Record.push_back(I.first);
1476       Record.push_back(VE.getMetadataID(I.second));
1477     }
1478     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1479     Record.clear();
1480   }
1481 
1482   for (const BasicBlock &BB : F)
1483     for (const Instruction &I : BB) {
1484       MDs.clear();
1485       I.getAllMetadataOtherThanDebugLoc(MDs);
1486 
1487       // If no metadata, ignore instruction.
1488       if (MDs.empty()) continue;
1489 
1490       Record.push_back(VE.getInstructionID(&I));
1491 
1492       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1493         Record.push_back(MDs[i].first);
1494         Record.push_back(VE.getMetadataID(MDs[i].second));
1495       }
1496       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1497       Record.clear();
1498     }
1499 
1500   Stream.ExitBlock();
1501 }
1502 
1503 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1504   SmallVector<uint64_t, 64> Record;
1505 
1506   // Write metadata kinds
1507   // METADATA_KIND - [n x [id, name]]
1508   SmallVector<StringRef, 8> Names;
1509   M->getMDKindNames(Names);
1510 
1511   if (Names.empty()) return;
1512 
1513   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1514 
1515   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1516     Record.push_back(MDKindID);
1517     StringRef KName = Names[MDKindID];
1518     Record.append(KName.begin(), KName.end());
1519 
1520     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1521     Record.clear();
1522   }
1523 
1524   Stream.ExitBlock();
1525 }
1526 
1527 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
1528   // Write metadata kinds
1529   //
1530   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1531   //
1532   // OPERAND_BUNDLE_TAG - [strchr x N]
1533 
1534   SmallVector<StringRef, 8> Tags;
1535   M->getOperandBundleTags(Tags);
1536 
1537   if (Tags.empty())
1538     return;
1539 
1540   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
1541 
1542   SmallVector<uint64_t, 64> Record;
1543 
1544   for (auto Tag : Tags) {
1545     Record.append(Tag.begin(), Tag.end());
1546 
1547     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
1548     Record.clear();
1549   }
1550 
1551   Stream.ExitBlock();
1552 }
1553 
1554 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1555   if ((int64_t)V >= 0)
1556     Vals.push_back(V << 1);
1557   else
1558     Vals.push_back((-V << 1) | 1);
1559 }
1560 
1561 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1562                            const ValueEnumerator &VE,
1563                            BitstreamWriter &Stream, bool isGlobal) {
1564   if (FirstVal == LastVal) return;
1565 
1566   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1567 
1568   unsigned AggregateAbbrev = 0;
1569   unsigned String8Abbrev = 0;
1570   unsigned CString7Abbrev = 0;
1571   unsigned CString6Abbrev = 0;
1572   // If this is a constant pool for the module, emit module-specific abbrevs.
1573   if (isGlobal) {
1574     // Abbrev for CST_CODE_AGGREGATE.
1575     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1576     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1577     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1578     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1579     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1580 
1581     // Abbrev for CST_CODE_STRING.
1582     Abbv = new BitCodeAbbrev();
1583     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1584     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1585     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1586     String8Abbrev = Stream.EmitAbbrev(Abbv);
1587     // Abbrev for CST_CODE_CSTRING.
1588     Abbv = new BitCodeAbbrev();
1589     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1590     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1591     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1592     CString7Abbrev = Stream.EmitAbbrev(Abbv);
1593     // Abbrev for CST_CODE_CSTRING.
1594     Abbv = new BitCodeAbbrev();
1595     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1596     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1597     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1598     CString6Abbrev = Stream.EmitAbbrev(Abbv);
1599   }
1600 
1601   SmallVector<uint64_t, 64> Record;
1602 
1603   const ValueEnumerator::ValueList &Vals = VE.getValues();
1604   Type *LastTy = nullptr;
1605   for (unsigned i = FirstVal; i != LastVal; ++i) {
1606     const Value *V = Vals[i].first;
1607     // If we need to switch types, do so now.
1608     if (V->getType() != LastTy) {
1609       LastTy = V->getType();
1610       Record.push_back(VE.getTypeID(LastTy));
1611       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1612                         CONSTANTS_SETTYPE_ABBREV);
1613       Record.clear();
1614     }
1615 
1616     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1617       Record.push_back(unsigned(IA->hasSideEffects()) |
1618                        unsigned(IA->isAlignStack()) << 1 |
1619                        unsigned(IA->getDialect()&1) << 2);
1620 
1621       // Add the asm string.
1622       const std::string &AsmStr = IA->getAsmString();
1623       Record.push_back(AsmStr.size());
1624       Record.append(AsmStr.begin(), AsmStr.end());
1625 
1626       // Add the constraint string.
1627       const std::string &ConstraintStr = IA->getConstraintString();
1628       Record.push_back(ConstraintStr.size());
1629       Record.append(ConstraintStr.begin(), ConstraintStr.end());
1630       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1631       Record.clear();
1632       continue;
1633     }
1634     const Constant *C = cast<Constant>(V);
1635     unsigned Code = -1U;
1636     unsigned AbbrevToUse = 0;
1637     if (C->isNullValue()) {
1638       Code = bitc::CST_CODE_NULL;
1639     } else if (isa<UndefValue>(C)) {
1640       Code = bitc::CST_CODE_UNDEF;
1641     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1642       if (IV->getBitWidth() <= 64) {
1643         uint64_t V = IV->getSExtValue();
1644         emitSignedInt64(Record, V);
1645         Code = bitc::CST_CODE_INTEGER;
1646         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1647       } else {                             // Wide integers, > 64 bits in size.
1648         // We have an arbitrary precision integer value to write whose
1649         // bit width is > 64. However, in canonical unsigned integer
1650         // format it is likely that the high bits are going to be zero.
1651         // So, we only write the number of active words.
1652         unsigned NWords = IV->getValue().getActiveWords();
1653         const uint64_t *RawWords = IV->getValue().getRawData();
1654         for (unsigned i = 0; i != NWords; ++i) {
1655           emitSignedInt64(Record, RawWords[i]);
1656         }
1657         Code = bitc::CST_CODE_WIDE_INTEGER;
1658       }
1659     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1660       Code = bitc::CST_CODE_FLOAT;
1661       Type *Ty = CFP->getType();
1662       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1663         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1664       } else if (Ty->isX86_FP80Ty()) {
1665         // api needed to prevent premature destruction
1666         // bits are not in the same order as a normal i80 APInt, compensate.
1667         APInt api = CFP->getValueAPF().bitcastToAPInt();
1668         const uint64_t *p = api.getRawData();
1669         Record.push_back((p[1] << 48) | (p[0] >> 16));
1670         Record.push_back(p[0] & 0xffffLL);
1671       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1672         APInt api = CFP->getValueAPF().bitcastToAPInt();
1673         const uint64_t *p = api.getRawData();
1674         Record.push_back(p[0]);
1675         Record.push_back(p[1]);
1676       } else {
1677         assert (0 && "Unknown FP type!");
1678       }
1679     } else if (isa<ConstantDataSequential>(C) &&
1680                cast<ConstantDataSequential>(C)->isString()) {
1681       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1682       // Emit constant strings specially.
1683       unsigned NumElts = Str->getNumElements();
1684       // If this is a null-terminated string, use the denser CSTRING encoding.
1685       if (Str->isCString()) {
1686         Code = bitc::CST_CODE_CSTRING;
1687         --NumElts;  // Don't encode the null, which isn't allowed by char6.
1688       } else {
1689         Code = bitc::CST_CODE_STRING;
1690         AbbrevToUse = String8Abbrev;
1691       }
1692       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1693       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1694       for (unsigned i = 0; i != NumElts; ++i) {
1695         unsigned char V = Str->getElementAsInteger(i);
1696         Record.push_back(V);
1697         isCStr7 &= (V & 128) == 0;
1698         if (isCStrChar6)
1699           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1700       }
1701 
1702       if (isCStrChar6)
1703         AbbrevToUse = CString6Abbrev;
1704       else if (isCStr7)
1705         AbbrevToUse = CString7Abbrev;
1706     } else if (const ConstantDataSequential *CDS =
1707                   dyn_cast<ConstantDataSequential>(C)) {
1708       Code = bitc::CST_CODE_DATA;
1709       Type *EltTy = CDS->getType()->getElementType();
1710       if (isa<IntegerType>(EltTy)) {
1711         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1712           Record.push_back(CDS->getElementAsInteger(i));
1713       } else {
1714         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1715           Record.push_back(
1716               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
1717       }
1718     } else if (isa<ConstantAggregate>(C)) {
1719       Code = bitc::CST_CODE_AGGREGATE;
1720       for (const Value *Op : C->operands())
1721         Record.push_back(VE.getValueID(Op));
1722       AbbrevToUse = AggregateAbbrev;
1723     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1724       switch (CE->getOpcode()) {
1725       default:
1726         if (Instruction::isCast(CE->getOpcode())) {
1727           Code = bitc::CST_CODE_CE_CAST;
1728           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1729           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1730           Record.push_back(VE.getValueID(C->getOperand(0)));
1731           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1732         } else {
1733           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1734           Code = bitc::CST_CODE_CE_BINOP;
1735           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1736           Record.push_back(VE.getValueID(C->getOperand(0)));
1737           Record.push_back(VE.getValueID(C->getOperand(1)));
1738           uint64_t Flags = GetOptimizationFlags(CE);
1739           if (Flags != 0)
1740             Record.push_back(Flags);
1741         }
1742         break;
1743       case Instruction::GetElementPtr: {
1744         Code = bitc::CST_CODE_CE_GEP;
1745         const auto *GO = cast<GEPOperator>(C);
1746         if (GO->isInBounds())
1747           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1748         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1749         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1750           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1751           Record.push_back(VE.getValueID(C->getOperand(i)));
1752         }
1753         break;
1754       }
1755       case Instruction::Select:
1756         Code = bitc::CST_CODE_CE_SELECT;
1757         Record.push_back(VE.getValueID(C->getOperand(0)));
1758         Record.push_back(VE.getValueID(C->getOperand(1)));
1759         Record.push_back(VE.getValueID(C->getOperand(2)));
1760         break;
1761       case Instruction::ExtractElement:
1762         Code = bitc::CST_CODE_CE_EXTRACTELT;
1763         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1764         Record.push_back(VE.getValueID(C->getOperand(0)));
1765         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1766         Record.push_back(VE.getValueID(C->getOperand(1)));
1767         break;
1768       case Instruction::InsertElement:
1769         Code = bitc::CST_CODE_CE_INSERTELT;
1770         Record.push_back(VE.getValueID(C->getOperand(0)));
1771         Record.push_back(VE.getValueID(C->getOperand(1)));
1772         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1773         Record.push_back(VE.getValueID(C->getOperand(2)));
1774         break;
1775       case Instruction::ShuffleVector:
1776         // If the return type and argument types are the same, this is a
1777         // standard shufflevector instruction.  If the types are different,
1778         // then the shuffle is widening or truncating the input vectors, and
1779         // the argument type must also be encoded.
1780         if (C->getType() == C->getOperand(0)->getType()) {
1781           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1782         } else {
1783           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1784           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1785         }
1786         Record.push_back(VE.getValueID(C->getOperand(0)));
1787         Record.push_back(VE.getValueID(C->getOperand(1)));
1788         Record.push_back(VE.getValueID(C->getOperand(2)));
1789         break;
1790       case Instruction::ICmp:
1791       case Instruction::FCmp:
1792         Code = bitc::CST_CODE_CE_CMP;
1793         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1794         Record.push_back(VE.getValueID(C->getOperand(0)));
1795         Record.push_back(VE.getValueID(C->getOperand(1)));
1796         Record.push_back(CE->getPredicate());
1797         break;
1798       }
1799     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1800       Code = bitc::CST_CODE_BLOCKADDRESS;
1801       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1802       Record.push_back(VE.getValueID(BA->getFunction()));
1803       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1804     } else {
1805 #ifndef NDEBUG
1806       C->dump();
1807 #endif
1808       llvm_unreachable("Unknown constant!");
1809     }
1810     Stream.EmitRecord(Code, Record, AbbrevToUse);
1811     Record.clear();
1812   }
1813 
1814   Stream.ExitBlock();
1815 }
1816 
1817 static void WriteModuleConstants(const ValueEnumerator &VE,
1818                                  BitstreamWriter &Stream) {
1819   const ValueEnumerator::ValueList &Vals = VE.getValues();
1820 
1821   // Find the first constant to emit, which is the first non-globalvalue value.
1822   // We know globalvalues have been emitted by WriteModuleInfo.
1823   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1824     if (!isa<GlobalValue>(Vals[i].first)) {
1825       WriteConstants(i, Vals.size(), VE, Stream, true);
1826       return;
1827     }
1828   }
1829 }
1830 
1831 /// PushValueAndType - The file has to encode both the value and type id for
1832 /// many values, because we need to know what type to create for forward
1833 /// references.  However, most operands are not forward references, so this type
1834 /// field is not needed.
1835 ///
1836 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1837 /// instruction ID, then it is a forward reference, and it also includes the
1838 /// type ID.  The value ID that is written is encoded relative to the InstID.
1839 static bool PushValueAndType(const Value *V, unsigned InstID,
1840                              SmallVectorImpl<unsigned> &Vals,
1841                              ValueEnumerator &VE) {
1842   unsigned ValID = VE.getValueID(V);
1843   // Make encoding relative to the InstID.
1844   Vals.push_back(InstID - ValID);
1845   if (ValID >= InstID) {
1846     Vals.push_back(VE.getTypeID(V->getType()));
1847     return true;
1848   }
1849   return false;
1850 }
1851 
1852 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
1853                                 unsigned InstID, ValueEnumerator &VE) {
1854   SmallVector<unsigned, 64> Record;
1855   LLVMContext &C = CS.getInstruction()->getContext();
1856 
1857   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1858     const auto &Bundle = CS.getOperandBundleAt(i);
1859     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
1860 
1861     for (auto &Input : Bundle.Inputs)
1862       PushValueAndType(Input, InstID, Record, VE);
1863 
1864     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
1865     Record.clear();
1866   }
1867 }
1868 
1869 /// pushValue - Like PushValueAndType, but where the type of the value is
1870 /// omitted (perhaps it was already encoded in an earlier operand).
1871 static void pushValue(const Value *V, unsigned InstID,
1872                       SmallVectorImpl<unsigned> &Vals,
1873                       ValueEnumerator &VE) {
1874   unsigned ValID = VE.getValueID(V);
1875   Vals.push_back(InstID - ValID);
1876 }
1877 
1878 static void pushValueSigned(const Value *V, unsigned InstID,
1879                             SmallVectorImpl<uint64_t> &Vals,
1880                             ValueEnumerator &VE) {
1881   unsigned ValID = VE.getValueID(V);
1882   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1883   emitSignedInt64(Vals, diff);
1884 }
1885 
1886 /// WriteInstruction - Emit an instruction to the specified stream.
1887 static void WriteInstruction(const Instruction &I, unsigned InstID,
1888                              ValueEnumerator &VE, BitstreamWriter &Stream,
1889                              SmallVectorImpl<unsigned> &Vals) {
1890   unsigned Code = 0;
1891   unsigned AbbrevToUse = 0;
1892   VE.setInstructionID(&I);
1893   switch (I.getOpcode()) {
1894   default:
1895     if (Instruction::isCast(I.getOpcode())) {
1896       Code = bitc::FUNC_CODE_INST_CAST;
1897       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1898         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1899       Vals.push_back(VE.getTypeID(I.getType()));
1900       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1901     } else {
1902       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1903       Code = bitc::FUNC_CODE_INST_BINOP;
1904       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1905         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1906       pushValue(I.getOperand(1), InstID, Vals, VE);
1907       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1908       uint64_t Flags = GetOptimizationFlags(&I);
1909       if (Flags != 0) {
1910         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1911           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1912         Vals.push_back(Flags);
1913       }
1914     }
1915     break;
1916 
1917   case Instruction::GetElementPtr: {
1918     Code = bitc::FUNC_CODE_INST_GEP;
1919     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1920     auto &GEPInst = cast<GetElementPtrInst>(I);
1921     Vals.push_back(GEPInst.isInBounds());
1922     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1923     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1924       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1925     break;
1926   }
1927   case Instruction::ExtractValue: {
1928     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1929     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1930     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1931     Vals.append(EVI->idx_begin(), EVI->idx_end());
1932     break;
1933   }
1934   case Instruction::InsertValue: {
1935     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1936     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1937     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1938     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1939     Vals.append(IVI->idx_begin(), IVI->idx_end());
1940     break;
1941   }
1942   case Instruction::Select:
1943     Code = bitc::FUNC_CODE_INST_VSELECT;
1944     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1945     pushValue(I.getOperand(2), InstID, Vals, VE);
1946     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1947     break;
1948   case Instruction::ExtractElement:
1949     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1950     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1951     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1952     break;
1953   case Instruction::InsertElement:
1954     Code = bitc::FUNC_CODE_INST_INSERTELT;
1955     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1956     pushValue(I.getOperand(1), InstID, Vals, VE);
1957     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1958     break;
1959   case Instruction::ShuffleVector:
1960     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1961     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1962     pushValue(I.getOperand(1), InstID, Vals, VE);
1963     pushValue(I.getOperand(2), InstID, Vals, VE);
1964     break;
1965   case Instruction::ICmp:
1966   case Instruction::FCmp: {
1967     // compare returning Int1Ty or vector of Int1Ty
1968     Code = bitc::FUNC_CODE_INST_CMP2;
1969     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1970     pushValue(I.getOperand(1), InstID, Vals, VE);
1971     Vals.push_back(cast<CmpInst>(I).getPredicate());
1972     uint64_t Flags = GetOptimizationFlags(&I);
1973     if (Flags != 0)
1974       Vals.push_back(Flags);
1975     break;
1976   }
1977 
1978   case Instruction::Ret:
1979     {
1980       Code = bitc::FUNC_CODE_INST_RET;
1981       unsigned NumOperands = I.getNumOperands();
1982       if (NumOperands == 0)
1983         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1984       else if (NumOperands == 1) {
1985         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1986           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1987       } else {
1988         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1989           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1990       }
1991     }
1992     break;
1993   case Instruction::Br:
1994     {
1995       Code = bitc::FUNC_CODE_INST_BR;
1996       const BranchInst &II = cast<BranchInst>(I);
1997       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1998       if (II.isConditional()) {
1999         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2000         pushValue(II.getCondition(), InstID, Vals, VE);
2001       }
2002     }
2003     break;
2004   case Instruction::Switch:
2005     {
2006       Code = bitc::FUNC_CODE_INST_SWITCH;
2007       const SwitchInst &SI = cast<SwitchInst>(I);
2008       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2009       pushValue(SI.getCondition(), InstID, Vals, VE);
2010       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2011       for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2012         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2013         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2014       }
2015     }
2016     break;
2017   case Instruction::IndirectBr:
2018     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2019     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2020     // Encode the address operand as relative, but not the basic blocks.
2021     pushValue(I.getOperand(0), InstID, Vals, VE);
2022     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2023       Vals.push_back(VE.getValueID(I.getOperand(i)));
2024     break;
2025 
2026   case Instruction::Invoke: {
2027     const InvokeInst *II = cast<InvokeInst>(&I);
2028     const Value *Callee = II->getCalledValue();
2029     FunctionType *FTy = II->getFunctionType();
2030 
2031     if (II->hasOperandBundles())
2032       WriteOperandBundles(Stream, II, InstID, VE);
2033 
2034     Code = bitc::FUNC_CODE_INST_INVOKE;
2035 
2036     Vals.push_back(VE.getAttributeID(II->getAttributes()));
2037     Vals.push_back(II->getCallingConv() | 1 << 13);
2038     Vals.push_back(VE.getValueID(II->getNormalDest()));
2039     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2040     Vals.push_back(VE.getTypeID(FTy));
2041     PushValueAndType(Callee, InstID, Vals, VE);
2042 
2043     // Emit value #'s for the fixed parameters.
2044     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2045       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
2046 
2047     // Emit type/value pairs for varargs params.
2048     if (FTy->isVarArg()) {
2049       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
2050            i != e; ++i)
2051         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
2052     }
2053     break;
2054   }
2055   case Instruction::Resume:
2056     Code = bitc::FUNC_CODE_INST_RESUME;
2057     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2058     break;
2059   case Instruction::CleanupRet: {
2060     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2061     const auto &CRI = cast<CleanupReturnInst>(I);
2062     pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
2063     if (CRI.hasUnwindDest())
2064       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2065     break;
2066   }
2067   case Instruction::CatchRet: {
2068     Code = bitc::FUNC_CODE_INST_CATCHRET;
2069     const auto &CRI = cast<CatchReturnInst>(I);
2070     pushValue(CRI.getCatchPad(), InstID, Vals, VE);
2071     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2072     break;
2073   }
2074   case Instruction::CleanupPad:
2075   case Instruction::CatchPad: {
2076     const auto &FuncletPad = cast<FuncletPadInst>(I);
2077     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2078                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2079     pushValue(FuncletPad.getParentPad(), InstID, Vals, VE);
2080 
2081     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2082     Vals.push_back(NumArgOperands);
2083     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2084       PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE);
2085     break;
2086   }
2087   case Instruction::CatchSwitch: {
2088     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2089     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2090 
2091     pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE);
2092 
2093     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2094     Vals.push_back(NumHandlers);
2095     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2096       Vals.push_back(VE.getValueID(CatchPadBB));
2097 
2098     if (CatchSwitch.hasUnwindDest())
2099       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2100     break;
2101   }
2102   case Instruction::Unreachable:
2103     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2104     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2105     break;
2106 
2107   case Instruction::PHI: {
2108     const PHINode &PN = cast<PHINode>(I);
2109     Code = bitc::FUNC_CODE_INST_PHI;
2110     // With the newer instruction encoding, forward references could give
2111     // negative valued IDs.  This is most common for PHIs, so we use
2112     // signed VBRs.
2113     SmallVector<uint64_t, 128> Vals64;
2114     Vals64.push_back(VE.getTypeID(PN.getType()));
2115     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2116       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
2117       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2118     }
2119     // Emit a Vals64 vector and exit.
2120     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2121     Vals64.clear();
2122     return;
2123   }
2124 
2125   case Instruction::LandingPad: {
2126     const LandingPadInst &LP = cast<LandingPadInst>(I);
2127     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2128     Vals.push_back(VE.getTypeID(LP.getType()));
2129     Vals.push_back(LP.isCleanup());
2130     Vals.push_back(LP.getNumClauses());
2131     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2132       if (LP.isCatch(I))
2133         Vals.push_back(LandingPadInst::Catch);
2134       else
2135         Vals.push_back(LandingPadInst::Filter);
2136       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
2137     }
2138     break;
2139   }
2140 
2141   case Instruction::Alloca: {
2142     Code = bitc::FUNC_CODE_INST_ALLOCA;
2143     const AllocaInst &AI = cast<AllocaInst>(I);
2144     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2145     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2146     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2147     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2148     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2149            "not enough bits for maximum alignment");
2150     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2151     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2152     AlignRecord |= 1 << 6;
2153     AlignRecord |= AI.isSwiftError() << 7;
2154     Vals.push_back(AlignRecord);
2155     break;
2156   }
2157 
2158   case Instruction::Load:
2159     if (cast<LoadInst>(I).isAtomic()) {
2160       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2161       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2162     } else {
2163       Code = bitc::FUNC_CODE_INST_LOAD;
2164       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
2165         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2166     }
2167     Vals.push_back(VE.getTypeID(I.getType()));
2168     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2169     Vals.push_back(cast<LoadInst>(I).isVolatile());
2170     if (cast<LoadInst>(I).isAtomic()) {
2171       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2172       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2173     }
2174     break;
2175   case Instruction::Store:
2176     if (cast<StoreInst>(I).isAtomic())
2177       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2178     else
2179       Code = bitc::FUNC_CODE_INST_STORE;
2180     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
2181     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // valty + val
2182     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2183     Vals.push_back(cast<StoreInst>(I).isVolatile());
2184     if (cast<StoreInst>(I).isAtomic()) {
2185       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2186       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2187     }
2188     break;
2189   case Instruction::AtomicCmpXchg:
2190     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2191     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2192     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // cmp.
2193     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
2194     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2195     Vals.push_back(GetEncodedOrdering(
2196                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2197     Vals.push_back(GetEncodedSynchScope(
2198                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
2199     Vals.push_back(GetEncodedOrdering(
2200                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2201     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2202     break;
2203   case Instruction::AtomicRMW:
2204     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2205     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2206     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
2207     Vals.push_back(GetEncodedRMWOperation(
2208                      cast<AtomicRMWInst>(I).getOperation()));
2209     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2210     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2211     Vals.push_back(GetEncodedSynchScope(
2212                      cast<AtomicRMWInst>(I).getSynchScope()));
2213     break;
2214   case Instruction::Fence:
2215     Code = bitc::FUNC_CODE_INST_FENCE;
2216     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2217     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2218     break;
2219   case Instruction::Call: {
2220     const CallInst &CI = cast<CallInst>(I);
2221     FunctionType *FTy = CI.getFunctionType();
2222 
2223     if (CI.hasOperandBundles())
2224       WriteOperandBundles(Stream, &CI, InstID, VE);
2225 
2226     Code = bitc::FUNC_CODE_INST_CALL;
2227 
2228     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2229 
2230     unsigned Flags = GetOptimizationFlags(&I);
2231     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2232                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2233                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2234                    1 << bitc::CALL_EXPLICIT_TYPE |
2235                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2236                    unsigned(Flags != 0) << bitc::CALL_FMF);
2237     if (Flags != 0)
2238       Vals.push_back(Flags);
2239 
2240     Vals.push_back(VE.getTypeID(FTy));
2241     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
2242 
2243     // Emit value #'s for the fixed parameters.
2244     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2245       // Check for labels (can happen with asm labels).
2246       if (FTy->getParamType(i)->isLabelTy())
2247         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2248       else
2249         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
2250     }
2251 
2252     // Emit type/value pairs for varargs params.
2253     if (FTy->isVarArg()) {
2254       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2255            i != e; ++i)
2256         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
2257     }
2258     break;
2259   }
2260   case Instruction::VAArg:
2261     Code = bitc::FUNC_CODE_INST_VAARG;
2262     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
2263     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2264     Vals.push_back(VE.getTypeID(I.getType())); // restype.
2265     break;
2266   }
2267 
2268   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2269   Vals.clear();
2270 }
2271 
2272 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2273 /// BitcodeStartBit and ModuleSummaryIndex are only passed for the module-level
2274 /// VST, where we are including a function bitcode index and need to
2275 /// backpatch the VST forward declaration record.
2276 static void WriteValueSymbolTable(
2277     const ValueSymbolTable &VST, const ValueEnumerator &VE,
2278     BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2279     uint64_t BitcodeStartBit = 0,
2280     DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr) {
2281   if (VST.empty()) {
2282     // WriteValueSymbolTableForwardDecl should have returned early as
2283     // well. Ensure this handling remains in sync by asserting that
2284     // the placeholder offset is not set.
2285     assert(VSTOffsetPlaceholder == 0);
2286     return;
2287   }
2288 
2289   if (VSTOffsetPlaceholder > 0) {
2290     // Get the offset of the VST we are writing, and backpatch it into
2291     // the VST forward declaration record.
2292     uint64_t VSTOffset = Stream.GetCurrentBitNo();
2293     // The BitcodeStartBit was the stream offset of the actual bitcode
2294     // (e.g. excluding any initial darwin header).
2295     VSTOffset -= BitcodeStartBit;
2296     assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2297     Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2298   }
2299 
2300   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2301 
2302   // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2303   // records, which are not used in the per-function VSTs.
2304   unsigned FnEntry8BitAbbrev;
2305   unsigned FnEntry7BitAbbrev;
2306   unsigned FnEntry6BitAbbrev;
2307   if (VSTOffsetPlaceholder > 0) {
2308     // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2309     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2310     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2311     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2312     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2313     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2314     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2315     FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2316 
2317     // 7-bit fixed width VST_CODE_FNENTRY function strings.
2318     Abbv = new BitCodeAbbrev();
2319     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2320     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2321     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2322     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2323     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2324     FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2325 
2326     // 6-bit char6 VST_CODE_FNENTRY function strings.
2327     Abbv = new BitCodeAbbrev();
2328     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2329     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2330     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2331     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2332     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2333     FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2334   }
2335 
2336   // FIXME: Set up the abbrev, we know how many values there are!
2337   // FIXME: We know if the type names can use 7-bit ascii.
2338   SmallVector<unsigned, 64> NameVals;
2339 
2340   for (const ValueName &Name : VST) {
2341     // Figure out the encoding to use for the name.
2342     StringEncoding Bits =
2343         getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2344 
2345     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2346     NameVals.push_back(VE.getValueID(Name.getValue()));
2347 
2348     Function *F = dyn_cast<Function>(Name.getValue());
2349     if (!F) {
2350       // If value is an alias, need to get the aliased base object to
2351       // see if it is a function.
2352       auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2353       if (GA && GA->getBaseObject())
2354         F = dyn_cast<Function>(GA->getBaseObject());
2355     }
2356 
2357     // VST_CODE_ENTRY:   [valueid, namechar x N]
2358     // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2359     // VST_CODE_BBENTRY: [bbid, namechar x N]
2360     unsigned Code;
2361     if (isa<BasicBlock>(Name.getValue())) {
2362       Code = bitc::VST_CODE_BBENTRY;
2363       if (Bits == SE_Char6)
2364         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2365     } else if (F && !F->isDeclaration()) {
2366       // Must be the module-level VST, where we pass in the Index and
2367       // have a VSTOffsetPlaceholder. The function-level VST should not
2368       // contain any Function symbols.
2369       assert(FunctionToBitcodeIndex);
2370       assert(VSTOffsetPlaceholder > 0);
2371 
2372       // Save the word offset of the function (from the start of the
2373       // actual bitcode written to the stream).
2374       uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - BitcodeStartBit;
2375       assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2376       NameVals.push_back(BitcodeIndex / 32);
2377 
2378       Code = bitc::VST_CODE_FNENTRY;
2379       AbbrevToUse = FnEntry8BitAbbrev;
2380       if (Bits == SE_Char6)
2381         AbbrevToUse = FnEntry6BitAbbrev;
2382       else if (Bits == SE_Fixed7)
2383         AbbrevToUse = FnEntry7BitAbbrev;
2384     } else {
2385       Code = bitc::VST_CODE_ENTRY;
2386       if (Bits == SE_Char6)
2387         AbbrevToUse = VST_ENTRY_6_ABBREV;
2388       else if (Bits == SE_Fixed7)
2389         AbbrevToUse = VST_ENTRY_7_ABBREV;
2390     }
2391 
2392     for (const auto P : Name.getKey())
2393       NameVals.push_back((unsigned char)P);
2394 
2395     // Emit the finished record.
2396     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2397     NameVals.clear();
2398   }
2399   Stream.ExitBlock();
2400 }
2401 
2402 /// Emit function names and summary offsets for the combined index
2403 /// used by ThinLTO.
2404 static void WriteCombinedValueSymbolTable(
2405     const ModuleSummaryIndex &Index, BitstreamWriter &Stream,
2406     std::map<GlobalValue::GUID, unsigned> &GUIDToValueIdMap,
2407     uint64_t VSTOffsetPlaceholder) {
2408   assert(VSTOffsetPlaceholder > 0 && "Expected non-zero VSTOffsetPlaceholder");
2409   // Get the offset of the VST we are writing, and backpatch it into
2410   // the VST forward declaration record.
2411   uint64_t VSTOffset = Stream.GetCurrentBitNo();
2412   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2413   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2414 
2415   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2416 
2417   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2418   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_GVDEFENTRY));
2419   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2420   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // sumoffset
2421   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // guid
2422   unsigned DefEntryAbbrev = Stream.EmitAbbrev(Abbv);
2423 
2424   Abbv = new BitCodeAbbrev();
2425   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2426   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2427   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2428   unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
2429 
2430   SmallVector<uint64_t, 64> NameVals;
2431 
2432   for (const auto &FII : Index) {
2433     GlobalValue::GUID FuncGUID = FII.first;
2434     const auto &VMI = GUIDToValueIdMap.find(FuncGUID);
2435     assert(VMI != GUIDToValueIdMap.end());
2436 
2437     for (const auto &FI : FII.second) {
2438       // VST_CODE_COMBINED_GVDEFENTRY: [valueid, sumoffset, guid]
2439       NameVals.push_back(VMI->second);
2440       NameVals.push_back(FI->bitcodeIndex());
2441       NameVals.push_back(FuncGUID);
2442 
2443       // Emit the finished record.
2444       Stream.EmitRecord(bitc::VST_CODE_COMBINED_GVDEFENTRY, NameVals,
2445                         DefEntryAbbrev);
2446       NameVals.clear();
2447     }
2448     GUIDToValueIdMap.erase(VMI);
2449   }
2450   for (const auto &GVI : GUIDToValueIdMap) {
2451     // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2452     NameVals.push_back(GVI.second);
2453     NameVals.push_back(GVI.first);
2454 
2455     // Emit the finished record.
2456     Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
2457     NameVals.clear();
2458   }
2459   Stream.ExitBlock();
2460 }
2461 
2462 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2463                          BitstreamWriter &Stream) {
2464   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2465   unsigned Code;
2466   if (isa<BasicBlock>(Order.V))
2467     Code = bitc::USELIST_CODE_BB;
2468   else
2469     Code = bitc::USELIST_CODE_DEFAULT;
2470 
2471   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2472   Record.push_back(VE.getValueID(Order.V));
2473   Stream.EmitRecord(Code, Record);
2474 }
2475 
2476 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2477                               BitstreamWriter &Stream) {
2478   assert(VE.shouldPreserveUseListOrder() &&
2479          "Expected to be preserving use-list order");
2480 
2481   auto hasMore = [&]() {
2482     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2483   };
2484   if (!hasMore())
2485     // Nothing to do.
2486     return;
2487 
2488   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2489   while (hasMore()) {
2490     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2491     VE.UseListOrders.pop_back();
2492   }
2493   Stream.ExitBlock();
2494 }
2495 
2496 /// Emit a function body to the module stream.
2497 static void
2498 WriteFunction(const Function &F, const Module *M, ValueEnumerator &VE,
2499               BitstreamWriter &Stream,
2500               DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2501   // Save the bitcode index of the start of this function block for recording
2502   // in the VST.
2503   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
2504 
2505   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2506   VE.incorporateFunction(F);
2507 
2508   SmallVector<unsigned, 64> Vals;
2509 
2510   // Emit the number of basic blocks, so the reader can create them ahead of
2511   // time.
2512   Vals.push_back(VE.getBasicBlocks().size());
2513   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2514   Vals.clear();
2515 
2516   // If there are function-local constants, emit them now.
2517   unsigned CstStart, CstEnd;
2518   VE.getFunctionConstantRange(CstStart, CstEnd);
2519   WriteConstants(CstStart, CstEnd, VE, Stream, false);
2520 
2521   // If there is function-local metadata, emit it now.
2522   writeFunctionMetadata(F, VE, Stream);
2523 
2524   // Keep a running idea of what the instruction ID is.
2525   unsigned InstID = CstEnd;
2526 
2527   bool NeedsMetadataAttachment = F.hasMetadata();
2528 
2529   DILocation *LastDL = nullptr;
2530   // Finally, emit all the instructions, in order.
2531   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2532     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2533          I != E; ++I) {
2534       WriteInstruction(*I, InstID, VE, Stream, Vals);
2535 
2536       if (!I->getType()->isVoidTy())
2537         ++InstID;
2538 
2539       // If the instruction has metadata, write a metadata attachment later.
2540       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2541 
2542       // If the instruction has a debug location, emit it.
2543       DILocation *DL = I->getDebugLoc();
2544       if (!DL)
2545         continue;
2546 
2547       if (DL == LastDL) {
2548         // Just repeat the same debug loc as last time.
2549         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2550         continue;
2551       }
2552 
2553       Vals.push_back(DL->getLine());
2554       Vals.push_back(DL->getColumn());
2555       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2556       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2557       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2558       Vals.clear();
2559 
2560       LastDL = DL;
2561     }
2562 
2563   // Emit names for all the instructions etc.
2564   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2565 
2566   if (NeedsMetadataAttachment)
2567     WriteMetadataAttachment(F, VE, Stream);
2568   if (VE.shouldPreserveUseListOrder())
2569     WriteUseListBlock(&F, VE, Stream);
2570   VE.purgeFunction();
2571   Stream.ExitBlock();
2572 }
2573 
2574 // Emit blockinfo, which defines the standard abbreviations etc.
2575 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2576   // We only want to emit block info records for blocks that have multiple
2577   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2578   // Other blocks can define their abbrevs inline.
2579   Stream.EnterBlockInfoBlock(2);
2580 
2581   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
2582     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2583     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2584     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2585     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2586     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2587     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2588                                    Abbv) != VST_ENTRY_8_ABBREV)
2589       llvm_unreachable("Unexpected abbrev ordering!");
2590   }
2591 
2592   { // 7-bit fixed width VST_CODE_ENTRY strings.
2593     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2594     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2595     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2596     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2597     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2598     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2599                                    Abbv) != VST_ENTRY_7_ABBREV)
2600       llvm_unreachable("Unexpected abbrev ordering!");
2601   }
2602   { // 6-bit char6 VST_CODE_ENTRY strings.
2603     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2604     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2605     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2606     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2607     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2608     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2609                                    Abbv) != VST_ENTRY_6_ABBREV)
2610       llvm_unreachable("Unexpected abbrev ordering!");
2611   }
2612   { // 6-bit char6 VST_CODE_BBENTRY strings.
2613     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2614     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2615     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2616     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2617     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2618     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2619                                    Abbv) != VST_BBENTRY_6_ABBREV)
2620       llvm_unreachable("Unexpected abbrev ordering!");
2621   }
2622 
2623 
2624 
2625   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2626     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2627     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2628     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2629                               VE.computeBitsRequiredForTypeIndicies()));
2630     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2631                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
2632       llvm_unreachable("Unexpected abbrev ordering!");
2633   }
2634 
2635   { // INTEGER abbrev for CONSTANTS_BLOCK.
2636     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2637     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2638     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2639     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2640                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
2641       llvm_unreachable("Unexpected abbrev ordering!");
2642   }
2643 
2644   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2645     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2646     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2647     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
2648     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
2649                               VE.computeBitsRequiredForTypeIndicies()));
2650     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
2651 
2652     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2653                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
2654       llvm_unreachable("Unexpected abbrev ordering!");
2655   }
2656   { // NULL abbrev for CONSTANTS_BLOCK.
2657     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2658     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2659     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2660                                    Abbv) != CONSTANTS_NULL_Abbrev)
2661       llvm_unreachable("Unexpected abbrev ordering!");
2662   }
2663 
2664   // FIXME: This should only use space for first class types!
2665 
2666   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2667     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2668     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2669     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2670     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2671                               VE.computeBitsRequiredForTypeIndicies()));
2672     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2673     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2674     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2675                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
2676       llvm_unreachable("Unexpected abbrev ordering!");
2677   }
2678   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2679     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2680     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2681     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2682     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2683     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2684     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2685                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
2686       llvm_unreachable("Unexpected abbrev ordering!");
2687   }
2688   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2689     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2690     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2691     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2692     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2693     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2694     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2695     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2696                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2697       llvm_unreachable("Unexpected abbrev ordering!");
2698   }
2699   { // INST_CAST abbrev for FUNCTION_BLOCK.
2700     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2701     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2702     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
2703     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
2704                               VE.computeBitsRequiredForTypeIndicies()));
2705     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
2706     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2707                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
2708       llvm_unreachable("Unexpected abbrev ordering!");
2709   }
2710 
2711   { // INST_RET abbrev for FUNCTION_BLOCK.
2712     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2713     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2714     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2715                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2716       llvm_unreachable("Unexpected abbrev ordering!");
2717   }
2718   { // INST_RET abbrev for FUNCTION_BLOCK.
2719     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2720     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2721     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2722     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2723                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2724       llvm_unreachable("Unexpected abbrev ordering!");
2725   }
2726   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2727     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2728     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2729     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2730                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2731       llvm_unreachable("Unexpected abbrev ordering!");
2732   }
2733   {
2734     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2735     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2736     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2737     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2738                               Log2_32_Ceil(VE.getTypes().size() + 1)));
2739     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2740     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2741     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2742         FUNCTION_INST_GEP_ABBREV)
2743       llvm_unreachable("Unexpected abbrev ordering!");
2744   }
2745 
2746   Stream.ExitBlock();
2747 }
2748 
2749 /// Write the module path strings, currently only used when generating
2750 /// a combined index file.
2751 static void WriteModStrings(const ModuleSummaryIndex &I,
2752                             BitstreamWriter &Stream) {
2753   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
2754 
2755   // TODO: See which abbrev sizes we actually need to emit
2756 
2757   // 8-bit fixed-width MST_ENTRY strings.
2758   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2759   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2760   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2761   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2762   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2763   unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
2764 
2765   // 7-bit fixed width MST_ENTRY strings.
2766   Abbv = new BitCodeAbbrev();
2767   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2768   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2769   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2770   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2771   unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
2772 
2773   // 6-bit char6 MST_ENTRY strings.
2774   Abbv = new BitCodeAbbrev();
2775   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2776   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2777   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2778   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2779   unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
2780 
2781   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
2782   Abbv = new BitCodeAbbrev();
2783   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
2784   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2785   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2786   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2787   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2788   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2789   unsigned AbbrevHash = Stream.EmitAbbrev(Abbv);
2790 
2791   SmallVector<unsigned, 64> Vals;
2792   for (const auto &MPSE : I.modulePaths()) {
2793     StringEncoding Bits =
2794         getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
2795     unsigned AbbrevToUse = Abbrev8Bit;
2796     if (Bits == SE_Char6)
2797       AbbrevToUse = Abbrev6Bit;
2798     else if (Bits == SE_Fixed7)
2799       AbbrevToUse = Abbrev7Bit;
2800 
2801     Vals.push_back(MPSE.getValue().first);
2802 
2803     for (const auto P : MPSE.getKey())
2804       Vals.push_back((unsigned char)P);
2805 
2806     // Emit the finished record.
2807     Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
2808 
2809     Vals.clear();
2810     // Emit an optional hash for the module now
2811     auto &Hash = MPSE.getValue().second;
2812     bool AllZero = true; // Detect if the hash is empty, and do not generate it
2813     for (auto Val : Hash) {
2814       if (Val)
2815         AllZero = false;
2816       Vals.push_back(Val);
2817     }
2818     if (!AllZero) {
2819       // Emit the hash record.
2820       Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
2821     }
2822 
2823     Vals.clear();
2824   }
2825   Stream.ExitBlock();
2826 }
2827 
2828 // Helper to emit a single function summary record.
2829 static void WritePerModuleFunctionSummaryRecord(
2830     SmallVector<uint64_t, 64> &NameVals, GlobalValueInfo *Info,
2831     unsigned ValueID, const ValueEnumerator &VE, unsigned FSCallsAbbrev,
2832     unsigned FSCallsProfileAbbrev, BitstreamWriter &Stream, const Function &F) {
2833   NameVals.push_back(ValueID);
2834 
2835   FunctionSummary *FS = cast<FunctionSummary>(Info->summary());
2836   NameVals.push_back(getEncodedLinkage(FS->linkage()));
2837   NameVals.push_back(FS->instCount());
2838   NameVals.push_back(FS->refs().size());
2839 
2840   for (auto &RI : FS->refs())
2841     NameVals.push_back(VE.getValueID(RI.getValue()));
2842 
2843   bool HasProfileData = F.getEntryCount().hasValue();
2844   for (auto &ECI : FS->calls()) {
2845     NameVals.push_back(VE.getValueID(ECI.first.getValue()));
2846     assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite");
2847     NameVals.push_back(ECI.second.CallsiteCount);
2848     if (HasProfileData)
2849       NameVals.push_back(ECI.second.ProfileCount);
2850   }
2851 
2852   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
2853   unsigned Code =
2854       (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
2855 
2856   // Emit the finished record.
2857   Stream.EmitRecord(Code, NameVals, FSAbbrev);
2858   NameVals.clear();
2859 }
2860 
2861 // Collect the global value references in the given variable's initializer,
2862 // and emit them in a summary record.
2863 static void WriteModuleLevelReferences(const GlobalVariable &V,
2864                                        const ModuleSummaryIndex &Index,
2865                                        const ValueEnumerator &VE,
2866                                        SmallVector<uint64_t, 64> &NameVals,
2867                                        unsigned FSModRefsAbbrev,
2868                                        BitstreamWriter &Stream) {
2869   // Only interested in recording variable defs in the summary.
2870   if (V.isDeclaration())
2871     return;
2872   NameVals.push_back(VE.getValueID(&V));
2873   NameVals.push_back(getEncodedLinkage(V.getLinkage()));
2874   auto *Info = Index.getGlobalValueInfo(V);
2875   GlobalVarSummary *VS = cast<GlobalVarSummary>(Info->summary());
2876   for (auto Ref : VS->refs())
2877     NameVals.push_back(VE.getValueID(Ref.getValue()));
2878   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
2879                     FSModRefsAbbrev);
2880   NameVals.clear();
2881 }
2882 
2883 /// Emit the per-module summary section alongside the rest of
2884 /// the module's bitcode.
2885 static void WritePerModuleGlobalValueSummary(const Module *M,
2886                                              const ModuleSummaryIndex &Index,
2887                                              const ValueEnumerator &VE,
2888                                              BitstreamWriter &Stream) {
2889   if (M->empty())
2890     return;
2891 
2892   if (Index.begin() == Index.end())
2893     return;
2894 
2895   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
2896 
2897   // Abbrev for FS_PERMODULE.
2898   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2899   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
2900   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2901   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2902   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2903   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2904   // numrefs x valueid, n x (valueid, callsitecount)
2905   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2906   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2907   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
2908 
2909   // Abbrev for FS_PERMODULE_PROFILE.
2910   Abbv = new BitCodeAbbrev();
2911   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
2912   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2913   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2914   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2915   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2916   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
2917   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2918   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2919   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
2920 
2921   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
2922   Abbv = new BitCodeAbbrev();
2923   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
2924   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2925   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2926   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
2927   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2928   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
2929 
2930   // Abbrev for FS_ALIAS.
2931   Abbv = new BitCodeAbbrev();
2932   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
2933   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2934   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2935   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2936   unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
2937 
2938   SmallVector<uint64_t, 64> NameVals;
2939   // Iterate over the list of functions instead of the Index to
2940   // ensure the ordering is stable.
2941   for (const Function &F : *M) {
2942     if (F.isDeclaration())
2943       continue;
2944     // Summary emission does not support anonymous functions, they have to
2945     // renamed using the anonymous function renaming pass.
2946     if (!F.hasName())
2947       report_fatal_error("Unexpected anonymous function when writing summary");
2948 
2949     auto *Info = Index.getGlobalValueInfo(F);
2950     WritePerModuleFunctionSummaryRecord(
2951         NameVals, Info,
2952         VE.getValueID(M->getValueSymbolTable().lookup(F.getName())), VE,
2953         FSCallsAbbrev, FSCallsProfileAbbrev, Stream, F);
2954   }
2955 
2956   // Capture references from GlobalVariable initializers, which are outside
2957   // of a function scope.
2958   for (const GlobalVariable &G : M->globals())
2959     WriteModuleLevelReferences(G, Index, VE, NameVals, FSModRefsAbbrev, Stream);
2960 
2961   for (const GlobalAlias &A : M->aliases()) {
2962     auto *Aliasee = A.getBaseObject();
2963     if (!Aliasee->hasName())
2964       // Nameless function don't have an entry in the summary, skip it.
2965       continue;
2966     auto AliasId = VE.getValueID(&A);
2967     auto AliaseeId = VE.getValueID(Aliasee);
2968     NameVals.push_back(AliasId);
2969     NameVals.push_back(getEncodedLinkage(A.getLinkage()));
2970     NameVals.push_back(AliaseeId);
2971     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
2972     NameVals.clear();
2973   }
2974 
2975   Stream.ExitBlock();
2976 }
2977 
2978 /// Emit the combined summary section into the combined index file.
2979 static void WriteCombinedGlobalValueSummary(
2980     const ModuleSummaryIndex &Index, BitstreamWriter &Stream,
2981     std::map<GlobalValue::GUID, unsigned> &GUIDToValueIdMap,
2982     unsigned GlobalValueId) {
2983   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
2984 
2985   // Abbrev for FS_COMBINED.
2986   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2987   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
2988   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
2989   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2990   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2991   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2992   // numrefs x valueid, n x (valueid, callsitecount)
2993   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2994   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2995   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
2996 
2997   // Abbrev for FS_COMBINED_PROFILE.
2998   Abbv = new BitCodeAbbrev();
2999   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3000   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3001   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3002   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3003   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3004   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
3005   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3006   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3007   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
3008 
3009   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3010   Abbv = new BitCodeAbbrev();
3011   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3012   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3013   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3014   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
3015   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3016   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
3017 
3018   // Abbrev for FS_COMBINED_ALIAS.
3019   Abbv = new BitCodeAbbrev();
3020   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3021   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3022   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3023   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // offset
3024   unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
3025 
3026   // The aliases are emitted as a post-pass, and will point to the summary
3027   // offset id of the aliasee. For this purpose we need to be able to get back
3028   // from the summary to the offset
3029   SmallVector<GlobalValueInfo *, 64> Aliases;
3030   DenseMap<const GlobalValueSummary *, uint64_t> SummaryToOffsetMap;
3031 
3032   SmallVector<uint64_t, 64> NameVals;
3033   for (const auto &FII : Index) {
3034     for (auto &FI : FII.second) {
3035       GlobalValueSummary *S = FI->summary();
3036       assert(S);
3037       if (isa<AliasSummary>(S)) {
3038         // Will process aliases as a post-pass because the reader wants all
3039         // global to be loaded first.
3040         Aliases.push_back(FI.get());
3041         continue;
3042       }
3043 
3044       if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3045         NameVals.push_back(Index.getModuleId(VS->modulePath()));
3046         NameVals.push_back(getEncodedLinkage(VS->linkage()));
3047         for (auto &RI : VS->refs()) {
3048           const auto &VMI = GUIDToValueIdMap.find(RI.getGUID());
3049           unsigned RefId;
3050           // If this GUID doesn't have an entry, assign one.
3051           if (VMI == GUIDToValueIdMap.end()) {
3052             GUIDToValueIdMap[RI.getGUID()] = ++GlobalValueId;
3053             RefId = GlobalValueId;
3054           } else {
3055             RefId = VMI->second;
3056           }
3057           NameVals.push_back(RefId);
3058         }
3059 
3060         // Record the starting offset of this summary entry for use
3061         // in the VST entry. Add the current code size since the
3062         // reader will invoke readRecord after the abbrev id read.
3063         FI->setBitcodeIndex(Stream.GetCurrentBitNo() +
3064                             Stream.GetAbbrevIDWidth());
3065         // Store temporarily the offset in the map for a possible alias.
3066         SummaryToOffsetMap[S] = FI->bitcodeIndex();
3067 
3068         // Emit the finished record.
3069         Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3070                           FSModRefsAbbrev);
3071         NameVals.clear();
3072         continue;
3073       }
3074 
3075       auto *FS = cast<FunctionSummary>(S);
3076       NameVals.push_back(Index.getModuleId(FS->modulePath()));
3077       NameVals.push_back(getEncodedLinkage(FS->linkage()));
3078       NameVals.push_back(FS->instCount());
3079       NameVals.push_back(FS->refs().size());
3080 
3081       for (auto &RI : FS->refs()) {
3082         const auto &VMI = GUIDToValueIdMap.find(RI.getGUID());
3083         unsigned RefId;
3084         // If this GUID doesn't have an entry, assign one.
3085         if (VMI == GUIDToValueIdMap.end()) {
3086           GUIDToValueIdMap[RI.getGUID()] = ++GlobalValueId;
3087           RefId = GlobalValueId;
3088         } else {
3089           RefId = VMI->second;
3090         }
3091         NameVals.push_back(RefId);
3092       }
3093 
3094       bool HasProfileData = false;
3095       for (auto &EI : FS->calls()) {
3096         HasProfileData |= EI.second.ProfileCount != 0;
3097         if (HasProfileData)
3098           break;
3099       }
3100 
3101       for (auto &EI : FS->calls()) {
3102         const auto &VMI = GUIDToValueIdMap.find(EI.first.getGUID());
3103         // If this GUID doesn't have an entry, it doesn't have a function
3104         // summary and we don't need to record any calls to it.
3105         if (VMI == GUIDToValueIdMap.end())
3106           continue;
3107         NameVals.push_back(VMI->second);
3108         assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite");
3109         NameVals.push_back(EI.second.CallsiteCount);
3110         if (HasProfileData)
3111           NameVals.push_back(EI.second.ProfileCount);
3112       }
3113 
3114       // Record the starting offset of this summary entry for use
3115       // in the VST entry. Add the current code size since the
3116       // reader will invoke readRecord after the abbrev id read.
3117       FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
3118       // Store temporarily the offset in the map for a possible alias.
3119       SummaryToOffsetMap[S] = FI->bitcodeIndex();
3120 
3121       unsigned FSAbbrev =
3122           (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3123       unsigned Code =
3124           (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3125 
3126       // Emit the finished record.
3127       Stream.EmitRecord(Code, NameVals, FSAbbrev);
3128       NameVals.clear();
3129     }
3130   }
3131 
3132   for (auto GVI : Aliases) {
3133     AliasSummary *AS = cast<AliasSummary>(GVI->summary());
3134     NameVals.push_back(Index.getModuleId(AS->modulePath()));
3135     NameVals.push_back(getEncodedLinkage(AS->linkage()));
3136     auto AliaseeOffset = SummaryToOffsetMap[&AS->getAliasee()];
3137     assert(AliaseeOffset);
3138     NameVals.push_back(AliaseeOffset);
3139 
3140     // Record the starting offset of this summary entry for use
3141     // in the VST entry. Add the current code size since the
3142     // reader will invoke readRecord after the abbrev id read.
3143     GVI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
3144 
3145     // Emit the finished record.
3146     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3147     NameVals.clear();
3148   }
3149 
3150   Stream.ExitBlock();
3151 }
3152 
3153 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3154 // current llvm version, and a record for the epoch number.
3155 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
3156   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3157 
3158   // Write the "user readable" string identifying the bitcode producer
3159   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3160   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3161   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3162   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3163   auto StringAbbrev = Stream.EmitAbbrev(Abbv);
3164   WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
3165                     "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
3166 
3167   // Write the epoch version
3168   Abbv = new BitCodeAbbrev();
3169   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3170   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3171   auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
3172   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3173   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3174   Stream.ExitBlock();
3175 }
3176 
3177 static void writeModuleHash(BitstreamWriter &Stream,
3178                             SmallVectorImpl<char> &Buffer,
3179                             size_t BlockStartPos) {
3180   // Emit the module's hash.
3181   // MODULE_CODE_HASH: [5*i32]
3182   SHA1 Hasher;
3183   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Buffer[BlockStartPos],
3184                                   Buffer.size() - BlockStartPos));
3185   auto Hash = Hasher.result();
3186   SmallVector<uint64_t, 20> Vals;
3187   auto LShift = [&](unsigned char Val, unsigned Amount)
3188                     -> uint64_t { return ((uint64_t)Val) << Amount; };
3189   for (int Pos = 0; Pos < 20; Pos += 4) {
3190     uint32_t SubHash = LShift(Hash[Pos + 0], 24);
3191     SubHash |= LShift(Hash[Pos + 1], 16) | LShift(Hash[Pos + 2], 8) |
3192                (unsigned)(unsigned char)Hash[Pos + 3];
3193     Vals.push_back(SubHash);
3194   }
3195 
3196   // Emit the finished record.
3197   Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3198 }
3199 
3200 /// WriteModule - Emit the specified module to the bitstream.
3201 static void WriteModule(const Module *M, BitstreamWriter &Stream,
3202                         bool ShouldPreserveUseListOrder,
3203                         uint64_t BitcodeStartBit,
3204                         const ModuleSummaryIndex *Index, bool GenerateHash,
3205                         SmallVectorImpl<char> &Buffer) {
3206   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3207   size_t BlockStartPos = Buffer.size();
3208 
3209   SmallVector<unsigned, 1> Vals;
3210   unsigned CurVersion = 1;
3211   Vals.push_back(CurVersion);
3212   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3213 
3214   // Analyze the module, enumerating globals, functions, etc.
3215   ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
3216 
3217   // Emit blockinfo, which defines the standard abbreviations etc.
3218   WriteBlockInfo(VE, Stream);
3219 
3220   // Emit information about attribute groups.
3221   WriteAttributeGroupTable(VE, Stream);
3222 
3223   // Emit information about parameter attributes.
3224   WriteAttributeTable(VE, Stream);
3225 
3226   // Emit information describing all of the types in the module.
3227   WriteTypeTable(VE, Stream);
3228 
3229   writeComdats(VE, Stream);
3230 
3231   // Emit top-level description of module, including target triple, inline asm,
3232   // descriptors for global variables, and function prototype info.
3233   uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
3234 
3235   // Emit constants.
3236   WriteModuleConstants(VE, Stream);
3237 
3238   // Emit metadata.
3239   writeModuleMetadata(*M, VE, Stream);
3240 
3241   // Emit metadata.
3242   WriteModuleMetadataStore(M, Stream);
3243 
3244   // Emit module-level use-lists.
3245   if (VE.shouldPreserveUseListOrder())
3246     WriteUseListBlock(nullptr, VE, Stream);
3247 
3248   WriteOperandBundleTags(M, Stream);
3249 
3250   // Emit function bodies.
3251   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3252   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
3253     if (!F->isDeclaration())
3254       WriteFunction(*F, M, VE, Stream, FunctionToBitcodeIndex);
3255 
3256   // Need to write after the above call to WriteFunction which populates
3257   // the summary information in the index.
3258   if (Index)
3259     WritePerModuleGlobalValueSummary(M, *Index, VE, Stream);
3260 
3261   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
3262                         VSTOffsetPlaceholder, BitcodeStartBit,
3263                         &FunctionToBitcodeIndex);
3264 
3265   if (GenerateHash) {
3266     writeModuleHash(Stream, Buffer, BlockStartPos);
3267   }
3268 
3269   Stream.ExitBlock();
3270 }
3271 
3272 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
3273 /// header and trailer to make it compatible with the system archiver.  To do
3274 /// this we emit the following header, and then emit a trailer that pads the
3275 /// file out to be a multiple of 16 bytes.
3276 ///
3277 /// struct bc_header {
3278 ///   uint32_t Magic;         // 0x0B17C0DE
3279 ///   uint32_t Version;       // Version, currently always 0.
3280 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3281 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
3282 ///   uint32_t CPUType;       // CPU specifier.
3283 ///   ... potentially more later ...
3284 /// };
3285 
3286 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3287                                uint32_t &Position) {
3288   support::endian::write32le(&Buffer[Position], Value);
3289   Position += 4;
3290 }
3291 
3292 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3293                                          const Triple &TT) {
3294   unsigned CPUType = ~0U;
3295 
3296   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3297   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3298   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
3299   // specific constants here because they are implicitly part of the Darwin ABI.
3300   enum {
3301     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
3302     DARWIN_CPU_TYPE_X86        = 7,
3303     DARWIN_CPU_TYPE_ARM        = 12,
3304     DARWIN_CPU_TYPE_POWERPC    = 18
3305   };
3306 
3307   Triple::ArchType Arch = TT.getArch();
3308   if (Arch == Triple::x86_64)
3309     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3310   else if (Arch == Triple::x86)
3311     CPUType = DARWIN_CPU_TYPE_X86;
3312   else if (Arch == Triple::ppc)
3313     CPUType = DARWIN_CPU_TYPE_POWERPC;
3314   else if (Arch == Triple::ppc64)
3315     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3316   else if (Arch == Triple::arm || Arch == Triple::thumb)
3317     CPUType = DARWIN_CPU_TYPE_ARM;
3318 
3319   // Traditional Bitcode starts after header.
3320   assert(Buffer.size() >= BWH_HeaderSize &&
3321          "Expected header size to be reserved");
3322   unsigned BCOffset = BWH_HeaderSize;
3323   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3324 
3325   // Write the magic and version.
3326   unsigned Position = 0;
3327   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
3328   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
3329   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
3330   WriteInt32ToBuffer(BCSize     , Buffer, Position);
3331   WriteInt32ToBuffer(CPUType    , Buffer, Position);
3332 
3333   // If the file is not a multiple of 16 bytes, insert dummy padding.
3334   while (Buffer.size() & 15)
3335     Buffer.push_back(0);
3336 }
3337 
3338 /// Helper to write the header common to all bitcode files.
3339 static void WriteBitcodeHeader(BitstreamWriter &Stream) {
3340   // Emit the file header.
3341   Stream.Emit((unsigned)'B', 8);
3342   Stream.Emit((unsigned)'C', 8);
3343   Stream.Emit(0x0, 4);
3344   Stream.Emit(0xC, 4);
3345   Stream.Emit(0xE, 4);
3346   Stream.Emit(0xD, 4);
3347 }
3348 
3349 /// WriteBitcodeToFile - Write the specified module to the specified output
3350 /// stream.
3351 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3352                               bool ShouldPreserveUseListOrder,
3353                               const ModuleSummaryIndex *Index,
3354                               bool GenerateHash) {
3355   SmallVector<char, 0> Buffer;
3356   Buffer.reserve(256*1024);
3357 
3358   // If this is darwin or another generic macho target, reserve space for the
3359   // header.
3360   Triple TT(M->getTargetTriple());
3361   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3362     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3363 
3364   // Emit the module into the buffer.
3365   {
3366     BitstreamWriter Stream(Buffer);
3367     // Save the start bit of the actual bitcode, in case there is space
3368     // saved at the start for the darwin header above. The reader stream
3369     // will start at the bitcode, and we need the offset of the VST
3370     // to line up.
3371     uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
3372 
3373     // Emit the file header.
3374     WriteBitcodeHeader(Stream);
3375 
3376     WriteIdentificationBlock(M, Stream);
3377 
3378     // Emit the module.
3379     WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit, Index,
3380                 GenerateHash, Buffer);
3381   }
3382 
3383   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3384     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
3385 
3386   // Write the generated bitstream to "Out".
3387   Out.write((char*)&Buffer.front(), Buffer.size());
3388 }
3389 
3390 // Write the specified module summary index to the given raw output stream,
3391 // where it will be written in a new bitcode block. This is used when
3392 // writing the combined index file for ThinLTO.
3393 void llvm::WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out) {
3394   SmallVector<char, 0> Buffer;
3395   Buffer.reserve(256 * 1024);
3396 
3397   BitstreamWriter Stream(Buffer);
3398 
3399   // Emit the bitcode header.
3400   WriteBitcodeHeader(Stream);
3401 
3402   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3403 
3404   SmallVector<unsigned, 1> Vals;
3405   unsigned CurVersion = 1;
3406   Vals.push_back(CurVersion);
3407   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3408 
3409   // If we have a VST, write the VSTOFFSET record placeholder and record
3410   // its offset.
3411   uint64_t VSTOffsetPlaceholder = WriteValueSymbolTableForwardDecl(Stream);
3412 
3413   // Write the module paths in the combined index.
3414   WriteModStrings(Index, Stream);
3415 
3416   // Assign unique value ids to all functions in the index for use
3417   // in writing out the call graph edges. Save the mapping from GUID
3418   // to the new global value id to use when writing those edges, which
3419   // are currently saved in the index in terms of GUID.
3420   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
3421   unsigned GlobalValueId = 0;
3422   for (auto &II : Index)
3423     GUIDToValueIdMap[II.first] = ++GlobalValueId;
3424 
3425   // Write the summary combined index records.
3426   WriteCombinedGlobalValueSummary(Index, Stream, GUIDToValueIdMap,
3427                                   GlobalValueId);
3428 
3429   // Need a special VST writer for the combined index (we don't have a
3430   // real VST and real values when this is invoked).
3431   WriteCombinedValueSymbolTable(Index, Stream, GUIDToValueIdMap,
3432                                 VSTOffsetPlaceholder);
3433 
3434   Stream.ExitBlock();
3435 
3436   Out.write((char *)&Buffer.front(), Buffer.size());
3437 }
3438