xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 545d34a2724ef158d79c5e37dc817ceea9fbd1d8)
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 |= bitc::AllowReassoc;
1338     if (FPMO->hasNoNaNs())
1339       Flags |= bitc::NoNaNs;
1340     if (FPMO->hasNoInfs())
1341       Flags |= bitc::NoInfs;
1342     if (FPMO->hasNoSignedZeros())
1343       Flags |= bitc::NoSignedZeros;
1344     if (FPMO->hasAllowReciprocal())
1345       Flags |= bitc::AllowReciprocal;
1346     if (FPMO->hasAllowContract())
1347       Flags |= bitc::AllowContract;
1348     if (FPMO->hasApproxFunc())
1349       Flags |= bitc::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->isUnsigned() << 1) | 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   if (N->getRawChecksum()) {
1555     Record.push_back(N->getRawChecksum()->Kind);
1556     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1557   } else {
1558     // Maintain backwards compatibility with the old internal representation of
1559     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1560     Record.push_back(0);
1561     Record.push_back(VE.getMetadataOrNullID(nullptr));
1562   }
1563 
1564   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1565   Record.clear();
1566 }
1567 
1568 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1569                                              SmallVectorImpl<uint64_t> &Record,
1570                                              unsigned Abbrev) {
1571   assert(N->isDistinct() && "Expected distinct compile units");
1572   Record.push_back(/* IsDistinct */ true);
1573   Record.push_back(N->getSourceLanguage());
1574   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1575   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1576   Record.push_back(N->isOptimized());
1577   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1578   Record.push_back(N->getRuntimeVersion());
1579   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1580   Record.push_back(N->getEmissionKind());
1581   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1582   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1583   Record.push_back(/* subprograms */ 0);
1584   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1585   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1586   Record.push_back(N->getDWOId());
1587   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1588   Record.push_back(N->getSplitDebugInlining());
1589   Record.push_back(N->getDebugInfoForProfiling());
1590   Record.push_back(N->getGnuPubnames());
1591 
1592   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1593   Record.clear();
1594 }
1595 
1596 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1597                                             SmallVectorImpl<uint64_t> &Record,
1598                                             unsigned Abbrev) {
1599   uint64_t HasUnitFlag = 1 << 1;
1600   Record.push_back(N->isDistinct() | HasUnitFlag);
1601   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1602   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1603   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1604   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1605   Record.push_back(N->getLine());
1606   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1607   Record.push_back(N->isLocalToUnit());
1608   Record.push_back(N->isDefinition());
1609   Record.push_back(N->getScopeLine());
1610   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1611   Record.push_back(N->getVirtuality());
1612   Record.push_back(N->getVirtualIndex());
1613   Record.push_back(N->getFlags());
1614   Record.push_back(N->isOptimized());
1615   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1616   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1617   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1618   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1619   Record.push_back(N->getThisAdjustment());
1620   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1621 
1622   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1623   Record.clear();
1624 }
1625 
1626 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1627                                               SmallVectorImpl<uint64_t> &Record,
1628                                               unsigned Abbrev) {
1629   Record.push_back(N->isDistinct());
1630   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1631   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1632   Record.push_back(N->getLine());
1633   Record.push_back(N->getColumn());
1634 
1635   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1636   Record.clear();
1637 }
1638 
1639 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1640     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1641     unsigned Abbrev) {
1642   Record.push_back(N->isDistinct());
1643   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1644   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1645   Record.push_back(N->getDiscriminator());
1646 
1647   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1648   Record.clear();
1649 }
1650 
1651 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1652                                            SmallVectorImpl<uint64_t> &Record,
1653                                            unsigned Abbrev) {
1654   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1655   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1656   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1657 
1658   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1659   Record.clear();
1660 }
1661 
1662 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1663                                        SmallVectorImpl<uint64_t> &Record,
1664                                        unsigned Abbrev) {
1665   Record.push_back(N->isDistinct());
1666   Record.push_back(N->getMacinfoType());
1667   Record.push_back(N->getLine());
1668   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1669   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1670 
1671   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1672   Record.clear();
1673 }
1674 
1675 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1676                                            SmallVectorImpl<uint64_t> &Record,
1677                                            unsigned Abbrev) {
1678   Record.push_back(N->isDistinct());
1679   Record.push_back(N->getMacinfoType());
1680   Record.push_back(N->getLine());
1681   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1682   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1683 
1684   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1685   Record.clear();
1686 }
1687 
1688 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1689                                         SmallVectorImpl<uint64_t> &Record,
1690                                         unsigned Abbrev) {
1691   Record.push_back(N->isDistinct());
1692   for (auto &I : N->operands())
1693     Record.push_back(VE.getMetadataOrNullID(I));
1694 
1695   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1696   Record.clear();
1697 }
1698 
1699 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1700     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1701     unsigned Abbrev) {
1702   Record.push_back(N->isDistinct());
1703   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1704   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1705 
1706   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1707   Record.clear();
1708 }
1709 
1710 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1711     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1712     unsigned Abbrev) {
1713   Record.push_back(N->isDistinct());
1714   Record.push_back(N->getTag());
1715   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1716   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1717   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1718 
1719   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1720   Record.clear();
1721 }
1722 
1723 void ModuleBitcodeWriter::writeDIGlobalVariable(
1724     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1725     unsigned Abbrev) {
1726   const uint64_t Version = 1 << 1;
1727   Record.push_back((uint64_t)N->isDistinct() | Version);
1728   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1729   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1730   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1731   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1732   Record.push_back(N->getLine());
1733   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1734   Record.push_back(N->isLocalToUnit());
1735   Record.push_back(N->isDefinition());
1736   Record.push_back(/* expr */ 0);
1737   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1738   Record.push_back(N->getAlignInBits());
1739 
1740   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1741   Record.clear();
1742 }
1743 
1744 void ModuleBitcodeWriter::writeDILocalVariable(
1745     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1746     unsigned Abbrev) {
1747   // In order to support all possible bitcode formats in BitcodeReader we need
1748   // to distinguish the following cases:
1749   // 1) Record has no artificial tag (Record[1]),
1750   //   has no obsolete inlinedAt field (Record[9]).
1751   //   In this case Record size will be 8, HasAlignment flag is false.
1752   // 2) Record has artificial tag (Record[1]),
1753   //   has no obsolete inlignedAt field (Record[9]).
1754   //   In this case Record size will be 9, HasAlignment flag is false.
1755   // 3) Record has both artificial tag (Record[1]) and
1756   //   obsolete inlignedAt field (Record[9]).
1757   //   In this case Record size will be 10, HasAlignment flag is false.
1758   // 4) Record has neither artificial tag, nor inlignedAt field, but
1759   //   HasAlignment flag is true and Record[8] contains alignment value.
1760   const uint64_t HasAlignmentFlag = 1 << 1;
1761   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1762   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1763   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1764   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1765   Record.push_back(N->getLine());
1766   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1767   Record.push_back(N->getArg());
1768   Record.push_back(N->getFlags());
1769   Record.push_back(N->getAlignInBits());
1770 
1771   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1772   Record.clear();
1773 }
1774 
1775 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1776                                             SmallVectorImpl<uint64_t> &Record,
1777                                             unsigned Abbrev) {
1778   Record.reserve(N->getElements().size() + 1);
1779   const uint64_t Version = 3 << 1;
1780   Record.push_back((uint64_t)N->isDistinct() | Version);
1781   Record.append(N->elements_begin(), N->elements_end());
1782 
1783   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1784   Record.clear();
1785 }
1786 
1787 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1788     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1789     unsigned Abbrev) {
1790   Record.push_back(N->isDistinct());
1791   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1792   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1793 
1794   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1795   Record.clear();
1796 }
1797 
1798 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1799                                               SmallVectorImpl<uint64_t> &Record,
1800                                               unsigned Abbrev) {
1801   Record.push_back(N->isDistinct());
1802   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1803   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1804   Record.push_back(N->getLine());
1805   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1806   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1807   Record.push_back(N->getAttributes());
1808   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1809 
1810   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1811   Record.clear();
1812 }
1813 
1814 void ModuleBitcodeWriter::writeDIImportedEntity(
1815     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1816     unsigned Abbrev) {
1817   Record.push_back(N->isDistinct());
1818   Record.push_back(N->getTag());
1819   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1820   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1821   Record.push_back(N->getLine());
1822   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1823   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
1824 
1825   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1826   Record.clear();
1827 }
1828 
1829 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1830   auto Abbv = std::make_shared<BitCodeAbbrev>();
1831   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1832   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1833   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1834   return Stream.EmitAbbrev(std::move(Abbv));
1835 }
1836 
1837 void ModuleBitcodeWriter::writeNamedMetadata(
1838     SmallVectorImpl<uint64_t> &Record) {
1839   if (M.named_metadata_empty())
1840     return;
1841 
1842   unsigned Abbrev = createNamedMetadataAbbrev();
1843   for (const NamedMDNode &NMD : M.named_metadata()) {
1844     // Write name.
1845     StringRef Str = NMD.getName();
1846     Record.append(Str.bytes_begin(), Str.bytes_end());
1847     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1848     Record.clear();
1849 
1850     // Write named metadata operands.
1851     for (const MDNode *N : NMD.operands())
1852       Record.push_back(VE.getMetadataID(N));
1853     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1854     Record.clear();
1855   }
1856 }
1857 
1858 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1859   auto Abbv = std::make_shared<BitCodeAbbrev>();
1860   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1861   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1862   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1863   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1864   return Stream.EmitAbbrev(std::move(Abbv));
1865 }
1866 
1867 /// Write out a record for MDString.
1868 ///
1869 /// All the metadata strings in a metadata block are emitted in a single
1870 /// record.  The sizes and strings themselves are shoved into a blob.
1871 void ModuleBitcodeWriter::writeMetadataStrings(
1872     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1873   if (Strings.empty())
1874     return;
1875 
1876   // Start the record with the number of strings.
1877   Record.push_back(bitc::METADATA_STRINGS);
1878   Record.push_back(Strings.size());
1879 
1880   // Emit the sizes of the strings in the blob.
1881   SmallString<256> Blob;
1882   {
1883     BitstreamWriter W(Blob);
1884     for (const Metadata *MD : Strings)
1885       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1886     W.FlushToWord();
1887   }
1888 
1889   // Add the offset to the strings to the record.
1890   Record.push_back(Blob.size());
1891 
1892   // Add the strings to the blob.
1893   for (const Metadata *MD : Strings)
1894     Blob.append(cast<MDString>(MD)->getString());
1895 
1896   // Emit the final record.
1897   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1898   Record.clear();
1899 }
1900 
1901 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1902 enum MetadataAbbrev : unsigned {
1903 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1904 #include "llvm/IR/Metadata.def"
1905   LastPlusOne
1906 };
1907 
1908 void ModuleBitcodeWriter::writeMetadataRecords(
1909     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1910     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1911   if (MDs.empty())
1912     return;
1913 
1914   // Initialize MDNode abbreviations.
1915 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1916 #include "llvm/IR/Metadata.def"
1917 
1918   for (const Metadata *MD : MDs) {
1919     if (IndexPos)
1920       IndexPos->push_back(Stream.GetCurrentBitNo());
1921     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1922       assert(N->isResolved() && "Expected forward references to be resolved");
1923 
1924       switch (N->getMetadataID()) {
1925       default:
1926         llvm_unreachable("Invalid MDNode subclass");
1927 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1928   case Metadata::CLASS##Kind:                                                  \
1929     if (MDAbbrevs)                                                             \
1930       write##CLASS(cast<CLASS>(N), Record,                                     \
1931                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
1932     else                                                                       \
1933       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
1934     continue;
1935 #include "llvm/IR/Metadata.def"
1936       }
1937     }
1938     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1939   }
1940 }
1941 
1942 void ModuleBitcodeWriter::writeModuleMetadata() {
1943   if (!VE.hasMDs() && M.named_metadata_empty())
1944     return;
1945 
1946   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1947   SmallVector<uint64_t, 64> Record;
1948 
1949   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1950   // block and load any metadata.
1951   std::vector<unsigned> MDAbbrevs;
1952 
1953   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1954   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1955   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1956       createGenericDINodeAbbrev();
1957 
1958   auto Abbv = std::make_shared<BitCodeAbbrev>();
1959   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1960   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1961   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1962   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1963 
1964   Abbv = std::make_shared<BitCodeAbbrev>();
1965   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1966   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1967   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1968   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1969 
1970   // Emit MDStrings together upfront.
1971   writeMetadataStrings(VE.getMDStrings(), Record);
1972 
1973   // We only emit an index for the metadata record if we have more than a given
1974   // (naive) threshold of metadatas, otherwise it is not worth it.
1975   if (VE.getNonMDStrings().size() > IndexThreshold) {
1976     // Write a placeholder value in for the offset of the metadata index,
1977     // which is written after the records, so that it can include
1978     // the offset of each entry. The placeholder offset will be
1979     // updated after all records are emitted.
1980     uint64_t Vals[] = {0, 0};
1981     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1982   }
1983 
1984   // Compute and save the bit offset to the current position, which will be
1985   // patched when we emit the index later. We can simply subtract the 64-bit
1986   // fixed size from the current bit number to get the location to backpatch.
1987   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1988 
1989   // This index will contain the bitpos for each individual record.
1990   std::vector<uint64_t> IndexPos;
1991   IndexPos.reserve(VE.getNonMDStrings().size());
1992 
1993   // Write all the records
1994   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1995 
1996   if (VE.getNonMDStrings().size() > IndexThreshold) {
1997     // Now that we have emitted all the records we will emit the index. But
1998     // first
1999     // backpatch the forward reference so that the reader can skip the records
2000     // efficiently.
2001     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2002                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2003 
2004     // Delta encode the index.
2005     uint64_t PreviousValue = IndexOffsetRecordBitPos;
2006     for (auto &Elt : IndexPos) {
2007       auto EltDelta = Elt - PreviousValue;
2008       PreviousValue = Elt;
2009       Elt = EltDelta;
2010     }
2011     // Emit the index record.
2012     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2013     IndexPos.clear();
2014   }
2015 
2016   // Write the named metadata now.
2017   writeNamedMetadata(Record);
2018 
2019   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2020     SmallVector<uint64_t, 4> Record;
2021     Record.push_back(VE.getValueID(&GO));
2022     pushGlobalMetadataAttachment(Record, GO);
2023     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2024   };
2025   for (const Function &F : M)
2026     if (F.isDeclaration() && F.hasMetadata())
2027       AddDeclAttachedMetadata(F);
2028   // FIXME: Only store metadata for declarations here, and move data for global
2029   // variable definitions to a separate block (PR28134).
2030   for (const GlobalVariable &GV : M.globals())
2031     if (GV.hasMetadata())
2032       AddDeclAttachedMetadata(GV);
2033 
2034   Stream.ExitBlock();
2035 }
2036 
2037 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2038   if (!VE.hasMDs())
2039     return;
2040 
2041   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2042   SmallVector<uint64_t, 64> Record;
2043   writeMetadataStrings(VE.getMDStrings(), Record);
2044   writeMetadataRecords(VE.getNonMDStrings(), Record);
2045   Stream.ExitBlock();
2046 }
2047 
2048 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2049     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2050   // [n x [id, mdnode]]
2051   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2052   GO.getAllMetadata(MDs);
2053   for (const auto &I : MDs) {
2054     Record.push_back(I.first);
2055     Record.push_back(VE.getMetadataID(I.second));
2056   }
2057 }
2058 
2059 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2060   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2061 
2062   SmallVector<uint64_t, 64> Record;
2063 
2064   if (F.hasMetadata()) {
2065     pushGlobalMetadataAttachment(Record, F);
2066     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2067     Record.clear();
2068   }
2069 
2070   // Write metadata attachments
2071   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2072   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2073   for (const BasicBlock &BB : F)
2074     for (const Instruction &I : BB) {
2075       MDs.clear();
2076       I.getAllMetadataOtherThanDebugLoc(MDs);
2077 
2078       // If no metadata, ignore instruction.
2079       if (MDs.empty()) continue;
2080 
2081       Record.push_back(VE.getInstructionID(&I));
2082 
2083       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2084         Record.push_back(MDs[i].first);
2085         Record.push_back(VE.getMetadataID(MDs[i].second));
2086       }
2087       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2088       Record.clear();
2089     }
2090 
2091   Stream.ExitBlock();
2092 }
2093 
2094 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2095   SmallVector<uint64_t, 64> Record;
2096 
2097   // Write metadata kinds
2098   // METADATA_KIND - [n x [id, name]]
2099   SmallVector<StringRef, 8> Names;
2100   M.getMDKindNames(Names);
2101 
2102   if (Names.empty()) return;
2103 
2104   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2105 
2106   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2107     Record.push_back(MDKindID);
2108     StringRef KName = Names[MDKindID];
2109     Record.append(KName.begin(), KName.end());
2110 
2111     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2112     Record.clear();
2113   }
2114 
2115   Stream.ExitBlock();
2116 }
2117 
2118 void ModuleBitcodeWriter::writeOperandBundleTags() {
2119   // Write metadata kinds
2120   //
2121   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2122   //
2123   // OPERAND_BUNDLE_TAG - [strchr x N]
2124 
2125   SmallVector<StringRef, 8> Tags;
2126   M.getOperandBundleTags(Tags);
2127 
2128   if (Tags.empty())
2129     return;
2130 
2131   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2132 
2133   SmallVector<uint64_t, 64> Record;
2134 
2135   for (auto Tag : Tags) {
2136     Record.append(Tag.begin(), Tag.end());
2137 
2138     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2139     Record.clear();
2140   }
2141 
2142   Stream.ExitBlock();
2143 }
2144 
2145 void ModuleBitcodeWriter::writeSyncScopeNames() {
2146   SmallVector<StringRef, 8> SSNs;
2147   M.getContext().getSyncScopeNames(SSNs);
2148   if (SSNs.empty())
2149     return;
2150 
2151   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2152 
2153   SmallVector<uint64_t, 64> Record;
2154   for (auto SSN : SSNs) {
2155     Record.append(SSN.begin(), SSN.end());
2156     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2157     Record.clear();
2158   }
2159 
2160   Stream.ExitBlock();
2161 }
2162 
2163 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2164   if ((int64_t)V >= 0)
2165     Vals.push_back(V << 1);
2166   else
2167     Vals.push_back((-V << 1) | 1);
2168 }
2169 
2170 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2171                                          bool isGlobal) {
2172   if (FirstVal == LastVal) return;
2173 
2174   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2175 
2176   unsigned AggregateAbbrev = 0;
2177   unsigned String8Abbrev = 0;
2178   unsigned CString7Abbrev = 0;
2179   unsigned CString6Abbrev = 0;
2180   // If this is a constant pool for the module, emit module-specific abbrevs.
2181   if (isGlobal) {
2182     // Abbrev for CST_CODE_AGGREGATE.
2183     auto Abbv = std::make_shared<BitCodeAbbrev>();
2184     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2185     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2186     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2187     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2188 
2189     // Abbrev for CST_CODE_STRING.
2190     Abbv = std::make_shared<BitCodeAbbrev>();
2191     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2192     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2193     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2194     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2195     // Abbrev for CST_CODE_CSTRING.
2196     Abbv = std::make_shared<BitCodeAbbrev>();
2197     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2198     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2199     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2200     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2201     // Abbrev for CST_CODE_CSTRING.
2202     Abbv = std::make_shared<BitCodeAbbrev>();
2203     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2204     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2205     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2206     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2207   }
2208 
2209   SmallVector<uint64_t, 64> Record;
2210 
2211   const ValueEnumerator::ValueList &Vals = VE.getValues();
2212   Type *LastTy = nullptr;
2213   for (unsigned i = FirstVal; i != LastVal; ++i) {
2214     const Value *V = Vals[i].first;
2215     // If we need to switch types, do so now.
2216     if (V->getType() != LastTy) {
2217       LastTy = V->getType();
2218       Record.push_back(VE.getTypeID(LastTy));
2219       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2220                         CONSTANTS_SETTYPE_ABBREV);
2221       Record.clear();
2222     }
2223 
2224     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2225       Record.push_back(unsigned(IA->hasSideEffects()) |
2226                        unsigned(IA->isAlignStack()) << 1 |
2227                        unsigned(IA->getDialect()&1) << 2);
2228 
2229       // Add the asm string.
2230       const std::string &AsmStr = IA->getAsmString();
2231       Record.push_back(AsmStr.size());
2232       Record.append(AsmStr.begin(), AsmStr.end());
2233 
2234       // Add the constraint string.
2235       const std::string &ConstraintStr = IA->getConstraintString();
2236       Record.push_back(ConstraintStr.size());
2237       Record.append(ConstraintStr.begin(), ConstraintStr.end());
2238       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2239       Record.clear();
2240       continue;
2241     }
2242     const Constant *C = cast<Constant>(V);
2243     unsigned Code = -1U;
2244     unsigned AbbrevToUse = 0;
2245     if (C->isNullValue()) {
2246       Code = bitc::CST_CODE_NULL;
2247     } else if (isa<UndefValue>(C)) {
2248       Code = bitc::CST_CODE_UNDEF;
2249     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2250       if (IV->getBitWidth() <= 64) {
2251         uint64_t V = IV->getSExtValue();
2252         emitSignedInt64(Record, V);
2253         Code = bitc::CST_CODE_INTEGER;
2254         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2255       } else {                             // Wide integers, > 64 bits in size.
2256         // We have an arbitrary precision integer value to write whose
2257         // bit width is > 64. However, in canonical unsigned integer
2258         // format it is likely that the high bits are going to be zero.
2259         // So, we only write the number of active words.
2260         unsigned NWords = IV->getValue().getActiveWords();
2261         const uint64_t *RawWords = IV->getValue().getRawData();
2262         for (unsigned i = 0; i != NWords; ++i) {
2263           emitSignedInt64(Record, RawWords[i]);
2264         }
2265         Code = bitc::CST_CODE_WIDE_INTEGER;
2266       }
2267     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2268       Code = bitc::CST_CODE_FLOAT;
2269       Type *Ty = CFP->getType();
2270       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2271         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2272       } else if (Ty->isX86_FP80Ty()) {
2273         // api needed to prevent premature destruction
2274         // bits are not in the same order as a normal i80 APInt, compensate.
2275         APInt api = CFP->getValueAPF().bitcastToAPInt();
2276         const uint64_t *p = api.getRawData();
2277         Record.push_back((p[1] << 48) | (p[0] >> 16));
2278         Record.push_back(p[0] & 0xffffLL);
2279       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2280         APInt api = CFP->getValueAPF().bitcastToAPInt();
2281         const uint64_t *p = api.getRawData();
2282         Record.push_back(p[0]);
2283         Record.push_back(p[1]);
2284       } else {
2285         assert(0 && "Unknown FP type!");
2286       }
2287     } else if (isa<ConstantDataSequential>(C) &&
2288                cast<ConstantDataSequential>(C)->isString()) {
2289       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2290       // Emit constant strings specially.
2291       unsigned NumElts = Str->getNumElements();
2292       // If this is a null-terminated string, use the denser CSTRING encoding.
2293       if (Str->isCString()) {
2294         Code = bitc::CST_CODE_CSTRING;
2295         --NumElts;  // Don't encode the null, which isn't allowed by char6.
2296       } else {
2297         Code = bitc::CST_CODE_STRING;
2298         AbbrevToUse = String8Abbrev;
2299       }
2300       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2301       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2302       for (unsigned i = 0; i != NumElts; ++i) {
2303         unsigned char V = Str->getElementAsInteger(i);
2304         Record.push_back(V);
2305         isCStr7 &= (V & 128) == 0;
2306         if (isCStrChar6)
2307           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2308       }
2309 
2310       if (isCStrChar6)
2311         AbbrevToUse = CString6Abbrev;
2312       else if (isCStr7)
2313         AbbrevToUse = CString7Abbrev;
2314     } else if (const ConstantDataSequential *CDS =
2315                   dyn_cast<ConstantDataSequential>(C)) {
2316       Code = bitc::CST_CODE_DATA;
2317       Type *EltTy = CDS->getType()->getElementType();
2318       if (isa<IntegerType>(EltTy)) {
2319         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2320           Record.push_back(CDS->getElementAsInteger(i));
2321       } else {
2322         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2323           Record.push_back(
2324               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2325       }
2326     } else if (isa<ConstantAggregate>(C)) {
2327       Code = bitc::CST_CODE_AGGREGATE;
2328       for (const Value *Op : C->operands())
2329         Record.push_back(VE.getValueID(Op));
2330       AbbrevToUse = AggregateAbbrev;
2331     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2332       switch (CE->getOpcode()) {
2333       default:
2334         if (Instruction::isCast(CE->getOpcode())) {
2335           Code = bitc::CST_CODE_CE_CAST;
2336           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2337           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2338           Record.push_back(VE.getValueID(C->getOperand(0)));
2339           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2340         } else {
2341           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2342           Code = bitc::CST_CODE_CE_BINOP;
2343           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2344           Record.push_back(VE.getValueID(C->getOperand(0)));
2345           Record.push_back(VE.getValueID(C->getOperand(1)));
2346           uint64_t Flags = getOptimizationFlags(CE);
2347           if (Flags != 0)
2348             Record.push_back(Flags);
2349         }
2350         break;
2351       case Instruction::GetElementPtr: {
2352         Code = bitc::CST_CODE_CE_GEP;
2353         const auto *GO = cast<GEPOperator>(C);
2354         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2355         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2356           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2357           Record.push_back((*Idx << 1) | GO->isInBounds());
2358         } else if (GO->isInBounds())
2359           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2360         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2361           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2362           Record.push_back(VE.getValueID(C->getOperand(i)));
2363         }
2364         break;
2365       }
2366       case Instruction::Select:
2367         Code = bitc::CST_CODE_CE_SELECT;
2368         Record.push_back(VE.getValueID(C->getOperand(0)));
2369         Record.push_back(VE.getValueID(C->getOperand(1)));
2370         Record.push_back(VE.getValueID(C->getOperand(2)));
2371         break;
2372       case Instruction::ExtractElement:
2373         Code = bitc::CST_CODE_CE_EXTRACTELT;
2374         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2375         Record.push_back(VE.getValueID(C->getOperand(0)));
2376         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2377         Record.push_back(VE.getValueID(C->getOperand(1)));
2378         break;
2379       case Instruction::InsertElement:
2380         Code = bitc::CST_CODE_CE_INSERTELT;
2381         Record.push_back(VE.getValueID(C->getOperand(0)));
2382         Record.push_back(VE.getValueID(C->getOperand(1)));
2383         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2384         Record.push_back(VE.getValueID(C->getOperand(2)));
2385         break;
2386       case Instruction::ShuffleVector:
2387         // If the return type and argument types are the same, this is a
2388         // standard shufflevector instruction.  If the types are different,
2389         // then the shuffle is widening or truncating the input vectors, and
2390         // the argument type must also be encoded.
2391         if (C->getType() == C->getOperand(0)->getType()) {
2392           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2393         } else {
2394           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2395           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2396         }
2397         Record.push_back(VE.getValueID(C->getOperand(0)));
2398         Record.push_back(VE.getValueID(C->getOperand(1)));
2399         Record.push_back(VE.getValueID(C->getOperand(2)));
2400         break;
2401       case Instruction::ICmp:
2402       case Instruction::FCmp:
2403         Code = bitc::CST_CODE_CE_CMP;
2404         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2405         Record.push_back(VE.getValueID(C->getOperand(0)));
2406         Record.push_back(VE.getValueID(C->getOperand(1)));
2407         Record.push_back(CE->getPredicate());
2408         break;
2409       }
2410     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2411       Code = bitc::CST_CODE_BLOCKADDRESS;
2412       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2413       Record.push_back(VE.getValueID(BA->getFunction()));
2414       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2415     } else {
2416 #ifndef NDEBUG
2417       C->dump();
2418 #endif
2419       llvm_unreachable("Unknown constant!");
2420     }
2421     Stream.EmitRecord(Code, Record, AbbrevToUse);
2422     Record.clear();
2423   }
2424 
2425   Stream.ExitBlock();
2426 }
2427 
2428 void ModuleBitcodeWriter::writeModuleConstants() {
2429   const ValueEnumerator::ValueList &Vals = VE.getValues();
2430 
2431   // Find the first constant to emit, which is the first non-globalvalue value.
2432   // We know globalvalues have been emitted by WriteModuleInfo.
2433   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2434     if (!isa<GlobalValue>(Vals[i].first)) {
2435       writeConstants(i, Vals.size(), true);
2436       return;
2437     }
2438   }
2439 }
2440 
2441 /// pushValueAndType - The file has to encode both the value and type id for
2442 /// many values, because we need to know what type to create for forward
2443 /// references.  However, most operands are not forward references, so this type
2444 /// field is not needed.
2445 ///
2446 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2447 /// instruction ID, then it is a forward reference, and it also includes the
2448 /// type ID.  The value ID that is written is encoded relative to the InstID.
2449 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2450                                            SmallVectorImpl<unsigned> &Vals) {
2451   unsigned ValID = VE.getValueID(V);
2452   // Make encoding relative to the InstID.
2453   Vals.push_back(InstID - ValID);
2454   if (ValID >= InstID) {
2455     Vals.push_back(VE.getTypeID(V->getType()));
2456     return true;
2457   }
2458   return false;
2459 }
2460 
2461 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2462                                               unsigned InstID) {
2463   SmallVector<unsigned, 64> Record;
2464   LLVMContext &C = CS.getInstruction()->getContext();
2465 
2466   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2467     const auto &Bundle = CS.getOperandBundleAt(i);
2468     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2469 
2470     for (auto &Input : Bundle.Inputs)
2471       pushValueAndType(Input, InstID, Record);
2472 
2473     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2474     Record.clear();
2475   }
2476 }
2477 
2478 /// pushValue - Like pushValueAndType, but where the type of the value is
2479 /// omitted (perhaps it was already encoded in an earlier operand).
2480 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2481                                     SmallVectorImpl<unsigned> &Vals) {
2482   unsigned ValID = VE.getValueID(V);
2483   Vals.push_back(InstID - ValID);
2484 }
2485 
2486 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2487                                           SmallVectorImpl<uint64_t> &Vals) {
2488   unsigned ValID = VE.getValueID(V);
2489   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2490   emitSignedInt64(Vals, diff);
2491 }
2492 
2493 /// WriteInstruction - Emit an instruction to the specified stream.
2494 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2495                                            unsigned InstID,
2496                                            SmallVectorImpl<unsigned> &Vals) {
2497   unsigned Code = 0;
2498   unsigned AbbrevToUse = 0;
2499   VE.setInstructionID(&I);
2500   switch (I.getOpcode()) {
2501   default:
2502     if (Instruction::isCast(I.getOpcode())) {
2503       Code = bitc::FUNC_CODE_INST_CAST;
2504       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2505         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2506       Vals.push_back(VE.getTypeID(I.getType()));
2507       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2508     } else {
2509       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2510       Code = bitc::FUNC_CODE_INST_BINOP;
2511       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2512         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2513       pushValue(I.getOperand(1), InstID, Vals);
2514       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2515       uint64_t Flags = getOptimizationFlags(&I);
2516       if (Flags != 0) {
2517         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2518           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2519         Vals.push_back(Flags);
2520       }
2521     }
2522     break;
2523 
2524   case Instruction::GetElementPtr: {
2525     Code = bitc::FUNC_CODE_INST_GEP;
2526     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2527     auto &GEPInst = cast<GetElementPtrInst>(I);
2528     Vals.push_back(GEPInst.isInBounds());
2529     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2530     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2531       pushValueAndType(I.getOperand(i), InstID, Vals);
2532     break;
2533   }
2534   case Instruction::ExtractValue: {
2535     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2536     pushValueAndType(I.getOperand(0), InstID, Vals);
2537     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2538     Vals.append(EVI->idx_begin(), EVI->idx_end());
2539     break;
2540   }
2541   case Instruction::InsertValue: {
2542     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2543     pushValueAndType(I.getOperand(0), InstID, Vals);
2544     pushValueAndType(I.getOperand(1), InstID, Vals);
2545     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2546     Vals.append(IVI->idx_begin(), IVI->idx_end());
2547     break;
2548   }
2549   case Instruction::Select:
2550     Code = bitc::FUNC_CODE_INST_VSELECT;
2551     pushValueAndType(I.getOperand(1), InstID, Vals);
2552     pushValue(I.getOperand(2), InstID, Vals);
2553     pushValueAndType(I.getOperand(0), InstID, Vals);
2554     break;
2555   case Instruction::ExtractElement:
2556     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2557     pushValueAndType(I.getOperand(0), InstID, Vals);
2558     pushValueAndType(I.getOperand(1), InstID, Vals);
2559     break;
2560   case Instruction::InsertElement:
2561     Code = bitc::FUNC_CODE_INST_INSERTELT;
2562     pushValueAndType(I.getOperand(0), InstID, Vals);
2563     pushValue(I.getOperand(1), InstID, Vals);
2564     pushValueAndType(I.getOperand(2), InstID, Vals);
2565     break;
2566   case Instruction::ShuffleVector:
2567     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2568     pushValueAndType(I.getOperand(0), InstID, Vals);
2569     pushValue(I.getOperand(1), InstID, Vals);
2570     pushValue(I.getOperand(2), InstID, Vals);
2571     break;
2572   case Instruction::ICmp:
2573   case Instruction::FCmp: {
2574     // compare returning Int1Ty or vector of Int1Ty
2575     Code = bitc::FUNC_CODE_INST_CMP2;
2576     pushValueAndType(I.getOperand(0), InstID, Vals);
2577     pushValue(I.getOperand(1), InstID, Vals);
2578     Vals.push_back(cast<CmpInst>(I).getPredicate());
2579     uint64_t Flags = getOptimizationFlags(&I);
2580     if (Flags != 0)
2581       Vals.push_back(Flags);
2582     break;
2583   }
2584 
2585   case Instruction::Ret:
2586     {
2587       Code = bitc::FUNC_CODE_INST_RET;
2588       unsigned NumOperands = I.getNumOperands();
2589       if (NumOperands == 0)
2590         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2591       else if (NumOperands == 1) {
2592         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2593           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2594       } else {
2595         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2596           pushValueAndType(I.getOperand(i), InstID, Vals);
2597       }
2598     }
2599     break;
2600   case Instruction::Br:
2601     {
2602       Code = bitc::FUNC_CODE_INST_BR;
2603       const BranchInst &II = cast<BranchInst>(I);
2604       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2605       if (II.isConditional()) {
2606         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2607         pushValue(II.getCondition(), InstID, Vals);
2608       }
2609     }
2610     break;
2611   case Instruction::Switch:
2612     {
2613       Code = bitc::FUNC_CODE_INST_SWITCH;
2614       const SwitchInst &SI = cast<SwitchInst>(I);
2615       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2616       pushValue(SI.getCondition(), InstID, Vals);
2617       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2618       for (auto Case : SI.cases()) {
2619         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2620         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2621       }
2622     }
2623     break;
2624   case Instruction::IndirectBr:
2625     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2626     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2627     // Encode the address operand as relative, but not the basic blocks.
2628     pushValue(I.getOperand(0), InstID, Vals);
2629     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2630       Vals.push_back(VE.getValueID(I.getOperand(i)));
2631     break;
2632 
2633   case Instruction::Invoke: {
2634     const InvokeInst *II = cast<InvokeInst>(&I);
2635     const Value *Callee = II->getCalledValue();
2636     FunctionType *FTy = II->getFunctionType();
2637 
2638     if (II->hasOperandBundles())
2639       writeOperandBundles(II, InstID);
2640 
2641     Code = bitc::FUNC_CODE_INST_INVOKE;
2642 
2643     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2644     Vals.push_back(II->getCallingConv() | 1 << 13);
2645     Vals.push_back(VE.getValueID(II->getNormalDest()));
2646     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2647     Vals.push_back(VE.getTypeID(FTy));
2648     pushValueAndType(Callee, InstID, Vals);
2649 
2650     // Emit value #'s for the fixed parameters.
2651     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2652       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2653 
2654     // Emit type/value pairs for varargs params.
2655     if (FTy->isVarArg()) {
2656       for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2657            i != e; ++i)
2658         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2659     }
2660     break;
2661   }
2662   case Instruction::Resume:
2663     Code = bitc::FUNC_CODE_INST_RESUME;
2664     pushValueAndType(I.getOperand(0), InstID, Vals);
2665     break;
2666   case Instruction::CleanupRet: {
2667     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2668     const auto &CRI = cast<CleanupReturnInst>(I);
2669     pushValue(CRI.getCleanupPad(), InstID, Vals);
2670     if (CRI.hasUnwindDest())
2671       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2672     break;
2673   }
2674   case Instruction::CatchRet: {
2675     Code = bitc::FUNC_CODE_INST_CATCHRET;
2676     const auto &CRI = cast<CatchReturnInst>(I);
2677     pushValue(CRI.getCatchPad(), InstID, Vals);
2678     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2679     break;
2680   }
2681   case Instruction::CleanupPad:
2682   case Instruction::CatchPad: {
2683     const auto &FuncletPad = cast<FuncletPadInst>(I);
2684     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2685                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2686     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2687 
2688     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2689     Vals.push_back(NumArgOperands);
2690     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2691       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2692     break;
2693   }
2694   case Instruction::CatchSwitch: {
2695     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2696     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2697 
2698     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2699 
2700     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2701     Vals.push_back(NumHandlers);
2702     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2703       Vals.push_back(VE.getValueID(CatchPadBB));
2704 
2705     if (CatchSwitch.hasUnwindDest())
2706       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2707     break;
2708   }
2709   case Instruction::Unreachable:
2710     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2711     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2712     break;
2713 
2714   case Instruction::PHI: {
2715     const PHINode &PN = cast<PHINode>(I);
2716     Code = bitc::FUNC_CODE_INST_PHI;
2717     // With the newer instruction encoding, forward references could give
2718     // negative valued IDs.  This is most common for PHIs, so we use
2719     // signed VBRs.
2720     SmallVector<uint64_t, 128> Vals64;
2721     Vals64.push_back(VE.getTypeID(PN.getType()));
2722     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2723       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2724       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2725     }
2726     // Emit a Vals64 vector and exit.
2727     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2728     Vals64.clear();
2729     return;
2730   }
2731 
2732   case Instruction::LandingPad: {
2733     const LandingPadInst &LP = cast<LandingPadInst>(I);
2734     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2735     Vals.push_back(VE.getTypeID(LP.getType()));
2736     Vals.push_back(LP.isCleanup());
2737     Vals.push_back(LP.getNumClauses());
2738     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2739       if (LP.isCatch(I))
2740         Vals.push_back(LandingPadInst::Catch);
2741       else
2742         Vals.push_back(LandingPadInst::Filter);
2743       pushValueAndType(LP.getClause(I), InstID, Vals);
2744     }
2745     break;
2746   }
2747 
2748   case Instruction::Alloca: {
2749     Code = bitc::FUNC_CODE_INST_ALLOCA;
2750     const AllocaInst &AI = cast<AllocaInst>(I);
2751     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2752     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2753     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2754     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2755     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2756            "not enough bits for maximum alignment");
2757     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2758     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2759     AlignRecord |= 1 << 6;
2760     AlignRecord |= AI.isSwiftError() << 7;
2761     Vals.push_back(AlignRecord);
2762     break;
2763   }
2764 
2765   case Instruction::Load:
2766     if (cast<LoadInst>(I).isAtomic()) {
2767       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2768       pushValueAndType(I.getOperand(0), InstID, Vals);
2769     } else {
2770       Code = bitc::FUNC_CODE_INST_LOAD;
2771       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2772         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2773     }
2774     Vals.push_back(VE.getTypeID(I.getType()));
2775     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2776     Vals.push_back(cast<LoadInst>(I).isVolatile());
2777     if (cast<LoadInst>(I).isAtomic()) {
2778       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2779       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
2780     }
2781     break;
2782   case Instruction::Store:
2783     if (cast<StoreInst>(I).isAtomic())
2784       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2785     else
2786       Code = bitc::FUNC_CODE_INST_STORE;
2787     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2788     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2789     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2790     Vals.push_back(cast<StoreInst>(I).isVolatile());
2791     if (cast<StoreInst>(I).isAtomic()) {
2792       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2793       Vals.push_back(
2794           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
2795     }
2796     break;
2797   case Instruction::AtomicCmpXchg:
2798     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2799     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2800     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2801     pushValue(I.getOperand(2), InstID, Vals);        // newval.
2802     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2803     Vals.push_back(
2804         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2805     Vals.push_back(
2806         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
2807     Vals.push_back(
2808         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2809     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2810     break;
2811   case Instruction::AtomicRMW:
2812     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2813     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2814     pushValue(I.getOperand(1), InstID, Vals);        // val.
2815     Vals.push_back(
2816         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2817     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2818     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2819     Vals.push_back(
2820         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
2821     break;
2822   case Instruction::Fence:
2823     Code = bitc::FUNC_CODE_INST_FENCE;
2824     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2825     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
2826     break;
2827   case Instruction::Call: {
2828     const CallInst &CI = cast<CallInst>(I);
2829     FunctionType *FTy = CI.getFunctionType();
2830 
2831     if (CI.hasOperandBundles())
2832       writeOperandBundles(&CI, InstID);
2833 
2834     Code = bitc::FUNC_CODE_INST_CALL;
2835 
2836     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2837 
2838     unsigned Flags = getOptimizationFlags(&I);
2839     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2840                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2841                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2842                    1 << bitc::CALL_EXPLICIT_TYPE |
2843                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2844                    unsigned(Flags != 0) << bitc::CALL_FMF);
2845     if (Flags != 0)
2846       Vals.push_back(Flags);
2847 
2848     Vals.push_back(VE.getTypeID(FTy));
2849     pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2850 
2851     // Emit value #'s for the fixed parameters.
2852     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2853       // Check for labels (can happen with asm labels).
2854       if (FTy->getParamType(i)->isLabelTy())
2855         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2856       else
2857         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2858     }
2859 
2860     // Emit type/value pairs for varargs params.
2861     if (FTy->isVarArg()) {
2862       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2863            i != e; ++i)
2864         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2865     }
2866     break;
2867   }
2868   case Instruction::VAArg:
2869     Code = bitc::FUNC_CODE_INST_VAARG;
2870     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
2871     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
2872     Vals.push_back(VE.getTypeID(I.getType())); // restype.
2873     break;
2874   }
2875 
2876   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2877   Vals.clear();
2878 }
2879 
2880 /// Write a GlobalValue VST to the module. The purpose of this data structure is
2881 /// to allow clients to efficiently find the function body.
2882 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2883   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2884   // Get the offset of the VST we are writing, and backpatch it into
2885   // the VST forward declaration record.
2886   uint64_t VSTOffset = Stream.GetCurrentBitNo();
2887   // The BitcodeStartBit was the stream offset of the identification block.
2888   VSTOffset -= bitcodeStartBit();
2889   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2890   // Note that we add 1 here because the offset is relative to one word
2891   // before the start of the identification block, which was historically
2892   // always the start of the regular bitcode header.
2893   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2894 
2895   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2896 
2897   auto Abbv = std::make_shared<BitCodeAbbrev>();
2898   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2899   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2900   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2901   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2902 
2903   for (const Function &F : M) {
2904     uint64_t Record[2];
2905 
2906     if (F.isDeclaration())
2907       continue;
2908 
2909     Record[0] = VE.getValueID(&F);
2910 
2911     // Save the word offset of the function (from the start of the
2912     // actual bitcode written to the stream).
2913     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2914     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2915     // Note that we add 1 here because the offset is relative to one word
2916     // before the start of the identification block, which was historically
2917     // always the start of the regular bitcode header.
2918     Record[1] = BitcodeIndex / 32 + 1;
2919 
2920     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
2921   }
2922 
2923   Stream.ExitBlock();
2924 }
2925 
2926 /// Emit names for arguments, instructions and basic blocks in a function.
2927 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2928     const ValueSymbolTable &VST) {
2929   if (VST.empty())
2930     return;
2931 
2932   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2933 
2934   // FIXME: Set up the abbrev, we know how many values there are!
2935   // FIXME: We know if the type names can use 7-bit ascii.
2936   SmallVector<uint64_t, 64> NameVals;
2937 
2938   for (const ValueName &Name : VST) {
2939     // Figure out the encoding to use for the name.
2940     StringEncoding Bits = getStringEncoding(Name.getKey());
2941 
2942     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2943     NameVals.push_back(VE.getValueID(Name.getValue()));
2944 
2945     // VST_CODE_ENTRY:   [valueid, namechar x N]
2946     // VST_CODE_BBENTRY: [bbid, namechar x N]
2947     unsigned Code;
2948     if (isa<BasicBlock>(Name.getValue())) {
2949       Code = bitc::VST_CODE_BBENTRY;
2950       if (Bits == SE_Char6)
2951         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2952     } else {
2953       Code = bitc::VST_CODE_ENTRY;
2954       if (Bits == SE_Char6)
2955         AbbrevToUse = VST_ENTRY_6_ABBREV;
2956       else if (Bits == SE_Fixed7)
2957         AbbrevToUse = VST_ENTRY_7_ABBREV;
2958     }
2959 
2960     for (const auto P : Name.getKey())
2961       NameVals.push_back((unsigned char)P);
2962 
2963     // Emit the finished record.
2964     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2965     NameVals.clear();
2966   }
2967 
2968   Stream.ExitBlock();
2969 }
2970 
2971 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
2972   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2973   unsigned Code;
2974   if (isa<BasicBlock>(Order.V))
2975     Code = bitc::USELIST_CODE_BB;
2976   else
2977     Code = bitc::USELIST_CODE_DEFAULT;
2978 
2979   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2980   Record.push_back(VE.getValueID(Order.V));
2981   Stream.EmitRecord(Code, Record);
2982 }
2983 
2984 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
2985   assert(VE.shouldPreserveUseListOrder() &&
2986          "Expected to be preserving use-list order");
2987 
2988   auto hasMore = [&]() {
2989     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2990   };
2991   if (!hasMore())
2992     // Nothing to do.
2993     return;
2994 
2995   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2996   while (hasMore()) {
2997     writeUseList(std::move(VE.UseListOrders.back()));
2998     VE.UseListOrders.pop_back();
2999   }
3000   Stream.ExitBlock();
3001 }
3002 
3003 /// Emit a function body to the module stream.
3004 void ModuleBitcodeWriter::writeFunction(
3005     const Function &F,
3006     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3007   // Save the bitcode index of the start of this function block for recording
3008   // in the VST.
3009   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3010 
3011   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3012   VE.incorporateFunction(F);
3013 
3014   SmallVector<unsigned, 64> Vals;
3015 
3016   // Emit the number of basic blocks, so the reader can create them ahead of
3017   // time.
3018   Vals.push_back(VE.getBasicBlocks().size());
3019   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3020   Vals.clear();
3021 
3022   // If there are function-local constants, emit them now.
3023   unsigned CstStart, CstEnd;
3024   VE.getFunctionConstantRange(CstStart, CstEnd);
3025   writeConstants(CstStart, CstEnd, false);
3026 
3027   // If there is function-local metadata, emit it now.
3028   writeFunctionMetadata(F);
3029 
3030   // Keep a running idea of what the instruction ID is.
3031   unsigned InstID = CstEnd;
3032 
3033   bool NeedsMetadataAttachment = F.hasMetadata();
3034 
3035   DILocation *LastDL = nullptr;
3036   // Finally, emit all the instructions, in order.
3037   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3038     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3039          I != E; ++I) {
3040       writeInstruction(*I, InstID, Vals);
3041 
3042       if (!I->getType()->isVoidTy())
3043         ++InstID;
3044 
3045       // If the instruction has metadata, write a metadata attachment later.
3046       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3047 
3048       // If the instruction has a debug location, emit it.
3049       DILocation *DL = I->getDebugLoc();
3050       if (!DL)
3051         continue;
3052 
3053       if (DL == LastDL) {
3054         // Just repeat the same debug loc as last time.
3055         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3056         continue;
3057       }
3058 
3059       Vals.push_back(DL->getLine());
3060       Vals.push_back(DL->getColumn());
3061       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3062       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3063       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3064       Vals.clear();
3065 
3066       LastDL = DL;
3067     }
3068 
3069   // Emit names for all the instructions etc.
3070   if (auto *Symtab = F.getValueSymbolTable())
3071     writeFunctionLevelValueSymbolTable(*Symtab);
3072 
3073   if (NeedsMetadataAttachment)
3074     writeFunctionMetadataAttachment(F);
3075   if (VE.shouldPreserveUseListOrder())
3076     writeUseListBlock(&F);
3077   VE.purgeFunction();
3078   Stream.ExitBlock();
3079 }
3080 
3081 // Emit blockinfo, which defines the standard abbreviations etc.
3082 void ModuleBitcodeWriter::writeBlockInfo() {
3083   // We only want to emit block info records for blocks that have multiple
3084   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3085   // Other blocks can define their abbrevs inline.
3086   Stream.EnterBlockInfoBlock();
3087 
3088   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3089     auto Abbv = std::make_shared<BitCodeAbbrev>();
3090     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3091     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3092     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3093     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3094     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3095         VST_ENTRY_8_ABBREV)
3096       llvm_unreachable("Unexpected abbrev ordering!");
3097   }
3098 
3099   { // 7-bit fixed width VST_CODE_ENTRY strings.
3100     auto Abbv = std::make_shared<BitCodeAbbrev>();
3101     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3102     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3103     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3104     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3105     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3106         VST_ENTRY_7_ABBREV)
3107       llvm_unreachable("Unexpected abbrev ordering!");
3108   }
3109   { // 6-bit char6 VST_CODE_ENTRY strings.
3110     auto Abbv = std::make_shared<BitCodeAbbrev>();
3111     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3112     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3113     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3114     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3115     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3116         VST_ENTRY_6_ABBREV)
3117       llvm_unreachable("Unexpected abbrev ordering!");
3118   }
3119   { // 6-bit char6 VST_CODE_BBENTRY strings.
3120     auto Abbv = std::make_shared<BitCodeAbbrev>();
3121     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3122     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3123     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3124     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3125     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3126         VST_BBENTRY_6_ABBREV)
3127       llvm_unreachable("Unexpected abbrev ordering!");
3128   }
3129 
3130   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3131     auto Abbv = std::make_shared<BitCodeAbbrev>();
3132     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3133     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3134                               VE.computeBitsRequiredForTypeIndicies()));
3135     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3136         CONSTANTS_SETTYPE_ABBREV)
3137       llvm_unreachable("Unexpected abbrev ordering!");
3138   }
3139 
3140   { // INTEGER abbrev for CONSTANTS_BLOCK.
3141     auto Abbv = std::make_shared<BitCodeAbbrev>();
3142     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3143     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3144     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3145         CONSTANTS_INTEGER_ABBREV)
3146       llvm_unreachable("Unexpected abbrev ordering!");
3147   }
3148 
3149   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3150     auto Abbv = std::make_shared<BitCodeAbbrev>();
3151     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3152     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3153     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3154                               VE.computeBitsRequiredForTypeIndicies()));
3155     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3156 
3157     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3158         CONSTANTS_CE_CAST_Abbrev)
3159       llvm_unreachable("Unexpected abbrev ordering!");
3160   }
3161   { // NULL abbrev for CONSTANTS_BLOCK.
3162     auto Abbv = std::make_shared<BitCodeAbbrev>();
3163     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3164     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3165         CONSTANTS_NULL_Abbrev)
3166       llvm_unreachable("Unexpected abbrev ordering!");
3167   }
3168 
3169   // FIXME: This should only use space for first class types!
3170 
3171   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3172     auto Abbv = std::make_shared<BitCodeAbbrev>();
3173     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3174     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3175     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3176                               VE.computeBitsRequiredForTypeIndicies()));
3177     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3178     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3179     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3180         FUNCTION_INST_LOAD_ABBREV)
3181       llvm_unreachable("Unexpected abbrev ordering!");
3182   }
3183   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3184     auto Abbv = std::make_shared<BitCodeAbbrev>();
3185     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3186     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3187     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3188     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3189     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3190         FUNCTION_INST_BINOP_ABBREV)
3191       llvm_unreachable("Unexpected abbrev ordering!");
3192   }
3193   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3194     auto Abbv = std::make_shared<BitCodeAbbrev>();
3195     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3196     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3197     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3198     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3199     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3200     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3201         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3202       llvm_unreachable("Unexpected abbrev ordering!");
3203   }
3204   { // INST_CAST abbrev for FUNCTION_BLOCK.
3205     auto Abbv = std::make_shared<BitCodeAbbrev>();
3206     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3207     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3208     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3209                               VE.computeBitsRequiredForTypeIndicies()));
3210     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3211     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3212         FUNCTION_INST_CAST_ABBREV)
3213       llvm_unreachable("Unexpected abbrev ordering!");
3214   }
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     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3220         FUNCTION_INST_RET_VOID_ABBREV)
3221       llvm_unreachable("Unexpected abbrev ordering!");
3222   }
3223   { // INST_RET abbrev for FUNCTION_BLOCK.
3224     auto Abbv = std::make_shared<BitCodeAbbrev>();
3225     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3226     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3227     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3228         FUNCTION_INST_RET_VAL_ABBREV)
3229       llvm_unreachable("Unexpected abbrev ordering!");
3230   }
3231   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3232     auto Abbv = std::make_shared<BitCodeAbbrev>();
3233     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3234     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3235         FUNCTION_INST_UNREACHABLE_ABBREV)
3236       llvm_unreachable("Unexpected abbrev ordering!");
3237   }
3238   {
3239     auto Abbv = std::make_shared<BitCodeAbbrev>();
3240     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3241     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3242     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3243                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3244     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3245     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3246     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3247         FUNCTION_INST_GEP_ABBREV)
3248       llvm_unreachable("Unexpected abbrev ordering!");
3249   }
3250 
3251   Stream.ExitBlock();
3252 }
3253 
3254 /// Write the module path strings, currently only used when generating
3255 /// a combined index file.
3256 void IndexBitcodeWriter::writeModStrings() {
3257   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3258 
3259   // TODO: See which abbrev sizes we actually need to emit
3260 
3261   // 8-bit fixed-width MST_ENTRY strings.
3262   auto Abbv = std::make_shared<BitCodeAbbrev>();
3263   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3264   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3265   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3266   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3267   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3268 
3269   // 7-bit fixed width MST_ENTRY strings.
3270   Abbv = std::make_shared<BitCodeAbbrev>();
3271   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3272   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3273   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3274   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3275   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3276 
3277   // 6-bit char6 MST_ENTRY strings.
3278   Abbv = std::make_shared<BitCodeAbbrev>();
3279   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3280   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3281   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3282   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3283   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3284 
3285   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3286   Abbv = std::make_shared<BitCodeAbbrev>();
3287   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3288   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3289   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3290   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3291   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3292   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3293   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3294 
3295   SmallVector<unsigned, 64> Vals;
3296   forEachModule(
3297       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3298         StringRef Key = MPSE.getKey();
3299         const auto &Value = MPSE.getValue();
3300         StringEncoding Bits = getStringEncoding(Key);
3301         unsigned AbbrevToUse = Abbrev8Bit;
3302         if (Bits == SE_Char6)
3303           AbbrevToUse = Abbrev6Bit;
3304         else if (Bits == SE_Fixed7)
3305           AbbrevToUse = Abbrev7Bit;
3306 
3307         Vals.push_back(Value.first);
3308         Vals.append(Key.begin(), Key.end());
3309 
3310         // Emit the finished record.
3311         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3312 
3313         // Emit an optional hash for the module now
3314         const auto &Hash = Value.second;
3315         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3316           Vals.assign(Hash.begin(), Hash.end());
3317           // Emit the hash record.
3318           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3319         }
3320 
3321         Vals.clear();
3322       });
3323   Stream.ExitBlock();
3324 }
3325 
3326 /// Write the function type metadata related records that need to appear before
3327 /// a function summary entry (whether per-module or combined).
3328 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3329                                              FunctionSummary *FS) {
3330   if (!FS->type_tests().empty())
3331     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3332 
3333   SmallVector<uint64_t, 64> Record;
3334 
3335   auto WriteVFuncIdVec = [&](uint64_t Ty,
3336                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3337     if (VFs.empty())
3338       return;
3339     Record.clear();
3340     for (auto &VF : VFs) {
3341       Record.push_back(VF.GUID);
3342       Record.push_back(VF.Offset);
3343     }
3344     Stream.EmitRecord(Ty, Record);
3345   };
3346 
3347   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3348                   FS->type_test_assume_vcalls());
3349   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3350                   FS->type_checked_load_vcalls());
3351 
3352   auto WriteConstVCallVec = [&](uint64_t Ty,
3353                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3354     for (auto &VC : VCs) {
3355       Record.clear();
3356       Record.push_back(VC.VFunc.GUID);
3357       Record.push_back(VC.VFunc.Offset);
3358       Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3359       Stream.EmitRecord(Ty, Record);
3360     }
3361   };
3362 
3363   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3364                      FS->type_test_assume_const_vcalls());
3365   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3366                      FS->type_checked_load_const_vcalls());
3367 }
3368 
3369 static void writeWholeProgramDevirtResolutionByArg(
3370     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3371     const WholeProgramDevirtResolution::ByArg &ByArg) {
3372   NameVals.push_back(args.size());
3373   NameVals.insert(NameVals.end(), args.begin(), args.end());
3374 
3375   NameVals.push_back(ByArg.TheKind);
3376   NameVals.push_back(ByArg.Info);
3377   NameVals.push_back(ByArg.Byte);
3378   NameVals.push_back(ByArg.Bit);
3379 }
3380 
3381 static void writeWholeProgramDevirtResolution(
3382     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3383     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3384   NameVals.push_back(Id);
3385 
3386   NameVals.push_back(Wpd.TheKind);
3387   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3388   NameVals.push_back(Wpd.SingleImplName.size());
3389 
3390   NameVals.push_back(Wpd.ResByArg.size());
3391   for (auto &A : Wpd.ResByArg)
3392     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3393 }
3394 
3395 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3396                                      StringTableBuilder &StrtabBuilder,
3397                                      const std::string &Id,
3398                                      const TypeIdSummary &Summary) {
3399   NameVals.push_back(StrtabBuilder.add(Id));
3400   NameVals.push_back(Id.size());
3401 
3402   NameVals.push_back(Summary.TTRes.TheKind);
3403   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3404   NameVals.push_back(Summary.TTRes.AlignLog2);
3405   NameVals.push_back(Summary.TTRes.SizeM1);
3406   NameVals.push_back(Summary.TTRes.BitMask);
3407   NameVals.push_back(Summary.TTRes.InlineBits);
3408 
3409   for (auto &W : Summary.WPDRes)
3410     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3411                                       W.second);
3412 }
3413 
3414 // Helper to emit a single function summary record.
3415 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3416     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3417     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3418     const Function &F) {
3419   NameVals.push_back(ValueID);
3420 
3421   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3422   writeFunctionTypeMetadataRecords(Stream, FS);
3423 
3424   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3425   NameVals.push_back(FS->instCount());
3426   NameVals.push_back(getEncodedFFlags(FS->fflags()));
3427   NameVals.push_back(FS->refs().size());
3428 
3429   for (auto &RI : FS->refs())
3430     NameVals.push_back(VE.getValueID(RI.getValue()));
3431 
3432   bool HasProfileData = F.hasProfileData();
3433   for (auto &ECI : FS->calls()) {
3434     NameVals.push_back(getValueId(ECI.first));
3435     if (HasProfileData)
3436       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3437     else if (WriteRelBFToSummary)
3438       NameVals.push_back(ECI.second.RelBlockFreq);
3439   }
3440 
3441   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3442   unsigned Code =
3443       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3444                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3445                                              : bitc::FS_PERMODULE));
3446 
3447   // Emit the finished record.
3448   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3449   NameVals.clear();
3450 }
3451 
3452 // Collect the global value references in the given variable's initializer,
3453 // and emit them in a summary record.
3454 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3455     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3456     unsigned FSModRefsAbbrev) {
3457   auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3458   if (!VI || VI.getSummaryList().empty()) {
3459     // Only declarations should not have a summary (a declaration might however
3460     // have a summary if the def was in module level asm).
3461     assert(V.isDeclaration());
3462     return;
3463   }
3464   auto *Summary = VI.getSummaryList()[0].get();
3465   NameVals.push_back(VE.getValueID(&V));
3466   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3467   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3468 
3469   unsigned SizeBeforeRefs = NameVals.size();
3470   for (auto &RI : VS->refs())
3471     NameVals.push_back(VE.getValueID(RI.getValue()));
3472   // Sort the refs for determinism output, the vector returned by FS->refs() has
3473   // been initialized from a DenseSet.
3474   std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3475 
3476   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3477                     FSModRefsAbbrev);
3478   NameVals.clear();
3479 }
3480 
3481 // Current version for the summary.
3482 // This is bumped whenever we introduce changes in the way some record are
3483 // interpreted, like flags for instance.
3484 static const uint64_t INDEX_VERSION = 4;
3485 
3486 /// Emit the per-module summary section alongside the rest of
3487 /// the module's bitcode.
3488 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3489   // By default we compile with ThinLTO if the module has a summary, but the
3490   // client can request full LTO with a module flag.
3491   bool IsThinLTO = true;
3492   if (auto *MD =
3493           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3494     IsThinLTO = MD->getZExtValue();
3495   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3496                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3497                        4);
3498 
3499   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3500 
3501   if (Index->begin() == Index->end()) {
3502     Stream.ExitBlock();
3503     return;
3504   }
3505 
3506   for (const auto &GVI : valueIds()) {
3507     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3508                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3509   }
3510 
3511   // Abbrev for FS_PERMODULE_PROFILE.
3512   auto Abbv = std::make_shared<BitCodeAbbrev>();
3513   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3514   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3515   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3516   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3517   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3518   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3519   // numrefs x valueid, n x (valueid, hotness)
3520   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3521   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3522   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3523 
3524   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3525   Abbv = std::make_shared<BitCodeAbbrev>();
3526   if (WriteRelBFToSummary)
3527     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3528   else
3529     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3530   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3531   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3532   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3533   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3534   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3535   // numrefs x valueid, n x (valueid [, rel_block_freq])
3536   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3537   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3538   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3539 
3540   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3541   Abbv = std::make_shared<BitCodeAbbrev>();
3542   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3543   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3544   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3545   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3546   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3547   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3548 
3549   // Abbrev for FS_ALIAS.
3550   Abbv = std::make_shared<BitCodeAbbrev>();
3551   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3552   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3553   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3554   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3555   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3556 
3557   SmallVector<uint64_t, 64> NameVals;
3558   // Iterate over the list of functions instead of the Index to
3559   // ensure the ordering is stable.
3560   for (const Function &F : M) {
3561     // Summary emission does not support anonymous functions, they have to
3562     // renamed using the anonymous function renaming pass.
3563     if (!F.hasName())
3564       report_fatal_error("Unexpected anonymous function when writing summary");
3565 
3566     ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3567     if (!VI || VI.getSummaryList().empty()) {
3568       // Only declarations should not have a summary (a declaration might
3569       // however have a summary if the def was in module level asm).
3570       assert(F.isDeclaration());
3571       continue;
3572     }
3573     auto *Summary = VI.getSummaryList()[0].get();
3574     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3575                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
3576   }
3577 
3578   // Capture references from GlobalVariable initializers, which are outside
3579   // of a function scope.
3580   for (const GlobalVariable &G : M.globals())
3581     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3582 
3583   for (const GlobalAlias &A : M.aliases()) {
3584     auto *Aliasee = A.getBaseObject();
3585     if (!Aliasee->hasName())
3586       // Nameless function don't have an entry in the summary, skip it.
3587       continue;
3588     auto AliasId = VE.getValueID(&A);
3589     auto AliaseeId = VE.getValueID(Aliasee);
3590     NameVals.push_back(AliasId);
3591     auto *Summary = Index->getGlobalValueSummary(A);
3592     AliasSummary *AS = cast<AliasSummary>(Summary);
3593     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3594     NameVals.push_back(AliaseeId);
3595     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3596     NameVals.clear();
3597   }
3598 
3599   Stream.ExitBlock();
3600 }
3601 
3602 /// Emit the combined summary section into the combined index file.
3603 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3604   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3605   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3606 
3607   // Write the index flags.
3608   uint64_t Flags = 0;
3609   if (Index.withGlobalValueDeadStripping())
3610     Flags |= 0x1;
3611   if (Index.skipModuleByDistributedBackend())
3612     Flags |= 0x2;
3613   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3614 
3615   for (const auto &GVI : valueIds()) {
3616     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3617                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3618   }
3619 
3620   // Abbrev for FS_COMBINED.
3621   auto Abbv = std::make_shared<BitCodeAbbrev>();
3622   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3623   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3624   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3625   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3626   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3627   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3628   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3629   // numrefs x valueid, n x (valueid)
3630   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3631   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3632   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3633 
3634   // Abbrev for FS_COMBINED_PROFILE.
3635   Abbv = std::make_shared<BitCodeAbbrev>();
3636   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3637   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3638   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3639   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3640   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3641   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3642   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3643   // numrefs x valueid, n x (valueid, hotness)
3644   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3645   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3646   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3647 
3648   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3649   Abbv = std::make_shared<BitCodeAbbrev>();
3650   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3651   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3652   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3653   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3654   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
3655   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3656   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3657 
3658   // Abbrev for FS_COMBINED_ALIAS.
3659   Abbv = std::make_shared<BitCodeAbbrev>();
3660   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3661   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3662   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3663   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3664   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3665   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3666 
3667   // The aliases are emitted as a post-pass, and will point to the value
3668   // id of the aliasee. Save them in a vector for post-processing.
3669   SmallVector<AliasSummary *, 64> Aliases;
3670 
3671   // Save the value id for each summary for alias emission.
3672   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3673 
3674   SmallVector<uint64_t, 64> NameVals;
3675 
3676   // For local linkage, we also emit the original name separately
3677   // immediately after the record.
3678   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3679     if (!GlobalValue::isLocalLinkage(S.linkage()))
3680       return;
3681     NameVals.push_back(S.getOriginalName());
3682     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3683     NameVals.clear();
3684   };
3685 
3686   forEachSummary([&](GVInfo I, bool IsAliasee) {
3687     GlobalValueSummary *S = I.second;
3688     assert(S);
3689 
3690     auto ValueId = getValueId(I.first);
3691     assert(ValueId);
3692     SummaryToValueIdMap[S] = *ValueId;
3693 
3694     // If this is invoked for an aliasee, we want to record the above
3695     // mapping, but then not emit a summary entry (if the aliasee is
3696     // to be imported, we will invoke this separately with IsAliasee=false).
3697     if (IsAliasee)
3698       return;
3699 
3700     if (auto *AS = dyn_cast<AliasSummary>(S)) {
3701       // Will process aliases as a post-pass because the reader wants all
3702       // global to be loaded first.
3703       Aliases.push_back(AS);
3704       return;
3705     }
3706 
3707     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3708       NameVals.push_back(*ValueId);
3709       NameVals.push_back(Index.getModuleId(VS->modulePath()));
3710       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3711       for (auto &RI : VS->refs()) {
3712         auto RefValueId = getValueId(RI.getGUID());
3713         if (!RefValueId)
3714           continue;
3715         NameVals.push_back(*RefValueId);
3716       }
3717 
3718       // Emit the finished record.
3719       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3720                         FSModRefsAbbrev);
3721       NameVals.clear();
3722       MaybeEmitOriginalName(*S);
3723       return;
3724     }
3725 
3726     auto *FS = cast<FunctionSummary>(S);
3727     writeFunctionTypeMetadataRecords(Stream, FS);
3728 
3729     NameVals.push_back(*ValueId);
3730     NameVals.push_back(Index.getModuleId(FS->modulePath()));
3731     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3732     NameVals.push_back(FS->instCount());
3733     NameVals.push_back(getEncodedFFlags(FS->fflags()));
3734     // Fill in below
3735     NameVals.push_back(0);
3736 
3737     unsigned Count = 0;
3738     for (auto &RI : FS->refs()) {
3739       auto RefValueId = getValueId(RI.getGUID());
3740       if (!RefValueId)
3741         continue;
3742       NameVals.push_back(*RefValueId);
3743       Count++;
3744     }
3745     NameVals[5] = Count;
3746 
3747     bool HasProfileData = false;
3748     for (auto &EI : FS->calls()) {
3749       HasProfileData |=
3750           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
3751       if (HasProfileData)
3752         break;
3753     }
3754 
3755     for (auto &EI : FS->calls()) {
3756       // If this GUID doesn't have a value id, it doesn't have a function
3757       // summary and we don't need to record any calls to it.
3758       GlobalValue::GUID GUID = EI.first.getGUID();
3759       auto CallValueId = getValueId(GUID);
3760       if (!CallValueId) {
3761         // For SamplePGO, the indirect call targets for local functions will
3762         // have its original name annotated in profile. We try to find the
3763         // corresponding PGOFuncName as the GUID.
3764         GUID = Index.getGUIDFromOriginalID(GUID);
3765         if (GUID == 0)
3766           continue;
3767         CallValueId = getValueId(GUID);
3768         if (!CallValueId)
3769           continue;
3770         // The mapping from OriginalId to GUID may return a GUID
3771         // that corresponds to a static variable. Filter it out here.
3772         // This can happen when
3773         // 1) There is a call to a library function which does not have
3774         // a CallValidId;
3775         // 2) There is a static variable with the  OriginalGUID identical
3776         // to the GUID of the library function in 1);
3777         // When this happens, the logic for SamplePGO kicks in and
3778         // the static variable in 2) will be found, which needs to be
3779         // filtered out.
3780         auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3781         if (GVSum &&
3782             GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3783           continue;
3784       }
3785       NameVals.push_back(*CallValueId);
3786       if (HasProfileData)
3787         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3788     }
3789 
3790     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3791     unsigned Code =
3792         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3793 
3794     // Emit the finished record.
3795     Stream.EmitRecord(Code, NameVals, FSAbbrev);
3796     NameVals.clear();
3797     MaybeEmitOriginalName(*S);
3798   });
3799 
3800   for (auto *AS : Aliases) {
3801     auto AliasValueId = SummaryToValueIdMap[AS];
3802     assert(AliasValueId);
3803     NameVals.push_back(AliasValueId);
3804     NameVals.push_back(Index.getModuleId(AS->modulePath()));
3805     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3806     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3807     assert(AliaseeValueId);
3808     NameVals.push_back(AliaseeValueId);
3809 
3810     // Emit the finished record.
3811     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3812     NameVals.clear();
3813     MaybeEmitOriginalName(*AS);
3814   }
3815 
3816   if (!Index.cfiFunctionDefs().empty()) {
3817     for (auto &S : Index.cfiFunctionDefs()) {
3818       NameVals.push_back(StrtabBuilder.add(S));
3819       NameVals.push_back(S.size());
3820     }
3821     Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3822     NameVals.clear();
3823   }
3824 
3825   if (!Index.cfiFunctionDecls().empty()) {
3826     for (auto &S : Index.cfiFunctionDecls()) {
3827       NameVals.push_back(StrtabBuilder.add(S));
3828       NameVals.push_back(S.size());
3829     }
3830     Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3831     NameVals.clear();
3832   }
3833 
3834   if (!Index.typeIds().empty()) {
3835     for (auto &S : Index.typeIds()) {
3836       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, S.first, S.second);
3837       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
3838       NameVals.clear();
3839     }
3840   }
3841 
3842   Stream.ExitBlock();
3843 }
3844 
3845 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3846 /// current llvm version, and a record for the epoch number.
3847 static void writeIdentificationBlock(BitstreamWriter &Stream) {
3848   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3849 
3850   // Write the "user readable" string identifying the bitcode producer
3851   auto Abbv = std::make_shared<BitCodeAbbrev>();
3852   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3853   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3854   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3855   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3856   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3857                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
3858 
3859   // Write the epoch version
3860   Abbv = std::make_shared<BitCodeAbbrev>();
3861   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3862   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3863   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3864   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3865   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3866   Stream.ExitBlock();
3867 }
3868 
3869 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3870   // Emit the module's hash.
3871   // MODULE_CODE_HASH: [5*i32]
3872   if (GenerateHash) {
3873     uint32_t Vals[5];
3874     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3875                                     Buffer.size() - BlockStartPos));
3876     StringRef Hash = Hasher.result();
3877     for (int Pos = 0; Pos < 20; Pos += 4) {
3878       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3879     }
3880 
3881     // Emit the finished record.
3882     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3883 
3884     if (ModHash)
3885       // Save the written hash value.
3886       std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3887   }
3888 }
3889 
3890 void ModuleBitcodeWriter::write() {
3891   writeIdentificationBlock(Stream);
3892 
3893   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3894   size_t BlockStartPos = Buffer.size();
3895 
3896   writeModuleVersion();
3897 
3898   // Emit blockinfo, which defines the standard abbreviations etc.
3899   writeBlockInfo();
3900 
3901   // Emit information about attribute groups.
3902   writeAttributeGroupTable();
3903 
3904   // Emit information about parameter attributes.
3905   writeAttributeTable();
3906 
3907   // Emit information describing all of the types in the module.
3908   writeTypeTable();
3909 
3910   writeComdats();
3911 
3912   // Emit top-level description of module, including target triple, inline asm,
3913   // descriptors for global variables, and function prototype info.
3914   writeModuleInfo();
3915 
3916   // Emit constants.
3917   writeModuleConstants();
3918 
3919   // Emit metadata kind names.
3920   writeModuleMetadataKinds();
3921 
3922   // Emit metadata.
3923   writeModuleMetadata();
3924 
3925   // Emit module-level use-lists.
3926   if (VE.shouldPreserveUseListOrder())
3927     writeUseListBlock(nullptr);
3928 
3929   writeOperandBundleTags();
3930   writeSyncScopeNames();
3931 
3932   // Emit function bodies.
3933   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3934   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3935     if (!F->isDeclaration())
3936       writeFunction(*F, FunctionToBitcodeIndex);
3937 
3938   // Need to write after the above call to WriteFunction which populates
3939   // the summary information in the index.
3940   if (Index)
3941     writePerModuleGlobalValueSummary();
3942 
3943   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
3944 
3945   writeModuleHash(BlockStartPos);
3946 
3947   Stream.ExitBlock();
3948 }
3949 
3950 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3951                                uint32_t &Position) {
3952   support::endian::write32le(&Buffer[Position], Value);
3953   Position += 4;
3954 }
3955 
3956 /// If generating a bc file on darwin, we have to emit a
3957 /// header and trailer to make it compatible with the system archiver.  To do
3958 /// this we emit the following header, and then emit a trailer that pads the
3959 /// file out to be a multiple of 16 bytes.
3960 ///
3961 /// struct bc_header {
3962 ///   uint32_t Magic;         // 0x0B17C0DE
3963 ///   uint32_t Version;       // Version, currently always 0.
3964 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3965 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
3966 ///   uint32_t CPUType;       // CPU specifier.
3967 ///   ... potentially more later ...
3968 /// };
3969 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3970                                          const Triple &TT) {
3971   unsigned CPUType = ~0U;
3972 
3973   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3974   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3975   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
3976   // specific constants here because they are implicitly part of the Darwin ABI.
3977   enum {
3978     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
3979     DARWIN_CPU_TYPE_X86        = 7,
3980     DARWIN_CPU_TYPE_ARM        = 12,
3981     DARWIN_CPU_TYPE_POWERPC    = 18
3982   };
3983 
3984   Triple::ArchType Arch = TT.getArch();
3985   if (Arch == Triple::x86_64)
3986     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3987   else if (Arch == Triple::x86)
3988     CPUType = DARWIN_CPU_TYPE_X86;
3989   else if (Arch == Triple::ppc)
3990     CPUType = DARWIN_CPU_TYPE_POWERPC;
3991   else if (Arch == Triple::ppc64)
3992     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3993   else if (Arch == Triple::arm || Arch == Triple::thumb)
3994     CPUType = DARWIN_CPU_TYPE_ARM;
3995 
3996   // Traditional Bitcode starts after header.
3997   assert(Buffer.size() >= BWH_HeaderSize &&
3998          "Expected header size to be reserved");
3999   unsigned BCOffset = BWH_HeaderSize;
4000   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4001 
4002   // Write the magic and version.
4003   unsigned Position = 0;
4004   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4005   writeInt32ToBuffer(0, Buffer, Position); // Version.
4006   writeInt32ToBuffer(BCOffset, Buffer, Position);
4007   writeInt32ToBuffer(BCSize, Buffer, Position);
4008   writeInt32ToBuffer(CPUType, Buffer, Position);
4009 
4010   // If the file is not a multiple of 16 bytes, insert dummy padding.
4011   while (Buffer.size() & 15)
4012     Buffer.push_back(0);
4013 }
4014 
4015 /// Helper to write the header common to all bitcode files.
4016 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4017   // Emit the file header.
4018   Stream.Emit((unsigned)'B', 8);
4019   Stream.Emit((unsigned)'C', 8);
4020   Stream.Emit(0x0, 4);
4021   Stream.Emit(0xC, 4);
4022   Stream.Emit(0xE, 4);
4023   Stream.Emit(0xD, 4);
4024 }
4025 
4026 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4027     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4028   writeBitcodeHeader(*Stream);
4029 }
4030 
4031 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4032 
4033 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4034   Stream->EnterSubblock(Block, 3);
4035 
4036   auto Abbv = std::make_shared<BitCodeAbbrev>();
4037   Abbv->Add(BitCodeAbbrevOp(Record));
4038   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4039   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4040 
4041   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4042 
4043   Stream->ExitBlock();
4044 }
4045 
4046 void BitcodeWriter::writeSymtab() {
4047   assert(!WroteStrtab && !WroteSymtab);
4048 
4049   // If any module has module-level inline asm, we will require a registered asm
4050   // parser for the target so that we can create an accurate symbol table for
4051   // the module.
4052   for (Module *M : Mods) {
4053     if (M->getModuleInlineAsm().empty())
4054       continue;
4055 
4056     std::string Err;
4057     const Triple TT(M->getTargetTriple());
4058     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4059     if (!T || !T->hasMCAsmParser())
4060       return;
4061   }
4062 
4063   WroteSymtab = true;
4064   SmallVector<char, 0> Symtab;
4065   // The irsymtab::build function may be unable to create a symbol table if the
4066   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4067   // table is not required for correctness, but we still want to be able to
4068   // write malformed modules to bitcode files, so swallow the error.
4069   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4070     consumeError(std::move(E));
4071     return;
4072   }
4073 
4074   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4075             {Symtab.data(), Symtab.size()});
4076 }
4077 
4078 void BitcodeWriter::writeStrtab() {
4079   assert(!WroteStrtab);
4080 
4081   std::vector<char> Strtab;
4082   StrtabBuilder.finalizeInOrder();
4083   Strtab.resize(StrtabBuilder.getSize());
4084   StrtabBuilder.write((uint8_t *)Strtab.data());
4085 
4086   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4087             {Strtab.data(), Strtab.size()});
4088 
4089   WroteStrtab = true;
4090 }
4091 
4092 void BitcodeWriter::copyStrtab(StringRef Strtab) {
4093   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4094   WroteStrtab = true;
4095 }
4096 
4097 void BitcodeWriter::writeModule(const Module &M,
4098                                 bool ShouldPreserveUseListOrder,
4099                                 const ModuleSummaryIndex *Index,
4100                                 bool GenerateHash, ModuleHash *ModHash) {
4101   assert(!WroteStrtab);
4102 
4103   // The Mods vector is used by irsymtab::build, which requires non-const
4104   // Modules in case it needs to materialize metadata. But the bitcode writer
4105   // requires that the module is materialized, so we can cast to non-const here,
4106   // after checking that it is in fact materialized.
4107   assert(M.isMaterialized());
4108   Mods.push_back(const_cast<Module *>(&M));
4109 
4110   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4111                                    ShouldPreserveUseListOrder, Index,
4112                                    GenerateHash, ModHash);
4113   ModuleWriter.write();
4114 }
4115 
4116 void BitcodeWriter::writeIndex(
4117     const ModuleSummaryIndex *Index,
4118     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4119   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4120                                  ModuleToSummariesForIndex);
4121   IndexWriter.write();
4122 }
4123 
4124 /// Write the specified module to the specified output stream.
4125 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4126                               bool ShouldPreserveUseListOrder,
4127                               const ModuleSummaryIndex *Index,
4128                               bool GenerateHash, ModuleHash *ModHash) {
4129   SmallVector<char, 0> Buffer;
4130   Buffer.reserve(256*1024);
4131 
4132   // If this is darwin or another generic macho target, reserve space for the
4133   // header.
4134   Triple TT(M.getTargetTriple());
4135   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4136     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4137 
4138   BitcodeWriter Writer(Buffer);
4139   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4140                      ModHash);
4141   Writer.writeSymtab();
4142   Writer.writeStrtab();
4143 
4144   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4145     emitDarwinBCHeaderAndTrailer(Buffer, TT);
4146 
4147   // Write the generated bitstream to "Out".
4148   Out.write((char*)&Buffer.front(), Buffer.size());
4149 }
4150 
4151 void IndexBitcodeWriter::write() {
4152   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4153 
4154   writeModuleVersion();
4155 
4156   // Write the module paths in the combined index.
4157   writeModStrings();
4158 
4159   // Write the summary combined index records.
4160   writeCombinedGlobalValueSummary();
4161 
4162   Stream.ExitBlock();
4163 }
4164 
4165 // Write the specified module summary index to the given raw output stream,
4166 // where it will be written in a new bitcode block. This is used when
4167 // writing the combined index file for ThinLTO. When writing a subset of the
4168 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4169 void llvm::WriteIndexToFile(
4170     const ModuleSummaryIndex &Index, raw_ostream &Out,
4171     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4172   SmallVector<char, 0> Buffer;
4173   Buffer.reserve(256 * 1024);
4174 
4175   BitcodeWriter Writer(Buffer);
4176   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4177   Writer.writeStrtab();
4178 
4179   Out.write((char *)&Buffer.front(), Buffer.size());
4180 }
4181 
4182 namespace {
4183 
4184 /// Class to manage the bitcode writing for a thin link bitcode file.
4185 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4186   /// ModHash is for use in ThinLTO incremental build, generated while writing
4187   /// the module bitcode file.
4188   const ModuleHash *ModHash;
4189 
4190 public:
4191   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4192                         BitstreamWriter &Stream,
4193                         const ModuleSummaryIndex &Index,
4194                         const ModuleHash &ModHash)
4195       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4196                                 /*ShouldPreserveUseListOrder=*/false, &Index),
4197         ModHash(&ModHash) {}
4198 
4199   void write();
4200 
4201 private:
4202   void writeSimplifiedModuleInfo();
4203 };
4204 
4205 } // end anonymous namespace
4206 
4207 // This function writes a simpilified module info for thin link bitcode file.
4208 // It only contains the source file name along with the name(the offset and
4209 // size in strtab) and linkage for global values. For the global value info
4210 // entry, in order to keep linkage at offset 5, there are three zeros used
4211 // as padding.
4212 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4213   SmallVector<unsigned, 64> Vals;
4214   // Emit the module's source file name.
4215   {
4216     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4217     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4218     if (Bits == SE_Char6)
4219       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4220     else if (Bits == SE_Fixed7)
4221       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4222 
4223     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4224     auto Abbv = std::make_shared<BitCodeAbbrev>();
4225     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4226     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4227     Abbv->Add(AbbrevOpToUse);
4228     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4229 
4230     for (const auto P : M.getSourceFileName())
4231       Vals.push_back((unsigned char)P);
4232 
4233     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4234     Vals.clear();
4235   }
4236 
4237   // Emit the global variable information.
4238   for (const GlobalVariable &GV : M.globals()) {
4239     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4240     Vals.push_back(StrtabBuilder.add(GV.getName()));
4241     Vals.push_back(GV.getName().size());
4242     Vals.push_back(0);
4243     Vals.push_back(0);
4244     Vals.push_back(0);
4245     Vals.push_back(getEncodedLinkage(GV));
4246 
4247     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4248     Vals.clear();
4249   }
4250 
4251   // Emit the function proto information.
4252   for (const Function &F : M) {
4253     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
4254     Vals.push_back(StrtabBuilder.add(F.getName()));
4255     Vals.push_back(F.getName().size());
4256     Vals.push_back(0);
4257     Vals.push_back(0);
4258     Vals.push_back(0);
4259     Vals.push_back(getEncodedLinkage(F));
4260 
4261     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4262     Vals.clear();
4263   }
4264 
4265   // Emit the alias information.
4266   for (const GlobalAlias &A : M.aliases()) {
4267     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4268     Vals.push_back(StrtabBuilder.add(A.getName()));
4269     Vals.push_back(A.getName().size());
4270     Vals.push_back(0);
4271     Vals.push_back(0);
4272     Vals.push_back(0);
4273     Vals.push_back(getEncodedLinkage(A));
4274 
4275     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4276     Vals.clear();
4277   }
4278 
4279   // Emit the ifunc information.
4280   for (const GlobalIFunc &I : M.ifuncs()) {
4281     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4282     Vals.push_back(StrtabBuilder.add(I.getName()));
4283     Vals.push_back(I.getName().size());
4284     Vals.push_back(0);
4285     Vals.push_back(0);
4286     Vals.push_back(0);
4287     Vals.push_back(getEncodedLinkage(I));
4288 
4289     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4290     Vals.clear();
4291   }
4292 }
4293 
4294 void ThinLinkBitcodeWriter::write() {
4295   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4296 
4297   writeModuleVersion();
4298 
4299   writeSimplifiedModuleInfo();
4300 
4301   writePerModuleGlobalValueSummary();
4302 
4303   // Write module hash.
4304   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4305 
4306   Stream.ExitBlock();
4307 }
4308 
4309 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4310                                          const ModuleSummaryIndex &Index,
4311                                          const ModuleHash &ModHash) {
4312   assert(!WroteStrtab);
4313 
4314   // The Mods vector is used by irsymtab::build, which requires non-const
4315   // Modules in case it needs to materialize metadata. But the bitcode writer
4316   // requires that the module is materialized, so we can cast to non-const here,
4317   // after checking that it is in fact materialized.
4318   assert(M.isMaterialized());
4319   Mods.push_back(const_cast<Module *>(&M));
4320 
4321   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4322                                        ModHash);
4323   ThinLinkWriter.write();
4324 }
4325 
4326 // Write the specified thin link bitcode file to the given raw output stream,
4327 // where it will be written in a new bitcode block. This is used when
4328 // writing the per-module index file for ThinLTO.
4329 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4330                                       const ModuleSummaryIndex &Index,
4331                                       const ModuleHash &ModHash) {
4332   SmallVector<char, 0> Buffer;
4333   Buffer.reserve(256 * 1024);
4334 
4335   BitcodeWriter Writer(Buffer);
4336   Writer.writeThinLinkBitcode(M, Index, ModHash);
4337   Writer.writeSymtab();
4338   Writer.writeStrtab();
4339 
4340   Out.write((char *)&Buffer.front(), Buffer.size());
4341 }
4342