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