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