xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 31fda09b2db405bbaa225bb6068c5f787506b9db)
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         GV.hasPartition()) {
1267       Vals.push_back(getEncodedVisibility(GV));
1268       Vals.push_back(getEncodedThreadLocalMode(GV));
1269       Vals.push_back(getEncodedUnnamedAddr(GV));
1270       Vals.push_back(GV.isExternallyInitialized());
1271       Vals.push_back(getEncodedDLLStorageClass(GV));
1272       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1273 
1274       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1275       Vals.push_back(VE.getAttributeListID(AL));
1276 
1277       Vals.push_back(GV.isDSOLocal());
1278       Vals.push_back(addToStrtab(GV.getPartition()));
1279       Vals.push_back(GV.getPartition().size());
1280     } else {
1281       AbbrevToUse = SimpleGVarAbbrev;
1282     }
1283 
1284     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1285     Vals.clear();
1286   }
1287 
1288   // Emit the function proto information.
1289   for (const Function &F : M) {
1290     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
1291     //             linkage, paramattrs, alignment, section, visibility, gc,
1292     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
1293     //             prefixdata, personalityfn, DSO_Local, addrspace]
1294     Vals.push_back(addToStrtab(F.getName()));
1295     Vals.push_back(F.getName().size());
1296     Vals.push_back(VE.getTypeID(F.getFunctionType()));
1297     Vals.push_back(F.getCallingConv());
1298     Vals.push_back(F.isDeclaration());
1299     Vals.push_back(getEncodedLinkage(F));
1300     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1301     Vals.push_back(Log2_32(F.getAlignment())+1);
1302     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1303     Vals.push_back(getEncodedVisibility(F));
1304     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1305     Vals.push_back(getEncodedUnnamedAddr(F));
1306     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1307                                        : 0);
1308     Vals.push_back(getEncodedDLLStorageClass(F));
1309     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1310     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1311                                      : 0);
1312     Vals.push_back(
1313         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1314 
1315     Vals.push_back(F.isDSOLocal());
1316     Vals.push_back(F.getAddressSpace());
1317     Vals.push_back(addToStrtab(F.getPartition()));
1318     Vals.push_back(F.getPartition().size());
1319 
1320     unsigned AbbrevToUse = 0;
1321     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1322     Vals.clear();
1323   }
1324 
1325   // Emit the alias information.
1326   for (const GlobalAlias &A : M.aliases()) {
1327     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1328     //         visibility, dllstorageclass, threadlocal, unnamed_addr,
1329     //         DSO_Local]
1330     Vals.push_back(addToStrtab(A.getName()));
1331     Vals.push_back(A.getName().size());
1332     Vals.push_back(VE.getTypeID(A.getValueType()));
1333     Vals.push_back(A.getType()->getAddressSpace());
1334     Vals.push_back(VE.getValueID(A.getAliasee()));
1335     Vals.push_back(getEncodedLinkage(A));
1336     Vals.push_back(getEncodedVisibility(A));
1337     Vals.push_back(getEncodedDLLStorageClass(A));
1338     Vals.push_back(getEncodedThreadLocalMode(A));
1339     Vals.push_back(getEncodedUnnamedAddr(A));
1340     Vals.push_back(A.isDSOLocal());
1341     Vals.push_back(addToStrtab(A.getPartition()));
1342     Vals.push_back(A.getPartition().size());
1343 
1344     unsigned AbbrevToUse = 0;
1345     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1346     Vals.clear();
1347   }
1348 
1349   // Emit the ifunc information.
1350   for (const GlobalIFunc &I : M.ifuncs()) {
1351     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1352     //         val#, linkage, visibility, DSO_Local]
1353     Vals.push_back(addToStrtab(I.getName()));
1354     Vals.push_back(I.getName().size());
1355     Vals.push_back(VE.getTypeID(I.getValueType()));
1356     Vals.push_back(I.getType()->getAddressSpace());
1357     Vals.push_back(VE.getValueID(I.getResolver()));
1358     Vals.push_back(getEncodedLinkage(I));
1359     Vals.push_back(getEncodedVisibility(I));
1360     Vals.push_back(I.isDSOLocal());
1361     Vals.push_back(addToStrtab(I.getPartition()));
1362     Vals.push_back(I.getPartition().size());
1363     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1364     Vals.clear();
1365   }
1366 
1367   writeValueSymbolTableForwardDecl();
1368 }
1369 
1370 static uint64_t getOptimizationFlags(const Value *V) {
1371   uint64_t Flags = 0;
1372 
1373   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1374     if (OBO->hasNoSignedWrap())
1375       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1376     if (OBO->hasNoUnsignedWrap())
1377       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1378   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1379     if (PEO->isExact())
1380       Flags |= 1 << bitc::PEO_EXACT;
1381   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1382     if (FPMO->hasAllowReassoc())
1383       Flags |= bitc::AllowReassoc;
1384     if (FPMO->hasNoNaNs())
1385       Flags |= bitc::NoNaNs;
1386     if (FPMO->hasNoInfs())
1387       Flags |= bitc::NoInfs;
1388     if (FPMO->hasNoSignedZeros())
1389       Flags |= bitc::NoSignedZeros;
1390     if (FPMO->hasAllowReciprocal())
1391       Flags |= bitc::AllowReciprocal;
1392     if (FPMO->hasAllowContract())
1393       Flags |= bitc::AllowContract;
1394     if (FPMO->hasApproxFunc())
1395       Flags |= bitc::ApproxFunc;
1396   }
1397 
1398   return Flags;
1399 }
1400 
1401 void ModuleBitcodeWriter::writeValueAsMetadata(
1402     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1403   // Mimic an MDNode with a value as one operand.
1404   Value *V = MD->getValue();
1405   Record.push_back(VE.getTypeID(V->getType()));
1406   Record.push_back(VE.getValueID(V));
1407   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1408   Record.clear();
1409 }
1410 
1411 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1412                                        SmallVectorImpl<uint64_t> &Record,
1413                                        unsigned Abbrev) {
1414   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1415     Metadata *MD = N->getOperand(i);
1416     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1417            "Unexpected function-local metadata");
1418     Record.push_back(VE.getMetadataOrNullID(MD));
1419   }
1420   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1421                                     : bitc::METADATA_NODE,
1422                     Record, Abbrev);
1423   Record.clear();
1424 }
1425 
1426 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1427   // Assume the column is usually under 128, and always output the inlined-at
1428   // location (it's never more expensive than building an array size 1).
1429   auto Abbv = std::make_shared<BitCodeAbbrev>();
1430   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1431   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1432   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1433   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1434   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1435   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1436   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1437   return Stream.EmitAbbrev(std::move(Abbv));
1438 }
1439 
1440 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1441                                           SmallVectorImpl<uint64_t> &Record,
1442                                           unsigned &Abbrev) {
1443   if (!Abbrev)
1444     Abbrev = createDILocationAbbrev();
1445 
1446   Record.push_back(N->isDistinct());
1447   Record.push_back(N->getLine());
1448   Record.push_back(N->getColumn());
1449   Record.push_back(VE.getMetadataID(N->getScope()));
1450   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1451   Record.push_back(N->isImplicitCode());
1452 
1453   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1454   Record.clear();
1455 }
1456 
1457 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1458   // Assume the column is usually under 128, and always output the inlined-at
1459   // location (it's never more expensive than building an array size 1).
1460   auto Abbv = std::make_shared<BitCodeAbbrev>();
1461   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1462   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1463   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1464   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1465   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1466   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1467   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1468   return Stream.EmitAbbrev(std::move(Abbv));
1469 }
1470 
1471 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1472                                              SmallVectorImpl<uint64_t> &Record,
1473                                              unsigned &Abbrev) {
1474   if (!Abbrev)
1475     Abbrev = createGenericDINodeAbbrev();
1476 
1477   Record.push_back(N->isDistinct());
1478   Record.push_back(N->getTag());
1479   Record.push_back(0); // Per-tag version field; unused for now.
1480 
1481   for (auto &I : N->operands())
1482     Record.push_back(VE.getMetadataOrNullID(I));
1483 
1484   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1485   Record.clear();
1486 }
1487 
1488 static uint64_t rotateSign(int64_t I) {
1489   uint64_t U = I;
1490   return I < 0 ? ~(U << 1) : U << 1;
1491 }
1492 
1493 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1494                                           SmallVectorImpl<uint64_t> &Record,
1495                                           unsigned Abbrev) {
1496   const uint64_t Version = 1 << 1;
1497   Record.push_back((uint64_t)N->isDistinct() | Version);
1498   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1499   Record.push_back(rotateSign(N->getLowerBound()));
1500 
1501   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1502   Record.clear();
1503 }
1504 
1505 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1506                                             SmallVectorImpl<uint64_t> &Record,
1507                                             unsigned Abbrev) {
1508   Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
1509   Record.push_back(rotateSign(N->getValue()));
1510   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1511 
1512   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1513   Record.clear();
1514 }
1515 
1516 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1517                                            SmallVectorImpl<uint64_t> &Record,
1518                                            unsigned Abbrev) {
1519   Record.push_back(N->isDistinct());
1520   Record.push_back(N->getTag());
1521   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1522   Record.push_back(N->getSizeInBits());
1523   Record.push_back(N->getAlignInBits());
1524   Record.push_back(N->getEncoding());
1525   Record.push_back(N->getFlags());
1526 
1527   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1528   Record.clear();
1529 }
1530 
1531 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1532                                              SmallVectorImpl<uint64_t> &Record,
1533                                              unsigned Abbrev) {
1534   Record.push_back(N->isDistinct());
1535   Record.push_back(N->getTag());
1536   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1537   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1538   Record.push_back(N->getLine());
1539   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1540   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1541   Record.push_back(N->getSizeInBits());
1542   Record.push_back(N->getAlignInBits());
1543   Record.push_back(N->getOffsetInBits());
1544   Record.push_back(N->getFlags());
1545   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1546 
1547   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1548   // that there is no DWARF address space associated with DIDerivedType.
1549   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1550     Record.push_back(*DWARFAddressSpace + 1);
1551   else
1552     Record.push_back(0);
1553 
1554   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1555   Record.clear();
1556 }
1557 
1558 void ModuleBitcodeWriter::writeDICompositeType(
1559     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1560     unsigned Abbrev) {
1561   const unsigned IsNotUsedInOldTypeRef = 0x2;
1562   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1563   Record.push_back(N->getTag());
1564   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1565   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1566   Record.push_back(N->getLine());
1567   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1568   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1569   Record.push_back(N->getSizeInBits());
1570   Record.push_back(N->getAlignInBits());
1571   Record.push_back(N->getOffsetInBits());
1572   Record.push_back(N->getFlags());
1573   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1574   Record.push_back(N->getRuntimeLang());
1575   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1576   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1577   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1578   Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1579 
1580   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1581   Record.clear();
1582 }
1583 
1584 void ModuleBitcodeWriter::writeDISubroutineType(
1585     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1586     unsigned Abbrev) {
1587   const unsigned HasNoOldTypeRefs = 0x2;
1588   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1589   Record.push_back(N->getFlags());
1590   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1591   Record.push_back(N->getCC());
1592 
1593   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1594   Record.clear();
1595 }
1596 
1597 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1598                                       SmallVectorImpl<uint64_t> &Record,
1599                                       unsigned Abbrev) {
1600   Record.push_back(N->isDistinct());
1601   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1602   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1603   if (N->getRawChecksum()) {
1604     Record.push_back(N->getRawChecksum()->Kind);
1605     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1606   } else {
1607     // Maintain backwards compatibility with the old internal representation of
1608     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1609     Record.push_back(0);
1610     Record.push_back(VE.getMetadataOrNullID(nullptr));
1611   }
1612   auto Source = N->getRawSource();
1613   if (Source)
1614     Record.push_back(VE.getMetadataOrNullID(*Source));
1615 
1616   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1617   Record.clear();
1618 }
1619 
1620 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1621                                              SmallVectorImpl<uint64_t> &Record,
1622                                              unsigned Abbrev) {
1623   assert(N->isDistinct() && "Expected distinct compile units");
1624   Record.push_back(/* IsDistinct */ true);
1625   Record.push_back(N->getSourceLanguage());
1626   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1627   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1628   Record.push_back(N->isOptimized());
1629   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1630   Record.push_back(N->getRuntimeVersion());
1631   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1632   Record.push_back(N->getEmissionKind());
1633   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1634   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1635   Record.push_back(/* subprograms */ 0);
1636   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1637   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1638   Record.push_back(N->getDWOId());
1639   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1640   Record.push_back(N->getSplitDebugInlining());
1641   Record.push_back(N->getDebugInfoForProfiling());
1642   Record.push_back((unsigned)N->getNameTableKind());
1643 
1644   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1645   Record.clear();
1646 }
1647 
1648 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1649                                             SmallVectorImpl<uint64_t> &Record,
1650                                             unsigned Abbrev) {
1651   const uint64_t HasUnitFlag = 1 << 1;
1652   const uint64_t HasSPFlagsFlag = 1 << 2;
1653   Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1654   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1655   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1656   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1657   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1658   Record.push_back(N->getLine());
1659   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1660   Record.push_back(N->getScopeLine());
1661   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1662   Record.push_back(N->getSPFlags());
1663   Record.push_back(N->getVirtualIndex());
1664   Record.push_back(N->getFlags());
1665   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1666   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1667   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1668   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1669   Record.push_back(N->getThisAdjustment());
1670   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1671 
1672   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1673   Record.clear();
1674 }
1675 
1676 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1677                                               SmallVectorImpl<uint64_t> &Record,
1678                                               unsigned Abbrev) {
1679   Record.push_back(N->isDistinct());
1680   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1681   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1682   Record.push_back(N->getLine());
1683   Record.push_back(N->getColumn());
1684 
1685   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1686   Record.clear();
1687 }
1688 
1689 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1690     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1691     unsigned Abbrev) {
1692   Record.push_back(N->isDistinct());
1693   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1694   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1695   Record.push_back(N->getDiscriminator());
1696 
1697   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1698   Record.clear();
1699 }
1700 
1701 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
1702                                              SmallVectorImpl<uint64_t> &Record,
1703                                              unsigned Abbrev) {
1704   Record.push_back(N->isDistinct());
1705   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1706   Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1707   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1708   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1709   Record.push_back(N->getLineNo());
1710 
1711   Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
1712   Record.clear();
1713 }
1714 
1715 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1716                                            SmallVectorImpl<uint64_t> &Record,
1717                                            unsigned Abbrev) {
1718   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1719   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1720   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1721 
1722   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1723   Record.clear();
1724 }
1725 
1726 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1727                                        SmallVectorImpl<uint64_t> &Record,
1728                                        unsigned Abbrev) {
1729   Record.push_back(N->isDistinct());
1730   Record.push_back(N->getMacinfoType());
1731   Record.push_back(N->getLine());
1732   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1733   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1734 
1735   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1736   Record.clear();
1737 }
1738 
1739 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1740                                            SmallVectorImpl<uint64_t> &Record,
1741                                            unsigned Abbrev) {
1742   Record.push_back(N->isDistinct());
1743   Record.push_back(N->getMacinfoType());
1744   Record.push_back(N->getLine());
1745   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1746   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1747 
1748   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1749   Record.clear();
1750 }
1751 
1752 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1753                                         SmallVectorImpl<uint64_t> &Record,
1754                                         unsigned Abbrev) {
1755   Record.push_back(N->isDistinct());
1756   for (auto &I : N->operands())
1757     Record.push_back(VE.getMetadataOrNullID(I));
1758 
1759   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1760   Record.clear();
1761 }
1762 
1763 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1764     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1765     unsigned Abbrev) {
1766   Record.push_back(N->isDistinct());
1767   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1768   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1769 
1770   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1771   Record.clear();
1772 }
1773 
1774 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1775     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1776     unsigned Abbrev) {
1777   Record.push_back(N->isDistinct());
1778   Record.push_back(N->getTag());
1779   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1780   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1781   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1782 
1783   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1784   Record.clear();
1785 }
1786 
1787 void ModuleBitcodeWriter::writeDIGlobalVariable(
1788     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1789     unsigned Abbrev) {
1790   const uint64_t Version = 2 << 1;
1791   Record.push_back((uint64_t)N->isDistinct() | Version);
1792   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1793   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1794   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1795   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1796   Record.push_back(N->getLine());
1797   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1798   Record.push_back(N->isLocalToUnit());
1799   Record.push_back(N->isDefinition());
1800   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1801   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1802   Record.push_back(N->getAlignInBits());
1803 
1804   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1805   Record.clear();
1806 }
1807 
1808 void ModuleBitcodeWriter::writeDILocalVariable(
1809     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1810     unsigned Abbrev) {
1811   // In order to support all possible bitcode formats in BitcodeReader we need
1812   // to distinguish the following cases:
1813   // 1) Record has no artificial tag (Record[1]),
1814   //   has no obsolete inlinedAt field (Record[9]).
1815   //   In this case Record size will be 8, HasAlignment flag is false.
1816   // 2) Record has artificial tag (Record[1]),
1817   //   has no obsolete inlignedAt field (Record[9]).
1818   //   In this case Record size will be 9, HasAlignment flag is false.
1819   // 3) Record has both artificial tag (Record[1]) and
1820   //   obsolete inlignedAt field (Record[9]).
1821   //   In this case Record size will be 10, HasAlignment flag is false.
1822   // 4) Record has neither artificial tag, nor inlignedAt field, but
1823   //   HasAlignment flag is true and Record[8] contains alignment value.
1824   const uint64_t HasAlignmentFlag = 1 << 1;
1825   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1826   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1827   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1828   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1829   Record.push_back(N->getLine());
1830   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1831   Record.push_back(N->getArg());
1832   Record.push_back(N->getFlags());
1833   Record.push_back(N->getAlignInBits());
1834 
1835   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1836   Record.clear();
1837 }
1838 
1839 void ModuleBitcodeWriter::writeDILabel(
1840     const DILabel *N, SmallVectorImpl<uint64_t> &Record,
1841     unsigned Abbrev) {
1842   Record.push_back((uint64_t)N->isDistinct());
1843   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1844   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1845   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1846   Record.push_back(N->getLine());
1847 
1848   Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
1849   Record.clear();
1850 }
1851 
1852 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1853                                             SmallVectorImpl<uint64_t> &Record,
1854                                             unsigned Abbrev) {
1855   Record.reserve(N->getElements().size() + 1);
1856   const uint64_t Version = 3 << 1;
1857   Record.push_back((uint64_t)N->isDistinct() | Version);
1858   Record.append(N->elements_begin(), N->elements_end());
1859 
1860   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1861   Record.clear();
1862 }
1863 
1864 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1865     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1866     unsigned Abbrev) {
1867   Record.push_back(N->isDistinct());
1868   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1869   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1870 
1871   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1872   Record.clear();
1873 }
1874 
1875 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1876                                               SmallVectorImpl<uint64_t> &Record,
1877                                               unsigned Abbrev) {
1878   Record.push_back(N->isDistinct());
1879   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1880   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1881   Record.push_back(N->getLine());
1882   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1883   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1884   Record.push_back(N->getAttributes());
1885   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1886 
1887   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1888   Record.clear();
1889 }
1890 
1891 void ModuleBitcodeWriter::writeDIImportedEntity(
1892     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1893     unsigned Abbrev) {
1894   Record.push_back(N->isDistinct());
1895   Record.push_back(N->getTag());
1896   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1897   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1898   Record.push_back(N->getLine());
1899   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1900   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
1901 
1902   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1903   Record.clear();
1904 }
1905 
1906 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1907   auto Abbv = std::make_shared<BitCodeAbbrev>();
1908   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1909   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1910   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1911   return Stream.EmitAbbrev(std::move(Abbv));
1912 }
1913 
1914 void ModuleBitcodeWriter::writeNamedMetadata(
1915     SmallVectorImpl<uint64_t> &Record) {
1916   if (M.named_metadata_empty())
1917     return;
1918 
1919   unsigned Abbrev = createNamedMetadataAbbrev();
1920   for (const NamedMDNode &NMD : M.named_metadata()) {
1921     // Write name.
1922     StringRef Str = NMD.getName();
1923     Record.append(Str.bytes_begin(), Str.bytes_end());
1924     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1925     Record.clear();
1926 
1927     // Write named metadata operands.
1928     for (const MDNode *N : NMD.operands())
1929       Record.push_back(VE.getMetadataID(N));
1930     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1931     Record.clear();
1932   }
1933 }
1934 
1935 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1936   auto Abbv = std::make_shared<BitCodeAbbrev>();
1937   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1938   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1939   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1940   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1941   return Stream.EmitAbbrev(std::move(Abbv));
1942 }
1943 
1944 /// Write out a record for MDString.
1945 ///
1946 /// All the metadata strings in a metadata block are emitted in a single
1947 /// record.  The sizes and strings themselves are shoved into a blob.
1948 void ModuleBitcodeWriter::writeMetadataStrings(
1949     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1950   if (Strings.empty())
1951     return;
1952 
1953   // Start the record with the number of strings.
1954   Record.push_back(bitc::METADATA_STRINGS);
1955   Record.push_back(Strings.size());
1956 
1957   // Emit the sizes of the strings in the blob.
1958   SmallString<256> Blob;
1959   {
1960     BitstreamWriter W(Blob);
1961     for (const Metadata *MD : Strings)
1962       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1963     W.FlushToWord();
1964   }
1965 
1966   // Add the offset to the strings to the record.
1967   Record.push_back(Blob.size());
1968 
1969   // Add the strings to the blob.
1970   for (const Metadata *MD : Strings)
1971     Blob.append(cast<MDString>(MD)->getString());
1972 
1973   // Emit the final record.
1974   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1975   Record.clear();
1976 }
1977 
1978 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1979 enum MetadataAbbrev : unsigned {
1980 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1981 #include "llvm/IR/Metadata.def"
1982   LastPlusOne
1983 };
1984 
1985 void ModuleBitcodeWriter::writeMetadataRecords(
1986     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1987     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1988   if (MDs.empty())
1989     return;
1990 
1991   // Initialize MDNode abbreviations.
1992 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1993 #include "llvm/IR/Metadata.def"
1994 
1995   for (const Metadata *MD : MDs) {
1996     if (IndexPos)
1997       IndexPos->push_back(Stream.GetCurrentBitNo());
1998     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1999       assert(N->isResolved() && "Expected forward references to be resolved");
2000 
2001       switch (N->getMetadataID()) {
2002       default:
2003         llvm_unreachable("Invalid MDNode subclass");
2004 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
2005   case Metadata::CLASS##Kind:                                                  \
2006     if (MDAbbrevs)                                                             \
2007       write##CLASS(cast<CLASS>(N), Record,                                     \
2008                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
2009     else                                                                       \
2010       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
2011     continue;
2012 #include "llvm/IR/Metadata.def"
2013       }
2014     }
2015     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2016   }
2017 }
2018 
2019 void ModuleBitcodeWriter::writeModuleMetadata() {
2020   if (!VE.hasMDs() && M.named_metadata_empty())
2021     return;
2022 
2023   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
2024   SmallVector<uint64_t, 64> Record;
2025 
2026   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2027   // block and load any metadata.
2028   std::vector<unsigned> MDAbbrevs;
2029 
2030   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2031   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2032   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2033       createGenericDINodeAbbrev();
2034 
2035   auto Abbv = std::make_shared<BitCodeAbbrev>();
2036   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2037   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2038   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2039   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2040 
2041   Abbv = std::make_shared<BitCodeAbbrev>();
2042   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2043   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2044   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2045   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2046 
2047   // Emit MDStrings together upfront.
2048   writeMetadataStrings(VE.getMDStrings(), Record);
2049 
2050   // We only emit an index for the metadata record if we have more than a given
2051   // (naive) threshold of metadatas, otherwise it is not worth it.
2052   if (VE.getNonMDStrings().size() > IndexThreshold) {
2053     // Write a placeholder value in for the offset of the metadata index,
2054     // which is written after the records, so that it can include
2055     // the offset of each entry. The placeholder offset will be
2056     // updated after all records are emitted.
2057     uint64_t Vals[] = {0, 0};
2058     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2059   }
2060 
2061   // Compute and save the bit offset to the current position, which will be
2062   // patched when we emit the index later. We can simply subtract the 64-bit
2063   // fixed size from the current bit number to get the location to backpatch.
2064   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2065 
2066   // This index will contain the bitpos for each individual record.
2067   std::vector<uint64_t> IndexPos;
2068   IndexPos.reserve(VE.getNonMDStrings().size());
2069 
2070   // Write all the records
2071   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2072 
2073   if (VE.getNonMDStrings().size() > IndexThreshold) {
2074     // Now that we have emitted all the records we will emit the index. But
2075     // first
2076     // backpatch the forward reference so that the reader can skip the records
2077     // efficiently.
2078     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2079                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2080 
2081     // Delta encode the index.
2082     uint64_t PreviousValue = IndexOffsetRecordBitPos;
2083     for (auto &Elt : IndexPos) {
2084       auto EltDelta = Elt - PreviousValue;
2085       PreviousValue = Elt;
2086       Elt = EltDelta;
2087     }
2088     // Emit the index record.
2089     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2090     IndexPos.clear();
2091   }
2092 
2093   // Write the named metadata now.
2094   writeNamedMetadata(Record);
2095 
2096   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2097     SmallVector<uint64_t, 4> Record;
2098     Record.push_back(VE.getValueID(&GO));
2099     pushGlobalMetadataAttachment(Record, GO);
2100     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2101   };
2102   for (const Function &F : M)
2103     if (F.isDeclaration() && F.hasMetadata())
2104       AddDeclAttachedMetadata(F);
2105   // FIXME: Only store metadata for declarations here, and move data for global
2106   // variable definitions to a separate block (PR28134).
2107   for (const GlobalVariable &GV : M.globals())
2108     if (GV.hasMetadata())
2109       AddDeclAttachedMetadata(GV);
2110 
2111   Stream.ExitBlock();
2112 }
2113 
2114 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2115   if (!VE.hasMDs())
2116     return;
2117 
2118   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2119   SmallVector<uint64_t, 64> Record;
2120   writeMetadataStrings(VE.getMDStrings(), Record);
2121   writeMetadataRecords(VE.getNonMDStrings(), Record);
2122   Stream.ExitBlock();
2123 }
2124 
2125 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2126     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2127   // [n x [id, mdnode]]
2128   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2129   GO.getAllMetadata(MDs);
2130   for (const auto &I : MDs) {
2131     Record.push_back(I.first);
2132     Record.push_back(VE.getMetadataID(I.second));
2133   }
2134 }
2135 
2136 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2137   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2138 
2139   SmallVector<uint64_t, 64> Record;
2140 
2141   if (F.hasMetadata()) {
2142     pushGlobalMetadataAttachment(Record, F);
2143     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2144     Record.clear();
2145   }
2146 
2147   // Write metadata attachments
2148   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2149   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2150   for (const BasicBlock &BB : F)
2151     for (const Instruction &I : BB) {
2152       MDs.clear();
2153       I.getAllMetadataOtherThanDebugLoc(MDs);
2154 
2155       // If no metadata, ignore instruction.
2156       if (MDs.empty()) continue;
2157 
2158       Record.push_back(VE.getInstructionID(&I));
2159 
2160       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2161         Record.push_back(MDs[i].first);
2162         Record.push_back(VE.getMetadataID(MDs[i].second));
2163       }
2164       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2165       Record.clear();
2166     }
2167 
2168   Stream.ExitBlock();
2169 }
2170 
2171 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2172   SmallVector<uint64_t, 64> Record;
2173 
2174   // Write metadata kinds
2175   // METADATA_KIND - [n x [id, name]]
2176   SmallVector<StringRef, 8> Names;
2177   M.getMDKindNames(Names);
2178 
2179   if (Names.empty()) return;
2180 
2181   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2182 
2183   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2184     Record.push_back(MDKindID);
2185     StringRef KName = Names[MDKindID];
2186     Record.append(KName.begin(), KName.end());
2187 
2188     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2189     Record.clear();
2190   }
2191 
2192   Stream.ExitBlock();
2193 }
2194 
2195 void ModuleBitcodeWriter::writeOperandBundleTags() {
2196   // Write metadata kinds
2197   //
2198   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2199   //
2200   // OPERAND_BUNDLE_TAG - [strchr x N]
2201 
2202   SmallVector<StringRef, 8> Tags;
2203   M.getOperandBundleTags(Tags);
2204 
2205   if (Tags.empty())
2206     return;
2207 
2208   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2209 
2210   SmallVector<uint64_t, 64> Record;
2211 
2212   for (auto Tag : Tags) {
2213     Record.append(Tag.begin(), Tag.end());
2214 
2215     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2216     Record.clear();
2217   }
2218 
2219   Stream.ExitBlock();
2220 }
2221 
2222 void ModuleBitcodeWriter::writeSyncScopeNames() {
2223   SmallVector<StringRef, 8> SSNs;
2224   M.getContext().getSyncScopeNames(SSNs);
2225   if (SSNs.empty())
2226     return;
2227 
2228   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2229 
2230   SmallVector<uint64_t, 64> Record;
2231   for (auto SSN : SSNs) {
2232     Record.append(SSN.begin(), SSN.end());
2233     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2234     Record.clear();
2235   }
2236 
2237   Stream.ExitBlock();
2238 }
2239 
2240 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2241   if ((int64_t)V >= 0)
2242     Vals.push_back(V << 1);
2243   else
2244     Vals.push_back((-V << 1) | 1);
2245 }
2246 
2247 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2248                                          bool isGlobal) {
2249   if (FirstVal == LastVal) return;
2250 
2251   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2252 
2253   unsigned AggregateAbbrev = 0;
2254   unsigned String8Abbrev = 0;
2255   unsigned CString7Abbrev = 0;
2256   unsigned CString6Abbrev = 0;
2257   // If this is a constant pool for the module, emit module-specific abbrevs.
2258   if (isGlobal) {
2259     // Abbrev for CST_CODE_AGGREGATE.
2260     auto Abbv = std::make_shared<BitCodeAbbrev>();
2261     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2262     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2263     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2264     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2265 
2266     // Abbrev for CST_CODE_STRING.
2267     Abbv = std::make_shared<BitCodeAbbrev>();
2268     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2269     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2270     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2271     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2272     // Abbrev for CST_CODE_CSTRING.
2273     Abbv = std::make_shared<BitCodeAbbrev>();
2274     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2275     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2276     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2277     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2278     // Abbrev for CST_CODE_CSTRING.
2279     Abbv = std::make_shared<BitCodeAbbrev>();
2280     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2281     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2282     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2283     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2284   }
2285 
2286   SmallVector<uint64_t, 64> Record;
2287 
2288   const ValueEnumerator::ValueList &Vals = VE.getValues();
2289   Type *LastTy = nullptr;
2290   for (unsigned i = FirstVal; i != LastVal; ++i) {
2291     const Value *V = Vals[i].first;
2292     // If we need to switch types, do so now.
2293     if (V->getType() != LastTy) {
2294       LastTy = V->getType();
2295       Record.push_back(VE.getTypeID(LastTy));
2296       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2297                         CONSTANTS_SETTYPE_ABBREV);
2298       Record.clear();
2299     }
2300 
2301     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2302       Record.push_back(unsigned(IA->hasSideEffects()) |
2303                        unsigned(IA->isAlignStack()) << 1 |
2304                        unsigned(IA->getDialect()&1) << 2);
2305 
2306       // Add the asm string.
2307       const std::string &AsmStr = IA->getAsmString();
2308       Record.push_back(AsmStr.size());
2309       Record.append(AsmStr.begin(), AsmStr.end());
2310 
2311       // Add the constraint string.
2312       const std::string &ConstraintStr = IA->getConstraintString();
2313       Record.push_back(ConstraintStr.size());
2314       Record.append(ConstraintStr.begin(), ConstraintStr.end());
2315       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2316       Record.clear();
2317       continue;
2318     }
2319     const Constant *C = cast<Constant>(V);
2320     unsigned Code = -1U;
2321     unsigned AbbrevToUse = 0;
2322     if (C->isNullValue()) {
2323       Code = bitc::CST_CODE_NULL;
2324     } else if (isa<UndefValue>(C)) {
2325       Code = bitc::CST_CODE_UNDEF;
2326     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2327       if (IV->getBitWidth() <= 64) {
2328         uint64_t V = IV->getSExtValue();
2329         emitSignedInt64(Record, V);
2330         Code = bitc::CST_CODE_INTEGER;
2331         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2332       } else {                             // Wide integers, > 64 bits in size.
2333         // We have an arbitrary precision integer value to write whose
2334         // bit width is > 64. However, in canonical unsigned integer
2335         // format it is likely that the high bits are going to be zero.
2336         // So, we only write the number of active words.
2337         unsigned NWords = IV->getValue().getActiveWords();
2338         const uint64_t *RawWords = IV->getValue().getRawData();
2339         for (unsigned i = 0; i != NWords; ++i) {
2340           emitSignedInt64(Record, RawWords[i]);
2341         }
2342         Code = bitc::CST_CODE_WIDE_INTEGER;
2343       }
2344     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2345       Code = bitc::CST_CODE_FLOAT;
2346       Type *Ty = CFP->getType();
2347       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2348         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2349       } else if (Ty->isX86_FP80Ty()) {
2350         // api needed to prevent premature destruction
2351         // bits are not in the same order as a normal i80 APInt, compensate.
2352         APInt api = CFP->getValueAPF().bitcastToAPInt();
2353         const uint64_t *p = api.getRawData();
2354         Record.push_back((p[1] << 48) | (p[0] >> 16));
2355         Record.push_back(p[0] & 0xffffLL);
2356       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2357         APInt api = CFP->getValueAPF().bitcastToAPInt();
2358         const uint64_t *p = api.getRawData();
2359         Record.push_back(p[0]);
2360         Record.push_back(p[1]);
2361       } else {
2362         assert(0 && "Unknown FP type!");
2363       }
2364     } else if (isa<ConstantDataSequential>(C) &&
2365                cast<ConstantDataSequential>(C)->isString()) {
2366       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2367       // Emit constant strings specially.
2368       unsigned NumElts = Str->getNumElements();
2369       // If this is a null-terminated string, use the denser CSTRING encoding.
2370       if (Str->isCString()) {
2371         Code = bitc::CST_CODE_CSTRING;
2372         --NumElts;  // Don't encode the null, which isn't allowed by char6.
2373       } else {
2374         Code = bitc::CST_CODE_STRING;
2375         AbbrevToUse = String8Abbrev;
2376       }
2377       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2378       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2379       for (unsigned i = 0; i != NumElts; ++i) {
2380         unsigned char V = Str->getElementAsInteger(i);
2381         Record.push_back(V);
2382         isCStr7 &= (V & 128) == 0;
2383         if (isCStrChar6)
2384           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2385       }
2386 
2387       if (isCStrChar6)
2388         AbbrevToUse = CString6Abbrev;
2389       else if (isCStr7)
2390         AbbrevToUse = CString7Abbrev;
2391     } else if (const ConstantDataSequential *CDS =
2392                   dyn_cast<ConstantDataSequential>(C)) {
2393       Code = bitc::CST_CODE_DATA;
2394       Type *EltTy = CDS->getType()->getElementType();
2395       if (isa<IntegerType>(EltTy)) {
2396         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2397           Record.push_back(CDS->getElementAsInteger(i));
2398       } else {
2399         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2400           Record.push_back(
2401               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2402       }
2403     } else if (isa<ConstantAggregate>(C)) {
2404       Code = bitc::CST_CODE_AGGREGATE;
2405       for (const Value *Op : C->operands())
2406         Record.push_back(VE.getValueID(Op));
2407       AbbrevToUse = AggregateAbbrev;
2408     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2409       switch (CE->getOpcode()) {
2410       default:
2411         if (Instruction::isCast(CE->getOpcode())) {
2412           Code = bitc::CST_CODE_CE_CAST;
2413           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2414           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2415           Record.push_back(VE.getValueID(C->getOperand(0)));
2416           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2417         } else {
2418           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2419           Code = bitc::CST_CODE_CE_BINOP;
2420           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2421           Record.push_back(VE.getValueID(C->getOperand(0)));
2422           Record.push_back(VE.getValueID(C->getOperand(1)));
2423           uint64_t Flags = getOptimizationFlags(CE);
2424           if (Flags != 0)
2425             Record.push_back(Flags);
2426         }
2427         break;
2428       case Instruction::FNeg: {
2429         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2430         Code = bitc::CST_CODE_CE_UNOP;
2431         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2432         Record.push_back(VE.getValueID(C->getOperand(0)));
2433         uint64_t Flags = getOptimizationFlags(CE);
2434         if (Flags != 0)
2435           Record.push_back(Flags);
2436         break;
2437       }
2438       case Instruction::GetElementPtr: {
2439         Code = bitc::CST_CODE_CE_GEP;
2440         const auto *GO = cast<GEPOperator>(C);
2441         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2442         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2443           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2444           Record.push_back((*Idx << 1) | GO->isInBounds());
2445         } else if (GO->isInBounds())
2446           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2447         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2448           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2449           Record.push_back(VE.getValueID(C->getOperand(i)));
2450         }
2451         break;
2452       }
2453       case Instruction::Select:
2454         Code = bitc::CST_CODE_CE_SELECT;
2455         Record.push_back(VE.getValueID(C->getOperand(0)));
2456         Record.push_back(VE.getValueID(C->getOperand(1)));
2457         Record.push_back(VE.getValueID(C->getOperand(2)));
2458         break;
2459       case Instruction::ExtractElement:
2460         Code = bitc::CST_CODE_CE_EXTRACTELT;
2461         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2462         Record.push_back(VE.getValueID(C->getOperand(0)));
2463         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2464         Record.push_back(VE.getValueID(C->getOperand(1)));
2465         break;
2466       case Instruction::InsertElement:
2467         Code = bitc::CST_CODE_CE_INSERTELT;
2468         Record.push_back(VE.getValueID(C->getOperand(0)));
2469         Record.push_back(VE.getValueID(C->getOperand(1)));
2470         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2471         Record.push_back(VE.getValueID(C->getOperand(2)));
2472         break;
2473       case Instruction::ShuffleVector:
2474         // If the return type and argument types are the same, this is a
2475         // standard shufflevector instruction.  If the types are different,
2476         // then the shuffle is widening or truncating the input vectors, and
2477         // the argument type must also be encoded.
2478         if (C->getType() == C->getOperand(0)->getType()) {
2479           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2480         } else {
2481           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2482           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2483         }
2484         Record.push_back(VE.getValueID(C->getOperand(0)));
2485         Record.push_back(VE.getValueID(C->getOperand(1)));
2486         Record.push_back(VE.getValueID(C->getOperand(2)));
2487         break;
2488       case Instruction::ICmp:
2489       case Instruction::FCmp:
2490         Code = bitc::CST_CODE_CE_CMP;
2491         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2492         Record.push_back(VE.getValueID(C->getOperand(0)));
2493         Record.push_back(VE.getValueID(C->getOperand(1)));
2494         Record.push_back(CE->getPredicate());
2495         break;
2496       }
2497     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2498       Code = bitc::CST_CODE_BLOCKADDRESS;
2499       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2500       Record.push_back(VE.getValueID(BA->getFunction()));
2501       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2502     } else {
2503 #ifndef NDEBUG
2504       C->dump();
2505 #endif
2506       llvm_unreachable("Unknown constant!");
2507     }
2508     Stream.EmitRecord(Code, Record, AbbrevToUse);
2509     Record.clear();
2510   }
2511 
2512   Stream.ExitBlock();
2513 }
2514 
2515 void ModuleBitcodeWriter::writeModuleConstants() {
2516   const ValueEnumerator::ValueList &Vals = VE.getValues();
2517 
2518   // Find the first constant to emit, which is the first non-globalvalue value.
2519   // We know globalvalues have been emitted by WriteModuleInfo.
2520   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2521     if (!isa<GlobalValue>(Vals[i].first)) {
2522       writeConstants(i, Vals.size(), true);
2523       return;
2524     }
2525   }
2526 }
2527 
2528 /// pushValueAndType - The file has to encode both the value and type id for
2529 /// many values, because we need to know what type to create for forward
2530 /// references.  However, most operands are not forward references, so this type
2531 /// field is not needed.
2532 ///
2533 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2534 /// instruction ID, then it is a forward reference, and it also includes the
2535 /// type ID.  The value ID that is written is encoded relative to the InstID.
2536 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2537                                            SmallVectorImpl<unsigned> &Vals) {
2538   unsigned ValID = VE.getValueID(V);
2539   // Make encoding relative to the InstID.
2540   Vals.push_back(InstID - ValID);
2541   if (ValID >= InstID) {
2542     Vals.push_back(VE.getTypeID(V->getType()));
2543     return true;
2544   }
2545   return false;
2546 }
2547 
2548 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2549                                               unsigned InstID) {
2550   SmallVector<unsigned, 64> Record;
2551   LLVMContext &C = CS.getInstruction()->getContext();
2552 
2553   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2554     const auto &Bundle = CS.getOperandBundleAt(i);
2555     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2556 
2557     for (auto &Input : Bundle.Inputs)
2558       pushValueAndType(Input, InstID, Record);
2559 
2560     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2561     Record.clear();
2562   }
2563 }
2564 
2565 /// pushValue - Like pushValueAndType, but where the type of the value is
2566 /// omitted (perhaps it was already encoded in an earlier operand).
2567 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2568                                     SmallVectorImpl<unsigned> &Vals) {
2569   unsigned ValID = VE.getValueID(V);
2570   Vals.push_back(InstID - ValID);
2571 }
2572 
2573 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2574                                           SmallVectorImpl<uint64_t> &Vals) {
2575   unsigned ValID = VE.getValueID(V);
2576   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2577   emitSignedInt64(Vals, diff);
2578 }
2579 
2580 /// WriteInstruction - Emit an instruction to the specified stream.
2581 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2582                                            unsigned InstID,
2583                                            SmallVectorImpl<unsigned> &Vals) {
2584   unsigned Code = 0;
2585   unsigned AbbrevToUse = 0;
2586   VE.setInstructionID(&I);
2587   switch (I.getOpcode()) {
2588   default:
2589     if (Instruction::isCast(I.getOpcode())) {
2590       Code = bitc::FUNC_CODE_INST_CAST;
2591       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2592         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2593       Vals.push_back(VE.getTypeID(I.getType()));
2594       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2595     } else {
2596       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2597       Code = bitc::FUNC_CODE_INST_BINOP;
2598       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2599         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2600       pushValue(I.getOperand(1), InstID, Vals);
2601       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2602       uint64_t Flags = getOptimizationFlags(&I);
2603       if (Flags != 0) {
2604         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2605           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2606         Vals.push_back(Flags);
2607       }
2608     }
2609     break;
2610   case Instruction::FNeg: {
2611     Code = bitc::FUNC_CODE_INST_UNOP;
2612     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2613       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2614     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2615     uint64_t Flags = getOptimizationFlags(&I);
2616     if (Flags != 0) {
2617       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2618         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2619       Vals.push_back(Flags);
2620     }
2621     break;
2622   }
2623   case Instruction::GetElementPtr: {
2624     Code = bitc::FUNC_CODE_INST_GEP;
2625     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2626     auto &GEPInst = cast<GetElementPtrInst>(I);
2627     Vals.push_back(GEPInst.isInBounds());
2628     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2629     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2630       pushValueAndType(I.getOperand(i), InstID, Vals);
2631     break;
2632   }
2633   case Instruction::ExtractValue: {
2634     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2635     pushValueAndType(I.getOperand(0), InstID, Vals);
2636     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2637     Vals.append(EVI->idx_begin(), EVI->idx_end());
2638     break;
2639   }
2640   case Instruction::InsertValue: {
2641     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2642     pushValueAndType(I.getOperand(0), InstID, Vals);
2643     pushValueAndType(I.getOperand(1), InstID, Vals);
2644     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2645     Vals.append(IVI->idx_begin(), IVI->idx_end());
2646     break;
2647   }
2648   case Instruction::Select: {
2649     Code = bitc::FUNC_CODE_INST_VSELECT;
2650     pushValueAndType(I.getOperand(1), InstID, Vals);
2651     pushValue(I.getOperand(2), InstID, Vals);
2652     pushValueAndType(I.getOperand(0), InstID, Vals);
2653     uint64_t Flags = getOptimizationFlags(&I);
2654     if (Flags != 0)
2655       Vals.push_back(Flags);
2656     break;
2657   }
2658   case Instruction::ExtractElement:
2659     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2660     pushValueAndType(I.getOperand(0), InstID, Vals);
2661     pushValueAndType(I.getOperand(1), InstID, Vals);
2662     break;
2663   case Instruction::InsertElement:
2664     Code = bitc::FUNC_CODE_INST_INSERTELT;
2665     pushValueAndType(I.getOperand(0), InstID, Vals);
2666     pushValue(I.getOperand(1), InstID, Vals);
2667     pushValueAndType(I.getOperand(2), InstID, Vals);
2668     break;
2669   case Instruction::ShuffleVector:
2670     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2671     pushValueAndType(I.getOperand(0), InstID, Vals);
2672     pushValue(I.getOperand(1), InstID, Vals);
2673     pushValue(I.getOperand(2), InstID, Vals);
2674     break;
2675   case Instruction::ICmp:
2676   case Instruction::FCmp: {
2677     // compare returning Int1Ty or vector of Int1Ty
2678     Code = bitc::FUNC_CODE_INST_CMP2;
2679     pushValueAndType(I.getOperand(0), InstID, Vals);
2680     pushValue(I.getOperand(1), InstID, Vals);
2681     Vals.push_back(cast<CmpInst>(I).getPredicate());
2682     uint64_t Flags = getOptimizationFlags(&I);
2683     if (Flags != 0)
2684       Vals.push_back(Flags);
2685     break;
2686   }
2687 
2688   case Instruction::Ret:
2689     {
2690       Code = bitc::FUNC_CODE_INST_RET;
2691       unsigned NumOperands = I.getNumOperands();
2692       if (NumOperands == 0)
2693         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2694       else if (NumOperands == 1) {
2695         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2696           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2697       } else {
2698         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2699           pushValueAndType(I.getOperand(i), InstID, Vals);
2700       }
2701     }
2702     break;
2703   case Instruction::Br:
2704     {
2705       Code = bitc::FUNC_CODE_INST_BR;
2706       const BranchInst &II = cast<BranchInst>(I);
2707       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2708       if (II.isConditional()) {
2709         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2710         pushValue(II.getCondition(), InstID, Vals);
2711       }
2712     }
2713     break;
2714   case Instruction::Switch:
2715     {
2716       Code = bitc::FUNC_CODE_INST_SWITCH;
2717       const SwitchInst &SI = cast<SwitchInst>(I);
2718       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2719       pushValue(SI.getCondition(), InstID, Vals);
2720       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2721       for (auto Case : SI.cases()) {
2722         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2723         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2724       }
2725     }
2726     break;
2727   case Instruction::IndirectBr:
2728     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2729     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2730     // Encode the address operand as relative, but not the basic blocks.
2731     pushValue(I.getOperand(0), InstID, Vals);
2732     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2733       Vals.push_back(VE.getValueID(I.getOperand(i)));
2734     break;
2735 
2736   case Instruction::Invoke: {
2737     const InvokeInst *II = cast<InvokeInst>(&I);
2738     const Value *Callee = II->getCalledValue();
2739     FunctionType *FTy = II->getFunctionType();
2740 
2741     if (II->hasOperandBundles())
2742       writeOperandBundles(II, InstID);
2743 
2744     Code = bitc::FUNC_CODE_INST_INVOKE;
2745 
2746     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2747     Vals.push_back(II->getCallingConv() | 1 << 13);
2748     Vals.push_back(VE.getValueID(II->getNormalDest()));
2749     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2750     Vals.push_back(VE.getTypeID(FTy));
2751     pushValueAndType(Callee, InstID, Vals);
2752 
2753     // Emit value #'s for the fixed parameters.
2754     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2755       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2756 
2757     // Emit type/value pairs for varargs params.
2758     if (FTy->isVarArg()) {
2759       for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2760            i != e; ++i)
2761         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2762     }
2763     break;
2764   }
2765   case Instruction::Resume:
2766     Code = bitc::FUNC_CODE_INST_RESUME;
2767     pushValueAndType(I.getOperand(0), InstID, Vals);
2768     break;
2769   case Instruction::CleanupRet: {
2770     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2771     const auto &CRI = cast<CleanupReturnInst>(I);
2772     pushValue(CRI.getCleanupPad(), InstID, Vals);
2773     if (CRI.hasUnwindDest())
2774       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2775     break;
2776   }
2777   case Instruction::CatchRet: {
2778     Code = bitc::FUNC_CODE_INST_CATCHRET;
2779     const auto &CRI = cast<CatchReturnInst>(I);
2780     pushValue(CRI.getCatchPad(), InstID, Vals);
2781     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2782     break;
2783   }
2784   case Instruction::CleanupPad:
2785   case Instruction::CatchPad: {
2786     const auto &FuncletPad = cast<FuncletPadInst>(I);
2787     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2788                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2789     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2790 
2791     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2792     Vals.push_back(NumArgOperands);
2793     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2794       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2795     break;
2796   }
2797   case Instruction::CatchSwitch: {
2798     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2799     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2800 
2801     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2802 
2803     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2804     Vals.push_back(NumHandlers);
2805     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2806       Vals.push_back(VE.getValueID(CatchPadBB));
2807 
2808     if (CatchSwitch.hasUnwindDest())
2809       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2810     break;
2811   }
2812   case Instruction::CallBr: {
2813     const CallBrInst *CBI = cast<CallBrInst>(&I);
2814     const Value *Callee = CBI->getCalledValue();
2815     FunctionType *FTy = CBI->getFunctionType();
2816 
2817     if (CBI->hasOperandBundles())
2818       writeOperandBundles(CBI, InstID);
2819 
2820     Code = bitc::FUNC_CODE_INST_CALLBR;
2821 
2822     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
2823 
2824     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
2825                    1 << bitc::CALL_EXPLICIT_TYPE);
2826 
2827     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
2828     Vals.push_back(CBI->getNumIndirectDests());
2829     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
2830       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
2831 
2832     Vals.push_back(VE.getTypeID(FTy));
2833     pushValueAndType(Callee, InstID, Vals);
2834 
2835     // Emit value #'s for the fixed parameters.
2836     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2837       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2838 
2839     // Emit type/value pairs for varargs params.
2840     if (FTy->isVarArg()) {
2841       for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands();
2842            i != e; ++i)
2843         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2844     }
2845     break;
2846   }
2847   case Instruction::Unreachable:
2848     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2849     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2850     break;
2851 
2852   case Instruction::PHI: {
2853     const PHINode &PN = cast<PHINode>(I);
2854     Code = bitc::FUNC_CODE_INST_PHI;
2855     // With the newer instruction encoding, forward references could give
2856     // negative valued IDs.  This is most common for PHIs, so we use
2857     // signed VBRs.
2858     SmallVector<uint64_t, 128> Vals64;
2859     Vals64.push_back(VE.getTypeID(PN.getType()));
2860     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2861       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2862       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2863     }
2864     // Emit a Vals64 vector and exit.
2865     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2866     Vals64.clear();
2867     return;
2868   }
2869 
2870   case Instruction::LandingPad: {
2871     const LandingPadInst &LP = cast<LandingPadInst>(I);
2872     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2873     Vals.push_back(VE.getTypeID(LP.getType()));
2874     Vals.push_back(LP.isCleanup());
2875     Vals.push_back(LP.getNumClauses());
2876     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2877       if (LP.isCatch(I))
2878         Vals.push_back(LandingPadInst::Catch);
2879       else
2880         Vals.push_back(LandingPadInst::Filter);
2881       pushValueAndType(LP.getClause(I), InstID, Vals);
2882     }
2883     break;
2884   }
2885 
2886   case Instruction::Alloca: {
2887     Code = bitc::FUNC_CODE_INST_ALLOCA;
2888     const AllocaInst &AI = cast<AllocaInst>(I);
2889     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2890     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2891     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2892     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2893     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2894            "not enough bits for maximum alignment");
2895     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2896     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2897     AlignRecord |= 1 << 6;
2898     AlignRecord |= AI.isSwiftError() << 7;
2899     Vals.push_back(AlignRecord);
2900     break;
2901   }
2902 
2903   case Instruction::Load:
2904     if (cast<LoadInst>(I).isAtomic()) {
2905       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2906       pushValueAndType(I.getOperand(0), InstID, Vals);
2907     } else {
2908       Code = bitc::FUNC_CODE_INST_LOAD;
2909       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2910         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2911     }
2912     Vals.push_back(VE.getTypeID(I.getType()));
2913     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2914     Vals.push_back(cast<LoadInst>(I).isVolatile());
2915     if (cast<LoadInst>(I).isAtomic()) {
2916       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2917       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
2918     }
2919     break;
2920   case Instruction::Store:
2921     if (cast<StoreInst>(I).isAtomic())
2922       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2923     else
2924       Code = bitc::FUNC_CODE_INST_STORE;
2925     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2926     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2927     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2928     Vals.push_back(cast<StoreInst>(I).isVolatile());
2929     if (cast<StoreInst>(I).isAtomic()) {
2930       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2931       Vals.push_back(
2932           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
2933     }
2934     break;
2935   case Instruction::AtomicCmpXchg:
2936     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2937     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2938     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2939     pushValue(I.getOperand(2), InstID, Vals);        // newval.
2940     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2941     Vals.push_back(
2942         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2943     Vals.push_back(
2944         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
2945     Vals.push_back(
2946         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2947     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2948     break;
2949   case Instruction::AtomicRMW:
2950     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2951     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2952     pushValue(I.getOperand(1), InstID, Vals);        // val.
2953     Vals.push_back(
2954         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2955     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2956     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2957     Vals.push_back(
2958         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
2959     break;
2960   case Instruction::Fence:
2961     Code = bitc::FUNC_CODE_INST_FENCE;
2962     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2963     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
2964     break;
2965   case Instruction::Call: {
2966     const CallInst &CI = cast<CallInst>(I);
2967     FunctionType *FTy = CI.getFunctionType();
2968 
2969     if (CI.hasOperandBundles())
2970       writeOperandBundles(&CI, InstID);
2971 
2972     Code = bitc::FUNC_CODE_INST_CALL;
2973 
2974     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2975 
2976     unsigned Flags = getOptimizationFlags(&I);
2977     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2978                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2979                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2980                    1 << bitc::CALL_EXPLICIT_TYPE |
2981                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2982                    unsigned(Flags != 0) << bitc::CALL_FMF);
2983     if (Flags != 0)
2984       Vals.push_back(Flags);
2985 
2986     Vals.push_back(VE.getTypeID(FTy));
2987     pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2988 
2989     // Emit value #'s for the fixed parameters.
2990     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2991       // Check for labels (can happen with asm labels).
2992       if (FTy->getParamType(i)->isLabelTy())
2993         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2994       else
2995         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2996     }
2997 
2998     // Emit type/value pairs for varargs params.
2999     if (FTy->isVarArg()) {
3000       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
3001            i != e; ++i)
3002         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3003     }
3004     break;
3005   }
3006   case Instruction::VAArg:
3007     Code = bitc::FUNC_CODE_INST_VAARG;
3008     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
3009     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
3010     Vals.push_back(VE.getTypeID(I.getType())); // restype.
3011     break;
3012   }
3013 
3014   Stream.EmitRecord(Code, Vals, AbbrevToUse);
3015   Vals.clear();
3016 }
3017 
3018 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3019 /// to allow clients to efficiently find the function body.
3020 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3021   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3022   // Get the offset of the VST we are writing, and backpatch it into
3023   // the VST forward declaration record.
3024   uint64_t VSTOffset = Stream.GetCurrentBitNo();
3025   // The BitcodeStartBit was the stream offset of the identification block.
3026   VSTOffset -= bitcodeStartBit();
3027   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3028   // Note that we add 1 here because the offset is relative to one word
3029   // before the start of the identification block, which was historically
3030   // always the start of the regular bitcode header.
3031   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3032 
3033   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3034 
3035   auto Abbv = std::make_shared<BitCodeAbbrev>();
3036   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3037   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3038   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3039   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3040 
3041   for (const Function &F : M) {
3042     uint64_t Record[2];
3043 
3044     if (F.isDeclaration())
3045       continue;
3046 
3047     Record[0] = VE.getValueID(&F);
3048 
3049     // Save the word offset of the function (from the start of the
3050     // actual bitcode written to the stream).
3051     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3052     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3053     // Note that we add 1 here because the offset is relative to one word
3054     // before the start of the identification block, which was historically
3055     // always the start of the regular bitcode header.
3056     Record[1] = BitcodeIndex / 32 + 1;
3057 
3058     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3059   }
3060 
3061   Stream.ExitBlock();
3062 }
3063 
3064 /// Emit names for arguments, instructions and basic blocks in a function.
3065 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3066     const ValueSymbolTable &VST) {
3067   if (VST.empty())
3068     return;
3069 
3070   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3071 
3072   // FIXME: Set up the abbrev, we know how many values there are!
3073   // FIXME: We know if the type names can use 7-bit ascii.
3074   SmallVector<uint64_t, 64> NameVals;
3075 
3076   for (const ValueName &Name : VST) {
3077     // Figure out the encoding to use for the name.
3078     StringEncoding Bits = getStringEncoding(Name.getKey());
3079 
3080     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3081     NameVals.push_back(VE.getValueID(Name.getValue()));
3082 
3083     // VST_CODE_ENTRY:   [valueid, namechar x N]
3084     // VST_CODE_BBENTRY: [bbid, namechar x N]
3085     unsigned Code;
3086     if (isa<BasicBlock>(Name.getValue())) {
3087       Code = bitc::VST_CODE_BBENTRY;
3088       if (Bits == SE_Char6)
3089         AbbrevToUse = VST_BBENTRY_6_ABBREV;
3090     } else {
3091       Code = bitc::VST_CODE_ENTRY;
3092       if (Bits == SE_Char6)
3093         AbbrevToUse = VST_ENTRY_6_ABBREV;
3094       else if (Bits == SE_Fixed7)
3095         AbbrevToUse = VST_ENTRY_7_ABBREV;
3096     }
3097 
3098     for (const auto P : Name.getKey())
3099       NameVals.push_back((unsigned char)P);
3100 
3101     // Emit the finished record.
3102     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3103     NameVals.clear();
3104   }
3105 
3106   Stream.ExitBlock();
3107 }
3108 
3109 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3110   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3111   unsigned Code;
3112   if (isa<BasicBlock>(Order.V))
3113     Code = bitc::USELIST_CODE_BB;
3114   else
3115     Code = bitc::USELIST_CODE_DEFAULT;
3116 
3117   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3118   Record.push_back(VE.getValueID(Order.V));
3119   Stream.EmitRecord(Code, Record);
3120 }
3121 
3122 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3123   assert(VE.shouldPreserveUseListOrder() &&
3124          "Expected to be preserving use-list order");
3125 
3126   auto hasMore = [&]() {
3127     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3128   };
3129   if (!hasMore())
3130     // Nothing to do.
3131     return;
3132 
3133   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3134   while (hasMore()) {
3135     writeUseList(std::move(VE.UseListOrders.back()));
3136     VE.UseListOrders.pop_back();
3137   }
3138   Stream.ExitBlock();
3139 }
3140 
3141 /// Emit a function body to the module stream.
3142 void ModuleBitcodeWriter::writeFunction(
3143     const Function &F,
3144     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3145   // Save the bitcode index of the start of this function block for recording
3146   // in the VST.
3147   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3148 
3149   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3150   VE.incorporateFunction(F);
3151 
3152   SmallVector<unsigned, 64> Vals;
3153 
3154   // Emit the number of basic blocks, so the reader can create them ahead of
3155   // time.
3156   Vals.push_back(VE.getBasicBlocks().size());
3157   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3158   Vals.clear();
3159 
3160   // If there are function-local constants, emit them now.
3161   unsigned CstStart, CstEnd;
3162   VE.getFunctionConstantRange(CstStart, CstEnd);
3163   writeConstants(CstStart, CstEnd, false);
3164 
3165   // If there is function-local metadata, emit it now.
3166   writeFunctionMetadata(F);
3167 
3168   // Keep a running idea of what the instruction ID is.
3169   unsigned InstID = CstEnd;
3170 
3171   bool NeedsMetadataAttachment = F.hasMetadata();
3172 
3173   DILocation *LastDL = nullptr;
3174   // Finally, emit all the instructions, in order.
3175   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3176     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3177          I != E; ++I) {
3178       writeInstruction(*I, InstID, Vals);
3179 
3180       if (!I->getType()->isVoidTy())
3181         ++InstID;
3182 
3183       // If the instruction has metadata, write a metadata attachment later.
3184       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3185 
3186       // If the instruction has a debug location, emit it.
3187       DILocation *DL = I->getDebugLoc();
3188       if (!DL)
3189         continue;
3190 
3191       if (DL == LastDL) {
3192         // Just repeat the same debug loc as last time.
3193         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3194         continue;
3195       }
3196 
3197       Vals.push_back(DL->getLine());
3198       Vals.push_back(DL->getColumn());
3199       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3200       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3201       Vals.push_back(DL->isImplicitCode());
3202       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3203       Vals.clear();
3204 
3205       LastDL = DL;
3206     }
3207 
3208   // Emit names for all the instructions etc.
3209   if (auto *Symtab = F.getValueSymbolTable())
3210     writeFunctionLevelValueSymbolTable(*Symtab);
3211 
3212   if (NeedsMetadataAttachment)
3213     writeFunctionMetadataAttachment(F);
3214   if (VE.shouldPreserveUseListOrder())
3215     writeUseListBlock(&F);
3216   VE.purgeFunction();
3217   Stream.ExitBlock();
3218 }
3219 
3220 // Emit blockinfo, which defines the standard abbreviations etc.
3221 void ModuleBitcodeWriter::writeBlockInfo() {
3222   // We only want to emit block info records for blocks that have multiple
3223   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3224   // Other blocks can define their abbrevs inline.
3225   Stream.EnterBlockInfoBlock();
3226 
3227   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3228     auto Abbv = std::make_shared<BitCodeAbbrev>();
3229     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3230     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3231     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3232     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3233     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3234         VST_ENTRY_8_ABBREV)
3235       llvm_unreachable("Unexpected abbrev ordering!");
3236   }
3237 
3238   { // 7-bit fixed width VST_CODE_ENTRY strings.
3239     auto Abbv = std::make_shared<BitCodeAbbrev>();
3240     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3241     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3242     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3243     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3244     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3245         VST_ENTRY_7_ABBREV)
3246       llvm_unreachable("Unexpected abbrev ordering!");
3247   }
3248   { // 6-bit char6 VST_CODE_ENTRY strings.
3249     auto Abbv = std::make_shared<BitCodeAbbrev>();
3250     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3251     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3252     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3253     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3254     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3255         VST_ENTRY_6_ABBREV)
3256       llvm_unreachable("Unexpected abbrev ordering!");
3257   }
3258   { // 6-bit char6 VST_CODE_BBENTRY strings.
3259     auto Abbv = std::make_shared<BitCodeAbbrev>();
3260     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3261     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3262     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3263     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3264     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3265         VST_BBENTRY_6_ABBREV)
3266       llvm_unreachable("Unexpected abbrev ordering!");
3267   }
3268 
3269   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3270     auto Abbv = std::make_shared<BitCodeAbbrev>();
3271     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3272     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3273                               VE.computeBitsRequiredForTypeIndicies()));
3274     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3275         CONSTANTS_SETTYPE_ABBREV)
3276       llvm_unreachable("Unexpected abbrev ordering!");
3277   }
3278 
3279   { // INTEGER abbrev for CONSTANTS_BLOCK.
3280     auto Abbv = std::make_shared<BitCodeAbbrev>();
3281     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3282     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3283     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3284         CONSTANTS_INTEGER_ABBREV)
3285       llvm_unreachable("Unexpected abbrev ordering!");
3286   }
3287 
3288   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3289     auto Abbv = std::make_shared<BitCodeAbbrev>();
3290     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3291     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3292     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3293                               VE.computeBitsRequiredForTypeIndicies()));
3294     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3295 
3296     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3297         CONSTANTS_CE_CAST_Abbrev)
3298       llvm_unreachable("Unexpected abbrev ordering!");
3299   }
3300   { // NULL abbrev for CONSTANTS_BLOCK.
3301     auto Abbv = std::make_shared<BitCodeAbbrev>();
3302     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3303     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3304         CONSTANTS_NULL_Abbrev)
3305       llvm_unreachable("Unexpected abbrev ordering!");
3306   }
3307 
3308   // FIXME: This should only use space for first class types!
3309 
3310   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3311     auto Abbv = std::make_shared<BitCodeAbbrev>();
3312     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3313     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3314     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3315                               VE.computeBitsRequiredForTypeIndicies()));
3316     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3317     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3318     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3319         FUNCTION_INST_LOAD_ABBREV)
3320       llvm_unreachable("Unexpected abbrev ordering!");
3321   }
3322   { // INST_UNOP abbrev for FUNCTION_BLOCK.
3323     auto Abbv = std::make_shared<BitCodeAbbrev>();
3324     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3325     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3326     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3327     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3328         FUNCTION_INST_UNOP_ABBREV)
3329       llvm_unreachable("Unexpected abbrev ordering!");
3330   }
3331   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3332     auto Abbv = std::make_shared<BitCodeAbbrev>();
3333     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3334     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3335     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3336     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3337     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3338         FUNCTION_INST_UNOP_FLAGS_ABBREV)
3339       llvm_unreachable("Unexpected abbrev ordering!");
3340   }
3341   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3342     auto Abbv = std::make_shared<BitCodeAbbrev>();
3343     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3344     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3345     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3346     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3347     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3348         FUNCTION_INST_BINOP_ABBREV)
3349       llvm_unreachable("Unexpected abbrev ordering!");
3350   }
3351   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3352     auto Abbv = std::make_shared<BitCodeAbbrev>();
3353     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3354     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3355     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3356     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3357     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3358     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3359         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3360       llvm_unreachable("Unexpected abbrev ordering!");
3361   }
3362   { // INST_CAST abbrev for FUNCTION_BLOCK.
3363     auto Abbv = std::make_shared<BitCodeAbbrev>();
3364     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3365     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3366     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3367                               VE.computeBitsRequiredForTypeIndicies()));
3368     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3369     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3370         FUNCTION_INST_CAST_ABBREV)
3371       llvm_unreachable("Unexpected abbrev ordering!");
3372   }
3373 
3374   { // INST_RET abbrev for FUNCTION_BLOCK.
3375     auto Abbv = std::make_shared<BitCodeAbbrev>();
3376     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3377     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3378         FUNCTION_INST_RET_VOID_ABBREV)
3379       llvm_unreachable("Unexpected abbrev ordering!");
3380   }
3381   { // INST_RET abbrev for FUNCTION_BLOCK.
3382     auto Abbv = std::make_shared<BitCodeAbbrev>();
3383     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3384     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3385     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3386         FUNCTION_INST_RET_VAL_ABBREV)
3387       llvm_unreachable("Unexpected abbrev ordering!");
3388   }
3389   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3390     auto Abbv = std::make_shared<BitCodeAbbrev>();
3391     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3392     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3393         FUNCTION_INST_UNREACHABLE_ABBREV)
3394       llvm_unreachable("Unexpected abbrev ordering!");
3395   }
3396   {
3397     auto Abbv = std::make_shared<BitCodeAbbrev>();
3398     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3399     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3400     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3401                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3402     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3403     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3404     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3405         FUNCTION_INST_GEP_ABBREV)
3406       llvm_unreachable("Unexpected abbrev ordering!");
3407   }
3408 
3409   Stream.ExitBlock();
3410 }
3411 
3412 /// Write the module path strings, currently only used when generating
3413 /// a combined index file.
3414 void IndexBitcodeWriter::writeModStrings() {
3415   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3416 
3417   // TODO: See which abbrev sizes we actually need to emit
3418 
3419   // 8-bit fixed-width MST_ENTRY strings.
3420   auto Abbv = std::make_shared<BitCodeAbbrev>();
3421   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3422   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3423   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3424   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3425   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3426 
3427   // 7-bit fixed width MST_ENTRY strings.
3428   Abbv = std::make_shared<BitCodeAbbrev>();
3429   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3430   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3431   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3432   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3433   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3434 
3435   // 6-bit char6 MST_ENTRY strings.
3436   Abbv = std::make_shared<BitCodeAbbrev>();
3437   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3438   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3439   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3440   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3441   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3442 
3443   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3444   Abbv = std::make_shared<BitCodeAbbrev>();
3445   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3446   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3447   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3448   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3449   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3450   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3451   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3452 
3453   SmallVector<unsigned, 64> Vals;
3454   forEachModule(
3455       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3456         StringRef Key = MPSE.getKey();
3457         const auto &Value = MPSE.getValue();
3458         StringEncoding Bits = getStringEncoding(Key);
3459         unsigned AbbrevToUse = Abbrev8Bit;
3460         if (Bits == SE_Char6)
3461           AbbrevToUse = Abbrev6Bit;
3462         else if (Bits == SE_Fixed7)
3463           AbbrevToUse = Abbrev7Bit;
3464 
3465         Vals.push_back(Value.first);
3466         Vals.append(Key.begin(), Key.end());
3467 
3468         // Emit the finished record.
3469         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3470 
3471         // Emit an optional hash for the module now
3472         const auto &Hash = Value.second;
3473         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3474           Vals.assign(Hash.begin(), Hash.end());
3475           // Emit the hash record.
3476           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3477         }
3478 
3479         Vals.clear();
3480       });
3481   Stream.ExitBlock();
3482 }
3483 
3484 /// Write the function type metadata related records that need to appear before
3485 /// a function summary entry (whether per-module or combined).
3486 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3487                                              FunctionSummary *FS) {
3488   if (!FS->type_tests().empty())
3489     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3490 
3491   SmallVector<uint64_t, 64> Record;
3492 
3493   auto WriteVFuncIdVec = [&](uint64_t Ty,
3494                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3495     if (VFs.empty())
3496       return;
3497     Record.clear();
3498     for (auto &VF : VFs) {
3499       Record.push_back(VF.GUID);
3500       Record.push_back(VF.Offset);
3501     }
3502     Stream.EmitRecord(Ty, Record);
3503   };
3504 
3505   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3506                   FS->type_test_assume_vcalls());
3507   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3508                   FS->type_checked_load_vcalls());
3509 
3510   auto WriteConstVCallVec = [&](uint64_t Ty,
3511                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3512     for (auto &VC : VCs) {
3513       Record.clear();
3514       Record.push_back(VC.VFunc.GUID);
3515       Record.push_back(VC.VFunc.Offset);
3516       Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3517       Stream.EmitRecord(Ty, Record);
3518     }
3519   };
3520 
3521   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3522                      FS->type_test_assume_const_vcalls());
3523   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3524                      FS->type_checked_load_const_vcalls());
3525 }
3526 
3527 /// Collect type IDs from type tests used by function.
3528 static void
3529 getReferencedTypeIds(FunctionSummary *FS,
3530                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3531   if (!FS->type_tests().empty())
3532     for (auto &TT : FS->type_tests())
3533       ReferencedTypeIds.insert(TT);
3534 
3535   auto GetReferencedTypesFromVFuncIdVec =
3536       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3537         for (auto &VF : VFs)
3538           ReferencedTypeIds.insert(VF.GUID);
3539       };
3540 
3541   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3542   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3543 
3544   auto GetReferencedTypesFromConstVCallVec =
3545       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3546         for (auto &VC : VCs)
3547           ReferencedTypeIds.insert(VC.VFunc.GUID);
3548       };
3549 
3550   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3551   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3552 }
3553 
3554 static void writeWholeProgramDevirtResolutionByArg(
3555     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3556     const WholeProgramDevirtResolution::ByArg &ByArg) {
3557   NameVals.push_back(args.size());
3558   NameVals.insert(NameVals.end(), args.begin(), args.end());
3559 
3560   NameVals.push_back(ByArg.TheKind);
3561   NameVals.push_back(ByArg.Info);
3562   NameVals.push_back(ByArg.Byte);
3563   NameVals.push_back(ByArg.Bit);
3564 }
3565 
3566 static void writeWholeProgramDevirtResolution(
3567     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3568     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3569   NameVals.push_back(Id);
3570 
3571   NameVals.push_back(Wpd.TheKind);
3572   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3573   NameVals.push_back(Wpd.SingleImplName.size());
3574 
3575   NameVals.push_back(Wpd.ResByArg.size());
3576   for (auto &A : Wpd.ResByArg)
3577     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3578 }
3579 
3580 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3581                                      StringTableBuilder &StrtabBuilder,
3582                                      const std::string &Id,
3583                                      const TypeIdSummary &Summary) {
3584   NameVals.push_back(StrtabBuilder.add(Id));
3585   NameVals.push_back(Id.size());
3586 
3587   NameVals.push_back(Summary.TTRes.TheKind);
3588   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3589   NameVals.push_back(Summary.TTRes.AlignLog2);
3590   NameVals.push_back(Summary.TTRes.SizeM1);
3591   NameVals.push_back(Summary.TTRes.BitMask);
3592   NameVals.push_back(Summary.TTRes.InlineBits);
3593 
3594   for (auto &W : Summary.WPDRes)
3595     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3596                                       W.second);
3597 }
3598 
3599 // Helper to emit a single function summary record.
3600 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3601     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3602     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3603     const Function &F) {
3604   NameVals.push_back(ValueID);
3605 
3606   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3607   writeFunctionTypeMetadataRecords(Stream, FS);
3608 
3609   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3610   NameVals.push_back(FS->instCount());
3611   NameVals.push_back(getEncodedFFlags(FS->fflags()));
3612   NameVals.push_back(FS->refs().size());
3613   NameVals.push_back(FS->immutableRefCount());
3614 
3615   for (auto &RI : FS->refs())
3616     NameVals.push_back(VE.getValueID(RI.getValue()));
3617 
3618   bool HasProfileData =
3619       F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3620   for (auto &ECI : FS->calls()) {
3621     NameVals.push_back(getValueId(ECI.first));
3622     if (HasProfileData)
3623       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3624     else if (WriteRelBFToSummary)
3625       NameVals.push_back(ECI.second.RelBlockFreq);
3626   }
3627 
3628   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3629   unsigned Code =
3630       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3631                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3632                                              : bitc::FS_PERMODULE));
3633 
3634   // Emit the finished record.
3635   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3636   NameVals.clear();
3637 }
3638 
3639 // Collect the global value references in the given variable's initializer,
3640 // and emit them in a summary record.
3641 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3642     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3643     unsigned FSModRefsAbbrev) {
3644   auto VI = Index->getValueInfo(V.getGUID());
3645   if (!VI || VI.getSummaryList().empty()) {
3646     // Only declarations should not have a summary (a declaration might however
3647     // have a summary if the def was in module level asm).
3648     assert(V.isDeclaration());
3649     return;
3650   }
3651   auto *Summary = VI.getSummaryList()[0].get();
3652   NameVals.push_back(VE.getValueID(&V));
3653   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3654   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3655   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3656 
3657   unsigned SizeBeforeRefs = NameVals.size();
3658   for (auto &RI : VS->refs())
3659     NameVals.push_back(VE.getValueID(RI.getValue()));
3660   // Sort the refs for determinism output, the vector returned by FS->refs() has
3661   // been initialized from a DenseSet.
3662   llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3663 
3664   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3665                     FSModRefsAbbrev);
3666   NameVals.clear();
3667 }
3668 
3669 // Current version for the summary.
3670 // This is bumped whenever we introduce changes in the way some record are
3671 // interpreted, like flags for instance.
3672 static const uint64_t INDEX_VERSION = 6;
3673 
3674 /// Emit the per-module summary section alongside the rest of
3675 /// the module's bitcode.
3676 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3677   // By default we compile with ThinLTO if the module has a summary, but the
3678   // client can request full LTO with a module flag.
3679   bool IsThinLTO = true;
3680   if (auto *MD =
3681           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3682     IsThinLTO = MD->getZExtValue();
3683   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3684                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3685                        4);
3686 
3687   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3688 
3689   // Write the index flags.
3690   uint64_t Flags = 0;
3691   // Bits 1-3 are set only in the combined index, skip them.
3692   if (Index->enableSplitLTOUnit())
3693     Flags |= 0x8;
3694   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3695 
3696   if (Index->begin() == Index->end()) {
3697     Stream.ExitBlock();
3698     return;
3699   }
3700 
3701   for (const auto &GVI : valueIds()) {
3702     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3703                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3704   }
3705 
3706   // Abbrev for FS_PERMODULE_PROFILE.
3707   auto Abbv = std::make_shared<BitCodeAbbrev>();
3708   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3709   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3710   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3711   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3712   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3713   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3714   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // immutablerefcnt
3715   // numrefs x valueid, n x (valueid, hotness)
3716   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3717   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3718   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3719 
3720   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3721   Abbv = std::make_shared<BitCodeAbbrev>();
3722   if (WriteRelBFToSummary)
3723     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3724   else
3725     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3726   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3727   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3728   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3729   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3730   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3731   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // immutablerefcnt
3732   // numrefs x valueid, n x (valueid [, rel_block_freq])
3733   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3734   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3735   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3736 
3737   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3738   Abbv = std::make_shared<BitCodeAbbrev>();
3739   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3740   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3741   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3742   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3743   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3744   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3745 
3746   // Abbrev for FS_ALIAS.
3747   Abbv = std::make_shared<BitCodeAbbrev>();
3748   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3749   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3750   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3751   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3752   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3753 
3754   SmallVector<uint64_t, 64> NameVals;
3755   // Iterate over the list of functions instead of the Index to
3756   // ensure the ordering is stable.
3757   for (const Function &F : M) {
3758     // Summary emission does not support anonymous functions, they have to
3759     // renamed using the anonymous function renaming pass.
3760     if (!F.hasName())
3761       report_fatal_error("Unexpected anonymous function when writing summary");
3762 
3763     ValueInfo VI = Index->getValueInfo(F.getGUID());
3764     if (!VI || VI.getSummaryList().empty()) {
3765       // Only declarations should not have a summary (a declaration might
3766       // however have a summary if the def was in module level asm).
3767       assert(F.isDeclaration());
3768       continue;
3769     }
3770     auto *Summary = VI.getSummaryList()[0].get();
3771     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3772                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
3773   }
3774 
3775   // Capture references from GlobalVariable initializers, which are outside
3776   // of a function scope.
3777   for (const GlobalVariable &G : M.globals())
3778     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3779 
3780   for (const GlobalAlias &A : M.aliases()) {
3781     auto *Aliasee = A.getBaseObject();
3782     if (!Aliasee->hasName())
3783       // Nameless function don't have an entry in the summary, skip it.
3784       continue;
3785     auto AliasId = VE.getValueID(&A);
3786     auto AliaseeId = VE.getValueID(Aliasee);
3787     NameVals.push_back(AliasId);
3788     auto *Summary = Index->getGlobalValueSummary(A);
3789     AliasSummary *AS = cast<AliasSummary>(Summary);
3790     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3791     NameVals.push_back(AliaseeId);
3792     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3793     NameVals.clear();
3794   }
3795 
3796   Stream.ExitBlock();
3797 }
3798 
3799 /// Emit the combined summary section into the combined index file.
3800 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3801   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3802   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3803 
3804   // Write the index flags.
3805   uint64_t Flags = 0;
3806   if (Index.withGlobalValueDeadStripping())
3807     Flags |= 0x1;
3808   if (Index.skipModuleByDistributedBackend())
3809     Flags |= 0x2;
3810   if (Index.hasSyntheticEntryCounts())
3811     Flags |= 0x4;
3812   if (Index.enableSplitLTOUnit())
3813     Flags |= 0x8;
3814   if (Index.partiallySplitLTOUnits())
3815     Flags |= 0x10;
3816   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3817 
3818   for (const auto &GVI : valueIds()) {
3819     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3820                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3821   }
3822 
3823   // Abbrev for FS_COMBINED.
3824   auto Abbv = std::make_shared<BitCodeAbbrev>();
3825   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3826   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3827   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3828   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3829   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3830   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3831   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
3832   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3833   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // immutablerefcnt
3834   // numrefs x valueid, n x (valueid)
3835   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3836   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3837   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3838 
3839   // Abbrev for FS_COMBINED_PROFILE.
3840   Abbv = std::make_shared<BitCodeAbbrev>();
3841   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3842   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3843   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3844   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3845   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3846   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3847   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3848   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // immutablerefcnt
3849   // numrefs x valueid, n x (valueid, hotness)
3850   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3851   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3852   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3853 
3854   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3855   Abbv = std::make_shared<BitCodeAbbrev>();
3856   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3857   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3858   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3859   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3860   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
3861   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3862   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3863 
3864   // Abbrev for FS_COMBINED_ALIAS.
3865   Abbv = std::make_shared<BitCodeAbbrev>();
3866   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3867   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3868   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3869   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3870   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3871   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3872 
3873   // The aliases are emitted as a post-pass, and will point to the value
3874   // id of the aliasee. Save them in a vector for post-processing.
3875   SmallVector<AliasSummary *, 64> Aliases;
3876 
3877   // Save the value id for each summary for alias emission.
3878   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3879 
3880   SmallVector<uint64_t, 64> NameVals;
3881 
3882   // Set that will be populated during call to writeFunctionTypeMetadataRecords
3883   // with the type ids referenced by this index file.
3884   std::set<GlobalValue::GUID> ReferencedTypeIds;
3885 
3886   // For local linkage, we also emit the original name separately
3887   // immediately after the record.
3888   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3889     if (!GlobalValue::isLocalLinkage(S.linkage()))
3890       return;
3891     NameVals.push_back(S.getOriginalName());
3892     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3893     NameVals.clear();
3894   };
3895 
3896   forEachSummary([&](GVInfo I, bool IsAliasee) {
3897     GlobalValueSummary *S = I.second;
3898     assert(S);
3899 
3900     auto ValueId = getValueId(I.first);
3901     assert(ValueId);
3902     SummaryToValueIdMap[S] = *ValueId;
3903 
3904     // If this is invoked for an aliasee, we want to record the above
3905     // mapping, but then not emit a summary entry (if the aliasee is
3906     // to be imported, we will invoke this separately with IsAliasee=false).
3907     if (IsAliasee)
3908       return;
3909 
3910     if (auto *AS = dyn_cast<AliasSummary>(S)) {
3911       // Will process aliases as a post-pass because the reader wants all
3912       // global to be loaded first.
3913       Aliases.push_back(AS);
3914       return;
3915     }
3916 
3917     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3918       NameVals.push_back(*ValueId);
3919       NameVals.push_back(Index.getModuleId(VS->modulePath()));
3920       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3921       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3922       for (auto &RI : VS->refs()) {
3923         auto RefValueId = getValueId(RI.getGUID());
3924         if (!RefValueId)
3925           continue;
3926         NameVals.push_back(*RefValueId);
3927       }
3928 
3929       // Emit the finished record.
3930       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3931                         FSModRefsAbbrev);
3932       NameVals.clear();
3933       MaybeEmitOriginalName(*S);
3934       return;
3935     }
3936 
3937     auto *FS = cast<FunctionSummary>(S);
3938     writeFunctionTypeMetadataRecords(Stream, FS);
3939     getReferencedTypeIds(FS, ReferencedTypeIds);
3940 
3941     NameVals.push_back(*ValueId);
3942     NameVals.push_back(Index.getModuleId(FS->modulePath()));
3943     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3944     NameVals.push_back(FS->instCount());
3945     NameVals.push_back(getEncodedFFlags(FS->fflags()));
3946     NameVals.push_back(FS->entryCount());
3947 
3948     // Fill in below
3949     NameVals.push_back(0); // numrefs
3950     NameVals.push_back(0); // immutablerefcnt
3951 
3952     unsigned Count = 0, ImmutableRefCnt = 0;
3953     for (auto &RI : FS->refs()) {
3954       auto RefValueId = getValueId(RI.getGUID());
3955       if (!RefValueId)
3956         continue;
3957       NameVals.push_back(*RefValueId);
3958       if (RI.isReadOnly())
3959         ImmutableRefCnt++;
3960       Count++;
3961     }
3962     NameVals[6] = Count;
3963     NameVals[7] = ImmutableRefCnt;
3964 
3965     bool HasProfileData = false;
3966     for (auto &EI : FS->calls()) {
3967       HasProfileData |=
3968           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
3969       if (HasProfileData)
3970         break;
3971     }
3972 
3973     for (auto &EI : FS->calls()) {
3974       // If this GUID doesn't have a value id, it doesn't have a function
3975       // summary and we don't need to record any calls to it.
3976       GlobalValue::GUID GUID = EI.first.getGUID();
3977       auto CallValueId = getValueId(GUID);
3978       if (!CallValueId) {
3979         // For SamplePGO, the indirect call targets for local functions will
3980         // have its original name annotated in profile. We try to find the
3981         // corresponding PGOFuncName as the GUID.
3982         GUID = Index.getGUIDFromOriginalID(GUID);
3983         if (GUID == 0)
3984           continue;
3985         CallValueId = getValueId(GUID);
3986         if (!CallValueId)
3987           continue;
3988         // The mapping from OriginalId to GUID may return a GUID
3989         // that corresponds to a static variable. Filter it out here.
3990         // This can happen when
3991         // 1) There is a call to a library function which does not have
3992         // a CallValidId;
3993         // 2) There is a static variable with the  OriginalGUID identical
3994         // to the GUID of the library function in 1);
3995         // When this happens, the logic for SamplePGO kicks in and
3996         // the static variable in 2) will be found, which needs to be
3997         // filtered out.
3998         auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3999         if (GVSum &&
4000             GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
4001           continue;
4002       }
4003       NameVals.push_back(*CallValueId);
4004       if (HasProfileData)
4005         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4006     }
4007 
4008     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4009     unsigned Code =
4010         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4011 
4012     // Emit the finished record.
4013     Stream.EmitRecord(Code, NameVals, FSAbbrev);
4014     NameVals.clear();
4015     MaybeEmitOriginalName(*S);
4016   });
4017 
4018   for (auto *AS : Aliases) {
4019     auto AliasValueId = SummaryToValueIdMap[AS];
4020     assert(AliasValueId);
4021     NameVals.push_back(AliasValueId);
4022     NameVals.push_back(Index.getModuleId(AS->modulePath()));
4023     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4024     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4025     assert(AliaseeValueId);
4026     NameVals.push_back(AliaseeValueId);
4027 
4028     // Emit the finished record.
4029     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4030     NameVals.clear();
4031     MaybeEmitOriginalName(*AS);
4032 
4033     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4034       getReferencedTypeIds(FS, ReferencedTypeIds);
4035   }
4036 
4037   if (!Index.cfiFunctionDefs().empty()) {
4038     for (auto &S : Index.cfiFunctionDefs()) {
4039       NameVals.push_back(StrtabBuilder.add(S));
4040       NameVals.push_back(S.size());
4041     }
4042     Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4043     NameVals.clear();
4044   }
4045 
4046   if (!Index.cfiFunctionDecls().empty()) {
4047     for (auto &S : Index.cfiFunctionDecls()) {
4048       NameVals.push_back(StrtabBuilder.add(S));
4049       NameVals.push_back(S.size());
4050     }
4051     Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4052     NameVals.clear();
4053   }
4054 
4055   // Walk the GUIDs that were referenced, and write the
4056   // corresponding type id records.
4057   for (auto &T : ReferencedTypeIds) {
4058     auto TidIter = Index.typeIds().equal_range(T);
4059     for (auto It = TidIter.first; It != TidIter.second; ++It) {
4060       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4061                                It->second.second);
4062       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4063       NameVals.clear();
4064     }
4065   }
4066 
4067   Stream.ExitBlock();
4068 }
4069 
4070 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4071 /// current llvm version, and a record for the epoch number.
4072 static void writeIdentificationBlock(BitstreamWriter &Stream) {
4073   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4074 
4075   // Write the "user readable" string identifying the bitcode producer
4076   auto Abbv = std::make_shared<BitCodeAbbrev>();
4077   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4078   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4079   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4080   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4081   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4082                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4083 
4084   // Write the epoch version
4085   Abbv = std::make_shared<BitCodeAbbrev>();
4086   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4087   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4088   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4089   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
4090   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4091   Stream.ExitBlock();
4092 }
4093 
4094 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4095   // Emit the module's hash.
4096   // MODULE_CODE_HASH: [5*i32]
4097   if (GenerateHash) {
4098     uint32_t Vals[5];
4099     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4100                                     Buffer.size() - BlockStartPos));
4101     StringRef Hash = Hasher.result();
4102     for (int Pos = 0; Pos < 20; Pos += 4) {
4103       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4104     }
4105 
4106     // Emit the finished record.
4107     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4108 
4109     if (ModHash)
4110       // Save the written hash value.
4111       llvm::copy(Vals, std::begin(*ModHash));
4112   }
4113 }
4114 
4115 void ModuleBitcodeWriter::write() {
4116   writeIdentificationBlock(Stream);
4117 
4118   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4119   size_t BlockStartPos = Buffer.size();
4120 
4121   writeModuleVersion();
4122 
4123   // Emit blockinfo, which defines the standard abbreviations etc.
4124   writeBlockInfo();
4125 
4126   // Emit information about attribute groups.
4127   writeAttributeGroupTable();
4128 
4129   // Emit information about parameter attributes.
4130   writeAttributeTable();
4131 
4132   // Emit information describing all of the types in the module.
4133   writeTypeTable();
4134 
4135   writeComdats();
4136 
4137   // Emit top-level description of module, including target triple, inline asm,
4138   // descriptors for global variables, and function prototype info.
4139   writeModuleInfo();
4140 
4141   // Emit constants.
4142   writeModuleConstants();
4143 
4144   // Emit metadata kind names.
4145   writeModuleMetadataKinds();
4146 
4147   // Emit metadata.
4148   writeModuleMetadata();
4149 
4150   // Emit module-level use-lists.
4151   if (VE.shouldPreserveUseListOrder())
4152     writeUseListBlock(nullptr);
4153 
4154   writeOperandBundleTags();
4155   writeSyncScopeNames();
4156 
4157   // Emit function bodies.
4158   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4159   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
4160     if (!F->isDeclaration())
4161       writeFunction(*F, FunctionToBitcodeIndex);
4162 
4163   // Need to write after the above call to WriteFunction which populates
4164   // the summary information in the index.
4165   if (Index)
4166     writePerModuleGlobalValueSummary();
4167 
4168   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4169 
4170   writeModuleHash(BlockStartPos);
4171 
4172   Stream.ExitBlock();
4173 }
4174 
4175 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4176                                uint32_t &Position) {
4177   support::endian::write32le(&Buffer[Position], Value);
4178   Position += 4;
4179 }
4180 
4181 /// If generating a bc file on darwin, we have to emit a
4182 /// header and trailer to make it compatible with the system archiver.  To do
4183 /// this we emit the following header, and then emit a trailer that pads the
4184 /// file out to be a multiple of 16 bytes.
4185 ///
4186 /// struct bc_header {
4187 ///   uint32_t Magic;         // 0x0B17C0DE
4188 ///   uint32_t Version;       // Version, currently always 0.
4189 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4190 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
4191 ///   uint32_t CPUType;       // CPU specifier.
4192 ///   ... potentially more later ...
4193 /// };
4194 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
4195                                          const Triple &TT) {
4196   unsigned CPUType = ~0U;
4197 
4198   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4199   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4200   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
4201   // specific constants here because they are implicitly part of the Darwin ABI.
4202   enum {
4203     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
4204     DARWIN_CPU_TYPE_X86        = 7,
4205     DARWIN_CPU_TYPE_ARM        = 12,
4206     DARWIN_CPU_TYPE_POWERPC    = 18
4207   };
4208 
4209   Triple::ArchType Arch = TT.getArch();
4210   if (Arch == Triple::x86_64)
4211     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4212   else if (Arch == Triple::x86)
4213     CPUType = DARWIN_CPU_TYPE_X86;
4214   else if (Arch == Triple::ppc)
4215     CPUType = DARWIN_CPU_TYPE_POWERPC;
4216   else if (Arch == Triple::ppc64)
4217     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4218   else if (Arch == Triple::arm || Arch == Triple::thumb)
4219     CPUType = DARWIN_CPU_TYPE_ARM;
4220 
4221   // Traditional Bitcode starts after header.
4222   assert(Buffer.size() >= BWH_HeaderSize &&
4223          "Expected header size to be reserved");
4224   unsigned BCOffset = BWH_HeaderSize;
4225   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4226 
4227   // Write the magic and version.
4228   unsigned Position = 0;
4229   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4230   writeInt32ToBuffer(0, Buffer, Position); // Version.
4231   writeInt32ToBuffer(BCOffset, Buffer, Position);
4232   writeInt32ToBuffer(BCSize, Buffer, Position);
4233   writeInt32ToBuffer(CPUType, Buffer, Position);
4234 
4235   // If the file is not a multiple of 16 bytes, insert dummy padding.
4236   while (Buffer.size() & 15)
4237     Buffer.push_back(0);
4238 }
4239 
4240 /// Helper to write the header common to all bitcode files.
4241 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4242   // Emit the file header.
4243   Stream.Emit((unsigned)'B', 8);
4244   Stream.Emit((unsigned)'C', 8);
4245   Stream.Emit(0x0, 4);
4246   Stream.Emit(0xC, 4);
4247   Stream.Emit(0xE, 4);
4248   Stream.Emit(0xD, 4);
4249 }
4250 
4251 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4252     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4253   writeBitcodeHeader(*Stream);
4254 }
4255 
4256 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4257 
4258 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4259   Stream->EnterSubblock(Block, 3);
4260 
4261   auto Abbv = std::make_shared<BitCodeAbbrev>();
4262   Abbv->Add(BitCodeAbbrevOp(Record));
4263   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4264   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4265 
4266   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4267 
4268   Stream->ExitBlock();
4269 }
4270 
4271 void BitcodeWriter::writeSymtab() {
4272   assert(!WroteStrtab && !WroteSymtab);
4273 
4274   // If any module has module-level inline asm, we will require a registered asm
4275   // parser for the target so that we can create an accurate symbol table for
4276   // the module.
4277   for (Module *M : Mods) {
4278     if (M->getModuleInlineAsm().empty())
4279       continue;
4280 
4281     std::string Err;
4282     const Triple TT(M->getTargetTriple());
4283     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4284     if (!T || !T->hasMCAsmParser())
4285       return;
4286   }
4287 
4288   WroteSymtab = true;
4289   SmallVector<char, 0> Symtab;
4290   // The irsymtab::build function may be unable to create a symbol table if the
4291   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4292   // table is not required for correctness, but we still want to be able to
4293   // write malformed modules to bitcode files, so swallow the error.
4294   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4295     consumeError(std::move(E));
4296     return;
4297   }
4298 
4299   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4300             {Symtab.data(), Symtab.size()});
4301 }
4302 
4303 void BitcodeWriter::writeStrtab() {
4304   assert(!WroteStrtab);
4305 
4306   std::vector<char> Strtab;
4307   StrtabBuilder.finalizeInOrder();
4308   Strtab.resize(StrtabBuilder.getSize());
4309   StrtabBuilder.write((uint8_t *)Strtab.data());
4310 
4311   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4312             {Strtab.data(), Strtab.size()});
4313 
4314   WroteStrtab = true;
4315 }
4316 
4317 void BitcodeWriter::copyStrtab(StringRef Strtab) {
4318   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4319   WroteStrtab = true;
4320 }
4321 
4322 void BitcodeWriter::writeModule(const Module &M,
4323                                 bool ShouldPreserveUseListOrder,
4324                                 const ModuleSummaryIndex *Index,
4325                                 bool GenerateHash, ModuleHash *ModHash) {
4326   assert(!WroteStrtab);
4327 
4328   // The Mods vector is used by irsymtab::build, which requires non-const
4329   // Modules in case it needs to materialize metadata. But the bitcode writer
4330   // requires that the module is materialized, so we can cast to non-const here,
4331   // after checking that it is in fact materialized.
4332   assert(M.isMaterialized());
4333   Mods.push_back(const_cast<Module *>(&M));
4334 
4335   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4336                                    ShouldPreserveUseListOrder, Index,
4337                                    GenerateHash, ModHash);
4338   ModuleWriter.write();
4339 }
4340 
4341 void BitcodeWriter::writeIndex(
4342     const ModuleSummaryIndex *Index,
4343     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4344   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4345                                  ModuleToSummariesForIndex);
4346   IndexWriter.write();
4347 }
4348 
4349 /// Write the specified module to the specified output stream.
4350 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4351                               bool ShouldPreserveUseListOrder,
4352                               const ModuleSummaryIndex *Index,
4353                               bool GenerateHash, ModuleHash *ModHash) {
4354   SmallVector<char, 0> Buffer;
4355   Buffer.reserve(256*1024);
4356 
4357   // If this is darwin or another generic macho target, reserve space for the
4358   // header.
4359   Triple TT(M.getTargetTriple());
4360   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4361     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4362 
4363   BitcodeWriter Writer(Buffer);
4364   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4365                      ModHash);
4366   Writer.writeSymtab();
4367   Writer.writeStrtab();
4368 
4369   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4370     emitDarwinBCHeaderAndTrailer(Buffer, TT);
4371 
4372   // Write the generated bitstream to "Out".
4373   Out.write((char*)&Buffer.front(), Buffer.size());
4374 }
4375 
4376 void IndexBitcodeWriter::write() {
4377   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4378 
4379   writeModuleVersion();
4380 
4381   // Write the module paths in the combined index.
4382   writeModStrings();
4383 
4384   // Write the summary combined index records.
4385   writeCombinedGlobalValueSummary();
4386 
4387   Stream.ExitBlock();
4388 }
4389 
4390 // Write the specified module summary index to the given raw output stream,
4391 // where it will be written in a new bitcode block. This is used when
4392 // writing the combined index file for ThinLTO. When writing a subset of the
4393 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4394 void llvm::WriteIndexToFile(
4395     const ModuleSummaryIndex &Index, raw_ostream &Out,
4396     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4397   SmallVector<char, 0> Buffer;
4398   Buffer.reserve(256 * 1024);
4399 
4400   BitcodeWriter Writer(Buffer);
4401   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4402   Writer.writeStrtab();
4403 
4404   Out.write((char *)&Buffer.front(), Buffer.size());
4405 }
4406 
4407 namespace {
4408 
4409 /// Class to manage the bitcode writing for a thin link bitcode file.
4410 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4411   /// ModHash is for use in ThinLTO incremental build, generated while writing
4412   /// the module bitcode file.
4413   const ModuleHash *ModHash;
4414 
4415 public:
4416   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4417                         BitstreamWriter &Stream,
4418                         const ModuleSummaryIndex &Index,
4419                         const ModuleHash &ModHash)
4420       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4421                                 /*ShouldPreserveUseListOrder=*/false, &Index),
4422         ModHash(&ModHash) {}
4423 
4424   void write();
4425 
4426 private:
4427   void writeSimplifiedModuleInfo();
4428 };
4429 
4430 } // end anonymous namespace
4431 
4432 // This function writes a simpilified module info for thin link bitcode file.
4433 // It only contains the source file name along with the name(the offset and
4434 // size in strtab) and linkage for global values. For the global value info
4435 // entry, in order to keep linkage at offset 5, there are three zeros used
4436 // as padding.
4437 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4438   SmallVector<unsigned, 64> Vals;
4439   // Emit the module's source file name.
4440   {
4441     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4442     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4443     if (Bits == SE_Char6)
4444       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4445     else if (Bits == SE_Fixed7)
4446       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4447 
4448     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4449     auto Abbv = std::make_shared<BitCodeAbbrev>();
4450     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4451     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4452     Abbv->Add(AbbrevOpToUse);
4453     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4454 
4455     for (const auto P : M.getSourceFileName())
4456       Vals.push_back((unsigned char)P);
4457 
4458     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4459     Vals.clear();
4460   }
4461 
4462   // Emit the global variable information.
4463   for (const GlobalVariable &GV : M.globals()) {
4464     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4465     Vals.push_back(StrtabBuilder.add(GV.getName()));
4466     Vals.push_back(GV.getName().size());
4467     Vals.push_back(0);
4468     Vals.push_back(0);
4469     Vals.push_back(0);
4470     Vals.push_back(getEncodedLinkage(GV));
4471 
4472     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4473     Vals.clear();
4474   }
4475 
4476   // Emit the function proto information.
4477   for (const Function &F : M) {
4478     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
4479     Vals.push_back(StrtabBuilder.add(F.getName()));
4480     Vals.push_back(F.getName().size());
4481     Vals.push_back(0);
4482     Vals.push_back(0);
4483     Vals.push_back(0);
4484     Vals.push_back(getEncodedLinkage(F));
4485 
4486     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4487     Vals.clear();
4488   }
4489 
4490   // Emit the alias information.
4491   for (const GlobalAlias &A : M.aliases()) {
4492     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4493     Vals.push_back(StrtabBuilder.add(A.getName()));
4494     Vals.push_back(A.getName().size());
4495     Vals.push_back(0);
4496     Vals.push_back(0);
4497     Vals.push_back(0);
4498     Vals.push_back(getEncodedLinkage(A));
4499 
4500     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4501     Vals.clear();
4502   }
4503 
4504   // Emit the ifunc information.
4505   for (const GlobalIFunc &I : M.ifuncs()) {
4506     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4507     Vals.push_back(StrtabBuilder.add(I.getName()));
4508     Vals.push_back(I.getName().size());
4509     Vals.push_back(0);
4510     Vals.push_back(0);
4511     Vals.push_back(0);
4512     Vals.push_back(getEncodedLinkage(I));
4513 
4514     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4515     Vals.clear();
4516   }
4517 }
4518 
4519 void ThinLinkBitcodeWriter::write() {
4520   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4521 
4522   writeModuleVersion();
4523 
4524   writeSimplifiedModuleInfo();
4525 
4526   writePerModuleGlobalValueSummary();
4527 
4528   // Write module hash.
4529   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4530 
4531   Stream.ExitBlock();
4532 }
4533 
4534 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4535                                          const ModuleSummaryIndex &Index,
4536                                          const ModuleHash &ModHash) {
4537   assert(!WroteStrtab);
4538 
4539   // The Mods vector is used by irsymtab::build, which requires non-const
4540   // Modules in case it needs to materialize metadata. But the bitcode writer
4541   // requires that the module is materialized, so we can cast to non-const here,
4542   // after checking that it is in fact materialized.
4543   assert(M.isMaterialized());
4544   Mods.push_back(const_cast<Module *>(&M));
4545 
4546   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4547                                        ModHash);
4548   ThinLinkWriter.write();
4549 }
4550 
4551 // Write the specified thin link bitcode file to the given raw output stream,
4552 // where it will be written in a new bitcode block. This is used when
4553 // writing the per-module index file for ThinLTO.
4554 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4555                                       const ModuleSummaryIndex &Index,
4556                                       const ModuleHash &ModHash) {
4557   SmallVector<char, 0> Buffer;
4558   Buffer.reserve(256 * 1024);
4559 
4560   BitcodeWriter Writer(Buffer);
4561   Writer.writeThinLinkBitcode(M, Index, ModHash);
4562   Writer.writeSymtab();
4563   Writer.writeStrtab();
4564 
4565   Out.write((char *)&Buffer.front(), Buffer.size());
4566 }
4567