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