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