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