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