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