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