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