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