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