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