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