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