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