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