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