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