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