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