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