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