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