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