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