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