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