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