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