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