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