xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 0c6a4ff8dcd32c00b1362d7dd902fe4d4160d642)
1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Bitcode writer implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Bitcode/BitcodeWriter.h"
15 #include "ValueEnumerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/BitstreamWriter.h"
19 #include "llvm/Bitcode/LLVMBitCodes.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/UseListOrder.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/SHA1.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cctype>
37 #include <map>
38 using namespace llvm;
39 
40 namespace {
41 
42 cl::opt<unsigned>
43     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
44                    cl::desc("Number of metadatas above which we emit an index "
45                             "to enable lazy-loading"));
46 /// These are manifest constants used by the bitcode writer. They do not need to
47 /// be kept in sync with the reader, but need to be consistent within this file.
48 enum {
49   // VALUE_SYMTAB_BLOCK abbrev id's.
50   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51   VST_ENTRY_7_ABBREV,
52   VST_ENTRY_6_ABBREV,
53   VST_BBENTRY_6_ABBREV,
54 
55   // CONSTANTS_BLOCK abbrev id's.
56   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
57   CONSTANTS_INTEGER_ABBREV,
58   CONSTANTS_CE_CAST_Abbrev,
59   CONSTANTS_NULL_Abbrev,
60 
61   // FUNCTION_BLOCK abbrev id's.
62   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
63   FUNCTION_INST_BINOP_ABBREV,
64   FUNCTION_INST_BINOP_FLAGS_ABBREV,
65   FUNCTION_INST_CAST_ABBREV,
66   FUNCTION_INST_RET_VOID_ABBREV,
67   FUNCTION_INST_RET_VAL_ABBREV,
68   FUNCTION_INST_UNREACHABLE_ABBREV,
69   FUNCTION_INST_GEP_ABBREV,
70 };
71 
72 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
73 /// file type.
74 class BitcodeWriterBase {
75 protected:
76   /// The stream created and owned by the client.
77   BitstreamWriter &Stream;
78 
79   /// Saves the offset of the VSTOffset record that must eventually be
80   /// backpatched with the offset of the actual VST.
81   uint64_t VSTOffsetPlaceholder = 0;
82 
83 public:
84   /// Constructs a BitcodeWriterBase object that writes to the provided
85   /// \p Stream.
86   BitcodeWriterBase(BitstreamWriter &Stream) : Stream(Stream) {}
87 
88 protected:
89   bool hasVSTOffsetPlaceholder() { return VSTOffsetPlaceholder != 0; }
90   void writeValueSymbolTableForwardDecl();
91   void writeBitcodeHeader();
92 };
93 
94 /// Class to manage the bitcode writing for a module.
95 class ModuleBitcodeWriter : public BitcodeWriterBase {
96   /// Pointer to the buffer allocated by caller for bitcode writing.
97   const SmallVectorImpl<char> &Buffer;
98 
99   /// The Module to write to bitcode.
100   const Module &M;
101 
102   /// Enumerates ids for all values in the module.
103   ValueEnumerator VE;
104 
105   /// Optional per-module index to write for ThinLTO.
106   const ModuleSummaryIndex *Index;
107 
108   /// True if a module hash record should be written.
109   bool GenerateHash;
110 
111   /// If non-null, when GenerateHash is true, the resulting hash is written
112   /// into ModHash. When GenerateHash is false, that specified value
113   /// is used as the hash instead of computing from the generated bitcode.
114   /// Can be used to produce the same module hash for a minimized bitcode
115   /// used just for the thin link as in the regular full bitcode that will
116   /// be used in the backend.
117   ModuleHash *ModHash;
118 
119   /// The start bit of the identification block.
120   uint64_t BitcodeStartBit;
121 
122   /// Map that holds the correspondence between GUIDs in the summary index,
123   /// that came from indirect call profiles, and a value id generated by this
124   /// class to use in the VST and summary block records.
125   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
126 
127   /// Tracks the last value id recorded in the GUIDToValueMap.
128   unsigned GlobalValueId;
129 
130 public:
131   /// Constructs a ModuleBitcodeWriter object for the given Module,
132   /// writing to the provided \p Buffer.
133   ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
134                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
135                       const ModuleSummaryIndex *Index, bool GenerateHash,
136                       ModuleHash *ModHash = nullptr)
137       : BitcodeWriterBase(Stream), Buffer(Buffer), M(*M),
138         VE(*M, ShouldPreserveUseListOrder), Index(Index),
139         GenerateHash(GenerateHash), ModHash(ModHash),
140         BitcodeStartBit(Stream.GetCurrentBitNo()) {
141     // Assign ValueIds to any callee values in the index that came from
142     // indirect call profiles and were recorded as a GUID not a Value*
143     // (which would have been assigned an ID by the ValueEnumerator).
144     // The starting ValueId is just after the number of values in the
145     // ValueEnumerator, so that they can be emitted in the VST.
146     GlobalValueId = VE.getValues().size();
147     if (!Index)
148       return;
149     for (const auto &GUIDSummaryLists : *Index)
150       // Examine all summaries for this GUID.
151       for (auto &Summary : GUIDSummaryLists.second)
152         if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
153           // For each call in the function summary, see if the call
154           // is to a GUID (which means it is for an indirect call,
155           // otherwise we would have a Value for it). If so, synthesize
156           // a value id.
157           for (auto &CallEdge : FS->calls())
158             if (CallEdge.first.isGUID())
159               assignValueId(CallEdge.first.getGUID());
160   }
161 
162   /// Emit the current module to the bitstream.
163   void write();
164 
165 private:
166   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
167 
168   void writeAttributeGroupTable();
169   void writeAttributeTable();
170   void writeTypeTable();
171   void writeComdats();
172   void writeModuleInfo();
173   void writeValueAsMetadata(const ValueAsMetadata *MD,
174                             SmallVectorImpl<uint64_t> &Record);
175   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
176                     unsigned Abbrev);
177   unsigned createDILocationAbbrev();
178   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
179                        unsigned &Abbrev);
180   unsigned createGenericDINodeAbbrev();
181   void writeGenericDINode(const GenericDINode *N,
182                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
183   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
184                        unsigned Abbrev);
185   void writeDIEnumerator(const DIEnumerator *N,
186                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
187   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
188                         unsigned Abbrev);
189   void writeDIDerivedType(const DIDerivedType *N,
190                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
191   void writeDICompositeType(const DICompositeType *N,
192                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
193   void writeDISubroutineType(const DISubroutineType *N,
194                              SmallVectorImpl<uint64_t> &Record,
195                              unsigned Abbrev);
196   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
197                    unsigned Abbrev);
198   void writeDICompileUnit(const DICompileUnit *N,
199                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
200   void writeDISubprogram(const DISubprogram *N,
201                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
202   void writeDILexicalBlock(const DILexicalBlock *N,
203                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
204   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
205                                SmallVectorImpl<uint64_t> &Record,
206                                unsigned Abbrev);
207   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
208                         unsigned Abbrev);
209   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
210                     unsigned Abbrev);
211   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
212                         unsigned Abbrev);
213   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
214                      unsigned Abbrev);
215   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
216                                     SmallVectorImpl<uint64_t> &Record,
217                                     unsigned Abbrev);
218   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
219                                      SmallVectorImpl<uint64_t> &Record,
220                                      unsigned Abbrev);
221   void writeDIGlobalVariable(const DIGlobalVariable *N,
222                              SmallVectorImpl<uint64_t> &Record,
223                              unsigned Abbrev);
224   void writeDILocalVariable(const DILocalVariable *N,
225                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
226   void writeDIExpression(const DIExpression *N,
227                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
228   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
229                                        SmallVectorImpl<uint64_t> &Record,
230                                        unsigned Abbrev);
231   void writeDIObjCProperty(const DIObjCProperty *N,
232                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
233   void writeDIImportedEntity(const DIImportedEntity *N,
234                              SmallVectorImpl<uint64_t> &Record,
235                              unsigned Abbrev);
236   unsigned createNamedMetadataAbbrev();
237   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
238   unsigned createMetadataStringsAbbrev();
239   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
240                             SmallVectorImpl<uint64_t> &Record);
241   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
242                             SmallVectorImpl<uint64_t> &Record,
243                             std::vector<unsigned> *MDAbbrevs = nullptr,
244                             std::vector<uint64_t> *IndexPos = nullptr);
245   void writeModuleMetadata();
246   void writeFunctionMetadata(const Function &F);
247   void writeFunctionMetadataAttachment(const Function &F);
248   void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
249   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
250                                     const GlobalObject &GO);
251   void writeModuleMetadataKinds();
252   void writeOperandBundleTags();
253   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
254   void writeModuleConstants();
255   bool pushValueAndType(const Value *V, unsigned InstID,
256                         SmallVectorImpl<unsigned> &Vals);
257   void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
258   void pushValue(const Value *V, unsigned InstID,
259                  SmallVectorImpl<unsigned> &Vals);
260   void pushValueSigned(const Value *V, unsigned InstID,
261                        SmallVectorImpl<uint64_t> &Vals);
262   void writeInstruction(const Instruction &I, unsigned InstID,
263                         SmallVectorImpl<unsigned> &Vals);
264   void writeValueSymbolTable(
265       const ValueSymbolTable &VST, bool IsModuleLevel = false,
266       DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr);
267   void writeUseList(UseListOrder &&Order);
268   void writeUseListBlock(const Function *F);
269   void
270   writeFunction(const Function &F,
271                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
272   void writeBlockInfo();
273   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
274                                            GlobalValueSummary *Summary,
275                                            unsigned ValueID,
276                                            unsigned FSCallsAbbrev,
277                                            unsigned FSCallsProfileAbbrev,
278                                            const Function &F);
279   void writeModuleLevelReferences(const GlobalVariable &V,
280                                   SmallVector<uint64_t, 64> &NameVals,
281                                   unsigned FSModRefsAbbrev);
282   void writePerModuleGlobalValueSummary();
283   void writeModuleHash(size_t BlockStartPos);
284 
285   void assignValueId(GlobalValue::GUID ValGUID) {
286     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
287   }
288   unsigned getValueId(GlobalValue::GUID ValGUID) {
289     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
290     // Expect that any GUID value had a value Id assigned by an
291     // earlier call to assignValueId.
292     assert(VMI != GUIDToValueIdMap.end() &&
293            "GUID does not have assigned value Id");
294     return VMI->second;
295   }
296   // Helper to get the valueId for the type of value recorded in VI.
297   unsigned getValueId(ValueInfo VI) {
298     if (VI.isGUID())
299       return getValueId(VI.getGUID());
300     return VE.getValueID(VI.getValue());
301   }
302   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
303 };
304 
305 /// Class to manage the bitcode writing for a combined index.
306 class IndexBitcodeWriter : public BitcodeWriterBase {
307   /// The combined index to write to bitcode.
308   const ModuleSummaryIndex &Index;
309 
310   /// When writing a subset of the index for distributed backends, client
311   /// provides a map of modules to the corresponding GUIDs/summaries to write.
312   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
313 
314   /// Map that holds the correspondence between the GUID used in the combined
315   /// index and a value id generated by this class to use in references.
316   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
317 
318   /// Tracks the last value id recorded in the GUIDToValueMap.
319   unsigned GlobalValueId = 0;
320 
321 public:
322   /// Constructs a IndexBitcodeWriter object for the given combined index,
323   /// writing to the provided \p Buffer. When writing a subset of the index
324   /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
325   IndexBitcodeWriter(BitstreamWriter &Stream, const ModuleSummaryIndex &Index,
326                      const std::map<std::string, GVSummaryMapTy>
327                          *ModuleToSummariesForIndex = nullptr)
328       : BitcodeWriterBase(Stream), Index(Index),
329         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
330     // Assign unique value ids to all summaries to be written, for use
331     // in writing out the call graph edges. Save the mapping from GUID
332     // to the new global value id to use when writing those edges, which
333     // are currently saved in the index in terms of GUID.
334     for (const auto &I : *this)
335       GUIDToValueIdMap[I.first] = ++GlobalValueId;
336   }
337 
338   /// The below iterator returns the GUID and associated summary.
339   typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
340 
341   /// Iterator over the value GUID and summaries to be written to bitcode,
342   /// hides the details of whether they are being pulled from the entire
343   /// index or just those in a provided ModuleToSummariesForIndex map.
344   class iterator
345       : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
346                                           GVInfo> {
347     /// Enables access to parent class.
348     const IndexBitcodeWriter &Writer;
349 
350     // Iterators used when writing only those summaries in a provided
351     // ModuleToSummariesForIndex map:
352 
353     /// Points to the last element in outer ModuleToSummariesForIndex map.
354     std::map<std::string, GVSummaryMapTy>::const_iterator ModuleSummariesBack;
355     /// Iterator on outer ModuleToSummariesForIndex map.
356     std::map<std::string, GVSummaryMapTy>::const_iterator ModuleSummariesIter;
357     /// Iterator on an inner global variable summary map.
358     GVSummaryMapTy::const_iterator ModuleGVSummariesIter;
359 
360     // Iterators used when writing all summaries in the index:
361 
362     /// Points to the last element in the Index outer GlobalValueMap.
363     const_gvsummary_iterator IndexSummariesBack;
364     /// Iterator on outer GlobalValueMap.
365     const_gvsummary_iterator IndexSummariesIter;
366     /// Iterator on an inner GlobalValueSummaryList.
367     GlobalValueSummaryList::const_iterator IndexGVSummariesIter;
368 
369   public:
370     /// Construct iterator from parent \p Writer and indicate if we are
371     /// constructing the end iterator.
372     iterator(const IndexBitcodeWriter &Writer, bool IsAtEnd) : Writer(Writer) {
373       // Set up the appropriate set of iterators given whether we are writing
374       // the full index or just a subset.
375       // Can't setup the Back or inner iterators if the corresponding map
376       // is empty. This will be handled specially in operator== as well.
377       if (Writer.ModuleToSummariesForIndex &&
378           !Writer.ModuleToSummariesForIndex->empty()) {
379         for (ModuleSummariesBack = Writer.ModuleToSummariesForIndex->begin();
380              std::next(ModuleSummariesBack) !=
381              Writer.ModuleToSummariesForIndex->end();
382              ModuleSummariesBack++)
383           ;
384         ModuleSummariesIter = !IsAtEnd
385                                   ? Writer.ModuleToSummariesForIndex->begin()
386                                   : ModuleSummariesBack;
387         ModuleGVSummariesIter = !IsAtEnd ? ModuleSummariesIter->second.begin()
388                                          : ModuleSummariesBack->second.end();
389       } else if (!Writer.ModuleToSummariesForIndex &&
390                  Writer.Index.begin() != Writer.Index.end()) {
391         for (IndexSummariesBack = Writer.Index.begin();
392              std::next(IndexSummariesBack) != Writer.Index.end();
393              IndexSummariesBack++)
394           ;
395         IndexSummariesIter =
396             !IsAtEnd ? Writer.Index.begin() : IndexSummariesBack;
397         IndexGVSummariesIter = !IsAtEnd ? IndexSummariesIter->second.begin()
398                                         : IndexSummariesBack->second.end();
399       }
400     }
401 
402     /// Increment the appropriate set of iterators.
403     iterator &operator++() {
404       // First the inner iterator is incremented, then if it is at the end
405       // and there are more outer iterations to go, the inner is reset to
406       // the start of the next inner list.
407       if (Writer.ModuleToSummariesForIndex) {
408         ++ModuleGVSummariesIter;
409         if (ModuleGVSummariesIter == ModuleSummariesIter->second.end() &&
410             ModuleSummariesIter != ModuleSummariesBack) {
411           ++ModuleSummariesIter;
412           ModuleGVSummariesIter = ModuleSummariesIter->second.begin();
413         }
414       } else {
415         ++IndexGVSummariesIter;
416         if (IndexGVSummariesIter == IndexSummariesIter->second.end() &&
417             IndexSummariesIter != IndexSummariesBack) {
418           ++IndexSummariesIter;
419           IndexGVSummariesIter = IndexSummariesIter->second.begin();
420         }
421       }
422       return *this;
423     }
424 
425     /// Access the <GUID,GlobalValueSummary*> pair corresponding to the current
426     /// outer and inner iterator positions.
427     GVInfo operator*() {
428       if (Writer.ModuleToSummariesForIndex)
429         return std::make_pair(ModuleGVSummariesIter->first,
430                               ModuleGVSummariesIter->second);
431       return std::make_pair(IndexSummariesIter->first,
432                             IndexGVSummariesIter->get());
433     }
434 
435     /// Checks if the iterators are equal, with special handling for empty
436     /// indexes.
437     bool operator==(const iterator &RHS) const {
438       if (Writer.ModuleToSummariesForIndex) {
439         // First ensure that both are writing the same subset.
440         if (Writer.ModuleToSummariesForIndex !=
441             RHS.Writer.ModuleToSummariesForIndex)
442           return false;
443         // Already determined above that maps are the same, so if one is
444         // empty, they both are.
445         if (Writer.ModuleToSummariesForIndex->empty())
446           return true;
447         // Ensure the ModuleGVSummariesIter are iterating over the same
448         // container before checking them below.
449         if (ModuleSummariesIter != RHS.ModuleSummariesIter)
450           return false;
451         return ModuleGVSummariesIter == RHS.ModuleGVSummariesIter;
452       }
453       // First ensure RHS also writing the full index, and that both are
454       // writing the same full index.
455       if (RHS.Writer.ModuleToSummariesForIndex ||
456           &Writer.Index != &RHS.Writer.Index)
457         return false;
458       // Already determined above that maps are the same, so if one is
459       // empty, they both are.
460       if (Writer.Index.begin() == Writer.Index.end())
461         return true;
462       // Ensure the IndexGVSummariesIter are iterating over the same
463       // container before checking them below.
464       if (IndexSummariesIter != RHS.IndexSummariesIter)
465         return false;
466       return IndexGVSummariesIter == RHS.IndexGVSummariesIter;
467     }
468   };
469 
470   /// Obtain the start iterator over the summaries to be written.
471   iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
472   /// Obtain the end iterator over the summaries to be written.
473   iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
474 
475   /// Main entry point for writing a combined index to bitcode.
476   void write();
477 
478 private:
479   void writeIndex();
480   void writeModStrings();
481   void writeCombinedValueSymbolTable();
482   void writeCombinedGlobalValueSummary();
483 
484   /// Indicates whether the provided \p ModulePath should be written into
485   /// the module string table, e.g. if full index written or if it is in
486   /// the provided subset.
487   bool doIncludeModule(StringRef ModulePath) {
488     return !ModuleToSummariesForIndex ||
489            ModuleToSummariesForIndex->count(ModulePath);
490   }
491 
492   bool hasValueId(GlobalValue::GUID ValGUID) {
493     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
494     return VMI != GUIDToValueIdMap.end();
495   }
496   unsigned getValueId(GlobalValue::GUID ValGUID) {
497     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
498     // If this GUID doesn't have an entry, assign one.
499     if (VMI == GUIDToValueIdMap.end()) {
500       GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
501       return GlobalValueId;
502     } else {
503       return VMI->second;
504     }
505   }
506   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
507 };
508 } // end anonymous namespace
509 
510 static unsigned getEncodedCastOpcode(unsigned Opcode) {
511   switch (Opcode) {
512   default: llvm_unreachable("Unknown cast instruction!");
513   case Instruction::Trunc   : return bitc::CAST_TRUNC;
514   case Instruction::ZExt    : return bitc::CAST_ZEXT;
515   case Instruction::SExt    : return bitc::CAST_SEXT;
516   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
517   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
518   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
519   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
520   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
521   case Instruction::FPExt   : return bitc::CAST_FPEXT;
522   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
523   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
524   case Instruction::BitCast : return bitc::CAST_BITCAST;
525   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
526   }
527 }
528 
529 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
530   switch (Opcode) {
531   default: llvm_unreachable("Unknown binary instruction!");
532   case Instruction::Add:
533   case Instruction::FAdd: return bitc::BINOP_ADD;
534   case Instruction::Sub:
535   case Instruction::FSub: return bitc::BINOP_SUB;
536   case Instruction::Mul:
537   case Instruction::FMul: return bitc::BINOP_MUL;
538   case Instruction::UDiv: return bitc::BINOP_UDIV;
539   case Instruction::FDiv:
540   case Instruction::SDiv: return bitc::BINOP_SDIV;
541   case Instruction::URem: return bitc::BINOP_UREM;
542   case Instruction::FRem:
543   case Instruction::SRem: return bitc::BINOP_SREM;
544   case Instruction::Shl:  return bitc::BINOP_SHL;
545   case Instruction::LShr: return bitc::BINOP_LSHR;
546   case Instruction::AShr: return bitc::BINOP_ASHR;
547   case Instruction::And:  return bitc::BINOP_AND;
548   case Instruction::Or:   return bitc::BINOP_OR;
549   case Instruction::Xor:  return bitc::BINOP_XOR;
550   }
551 }
552 
553 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
554   switch (Op) {
555   default: llvm_unreachable("Unknown RMW operation!");
556   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
557   case AtomicRMWInst::Add: return bitc::RMW_ADD;
558   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
559   case AtomicRMWInst::And: return bitc::RMW_AND;
560   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
561   case AtomicRMWInst::Or: return bitc::RMW_OR;
562   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
563   case AtomicRMWInst::Max: return bitc::RMW_MAX;
564   case AtomicRMWInst::Min: return bitc::RMW_MIN;
565   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
566   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
567   }
568 }
569 
570 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
571   switch (Ordering) {
572   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
573   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
574   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
575   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
576   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
577   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
578   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
579   }
580   llvm_unreachable("Invalid ordering");
581 }
582 
583 static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
584   switch (SynchScope) {
585   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
586   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
587   }
588   llvm_unreachable("Invalid synch scope");
589 }
590 
591 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
592                               StringRef Str, unsigned AbbrevToUse) {
593   SmallVector<unsigned, 64> Vals;
594 
595   // Code: [strchar x N]
596   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
597     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
598       AbbrevToUse = 0;
599     Vals.push_back(Str[i]);
600   }
601 
602   // Emit the finished record.
603   Stream.EmitRecord(Code, Vals, AbbrevToUse);
604 }
605 
606 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
607   switch (Kind) {
608   case Attribute::Alignment:
609     return bitc::ATTR_KIND_ALIGNMENT;
610   case Attribute::AllocSize:
611     return bitc::ATTR_KIND_ALLOC_SIZE;
612   case Attribute::AlwaysInline:
613     return bitc::ATTR_KIND_ALWAYS_INLINE;
614   case Attribute::ArgMemOnly:
615     return bitc::ATTR_KIND_ARGMEMONLY;
616   case Attribute::Builtin:
617     return bitc::ATTR_KIND_BUILTIN;
618   case Attribute::ByVal:
619     return bitc::ATTR_KIND_BY_VAL;
620   case Attribute::Convergent:
621     return bitc::ATTR_KIND_CONVERGENT;
622   case Attribute::InAlloca:
623     return bitc::ATTR_KIND_IN_ALLOCA;
624   case Attribute::Cold:
625     return bitc::ATTR_KIND_COLD;
626   case Attribute::InaccessibleMemOnly:
627     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
628   case Attribute::InaccessibleMemOrArgMemOnly:
629     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
630   case Attribute::InlineHint:
631     return bitc::ATTR_KIND_INLINE_HINT;
632   case Attribute::InReg:
633     return bitc::ATTR_KIND_IN_REG;
634   case Attribute::JumpTable:
635     return bitc::ATTR_KIND_JUMP_TABLE;
636   case Attribute::MinSize:
637     return bitc::ATTR_KIND_MIN_SIZE;
638   case Attribute::Naked:
639     return bitc::ATTR_KIND_NAKED;
640   case Attribute::Nest:
641     return bitc::ATTR_KIND_NEST;
642   case Attribute::NoAlias:
643     return bitc::ATTR_KIND_NO_ALIAS;
644   case Attribute::NoBuiltin:
645     return bitc::ATTR_KIND_NO_BUILTIN;
646   case Attribute::NoCapture:
647     return bitc::ATTR_KIND_NO_CAPTURE;
648   case Attribute::NoDuplicate:
649     return bitc::ATTR_KIND_NO_DUPLICATE;
650   case Attribute::NoImplicitFloat:
651     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
652   case Attribute::NoInline:
653     return bitc::ATTR_KIND_NO_INLINE;
654   case Attribute::NoRecurse:
655     return bitc::ATTR_KIND_NO_RECURSE;
656   case Attribute::NonLazyBind:
657     return bitc::ATTR_KIND_NON_LAZY_BIND;
658   case Attribute::NonNull:
659     return bitc::ATTR_KIND_NON_NULL;
660   case Attribute::Dereferenceable:
661     return bitc::ATTR_KIND_DEREFERENCEABLE;
662   case Attribute::DereferenceableOrNull:
663     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
664   case Attribute::NoRedZone:
665     return bitc::ATTR_KIND_NO_RED_ZONE;
666   case Attribute::NoReturn:
667     return bitc::ATTR_KIND_NO_RETURN;
668   case Attribute::NoUnwind:
669     return bitc::ATTR_KIND_NO_UNWIND;
670   case Attribute::OptimizeForSize:
671     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
672   case Attribute::OptimizeNone:
673     return bitc::ATTR_KIND_OPTIMIZE_NONE;
674   case Attribute::ReadNone:
675     return bitc::ATTR_KIND_READ_NONE;
676   case Attribute::ReadOnly:
677     return bitc::ATTR_KIND_READ_ONLY;
678   case Attribute::Returned:
679     return bitc::ATTR_KIND_RETURNED;
680   case Attribute::ReturnsTwice:
681     return bitc::ATTR_KIND_RETURNS_TWICE;
682   case Attribute::SExt:
683     return bitc::ATTR_KIND_S_EXT;
684   case Attribute::StackAlignment:
685     return bitc::ATTR_KIND_STACK_ALIGNMENT;
686   case Attribute::StackProtect:
687     return bitc::ATTR_KIND_STACK_PROTECT;
688   case Attribute::StackProtectReq:
689     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
690   case Attribute::StackProtectStrong:
691     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
692   case Attribute::SafeStack:
693     return bitc::ATTR_KIND_SAFESTACK;
694   case Attribute::StructRet:
695     return bitc::ATTR_KIND_STRUCT_RET;
696   case Attribute::SanitizeAddress:
697     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
698   case Attribute::SanitizeThread:
699     return bitc::ATTR_KIND_SANITIZE_THREAD;
700   case Attribute::SanitizeMemory:
701     return bitc::ATTR_KIND_SANITIZE_MEMORY;
702   case Attribute::SwiftError:
703     return bitc::ATTR_KIND_SWIFT_ERROR;
704   case Attribute::SwiftSelf:
705     return bitc::ATTR_KIND_SWIFT_SELF;
706   case Attribute::UWTable:
707     return bitc::ATTR_KIND_UW_TABLE;
708   case Attribute::WriteOnly:
709     return bitc::ATTR_KIND_WRITEONLY;
710   case Attribute::ZExt:
711     return bitc::ATTR_KIND_Z_EXT;
712   case Attribute::EndAttrKinds:
713     llvm_unreachable("Can not encode end-attribute kinds marker.");
714   case Attribute::None:
715     llvm_unreachable("Can not encode none-attribute.");
716   }
717 
718   llvm_unreachable("Trying to encode unknown attribute");
719 }
720 
721 void ModuleBitcodeWriter::writeAttributeGroupTable() {
722   const std::vector<AttributeList> &AttrGrps = VE.getAttributeGroups();
723   if (AttrGrps.empty()) return;
724 
725   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
726 
727   SmallVector<uint64_t, 64> Record;
728   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
729     AttributeList AS = AttrGrps[i];
730     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
731       AttributeList A = AS.getSlotAttributes(i);
732 
733       Record.push_back(VE.getAttributeGroupID(A));
734       Record.push_back(AS.getSlotIndex(i));
735 
736       for (AttributeList::iterator I = AS.begin(0), E = AS.end(0); I != E;
737            ++I) {
738         Attribute Attr = *I;
739         if (Attr.isEnumAttribute()) {
740           Record.push_back(0);
741           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
742         } else if (Attr.isIntAttribute()) {
743           Record.push_back(1);
744           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
745           Record.push_back(Attr.getValueAsInt());
746         } else {
747           StringRef Kind = Attr.getKindAsString();
748           StringRef Val = Attr.getValueAsString();
749 
750           Record.push_back(Val.empty() ? 3 : 4);
751           Record.append(Kind.begin(), Kind.end());
752           Record.push_back(0);
753           if (!Val.empty()) {
754             Record.append(Val.begin(), Val.end());
755             Record.push_back(0);
756           }
757         }
758       }
759 
760       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
761       Record.clear();
762     }
763   }
764 
765   Stream.ExitBlock();
766 }
767 
768 void ModuleBitcodeWriter::writeAttributeTable() {
769   const std::vector<AttributeList> &Attrs = VE.getAttributes();
770   if (Attrs.empty()) return;
771 
772   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
773 
774   SmallVector<uint64_t, 64> Record;
775   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
776     const AttributeList &A = Attrs[i];
777     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
778       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
779 
780     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
781     Record.clear();
782   }
783 
784   Stream.ExitBlock();
785 }
786 
787 /// WriteTypeTable - Write out the type table for a module.
788 void ModuleBitcodeWriter::writeTypeTable() {
789   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
790 
791   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
792   SmallVector<uint64_t, 64> TypeVals;
793 
794   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
795 
796   // Abbrev for TYPE_CODE_POINTER.
797   auto Abbv = std::make_shared<BitCodeAbbrev>();
798   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
799   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
800   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
801   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
802 
803   // Abbrev for TYPE_CODE_FUNCTION.
804   Abbv = std::make_shared<BitCodeAbbrev>();
805   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
806   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
807   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
808   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
809 
810   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
811 
812   // Abbrev for TYPE_CODE_STRUCT_ANON.
813   Abbv = std::make_shared<BitCodeAbbrev>();
814   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
815   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
816   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
817   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
818 
819   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
820 
821   // Abbrev for TYPE_CODE_STRUCT_NAME.
822   Abbv = std::make_shared<BitCodeAbbrev>();
823   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
824   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
825   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
826   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
827 
828   // Abbrev for TYPE_CODE_STRUCT_NAMED.
829   Abbv = std::make_shared<BitCodeAbbrev>();
830   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
831   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
832   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
833   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
834 
835   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
836 
837   // Abbrev for TYPE_CODE_ARRAY.
838   Abbv = std::make_shared<BitCodeAbbrev>();
839   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
840   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
841   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
842 
843   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
844 
845   // Emit an entry count so the reader can reserve space.
846   TypeVals.push_back(TypeList.size());
847   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
848   TypeVals.clear();
849 
850   // Loop over all of the types, emitting each in turn.
851   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
852     Type *T = TypeList[i];
853     int AbbrevToUse = 0;
854     unsigned Code = 0;
855 
856     switch (T->getTypeID()) {
857     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
858     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
859     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
860     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
861     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
862     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
863     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
864     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
865     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
866     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
867     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
868     case Type::IntegerTyID:
869       // INTEGER: [width]
870       Code = bitc::TYPE_CODE_INTEGER;
871       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
872       break;
873     case Type::PointerTyID: {
874       PointerType *PTy = cast<PointerType>(T);
875       // POINTER: [pointee type, address space]
876       Code = bitc::TYPE_CODE_POINTER;
877       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
878       unsigned AddressSpace = PTy->getAddressSpace();
879       TypeVals.push_back(AddressSpace);
880       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
881       break;
882     }
883     case Type::FunctionTyID: {
884       FunctionType *FT = cast<FunctionType>(T);
885       // FUNCTION: [isvararg, retty, paramty x N]
886       Code = bitc::TYPE_CODE_FUNCTION;
887       TypeVals.push_back(FT->isVarArg());
888       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
889       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
890         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
891       AbbrevToUse = FunctionAbbrev;
892       break;
893     }
894     case Type::StructTyID: {
895       StructType *ST = cast<StructType>(T);
896       // STRUCT: [ispacked, eltty x N]
897       TypeVals.push_back(ST->isPacked());
898       // Output all of the element types.
899       for (StructType::element_iterator I = ST->element_begin(),
900            E = ST->element_end(); I != E; ++I)
901         TypeVals.push_back(VE.getTypeID(*I));
902 
903       if (ST->isLiteral()) {
904         Code = bitc::TYPE_CODE_STRUCT_ANON;
905         AbbrevToUse = StructAnonAbbrev;
906       } else {
907         if (ST->isOpaque()) {
908           Code = bitc::TYPE_CODE_OPAQUE;
909         } else {
910           Code = bitc::TYPE_CODE_STRUCT_NAMED;
911           AbbrevToUse = StructNamedAbbrev;
912         }
913 
914         // Emit the name if it is present.
915         if (!ST->getName().empty())
916           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
917                             StructNameAbbrev);
918       }
919       break;
920     }
921     case Type::ArrayTyID: {
922       ArrayType *AT = cast<ArrayType>(T);
923       // ARRAY: [numelts, eltty]
924       Code = bitc::TYPE_CODE_ARRAY;
925       TypeVals.push_back(AT->getNumElements());
926       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
927       AbbrevToUse = ArrayAbbrev;
928       break;
929     }
930     case Type::VectorTyID: {
931       VectorType *VT = cast<VectorType>(T);
932       // VECTOR [numelts, eltty]
933       Code = bitc::TYPE_CODE_VECTOR;
934       TypeVals.push_back(VT->getNumElements());
935       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
936       break;
937     }
938     }
939 
940     // Emit the finished record.
941     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
942     TypeVals.clear();
943   }
944 
945   Stream.ExitBlock();
946 }
947 
948 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
949   switch (Linkage) {
950   case GlobalValue::ExternalLinkage:
951     return 0;
952   case GlobalValue::WeakAnyLinkage:
953     return 16;
954   case GlobalValue::AppendingLinkage:
955     return 2;
956   case GlobalValue::InternalLinkage:
957     return 3;
958   case GlobalValue::LinkOnceAnyLinkage:
959     return 18;
960   case GlobalValue::ExternalWeakLinkage:
961     return 7;
962   case GlobalValue::CommonLinkage:
963     return 8;
964   case GlobalValue::PrivateLinkage:
965     return 9;
966   case GlobalValue::WeakODRLinkage:
967     return 17;
968   case GlobalValue::LinkOnceODRLinkage:
969     return 19;
970   case GlobalValue::AvailableExternallyLinkage:
971     return 12;
972   }
973   llvm_unreachable("Invalid linkage");
974 }
975 
976 static unsigned getEncodedLinkage(const GlobalValue &GV) {
977   return getEncodedLinkage(GV.getLinkage());
978 }
979 
980 // Decode the flags for GlobalValue in the summary
981 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
982   uint64_t RawFlags = 0;
983 
984   RawFlags |= Flags.NotEligibleToImport; // bool
985   RawFlags |= (Flags.LiveRoot << 1);
986   // Linkage don't need to be remapped at that time for the summary. Any future
987   // change to the getEncodedLinkage() function will need to be taken into
988   // account here as well.
989   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
990 
991   return RawFlags;
992 }
993 
994 static unsigned getEncodedVisibility(const GlobalValue &GV) {
995   switch (GV.getVisibility()) {
996   case GlobalValue::DefaultVisibility:   return 0;
997   case GlobalValue::HiddenVisibility:    return 1;
998   case GlobalValue::ProtectedVisibility: return 2;
999   }
1000   llvm_unreachable("Invalid visibility");
1001 }
1002 
1003 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1004   switch (GV.getDLLStorageClass()) {
1005   case GlobalValue::DefaultStorageClass:   return 0;
1006   case GlobalValue::DLLImportStorageClass: return 1;
1007   case GlobalValue::DLLExportStorageClass: return 2;
1008   }
1009   llvm_unreachable("Invalid DLL storage class");
1010 }
1011 
1012 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1013   switch (GV.getThreadLocalMode()) {
1014     case GlobalVariable::NotThreadLocal:         return 0;
1015     case GlobalVariable::GeneralDynamicTLSModel: return 1;
1016     case GlobalVariable::LocalDynamicTLSModel:   return 2;
1017     case GlobalVariable::InitialExecTLSModel:    return 3;
1018     case GlobalVariable::LocalExecTLSModel:      return 4;
1019   }
1020   llvm_unreachable("Invalid TLS model");
1021 }
1022 
1023 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1024   switch (C.getSelectionKind()) {
1025   case Comdat::Any:
1026     return bitc::COMDAT_SELECTION_KIND_ANY;
1027   case Comdat::ExactMatch:
1028     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1029   case Comdat::Largest:
1030     return bitc::COMDAT_SELECTION_KIND_LARGEST;
1031   case Comdat::NoDuplicates:
1032     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1033   case Comdat::SameSize:
1034     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1035   }
1036   llvm_unreachable("Invalid selection kind");
1037 }
1038 
1039 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1040   switch (GV.getUnnamedAddr()) {
1041   case GlobalValue::UnnamedAddr::None:   return 0;
1042   case GlobalValue::UnnamedAddr::Local:  return 2;
1043   case GlobalValue::UnnamedAddr::Global: return 1;
1044   }
1045   llvm_unreachable("Invalid unnamed_addr");
1046 }
1047 
1048 void ModuleBitcodeWriter::writeComdats() {
1049   SmallVector<unsigned, 64> Vals;
1050   for (const Comdat *C : VE.getComdats()) {
1051     // COMDAT: [selection_kind, name]
1052     Vals.push_back(getEncodedComdatSelectionKind(*C));
1053     size_t Size = C->getName().size();
1054     assert(isUInt<32>(Size));
1055     Vals.push_back(Size);
1056     for (char Chr : C->getName())
1057       Vals.push_back((unsigned char)Chr);
1058     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1059     Vals.clear();
1060   }
1061 }
1062 
1063 /// Write a record that will eventually hold the word offset of the
1064 /// module-level VST. For now the offset is 0, which will be backpatched
1065 /// after the real VST is written. Saves the bit offset to backpatch.
1066 void BitcodeWriterBase::writeValueSymbolTableForwardDecl() {
1067   // Write a placeholder value in for the offset of the real VST,
1068   // which is written after the function blocks so that it can include
1069   // the offset of each function. The placeholder offset will be
1070   // updated when the real VST is written.
1071   auto Abbv = std::make_shared<BitCodeAbbrev>();
1072   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1073   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1074   // hold the real VST offset. Must use fixed instead of VBR as we don't
1075   // know how many VBR chunks to reserve ahead of time.
1076   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1077   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1078 
1079   // Emit the placeholder
1080   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1081   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1082 
1083   // Compute and save the bit offset to the placeholder, which will be
1084   // patched when the real VST is written. We can simply subtract the 32-bit
1085   // fixed size from the current bit number to get the location to backpatch.
1086   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1087 }
1088 
1089 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1090 
1091 /// Determine the encoding to use for the given string name and length.
1092 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
1093   bool isChar6 = true;
1094   for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
1095     if (isChar6)
1096       isChar6 = BitCodeAbbrevOp::isChar6(*C);
1097     if ((unsigned char)*C & 128)
1098       // don't bother scanning the rest.
1099       return SE_Fixed8;
1100   }
1101   if (isChar6)
1102     return SE_Char6;
1103   else
1104     return SE_Fixed7;
1105 }
1106 
1107 /// Emit top-level description of module, including target triple, inline asm,
1108 /// descriptors for global variables, and function prototype info.
1109 /// Returns the bit offset to backpatch with the location of the real VST.
1110 void ModuleBitcodeWriter::writeModuleInfo() {
1111   // Emit various pieces of data attached to a module.
1112   if (!M.getTargetTriple().empty())
1113     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1114                       0 /*TODO*/);
1115   const std::string &DL = M.getDataLayoutStr();
1116   if (!DL.empty())
1117     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1118   if (!M.getModuleInlineAsm().empty())
1119     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1120                       0 /*TODO*/);
1121 
1122   // Emit information about sections and GC, computing how many there are. Also
1123   // compute the maximum alignment value.
1124   std::map<std::string, unsigned> SectionMap;
1125   std::map<std::string, unsigned> GCMap;
1126   unsigned MaxAlignment = 0;
1127   unsigned MaxGlobalType = 0;
1128   for (const GlobalValue &GV : M.globals()) {
1129     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1130     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1131     if (GV.hasSection()) {
1132       // Give section names unique ID's.
1133       unsigned &Entry = SectionMap[GV.getSection()];
1134       if (!Entry) {
1135         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1136                           0 /*TODO*/);
1137         Entry = SectionMap.size();
1138       }
1139     }
1140   }
1141   for (const Function &F : M) {
1142     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1143     if (F.hasSection()) {
1144       // Give section names unique ID's.
1145       unsigned &Entry = SectionMap[F.getSection()];
1146       if (!Entry) {
1147         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1148                           0 /*TODO*/);
1149         Entry = SectionMap.size();
1150       }
1151     }
1152     if (F.hasGC()) {
1153       // Same for GC names.
1154       unsigned &Entry = GCMap[F.getGC()];
1155       if (!Entry) {
1156         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1157                           0 /*TODO*/);
1158         Entry = GCMap.size();
1159       }
1160     }
1161   }
1162 
1163   // Emit abbrev for globals, now that we know # sections and max alignment.
1164   unsigned SimpleGVarAbbrev = 0;
1165   if (!M.global_empty()) {
1166     // Add an abbrev for common globals with no visibility or thread localness.
1167     auto Abbv = std::make_shared<BitCodeAbbrev>();
1168     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1169     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1170                               Log2_32_Ceil(MaxGlobalType+1)));
1171     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
1172                                                            //| explicitType << 1
1173                                                            //| constant
1174     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
1175     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1176     if (MaxAlignment == 0)                                 // Alignment.
1177       Abbv->Add(BitCodeAbbrevOp(0));
1178     else {
1179       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1180       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1181                                Log2_32_Ceil(MaxEncAlignment+1)));
1182     }
1183     if (SectionMap.empty())                                    // Section.
1184       Abbv->Add(BitCodeAbbrevOp(0));
1185     else
1186       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1187                                Log2_32_Ceil(SectionMap.size()+1)));
1188     // Don't bother emitting vis + thread local.
1189     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1190   }
1191 
1192   // Emit the global variable information.
1193   SmallVector<unsigned, 64> Vals;
1194   for (const GlobalVariable &GV : M.globals()) {
1195     unsigned AbbrevToUse = 0;
1196 
1197     // GLOBALVAR: [type, isconst, initid,
1198     //             linkage, alignment, section, visibility, threadlocal,
1199     //             unnamed_addr, externally_initialized, dllstorageclass,
1200     //             comdat]
1201     Vals.push_back(VE.getTypeID(GV.getValueType()));
1202     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1203     Vals.push_back(GV.isDeclaration() ? 0 :
1204                    (VE.getValueID(GV.getInitializer()) + 1));
1205     Vals.push_back(getEncodedLinkage(GV));
1206     Vals.push_back(Log2_32(GV.getAlignment())+1);
1207     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1208     if (GV.isThreadLocal() ||
1209         GV.getVisibility() != GlobalValue::DefaultVisibility ||
1210         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1211         GV.isExternallyInitialized() ||
1212         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1213         GV.hasComdat()) {
1214       Vals.push_back(getEncodedVisibility(GV));
1215       Vals.push_back(getEncodedThreadLocalMode(GV));
1216       Vals.push_back(getEncodedUnnamedAddr(GV));
1217       Vals.push_back(GV.isExternallyInitialized());
1218       Vals.push_back(getEncodedDLLStorageClass(GV));
1219       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1220     } else {
1221       AbbrevToUse = SimpleGVarAbbrev;
1222     }
1223 
1224     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1225     Vals.clear();
1226   }
1227 
1228   // Emit the function proto information.
1229   for (const Function &F : M) {
1230     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
1231     //             section, visibility, gc, unnamed_addr, prologuedata,
1232     //             dllstorageclass, comdat, prefixdata, personalityfn]
1233     Vals.push_back(VE.getTypeID(F.getFunctionType()));
1234     Vals.push_back(F.getCallingConv());
1235     Vals.push_back(F.isDeclaration());
1236     Vals.push_back(getEncodedLinkage(F));
1237     Vals.push_back(VE.getAttributeID(F.getAttributes()));
1238     Vals.push_back(Log2_32(F.getAlignment())+1);
1239     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1240     Vals.push_back(getEncodedVisibility(F));
1241     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1242     Vals.push_back(getEncodedUnnamedAddr(F));
1243     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1244                                        : 0);
1245     Vals.push_back(getEncodedDLLStorageClass(F));
1246     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1247     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1248                                      : 0);
1249     Vals.push_back(
1250         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1251 
1252     unsigned AbbrevToUse = 0;
1253     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1254     Vals.clear();
1255   }
1256 
1257   // Emit the alias information.
1258   for (const GlobalAlias &A : M.aliases()) {
1259     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass,
1260     //         threadlocal, unnamed_addr]
1261     Vals.push_back(VE.getTypeID(A.getValueType()));
1262     Vals.push_back(A.getType()->getAddressSpace());
1263     Vals.push_back(VE.getValueID(A.getAliasee()));
1264     Vals.push_back(getEncodedLinkage(A));
1265     Vals.push_back(getEncodedVisibility(A));
1266     Vals.push_back(getEncodedDLLStorageClass(A));
1267     Vals.push_back(getEncodedThreadLocalMode(A));
1268     Vals.push_back(getEncodedUnnamedAddr(A));
1269     unsigned AbbrevToUse = 0;
1270     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1271     Vals.clear();
1272   }
1273 
1274   // Emit the ifunc information.
1275   for (const GlobalIFunc &I : M.ifuncs()) {
1276     // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility]
1277     Vals.push_back(VE.getTypeID(I.getValueType()));
1278     Vals.push_back(I.getType()->getAddressSpace());
1279     Vals.push_back(VE.getValueID(I.getResolver()));
1280     Vals.push_back(getEncodedLinkage(I));
1281     Vals.push_back(getEncodedVisibility(I));
1282     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1283     Vals.clear();
1284   }
1285 
1286   // Emit the module's source file name.
1287   {
1288     StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1289                                             M.getSourceFileName().size());
1290     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1291     if (Bits == SE_Char6)
1292       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1293     else if (Bits == SE_Fixed7)
1294       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1295 
1296     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1297     auto Abbv = std::make_shared<BitCodeAbbrev>();
1298     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1299     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1300     Abbv->Add(AbbrevOpToUse);
1301     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1302 
1303     for (const auto P : M.getSourceFileName())
1304       Vals.push_back((unsigned char)P);
1305 
1306     // Emit the finished record.
1307     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1308     Vals.clear();
1309   }
1310 
1311   // If we have a VST, write the VSTOFFSET record placeholder.
1312   if (M.getValueSymbolTable().empty())
1313     return;
1314   writeValueSymbolTableForwardDecl();
1315 }
1316 
1317 static uint64_t getOptimizationFlags(const Value *V) {
1318   uint64_t Flags = 0;
1319 
1320   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1321     if (OBO->hasNoSignedWrap())
1322       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1323     if (OBO->hasNoUnsignedWrap())
1324       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1325   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1326     if (PEO->isExact())
1327       Flags |= 1 << bitc::PEO_EXACT;
1328   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1329     if (FPMO->hasUnsafeAlgebra())
1330       Flags |= FastMathFlags::UnsafeAlgebra;
1331     if (FPMO->hasNoNaNs())
1332       Flags |= FastMathFlags::NoNaNs;
1333     if (FPMO->hasNoInfs())
1334       Flags |= FastMathFlags::NoInfs;
1335     if (FPMO->hasNoSignedZeros())
1336       Flags |= FastMathFlags::NoSignedZeros;
1337     if (FPMO->hasAllowReciprocal())
1338       Flags |= FastMathFlags::AllowReciprocal;
1339   }
1340 
1341   return Flags;
1342 }
1343 
1344 void ModuleBitcodeWriter::writeValueAsMetadata(
1345     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1346   // Mimic an MDNode with a value as one operand.
1347   Value *V = MD->getValue();
1348   Record.push_back(VE.getTypeID(V->getType()));
1349   Record.push_back(VE.getValueID(V));
1350   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1351   Record.clear();
1352 }
1353 
1354 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1355                                        SmallVectorImpl<uint64_t> &Record,
1356                                        unsigned Abbrev) {
1357   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1358     Metadata *MD = N->getOperand(i);
1359     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1360            "Unexpected function-local metadata");
1361     Record.push_back(VE.getMetadataOrNullID(MD));
1362   }
1363   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1364                                     : bitc::METADATA_NODE,
1365                     Record, Abbrev);
1366   Record.clear();
1367 }
1368 
1369 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1370   // Assume the column is usually under 128, and always output the inlined-at
1371   // location (it's never more expensive than building an array size 1).
1372   auto Abbv = std::make_shared<BitCodeAbbrev>();
1373   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1374   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1375   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1376   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1377   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1378   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1379   return Stream.EmitAbbrev(std::move(Abbv));
1380 }
1381 
1382 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1383                                           SmallVectorImpl<uint64_t> &Record,
1384                                           unsigned &Abbrev) {
1385   if (!Abbrev)
1386     Abbrev = createDILocationAbbrev();
1387 
1388   Record.push_back(N->isDistinct());
1389   Record.push_back(N->getLine());
1390   Record.push_back(N->getColumn());
1391   Record.push_back(VE.getMetadataID(N->getScope()));
1392   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1393 
1394   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1395   Record.clear();
1396 }
1397 
1398 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1399   // Assume the column is usually under 128, and always output the inlined-at
1400   // location (it's never more expensive than building an array size 1).
1401   auto Abbv = std::make_shared<BitCodeAbbrev>();
1402   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1403   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1404   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1405   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1406   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1407   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1408   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1409   return Stream.EmitAbbrev(std::move(Abbv));
1410 }
1411 
1412 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1413                                              SmallVectorImpl<uint64_t> &Record,
1414                                              unsigned &Abbrev) {
1415   if (!Abbrev)
1416     Abbrev = createGenericDINodeAbbrev();
1417 
1418   Record.push_back(N->isDistinct());
1419   Record.push_back(N->getTag());
1420   Record.push_back(0); // Per-tag version field; unused for now.
1421 
1422   for (auto &I : N->operands())
1423     Record.push_back(VE.getMetadataOrNullID(I));
1424 
1425   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1426   Record.clear();
1427 }
1428 
1429 static uint64_t rotateSign(int64_t I) {
1430   uint64_t U = I;
1431   return I < 0 ? ~(U << 1) : U << 1;
1432 }
1433 
1434 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1435                                           SmallVectorImpl<uint64_t> &Record,
1436                                           unsigned Abbrev) {
1437   Record.push_back(N->isDistinct());
1438   Record.push_back(N->getCount());
1439   Record.push_back(rotateSign(N->getLowerBound()));
1440 
1441   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1442   Record.clear();
1443 }
1444 
1445 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1446                                             SmallVectorImpl<uint64_t> &Record,
1447                                             unsigned Abbrev) {
1448   Record.push_back(N->isDistinct());
1449   Record.push_back(rotateSign(N->getValue()));
1450   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1451 
1452   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1453   Record.clear();
1454 }
1455 
1456 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1457                                            SmallVectorImpl<uint64_t> &Record,
1458                                            unsigned Abbrev) {
1459   Record.push_back(N->isDistinct());
1460   Record.push_back(N->getTag());
1461   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1462   Record.push_back(N->getSizeInBits());
1463   Record.push_back(N->getAlignInBits());
1464   Record.push_back(N->getEncoding());
1465 
1466   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1467   Record.clear();
1468 }
1469 
1470 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1471                                              SmallVectorImpl<uint64_t> &Record,
1472                                              unsigned Abbrev) {
1473   Record.push_back(N->isDistinct());
1474   Record.push_back(N->getTag());
1475   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1476   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1477   Record.push_back(N->getLine());
1478   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1479   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1480   Record.push_back(N->getSizeInBits());
1481   Record.push_back(N->getAlignInBits());
1482   Record.push_back(N->getOffsetInBits());
1483   Record.push_back(N->getFlags());
1484   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1485 
1486   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1487   // that there is no DWARF address space associated with DIDerivedType.
1488   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1489     Record.push_back(*DWARFAddressSpace + 1);
1490   else
1491     Record.push_back(0);
1492 
1493   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1494   Record.clear();
1495 }
1496 
1497 void ModuleBitcodeWriter::writeDICompositeType(
1498     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1499     unsigned Abbrev) {
1500   const unsigned IsNotUsedInOldTypeRef = 0x2;
1501   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1502   Record.push_back(N->getTag());
1503   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1504   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1505   Record.push_back(N->getLine());
1506   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1507   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1508   Record.push_back(N->getSizeInBits());
1509   Record.push_back(N->getAlignInBits());
1510   Record.push_back(N->getOffsetInBits());
1511   Record.push_back(N->getFlags());
1512   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1513   Record.push_back(N->getRuntimeLang());
1514   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1515   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1516   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1517 
1518   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1519   Record.clear();
1520 }
1521 
1522 void ModuleBitcodeWriter::writeDISubroutineType(
1523     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1524     unsigned Abbrev) {
1525   const unsigned HasNoOldTypeRefs = 0x2;
1526   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1527   Record.push_back(N->getFlags());
1528   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1529   Record.push_back(N->getCC());
1530 
1531   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1532   Record.clear();
1533 }
1534 
1535 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1536                                       SmallVectorImpl<uint64_t> &Record,
1537                                       unsigned Abbrev) {
1538   Record.push_back(N->isDistinct());
1539   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1540   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1541   Record.push_back(N->getChecksumKind());
1542   Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1543 
1544   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1545   Record.clear();
1546 }
1547 
1548 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1549                                              SmallVectorImpl<uint64_t> &Record,
1550                                              unsigned Abbrev) {
1551   assert(N->isDistinct() && "Expected distinct compile units");
1552   Record.push_back(/* IsDistinct */ true);
1553   Record.push_back(N->getSourceLanguage());
1554   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1555   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1556   Record.push_back(N->isOptimized());
1557   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1558   Record.push_back(N->getRuntimeVersion());
1559   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1560   Record.push_back(N->getEmissionKind());
1561   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1562   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1563   Record.push_back(/* subprograms */ 0);
1564   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1565   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1566   Record.push_back(N->getDWOId());
1567   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1568   Record.push_back(N->getSplitDebugInlining());
1569   Record.push_back(N->getDebugInfoForProfiling());
1570 
1571   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1572   Record.clear();
1573 }
1574 
1575 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1576                                             SmallVectorImpl<uint64_t> &Record,
1577                                             unsigned Abbrev) {
1578   uint64_t HasUnitFlag = 1 << 1;
1579   Record.push_back(N->isDistinct() | HasUnitFlag);
1580   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1581   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1582   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1583   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1584   Record.push_back(N->getLine());
1585   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1586   Record.push_back(N->isLocalToUnit());
1587   Record.push_back(N->isDefinition());
1588   Record.push_back(N->getScopeLine());
1589   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1590   Record.push_back(N->getVirtuality());
1591   Record.push_back(N->getVirtualIndex());
1592   Record.push_back(N->getFlags());
1593   Record.push_back(N->isOptimized());
1594   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1595   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1596   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1597   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1598   Record.push_back(N->getThisAdjustment());
1599 
1600   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1601   Record.clear();
1602 }
1603 
1604 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1605                                               SmallVectorImpl<uint64_t> &Record,
1606                                               unsigned Abbrev) {
1607   Record.push_back(N->isDistinct());
1608   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1609   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1610   Record.push_back(N->getLine());
1611   Record.push_back(N->getColumn());
1612 
1613   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1614   Record.clear();
1615 }
1616 
1617 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1618     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1619     unsigned Abbrev) {
1620   Record.push_back(N->isDistinct());
1621   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1622   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1623   Record.push_back(N->getDiscriminator());
1624 
1625   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1626   Record.clear();
1627 }
1628 
1629 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1630                                            SmallVectorImpl<uint64_t> &Record,
1631                                            unsigned Abbrev) {
1632   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1633   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1634   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1635   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1636   Record.push_back(N->getLine());
1637 
1638   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1639   Record.clear();
1640 }
1641 
1642 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1643                                        SmallVectorImpl<uint64_t> &Record,
1644                                        unsigned Abbrev) {
1645   Record.push_back(N->isDistinct());
1646   Record.push_back(N->getMacinfoType());
1647   Record.push_back(N->getLine());
1648   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1649   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1650 
1651   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1652   Record.clear();
1653 }
1654 
1655 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1656                                            SmallVectorImpl<uint64_t> &Record,
1657                                            unsigned Abbrev) {
1658   Record.push_back(N->isDistinct());
1659   Record.push_back(N->getMacinfoType());
1660   Record.push_back(N->getLine());
1661   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1662   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1663 
1664   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1665   Record.clear();
1666 }
1667 
1668 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1669                                         SmallVectorImpl<uint64_t> &Record,
1670                                         unsigned Abbrev) {
1671   Record.push_back(N->isDistinct());
1672   for (auto &I : N->operands())
1673     Record.push_back(VE.getMetadataOrNullID(I));
1674 
1675   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1676   Record.clear();
1677 }
1678 
1679 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1680     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1681     unsigned Abbrev) {
1682   Record.push_back(N->isDistinct());
1683   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1684   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1685 
1686   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1687   Record.clear();
1688 }
1689 
1690 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1691     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1692     unsigned Abbrev) {
1693   Record.push_back(N->isDistinct());
1694   Record.push_back(N->getTag());
1695   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1696   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1697   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1698 
1699   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1700   Record.clear();
1701 }
1702 
1703 void ModuleBitcodeWriter::writeDIGlobalVariable(
1704     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1705     unsigned Abbrev) {
1706   const uint64_t Version = 1 << 1;
1707   Record.push_back((uint64_t)N->isDistinct() | Version);
1708   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1709   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1710   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1711   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1712   Record.push_back(N->getLine());
1713   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1714   Record.push_back(N->isLocalToUnit());
1715   Record.push_back(N->isDefinition());
1716   Record.push_back(/* expr */ 0);
1717   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1718   Record.push_back(N->getAlignInBits());
1719 
1720   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1721   Record.clear();
1722 }
1723 
1724 void ModuleBitcodeWriter::writeDILocalVariable(
1725     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1726     unsigned Abbrev) {
1727   // In order to support all possible bitcode formats in BitcodeReader we need
1728   // to distinguish the following cases:
1729   // 1) Record has no artificial tag (Record[1]),
1730   //   has no obsolete inlinedAt field (Record[9]).
1731   //   In this case Record size will be 8, HasAlignment flag is false.
1732   // 2) Record has artificial tag (Record[1]),
1733   //   has no obsolete inlignedAt field (Record[9]).
1734   //   In this case Record size will be 9, HasAlignment flag is false.
1735   // 3) Record has both artificial tag (Record[1]) and
1736   //   obsolete inlignedAt field (Record[9]).
1737   //   In this case Record size will be 10, HasAlignment flag is false.
1738   // 4) Record has neither artificial tag, nor inlignedAt field, but
1739   //   HasAlignment flag is true and Record[8] contains alignment value.
1740   const uint64_t HasAlignmentFlag = 1 << 1;
1741   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1742   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1743   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1744   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1745   Record.push_back(N->getLine());
1746   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1747   Record.push_back(N->getArg());
1748   Record.push_back(N->getFlags());
1749   Record.push_back(N->getAlignInBits());
1750 
1751   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1752   Record.clear();
1753 }
1754 
1755 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1756                                             SmallVectorImpl<uint64_t> &Record,
1757                                             unsigned Abbrev) {
1758   Record.reserve(N->getElements().size() + 1);
1759 
1760   const uint64_t HasOpFragmentFlag = 1 << 1;
1761   Record.push_back((uint64_t)N->isDistinct() | HasOpFragmentFlag);
1762   Record.append(N->elements_begin(), N->elements_end());
1763 
1764   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1765   Record.clear();
1766 }
1767 
1768 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1769     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1770     unsigned Abbrev) {
1771   Record.push_back(N->isDistinct());
1772   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1773   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1774 
1775   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1776   Record.clear();
1777 }
1778 
1779 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1780                                               SmallVectorImpl<uint64_t> &Record,
1781                                               unsigned Abbrev) {
1782   Record.push_back(N->isDistinct());
1783   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1784   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1785   Record.push_back(N->getLine());
1786   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1787   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1788   Record.push_back(N->getAttributes());
1789   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1790 
1791   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1792   Record.clear();
1793 }
1794 
1795 void ModuleBitcodeWriter::writeDIImportedEntity(
1796     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1797     unsigned Abbrev) {
1798   Record.push_back(N->isDistinct());
1799   Record.push_back(N->getTag());
1800   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1801   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1802   Record.push_back(N->getLine());
1803   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1804 
1805   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1806   Record.clear();
1807 }
1808 
1809 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1810   auto Abbv = std::make_shared<BitCodeAbbrev>();
1811   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1812   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1813   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1814   return Stream.EmitAbbrev(std::move(Abbv));
1815 }
1816 
1817 void ModuleBitcodeWriter::writeNamedMetadata(
1818     SmallVectorImpl<uint64_t> &Record) {
1819   if (M.named_metadata_empty())
1820     return;
1821 
1822   unsigned Abbrev = createNamedMetadataAbbrev();
1823   for (const NamedMDNode &NMD : M.named_metadata()) {
1824     // Write name.
1825     StringRef Str = NMD.getName();
1826     Record.append(Str.bytes_begin(), Str.bytes_end());
1827     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1828     Record.clear();
1829 
1830     // Write named metadata operands.
1831     for (const MDNode *N : NMD.operands())
1832       Record.push_back(VE.getMetadataID(N));
1833     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1834     Record.clear();
1835   }
1836 }
1837 
1838 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1839   auto Abbv = std::make_shared<BitCodeAbbrev>();
1840   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1841   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1842   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1843   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1844   return Stream.EmitAbbrev(std::move(Abbv));
1845 }
1846 
1847 /// Write out a record for MDString.
1848 ///
1849 /// All the metadata strings in a metadata block are emitted in a single
1850 /// record.  The sizes and strings themselves are shoved into a blob.
1851 void ModuleBitcodeWriter::writeMetadataStrings(
1852     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1853   if (Strings.empty())
1854     return;
1855 
1856   // Start the record with the number of strings.
1857   Record.push_back(bitc::METADATA_STRINGS);
1858   Record.push_back(Strings.size());
1859 
1860   // Emit the sizes of the strings in the blob.
1861   SmallString<256> Blob;
1862   {
1863     BitstreamWriter W(Blob);
1864     for (const Metadata *MD : Strings)
1865       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1866     W.FlushToWord();
1867   }
1868 
1869   // Add the offset to the strings to the record.
1870   Record.push_back(Blob.size());
1871 
1872   // Add the strings to the blob.
1873   for (const Metadata *MD : Strings)
1874     Blob.append(cast<MDString>(MD)->getString());
1875 
1876   // Emit the final record.
1877   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1878   Record.clear();
1879 }
1880 
1881 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1882 enum MetadataAbbrev : unsigned {
1883 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1884 #include "llvm/IR/Metadata.def"
1885   LastPlusOne
1886 };
1887 
1888 void ModuleBitcodeWriter::writeMetadataRecords(
1889     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1890     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1891   if (MDs.empty())
1892     return;
1893 
1894   // Initialize MDNode abbreviations.
1895 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1896 #include "llvm/IR/Metadata.def"
1897 
1898   for (const Metadata *MD : MDs) {
1899     if (IndexPos)
1900       IndexPos->push_back(Stream.GetCurrentBitNo());
1901     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1902       assert(N->isResolved() && "Expected forward references to be resolved");
1903 
1904       switch (N->getMetadataID()) {
1905       default:
1906         llvm_unreachable("Invalid MDNode subclass");
1907 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1908   case Metadata::CLASS##Kind:                                                  \
1909     if (MDAbbrevs)                                                             \
1910       write##CLASS(cast<CLASS>(N), Record,                                     \
1911                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
1912     else                                                                       \
1913       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
1914     continue;
1915 #include "llvm/IR/Metadata.def"
1916       }
1917     }
1918     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1919   }
1920 }
1921 
1922 void ModuleBitcodeWriter::writeModuleMetadata() {
1923   if (!VE.hasMDs() && M.named_metadata_empty())
1924     return;
1925 
1926   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1927   SmallVector<uint64_t, 64> Record;
1928 
1929   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1930   // block and load any metadata.
1931   std::vector<unsigned> MDAbbrevs;
1932 
1933   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1934   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1935   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1936       createGenericDINodeAbbrev();
1937 
1938   auto Abbv = std::make_shared<BitCodeAbbrev>();
1939   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1940   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1941   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1942   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1943 
1944   Abbv = std::make_shared<BitCodeAbbrev>();
1945   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1946   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1947   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1948   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1949 
1950   // Emit MDStrings together upfront.
1951   writeMetadataStrings(VE.getMDStrings(), Record);
1952 
1953   // We only emit an index for the metadata record if we have more than a given
1954   // (naive) threshold of metadatas, otherwise it is not worth it.
1955   if (VE.getNonMDStrings().size() > IndexThreshold) {
1956     // Write a placeholder value in for the offset of the metadata index,
1957     // which is written after the records, so that it can include
1958     // the offset of each entry. The placeholder offset will be
1959     // updated after all records are emitted.
1960     uint64_t Vals[] = {0, 0};
1961     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1962   }
1963 
1964   // Compute and save the bit offset to the current position, which will be
1965   // patched when we emit the index later. We can simply subtract the 64-bit
1966   // fixed size from the current bit number to get the location to backpatch.
1967   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1968 
1969   // This index will contain the bitpos for each individual record.
1970   std::vector<uint64_t> IndexPos;
1971   IndexPos.reserve(VE.getNonMDStrings().size());
1972 
1973   // Write all the records
1974   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1975 
1976   if (VE.getNonMDStrings().size() > IndexThreshold) {
1977     // Now that we have emitted all the records we will emit the index. But
1978     // first
1979     // backpatch the forward reference so that the reader can skip the records
1980     // efficiently.
1981     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1982                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1983 
1984     // Delta encode the index.
1985     uint64_t PreviousValue = IndexOffsetRecordBitPos;
1986     for (auto &Elt : IndexPos) {
1987       auto EltDelta = Elt - PreviousValue;
1988       PreviousValue = Elt;
1989       Elt = EltDelta;
1990     }
1991     // Emit the index record.
1992     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1993     IndexPos.clear();
1994   }
1995 
1996   // Write the named metadata now.
1997   writeNamedMetadata(Record);
1998 
1999   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2000     SmallVector<uint64_t, 4> Record;
2001     Record.push_back(VE.getValueID(&GO));
2002     pushGlobalMetadataAttachment(Record, GO);
2003     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2004   };
2005   for (const Function &F : M)
2006     if (F.isDeclaration() && F.hasMetadata())
2007       AddDeclAttachedMetadata(F);
2008   // FIXME: Only store metadata for declarations here, and move data for global
2009   // variable definitions to a separate block (PR28134).
2010   for (const GlobalVariable &GV : M.globals())
2011     if (GV.hasMetadata())
2012       AddDeclAttachedMetadata(GV);
2013 
2014   Stream.ExitBlock();
2015 }
2016 
2017 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2018   if (!VE.hasMDs())
2019     return;
2020 
2021   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2022   SmallVector<uint64_t, 64> Record;
2023   writeMetadataStrings(VE.getMDStrings(), Record);
2024   writeMetadataRecords(VE.getNonMDStrings(), Record);
2025   Stream.ExitBlock();
2026 }
2027 
2028 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2029     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2030   // [n x [id, mdnode]]
2031   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2032   GO.getAllMetadata(MDs);
2033   for (const auto &I : MDs) {
2034     Record.push_back(I.first);
2035     Record.push_back(VE.getMetadataID(I.second));
2036   }
2037 }
2038 
2039 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2040   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2041 
2042   SmallVector<uint64_t, 64> Record;
2043 
2044   if (F.hasMetadata()) {
2045     pushGlobalMetadataAttachment(Record, F);
2046     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2047     Record.clear();
2048   }
2049 
2050   // Write metadata attachments
2051   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2052   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2053   for (const BasicBlock &BB : F)
2054     for (const Instruction &I : BB) {
2055       MDs.clear();
2056       I.getAllMetadataOtherThanDebugLoc(MDs);
2057 
2058       // If no metadata, ignore instruction.
2059       if (MDs.empty()) continue;
2060 
2061       Record.push_back(VE.getInstructionID(&I));
2062 
2063       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2064         Record.push_back(MDs[i].first);
2065         Record.push_back(VE.getMetadataID(MDs[i].second));
2066       }
2067       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2068       Record.clear();
2069     }
2070 
2071   Stream.ExitBlock();
2072 }
2073 
2074 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2075   SmallVector<uint64_t, 64> Record;
2076 
2077   // Write metadata kinds
2078   // METADATA_KIND - [n x [id, name]]
2079   SmallVector<StringRef, 8> Names;
2080   M.getMDKindNames(Names);
2081 
2082   if (Names.empty()) return;
2083 
2084   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2085 
2086   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2087     Record.push_back(MDKindID);
2088     StringRef KName = Names[MDKindID];
2089     Record.append(KName.begin(), KName.end());
2090 
2091     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2092     Record.clear();
2093   }
2094 
2095   Stream.ExitBlock();
2096 }
2097 
2098 void ModuleBitcodeWriter::writeOperandBundleTags() {
2099   // Write metadata kinds
2100   //
2101   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2102   //
2103   // OPERAND_BUNDLE_TAG - [strchr x N]
2104 
2105   SmallVector<StringRef, 8> Tags;
2106   M.getOperandBundleTags(Tags);
2107 
2108   if (Tags.empty())
2109     return;
2110 
2111   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2112 
2113   SmallVector<uint64_t, 64> Record;
2114 
2115   for (auto Tag : Tags) {
2116     Record.append(Tag.begin(), Tag.end());
2117 
2118     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2119     Record.clear();
2120   }
2121 
2122   Stream.ExitBlock();
2123 }
2124 
2125 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2126   if ((int64_t)V >= 0)
2127     Vals.push_back(V << 1);
2128   else
2129     Vals.push_back((-V << 1) | 1);
2130 }
2131 
2132 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2133                                          bool isGlobal) {
2134   if (FirstVal == LastVal) return;
2135 
2136   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2137 
2138   unsigned AggregateAbbrev = 0;
2139   unsigned String8Abbrev = 0;
2140   unsigned CString7Abbrev = 0;
2141   unsigned CString6Abbrev = 0;
2142   // If this is a constant pool for the module, emit module-specific abbrevs.
2143   if (isGlobal) {
2144     // Abbrev for CST_CODE_AGGREGATE.
2145     auto Abbv = std::make_shared<BitCodeAbbrev>();
2146     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2147     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2148     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2149     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2150 
2151     // Abbrev for CST_CODE_STRING.
2152     Abbv = std::make_shared<BitCodeAbbrev>();
2153     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2154     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2155     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2156     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2157     // Abbrev for CST_CODE_CSTRING.
2158     Abbv = std::make_shared<BitCodeAbbrev>();
2159     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2160     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2161     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2162     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2163     // Abbrev for CST_CODE_CSTRING.
2164     Abbv = std::make_shared<BitCodeAbbrev>();
2165     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2166     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2167     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2168     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2169   }
2170 
2171   SmallVector<uint64_t, 64> Record;
2172 
2173   const ValueEnumerator::ValueList &Vals = VE.getValues();
2174   Type *LastTy = nullptr;
2175   for (unsigned i = FirstVal; i != LastVal; ++i) {
2176     const Value *V = Vals[i].first;
2177     // If we need to switch types, do so now.
2178     if (V->getType() != LastTy) {
2179       LastTy = V->getType();
2180       Record.push_back(VE.getTypeID(LastTy));
2181       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2182                         CONSTANTS_SETTYPE_ABBREV);
2183       Record.clear();
2184     }
2185 
2186     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2187       Record.push_back(unsigned(IA->hasSideEffects()) |
2188                        unsigned(IA->isAlignStack()) << 1 |
2189                        unsigned(IA->getDialect()&1) << 2);
2190 
2191       // Add the asm string.
2192       const std::string &AsmStr = IA->getAsmString();
2193       Record.push_back(AsmStr.size());
2194       Record.append(AsmStr.begin(), AsmStr.end());
2195 
2196       // Add the constraint string.
2197       const std::string &ConstraintStr = IA->getConstraintString();
2198       Record.push_back(ConstraintStr.size());
2199       Record.append(ConstraintStr.begin(), ConstraintStr.end());
2200       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2201       Record.clear();
2202       continue;
2203     }
2204     const Constant *C = cast<Constant>(V);
2205     unsigned Code = -1U;
2206     unsigned AbbrevToUse = 0;
2207     if (C->isNullValue()) {
2208       Code = bitc::CST_CODE_NULL;
2209     } else if (isa<UndefValue>(C)) {
2210       Code = bitc::CST_CODE_UNDEF;
2211     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2212       if (IV->getBitWidth() <= 64) {
2213         uint64_t V = IV->getSExtValue();
2214         emitSignedInt64(Record, V);
2215         Code = bitc::CST_CODE_INTEGER;
2216         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2217       } else {                             // Wide integers, > 64 bits in size.
2218         // We have an arbitrary precision integer value to write whose
2219         // bit width is > 64. However, in canonical unsigned integer
2220         // format it is likely that the high bits are going to be zero.
2221         // So, we only write the number of active words.
2222         unsigned NWords = IV->getValue().getActiveWords();
2223         const uint64_t *RawWords = IV->getValue().getRawData();
2224         for (unsigned i = 0; i != NWords; ++i) {
2225           emitSignedInt64(Record, RawWords[i]);
2226         }
2227         Code = bitc::CST_CODE_WIDE_INTEGER;
2228       }
2229     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2230       Code = bitc::CST_CODE_FLOAT;
2231       Type *Ty = CFP->getType();
2232       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2233         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2234       } else if (Ty->isX86_FP80Ty()) {
2235         // api needed to prevent premature destruction
2236         // bits are not in the same order as a normal i80 APInt, compensate.
2237         APInt api = CFP->getValueAPF().bitcastToAPInt();
2238         const uint64_t *p = api.getRawData();
2239         Record.push_back((p[1] << 48) | (p[0] >> 16));
2240         Record.push_back(p[0] & 0xffffLL);
2241       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2242         APInt api = CFP->getValueAPF().bitcastToAPInt();
2243         const uint64_t *p = api.getRawData();
2244         Record.push_back(p[0]);
2245         Record.push_back(p[1]);
2246       } else {
2247         assert (0 && "Unknown FP type!");
2248       }
2249     } else if (isa<ConstantDataSequential>(C) &&
2250                cast<ConstantDataSequential>(C)->isString()) {
2251       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2252       // Emit constant strings specially.
2253       unsigned NumElts = Str->getNumElements();
2254       // If this is a null-terminated string, use the denser CSTRING encoding.
2255       if (Str->isCString()) {
2256         Code = bitc::CST_CODE_CSTRING;
2257         --NumElts;  // Don't encode the null, which isn't allowed by char6.
2258       } else {
2259         Code = bitc::CST_CODE_STRING;
2260         AbbrevToUse = String8Abbrev;
2261       }
2262       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2263       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2264       for (unsigned i = 0; i != NumElts; ++i) {
2265         unsigned char V = Str->getElementAsInteger(i);
2266         Record.push_back(V);
2267         isCStr7 &= (V & 128) == 0;
2268         if (isCStrChar6)
2269           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2270       }
2271 
2272       if (isCStrChar6)
2273         AbbrevToUse = CString6Abbrev;
2274       else if (isCStr7)
2275         AbbrevToUse = CString7Abbrev;
2276     } else if (const ConstantDataSequential *CDS =
2277                   dyn_cast<ConstantDataSequential>(C)) {
2278       Code = bitc::CST_CODE_DATA;
2279       Type *EltTy = CDS->getType()->getElementType();
2280       if (isa<IntegerType>(EltTy)) {
2281         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2282           Record.push_back(CDS->getElementAsInteger(i));
2283       } else {
2284         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2285           Record.push_back(
2286               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2287       }
2288     } else if (isa<ConstantAggregate>(C)) {
2289       Code = bitc::CST_CODE_AGGREGATE;
2290       for (const Value *Op : C->operands())
2291         Record.push_back(VE.getValueID(Op));
2292       AbbrevToUse = AggregateAbbrev;
2293     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2294       switch (CE->getOpcode()) {
2295       default:
2296         if (Instruction::isCast(CE->getOpcode())) {
2297           Code = bitc::CST_CODE_CE_CAST;
2298           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2299           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2300           Record.push_back(VE.getValueID(C->getOperand(0)));
2301           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2302         } else {
2303           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2304           Code = bitc::CST_CODE_CE_BINOP;
2305           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2306           Record.push_back(VE.getValueID(C->getOperand(0)));
2307           Record.push_back(VE.getValueID(C->getOperand(1)));
2308           uint64_t Flags = getOptimizationFlags(CE);
2309           if (Flags != 0)
2310             Record.push_back(Flags);
2311         }
2312         break;
2313       case Instruction::GetElementPtr: {
2314         Code = bitc::CST_CODE_CE_GEP;
2315         const auto *GO = cast<GEPOperator>(C);
2316         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2317         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2318           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2319           Record.push_back((*Idx << 1) | GO->isInBounds());
2320         } else if (GO->isInBounds())
2321           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2322         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2323           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2324           Record.push_back(VE.getValueID(C->getOperand(i)));
2325         }
2326         break;
2327       }
2328       case Instruction::Select:
2329         Code = bitc::CST_CODE_CE_SELECT;
2330         Record.push_back(VE.getValueID(C->getOperand(0)));
2331         Record.push_back(VE.getValueID(C->getOperand(1)));
2332         Record.push_back(VE.getValueID(C->getOperand(2)));
2333         break;
2334       case Instruction::ExtractElement:
2335         Code = bitc::CST_CODE_CE_EXTRACTELT;
2336         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2337         Record.push_back(VE.getValueID(C->getOperand(0)));
2338         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2339         Record.push_back(VE.getValueID(C->getOperand(1)));
2340         break;
2341       case Instruction::InsertElement:
2342         Code = bitc::CST_CODE_CE_INSERTELT;
2343         Record.push_back(VE.getValueID(C->getOperand(0)));
2344         Record.push_back(VE.getValueID(C->getOperand(1)));
2345         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2346         Record.push_back(VE.getValueID(C->getOperand(2)));
2347         break;
2348       case Instruction::ShuffleVector:
2349         // If the return type and argument types are the same, this is a
2350         // standard shufflevector instruction.  If the types are different,
2351         // then the shuffle is widening or truncating the input vectors, and
2352         // the argument type must also be encoded.
2353         if (C->getType() == C->getOperand(0)->getType()) {
2354           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2355         } else {
2356           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2357           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2358         }
2359         Record.push_back(VE.getValueID(C->getOperand(0)));
2360         Record.push_back(VE.getValueID(C->getOperand(1)));
2361         Record.push_back(VE.getValueID(C->getOperand(2)));
2362         break;
2363       case Instruction::ICmp:
2364       case Instruction::FCmp:
2365         Code = bitc::CST_CODE_CE_CMP;
2366         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2367         Record.push_back(VE.getValueID(C->getOperand(0)));
2368         Record.push_back(VE.getValueID(C->getOperand(1)));
2369         Record.push_back(CE->getPredicate());
2370         break;
2371       }
2372     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2373       Code = bitc::CST_CODE_BLOCKADDRESS;
2374       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2375       Record.push_back(VE.getValueID(BA->getFunction()));
2376       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2377     } else {
2378 #ifndef NDEBUG
2379       C->dump();
2380 #endif
2381       llvm_unreachable("Unknown constant!");
2382     }
2383     Stream.EmitRecord(Code, Record, AbbrevToUse);
2384     Record.clear();
2385   }
2386 
2387   Stream.ExitBlock();
2388 }
2389 
2390 void ModuleBitcodeWriter::writeModuleConstants() {
2391   const ValueEnumerator::ValueList &Vals = VE.getValues();
2392 
2393   // Find the first constant to emit, which is the first non-globalvalue value.
2394   // We know globalvalues have been emitted by WriteModuleInfo.
2395   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2396     if (!isa<GlobalValue>(Vals[i].first)) {
2397       writeConstants(i, Vals.size(), true);
2398       return;
2399     }
2400   }
2401 }
2402 
2403 /// pushValueAndType - The file has to encode both the value and type id for
2404 /// many values, because we need to know what type to create for forward
2405 /// references.  However, most operands are not forward references, so this type
2406 /// field is not needed.
2407 ///
2408 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2409 /// instruction ID, then it is a forward reference, and it also includes the
2410 /// type ID.  The value ID that is written is encoded relative to the InstID.
2411 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2412                                            SmallVectorImpl<unsigned> &Vals) {
2413   unsigned ValID = VE.getValueID(V);
2414   // Make encoding relative to the InstID.
2415   Vals.push_back(InstID - ValID);
2416   if (ValID >= InstID) {
2417     Vals.push_back(VE.getTypeID(V->getType()));
2418     return true;
2419   }
2420   return false;
2421 }
2422 
2423 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2424                                               unsigned InstID) {
2425   SmallVector<unsigned, 64> Record;
2426   LLVMContext &C = CS.getInstruction()->getContext();
2427 
2428   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2429     const auto &Bundle = CS.getOperandBundleAt(i);
2430     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2431 
2432     for (auto &Input : Bundle.Inputs)
2433       pushValueAndType(Input, InstID, Record);
2434 
2435     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2436     Record.clear();
2437   }
2438 }
2439 
2440 /// pushValue - Like pushValueAndType, but where the type of the value is
2441 /// omitted (perhaps it was already encoded in an earlier operand).
2442 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2443                                     SmallVectorImpl<unsigned> &Vals) {
2444   unsigned ValID = VE.getValueID(V);
2445   Vals.push_back(InstID - ValID);
2446 }
2447 
2448 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2449                                           SmallVectorImpl<uint64_t> &Vals) {
2450   unsigned ValID = VE.getValueID(V);
2451   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2452   emitSignedInt64(Vals, diff);
2453 }
2454 
2455 /// WriteInstruction - Emit an instruction to the specified stream.
2456 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2457                                            unsigned InstID,
2458                                            SmallVectorImpl<unsigned> &Vals) {
2459   unsigned Code = 0;
2460   unsigned AbbrevToUse = 0;
2461   VE.setInstructionID(&I);
2462   switch (I.getOpcode()) {
2463   default:
2464     if (Instruction::isCast(I.getOpcode())) {
2465       Code = bitc::FUNC_CODE_INST_CAST;
2466       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2467         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2468       Vals.push_back(VE.getTypeID(I.getType()));
2469       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2470     } else {
2471       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2472       Code = bitc::FUNC_CODE_INST_BINOP;
2473       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2474         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2475       pushValue(I.getOperand(1), InstID, Vals);
2476       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2477       uint64_t Flags = getOptimizationFlags(&I);
2478       if (Flags != 0) {
2479         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2480           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2481         Vals.push_back(Flags);
2482       }
2483     }
2484     break;
2485 
2486   case Instruction::GetElementPtr: {
2487     Code = bitc::FUNC_CODE_INST_GEP;
2488     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2489     auto &GEPInst = cast<GetElementPtrInst>(I);
2490     Vals.push_back(GEPInst.isInBounds());
2491     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2492     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2493       pushValueAndType(I.getOperand(i), InstID, Vals);
2494     break;
2495   }
2496   case Instruction::ExtractValue: {
2497     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2498     pushValueAndType(I.getOperand(0), InstID, Vals);
2499     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2500     Vals.append(EVI->idx_begin(), EVI->idx_end());
2501     break;
2502   }
2503   case Instruction::InsertValue: {
2504     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2505     pushValueAndType(I.getOperand(0), InstID, Vals);
2506     pushValueAndType(I.getOperand(1), InstID, Vals);
2507     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2508     Vals.append(IVI->idx_begin(), IVI->idx_end());
2509     break;
2510   }
2511   case Instruction::Select:
2512     Code = bitc::FUNC_CODE_INST_VSELECT;
2513     pushValueAndType(I.getOperand(1), InstID, Vals);
2514     pushValue(I.getOperand(2), InstID, Vals);
2515     pushValueAndType(I.getOperand(0), InstID, Vals);
2516     break;
2517   case Instruction::ExtractElement:
2518     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2519     pushValueAndType(I.getOperand(0), InstID, Vals);
2520     pushValueAndType(I.getOperand(1), InstID, Vals);
2521     break;
2522   case Instruction::InsertElement:
2523     Code = bitc::FUNC_CODE_INST_INSERTELT;
2524     pushValueAndType(I.getOperand(0), InstID, Vals);
2525     pushValue(I.getOperand(1), InstID, Vals);
2526     pushValueAndType(I.getOperand(2), InstID, Vals);
2527     break;
2528   case Instruction::ShuffleVector:
2529     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2530     pushValueAndType(I.getOperand(0), InstID, Vals);
2531     pushValue(I.getOperand(1), InstID, Vals);
2532     pushValue(I.getOperand(2), InstID, Vals);
2533     break;
2534   case Instruction::ICmp:
2535   case Instruction::FCmp: {
2536     // compare returning Int1Ty or vector of Int1Ty
2537     Code = bitc::FUNC_CODE_INST_CMP2;
2538     pushValueAndType(I.getOperand(0), InstID, Vals);
2539     pushValue(I.getOperand(1), InstID, Vals);
2540     Vals.push_back(cast<CmpInst>(I).getPredicate());
2541     uint64_t Flags = getOptimizationFlags(&I);
2542     if (Flags != 0)
2543       Vals.push_back(Flags);
2544     break;
2545   }
2546 
2547   case Instruction::Ret:
2548     {
2549       Code = bitc::FUNC_CODE_INST_RET;
2550       unsigned NumOperands = I.getNumOperands();
2551       if (NumOperands == 0)
2552         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2553       else if (NumOperands == 1) {
2554         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2555           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2556       } else {
2557         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2558           pushValueAndType(I.getOperand(i), InstID, Vals);
2559       }
2560     }
2561     break;
2562   case Instruction::Br:
2563     {
2564       Code = bitc::FUNC_CODE_INST_BR;
2565       const BranchInst &II = cast<BranchInst>(I);
2566       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2567       if (II.isConditional()) {
2568         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2569         pushValue(II.getCondition(), InstID, Vals);
2570       }
2571     }
2572     break;
2573   case Instruction::Switch:
2574     {
2575       Code = bitc::FUNC_CODE_INST_SWITCH;
2576       const SwitchInst &SI = cast<SwitchInst>(I);
2577       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2578       pushValue(SI.getCondition(), InstID, Vals);
2579       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2580       for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2581         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2582         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2583       }
2584     }
2585     break;
2586   case Instruction::IndirectBr:
2587     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2588     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2589     // Encode the address operand as relative, but not the basic blocks.
2590     pushValue(I.getOperand(0), InstID, Vals);
2591     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2592       Vals.push_back(VE.getValueID(I.getOperand(i)));
2593     break;
2594 
2595   case Instruction::Invoke: {
2596     const InvokeInst *II = cast<InvokeInst>(&I);
2597     const Value *Callee = II->getCalledValue();
2598     FunctionType *FTy = II->getFunctionType();
2599 
2600     if (II->hasOperandBundles())
2601       writeOperandBundles(II, InstID);
2602 
2603     Code = bitc::FUNC_CODE_INST_INVOKE;
2604 
2605     Vals.push_back(VE.getAttributeID(II->getAttributes()));
2606     Vals.push_back(II->getCallingConv() | 1 << 13);
2607     Vals.push_back(VE.getValueID(II->getNormalDest()));
2608     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2609     Vals.push_back(VE.getTypeID(FTy));
2610     pushValueAndType(Callee, InstID, Vals);
2611 
2612     // Emit value #'s for the fixed parameters.
2613     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2614       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2615 
2616     // Emit type/value pairs for varargs params.
2617     if (FTy->isVarArg()) {
2618       for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2619            i != e; ++i)
2620         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2621     }
2622     break;
2623   }
2624   case Instruction::Resume:
2625     Code = bitc::FUNC_CODE_INST_RESUME;
2626     pushValueAndType(I.getOperand(0), InstID, Vals);
2627     break;
2628   case Instruction::CleanupRet: {
2629     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2630     const auto &CRI = cast<CleanupReturnInst>(I);
2631     pushValue(CRI.getCleanupPad(), InstID, Vals);
2632     if (CRI.hasUnwindDest())
2633       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2634     break;
2635   }
2636   case Instruction::CatchRet: {
2637     Code = bitc::FUNC_CODE_INST_CATCHRET;
2638     const auto &CRI = cast<CatchReturnInst>(I);
2639     pushValue(CRI.getCatchPad(), InstID, Vals);
2640     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2641     break;
2642   }
2643   case Instruction::CleanupPad:
2644   case Instruction::CatchPad: {
2645     const auto &FuncletPad = cast<FuncletPadInst>(I);
2646     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2647                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2648     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2649 
2650     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2651     Vals.push_back(NumArgOperands);
2652     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2653       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2654     break;
2655   }
2656   case Instruction::CatchSwitch: {
2657     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2658     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2659 
2660     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2661 
2662     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2663     Vals.push_back(NumHandlers);
2664     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2665       Vals.push_back(VE.getValueID(CatchPadBB));
2666 
2667     if (CatchSwitch.hasUnwindDest())
2668       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2669     break;
2670   }
2671   case Instruction::Unreachable:
2672     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2673     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2674     break;
2675 
2676   case Instruction::PHI: {
2677     const PHINode &PN = cast<PHINode>(I);
2678     Code = bitc::FUNC_CODE_INST_PHI;
2679     // With the newer instruction encoding, forward references could give
2680     // negative valued IDs.  This is most common for PHIs, so we use
2681     // signed VBRs.
2682     SmallVector<uint64_t, 128> Vals64;
2683     Vals64.push_back(VE.getTypeID(PN.getType()));
2684     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2685       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2686       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2687     }
2688     // Emit a Vals64 vector and exit.
2689     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2690     Vals64.clear();
2691     return;
2692   }
2693 
2694   case Instruction::LandingPad: {
2695     const LandingPadInst &LP = cast<LandingPadInst>(I);
2696     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2697     Vals.push_back(VE.getTypeID(LP.getType()));
2698     Vals.push_back(LP.isCleanup());
2699     Vals.push_back(LP.getNumClauses());
2700     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2701       if (LP.isCatch(I))
2702         Vals.push_back(LandingPadInst::Catch);
2703       else
2704         Vals.push_back(LandingPadInst::Filter);
2705       pushValueAndType(LP.getClause(I), InstID, Vals);
2706     }
2707     break;
2708   }
2709 
2710   case Instruction::Alloca: {
2711     Code = bitc::FUNC_CODE_INST_ALLOCA;
2712     const AllocaInst &AI = cast<AllocaInst>(I);
2713     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2714     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2715     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2716     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2717     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2718            "not enough bits for maximum alignment");
2719     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2720     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2721     AlignRecord |= 1 << 6;
2722     AlignRecord |= AI.isSwiftError() << 7;
2723     Vals.push_back(AlignRecord);
2724     break;
2725   }
2726 
2727   case Instruction::Load:
2728     if (cast<LoadInst>(I).isAtomic()) {
2729       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2730       pushValueAndType(I.getOperand(0), InstID, Vals);
2731     } else {
2732       Code = bitc::FUNC_CODE_INST_LOAD;
2733       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2734         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2735     }
2736     Vals.push_back(VE.getTypeID(I.getType()));
2737     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2738     Vals.push_back(cast<LoadInst>(I).isVolatile());
2739     if (cast<LoadInst>(I).isAtomic()) {
2740       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2741       Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2742     }
2743     break;
2744   case Instruction::Store:
2745     if (cast<StoreInst>(I).isAtomic())
2746       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2747     else
2748       Code = bitc::FUNC_CODE_INST_STORE;
2749     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2750     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2751     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2752     Vals.push_back(cast<StoreInst>(I).isVolatile());
2753     if (cast<StoreInst>(I).isAtomic()) {
2754       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2755       Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2756     }
2757     break;
2758   case Instruction::AtomicCmpXchg:
2759     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2760     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2761     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2762     pushValue(I.getOperand(2), InstID, Vals);        // newval.
2763     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2764     Vals.push_back(
2765         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2766     Vals.push_back(
2767         getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2768     Vals.push_back(
2769         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2770     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2771     break;
2772   case Instruction::AtomicRMW:
2773     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2774     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2775     pushValue(I.getOperand(1), InstID, Vals);        // val.
2776     Vals.push_back(
2777         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2778     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2779     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2780     Vals.push_back(
2781         getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2782     break;
2783   case Instruction::Fence:
2784     Code = bitc::FUNC_CODE_INST_FENCE;
2785     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2786     Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2787     break;
2788   case Instruction::Call: {
2789     const CallInst &CI = cast<CallInst>(I);
2790     FunctionType *FTy = CI.getFunctionType();
2791 
2792     if (CI.hasOperandBundles())
2793       writeOperandBundles(&CI, InstID);
2794 
2795     Code = bitc::FUNC_CODE_INST_CALL;
2796 
2797     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2798 
2799     unsigned Flags = getOptimizationFlags(&I);
2800     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2801                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2802                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2803                    1 << bitc::CALL_EXPLICIT_TYPE |
2804                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2805                    unsigned(Flags != 0) << bitc::CALL_FMF);
2806     if (Flags != 0)
2807       Vals.push_back(Flags);
2808 
2809     Vals.push_back(VE.getTypeID(FTy));
2810     pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2811 
2812     // Emit value #'s for the fixed parameters.
2813     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2814       // Check for labels (can happen with asm labels).
2815       if (FTy->getParamType(i)->isLabelTy())
2816         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2817       else
2818         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2819     }
2820 
2821     // Emit type/value pairs for varargs params.
2822     if (FTy->isVarArg()) {
2823       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2824            i != e; ++i)
2825         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2826     }
2827     break;
2828   }
2829   case Instruction::VAArg:
2830     Code = bitc::FUNC_CODE_INST_VAARG;
2831     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
2832     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
2833     Vals.push_back(VE.getTypeID(I.getType())); // restype.
2834     break;
2835   }
2836 
2837   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2838   Vals.clear();
2839 }
2840 
2841 /// Emit names for globals/functions etc. \p IsModuleLevel is true when
2842 /// we are writing the module-level VST, where we are including a function
2843 /// bitcode index and need to backpatch the VST forward declaration record.
2844 void ModuleBitcodeWriter::writeValueSymbolTable(
2845     const ValueSymbolTable &VST, bool IsModuleLevel,
2846     DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) {
2847   if (VST.empty()) {
2848     // writeValueSymbolTableForwardDecl should have returned early as
2849     // well. Ensure this handling remains in sync by asserting that
2850     // the placeholder offset is not set.
2851     assert(!IsModuleLevel || !hasVSTOffsetPlaceholder());
2852     return;
2853   }
2854 
2855   if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2856     // Get the offset of the VST we are writing, and backpatch it into
2857     // the VST forward declaration record.
2858     uint64_t VSTOffset = Stream.GetCurrentBitNo();
2859     // The BitcodeStartBit was the stream offset of the identification block.
2860     VSTOffset -= bitcodeStartBit();
2861     assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2862     // Note that we add 1 here because the offset is relative to one word
2863     // before the start of the identification block, which was historically
2864     // always the start of the regular bitcode header.
2865     Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2866   }
2867 
2868   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2869 
2870   // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2871   // records, which are not used in the per-function VSTs.
2872   unsigned FnEntry8BitAbbrev;
2873   unsigned FnEntry7BitAbbrev;
2874   unsigned FnEntry6BitAbbrev;
2875   unsigned GUIDEntryAbbrev;
2876   if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2877     // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2878     auto Abbv = std::make_shared<BitCodeAbbrev>();
2879     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2880     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2881     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2882     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2883     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2884     FnEntry8BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2885 
2886     // 7-bit fixed width VST_CODE_FNENTRY function strings.
2887     Abbv = std::make_shared<BitCodeAbbrev>();
2888     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2889     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2890     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2891     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2892     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2893     FnEntry7BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2894 
2895     // 6-bit char6 VST_CODE_FNENTRY function strings.
2896     Abbv = std::make_shared<BitCodeAbbrev>();
2897     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2898     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2899     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2900     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2901     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2902     FnEntry6BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2903 
2904     // FIXME: Change the name of this record as it is now used by
2905     // the per-module index as well.
2906     Abbv = std::make_shared<BitCodeAbbrev>();
2907     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2908     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2909     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2910     GUIDEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2911   }
2912 
2913   // FIXME: Set up the abbrev, we know how many values there are!
2914   // FIXME: We know if the type names can use 7-bit ascii.
2915   SmallVector<uint64_t, 64> NameVals;
2916 
2917   for (const ValueName &Name : VST) {
2918     // Figure out the encoding to use for the name.
2919     StringEncoding Bits =
2920         getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2921 
2922     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2923     NameVals.push_back(VE.getValueID(Name.getValue()));
2924 
2925     Function *F = dyn_cast<Function>(Name.getValue());
2926     if (!F) {
2927       // If value is an alias, need to get the aliased base object to
2928       // see if it is a function.
2929       auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2930       if (GA && GA->getBaseObject())
2931         F = dyn_cast<Function>(GA->getBaseObject());
2932     }
2933 
2934     // VST_CODE_ENTRY:   [valueid, namechar x N]
2935     // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2936     // VST_CODE_BBENTRY: [bbid, namechar x N]
2937     unsigned Code;
2938     if (isa<BasicBlock>(Name.getValue())) {
2939       Code = bitc::VST_CODE_BBENTRY;
2940       if (Bits == SE_Char6)
2941         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2942     } else if (F && !F->isDeclaration()) {
2943       // Must be the module-level VST, where we pass in the Index and
2944       // have a VSTOffsetPlaceholder. The function-level VST should not
2945       // contain any Function symbols.
2946       assert(FunctionToBitcodeIndex);
2947       assert(hasVSTOffsetPlaceholder());
2948 
2949       // Save the word offset of the function (from the start of the
2950       // actual bitcode written to the stream).
2951       uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit();
2952       assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2953       // Note that we add 1 here because the offset is relative to one word
2954       // before the start of the identification block, which was historically
2955       // always the start of the regular bitcode header.
2956       NameVals.push_back(BitcodeIndex / 32 + 1);
2957 
2958       Code = bitc::VST_CODE_FNENTRY;
2959       AbbrevToUse = FnEntry8BitAbbrev;
2960       if (Bits == SE_Char6)
2961         AbbrevToUse = FnEntry6BitAbbrev;
2962       else if (Bits == SE_Fixed7)
2963         AbbrevToUse = FnEntry7BitAbbrev;
2964     } else {
2965       Code = bitc::VST_CODE_ENTRY;
2966       if (Bits == SE_Char6)
2967         AbbrevToUse = VST_ENTRY_6_ABBREV;
2968       else if (Bits == SE_Fixed7)
2969         AbbrevToUse = VST_ENTRY_7_ABBREV;
2970     }
2971 
2972     for (const auto P : Name.getKey())
2973       NameVals.push_back((unsigned char)P);
2974 
2975     // Emit the finished record.
2976     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2977     NameVals.clear();
2978   }
2979   // Emit any GUID valueIDs created for indirect call edges into the
2980   // module-level VST.
2981   if (IsModuleLevel && hasVSTOffsetPlaceholder())
2982     for (const auto &GI : valueIds()) {
2983       NameVals.push_back(GI.second);
2984       NameVals.push_back(GI.first);
2985       Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals,
2986                         GUIDEntryAbbrev);
2987       NameVals.clear();
2988     }
2989   Stream.ExitBlock();
2990 }
2991 
2992 /// Emit function names and summary offsets for the combined index
2993 /// used by ThinLTO.
2994 void IndexBitcodeWriter::writeCombinedValueSymbolTable() {
2995   assert(hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder");
2996   // Get the offset of the VST we are writing, and backpatch it into
2997   // the VST forward declaration record.
2998   uint64_t VSTOffset = Stream.GetCurrentBitNo();
2999   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3000   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
3001 
3002   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3003 
3004   auto Abbv = std::make_shared<BitCodeAbbrev>();
3005   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
3006   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3007   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
3008   unsigned EntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3009 
3010   SmallVector<uint64_t, 64> NameVals;
3011   for (const auto &GVI : valueIds()) {
3012     // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
3013     NameVals.push_back(GVI.second);
3014     NameVals.push_back(GVI.first);
3015 
3016     // Emit the finished record.
3017     Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
3018     NameVals.clear();
3019   }
3020   Stream.ExitBlock();
3021 }
3022 
3023 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3024   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3025   unsigned Code;
3026   if (isa<BasicBlock>(Order.V))
3027     Code = bitc::USELIST_CODE_BB;
3028   else
3029     Code = bitc::USELIST_CODE_DEFAULT;
3030 
3031   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3032   Record.push_back(VE.getValueID(Order.V));
3033   Stream.EmitRecord(Code, Record);
3034 }
3035 
3036 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3037   assert(VE.shouldPreserveUseListOrder() &&
3038          "Expected to be preserving use-list order");
3039 
3040   auto hasMore = [&]() {
3041     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3042   };
3043   if (!hasMore())
3044     // Nothing to do.
3045     return;
3046 
3047   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3048   while (hasMore()) {
3049     writeUseList(std::move(VE.UseListOrders.back()));
3050     VE.UseListOrders.pop_back();
3051   }
3052   Stream.ExitBlock();
3053 }
3054 
3055 /// Emit a function body to the module stream.
3056 void ModuleBitcodeWriter::writeFunction(
3057     const Function &F,
3058     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3059   // Save the bitcode index of the start of this function block for recording
3060   // in the VST.
3061   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3062 
3063   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3064   VE.incorporateFunction(F);
3065 
3066   SmallVector<unsigned, 64> Vals;
3067 
3068   // Emit the number of basic blocks, so the reader can create them ahead of
3069   // time.
3070   Vals.push_back(VE.getBasicBlocks().size());
3071   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3072   Vals.clear();
3073 
3074   // If there are function-local constants, emit them now.
3075   unsigned CstStart, CstEnd;
3076   VE.getFunctionConstantRange(CstStart, CstEnd);
3077   writeConstants(CstStart, CstEnd, false);
3078 
3079   // If there is function-local metadata, emit it now.
3080   writeFunctionMetadata(F);
3081 
3082   // Keep a running idea of what the instruction ID is.
3083   unsigned InstID = CstEnd;
3084 
3085   bool NeedsMetadataAttachment = F.hasMetadata();
3086 
3087   DILocation *LastDL = nullptr;
3088   // Finally, emit all the instructions, in order.
3089   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3090     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3091          I != E; ++I) {
3092       writeInstruction(*I, InstID, Vals);
3093 
3094       if (!I->getType()->isVoidTy())
3095         ++InstID;
3096 
3097       // If the instruction has metadata, write a metadata attachment later.
3098       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3099 
3100       // If the instruction has a debug location, emit it.
3101       DILocation *DL = I->getDebugLoc();
3102       if (!DL)
3103         continue;
3104 
3105       if (DL == LastDL) {
3106         // Just repeat the same debug loc as last time.
3107         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3108         continue;
3109       }
3110 
3111       Vals.push_back(DL->getLine());
3112       Vals.push_back(DL->getColumn());
3113       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3114       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3115       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3116       Vals.clear();
3117 
3118       LastDL = DL;
3119     }
3120 
3121   // Emit names for all the instructions etc.
3122   if (auto *Symtab = F.getValueSymbolTable())
3123     writeValueSymbolTable(*Symtab);
3124 
3125   if (NeedsMetadataAttachment)
3126     writeFunctionMetadataAttachment(F);
3127   if (VE.shouldPreserveUseListOrder())
3128     writeUseListBlock(&F);
3129   VE.purgeFunction();
3130   Stream.ExitBlock();
3131 }
3132 
3133 // Emit blockinfo, which defines the standard abbreviations etc.
3134 void ModuleBitcodeWriter::writeBlockInfo() {
3135   // We only want to emit block info records for blocks that have multiple
3136   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3137   // Other blocks can define their abbrevs inline.
3138   Stream.EnterBlockInfoBlock();
3139 
3140   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3141     auto Abbv = std::make_shared<BitCodeAbbrev>();
3142     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3143     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3144     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3145     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3146     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3147         VST_ENTRY_8_ABBREV)
3148       llvm_unreachable("Unexpected abbrev ordering!");
3149   }
3150 
3151   { // 7-bit fixed width VST_CODE_ENTRY strings.
3152     auto Abbv = std::make_shared<BitCodeAbbrev>();
3153     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3154     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3155     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3156     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3157     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3158         VST_ENTRY_7_ABBREV)
3159       llvm_unreachable("Unexpected abbrev ordering!");
3160   }
3161   { // 6-bit char6 VST_CODE_ENTRY strings.
3162     auto Abbv = std::make_shared<BitCodeAbbrev>();
3163     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3164     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3165     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3166     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3167     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3168         VST_ENTRY_6_ABBREV)
3169       llvm_unreachable("Unexpected abbrev ordering!");
3170   }
3171   { // 6-bit char6 VST_CODE_BBENTRY strings.
3172     auto Abbv = std::make_shared<BitCodeAbbrev>();
3173     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3174     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3175     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3176     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3177     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3178         VST_BBENTRY_6_ABBREV)
3179       llvm_unreachable("Unexpected abbrev ordering!");
3180   }
3181 
3182 
3183 
3184   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3185     auto Abbv = std::make_shared<BitCodeAbbrev>();
3186     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3187     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3188                               VE.computeBitsRequiredForTypeIndicies()));
3189     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3190         CONSTANTS_SETTYPE_ABBREV)
3191       llvm_unreachable("Unexpected abbrev ordering!");
3192   }
3193 
3194   { // INTEGER abbrev for CONSTANTS_BLOCK.
3195     auto Abbv = std::make_shared<BitCodeAbbrev>();
3196     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3197     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3198     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3199         CONSTANTS_INTEGER_ABBREV)
3200       llvm_unreachable("Unexpected abbrev ordering!");
3201   }
3202 
3203   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3204     auto Abbv = std::make_shared<BitCodeAbbrev>();
3205     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3206     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3207     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3208                               VE.computeBitsRequiredForTypeIndicies()));
3209     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3210 
3211     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3212         CONSTANTS_CE_CAST_Abbrev)
3213       llvm_unreachable("Unexpected abbrev ordering!");
3214   }
3215   { // NULL abbrev for CONSTANTS_BLOCK.
3216     auto Abbv = std::make_shared<BitCodeAbbrev>();
3217     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3218     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3219         CONSTANTS_NULL_Abbrev)
3220       llvm_unreachable("Unexpected abbrev ordering!");
3221   }
3222 
3223   // FIXME: This should only use space for first class types!
3224 
3225   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3226     auto Abbv = std::make_shared<BitCodeAbbrev>();
3227     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3228     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3229     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3230                               VE.computeBitsRequiredForTypeIndicies()));
3231     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3232     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3233     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3234         FUNCTION_INST_LOAD_ABBREV)
3235       llvm_unreachable("Unexpected abbrev ordering!");
3236   }
3237   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3238     auto Abbv = std::make_shared<BitCodeAbbrev>();
3239     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3240     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3241     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3242     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3243     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3244         FUNCTION_INST_BINOP_ABBREV)
3245       llvm_unreachable("Unexpected abbrev ordering!");
3246   }
3247   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3248     auto Abbv = std::make_shared<BitCodeAbbrev>();
3249     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3250     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3251     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3252     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3253     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3254     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3255         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3256       llvm_unreachable("Unexpected abbrev ordering!");
3257   }
3258   { // INST_CAST abbrev for FUNCTION_BLOCK.
3259     auto Abbv = std::make_shared<BitCodeAbbrev>();
3260     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3261     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3262     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3263                               VE.computeBitsRequiredForTypeIndicies()));
3264     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3265     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3266         FUNCTION_INST_CAST_ABBREV)
3267       llvm_unreachable("Unexpected abbrev ordering!");
3268   }
3269 
3270   { // INST_RET abbrev for FUNCTION_BLOCK.
3271     auto Abbv = std::make_shared<BitCodeAbbrev>();
3272     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3273     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3274         FUNCTION_INST_RET_VOID_ABBREV)
3275       llvm_unreachable("Unexpected abbrev ordering!");
3276   }
3277   { // INST_RET abbrev for FUNCTION_BLOCK.
3278     auto Abbv = std::make_shared<BitCodeAbbrev>();
3279     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3280     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3281     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3282         FUNCTION_INST_RET_VAL_ABBREV)
3283       llvm_unreachable("Unexpected abbrev ordering!");
3284   }
3285   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3286     auto Abbv = std::make_shared<BitCodeAbbrev>();
3287     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3288     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3289         FUNCTION_INST_UNREACHABLE_ABBREV)
3290       llvm_unreachable("Unexpected abbrev ordering!");
3291   }
3292   {
3293     auto Abbv = std::make_shared<BitCodeAbbrev>();
3294     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3295     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3296     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3297                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3298     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3299     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3300     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3301         FUNCTION_INST_GEP_ABBREV)
3302       llvm_unreachable("Unexpected abbrev ordering!");
3303   }
3304 
3305   Stream.ExitBlock();
3306 }
3307 
3308 /// Write the module path strings, currently only used when generating
3309 /// a combined index file.
3310 void IndexBitcodeWriter::writeModStrings() {
3311   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3312 
3313   // TODO: See which abbrev sizes we actually need to emit
3314 
3315   // 8-bit fixed-width MST_ENTRY strings.
3316   auto Abbv = std::make_shared<BitCodeAbbrev>();
3317   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3318   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3319   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3320   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3321   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3322 
3323   // 7-bit fixed width MST_ENTRY strings.
3324   Abbv = std::make_shared<BitCodeAbbrev>();
3325   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3326   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3327   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3328   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3329   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3330 
3331   // 6-bit char6 MST_ENTRY strings.
3332   Abbv = std::make_shared<BitCodeAbbrev>();
3333   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3334   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3335   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3336   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3337   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3338 
3339   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3340   Abbv = std::make_shared<BitCodeAbbrev>();
3341   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3342   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3343   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3344   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3345   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3346   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3347   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3348 
3349   SmallVector<unsigned, 64> Vals;
3350   for (const auto &MPSE : Index.modulePaths()) {
3351     if (!doIncludeModule(MPSE.getKey()))
3352       continue;
3353     StringEncoding Bits =
3354         getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3355     unsigned AbbrevToUse = Abbrev8Bit;
3356     if (Bits == SE_Char6)
3357       AbbrevToUse = Abbrev6Bit;
3358     else if (Bits == SE_Fixed7)
3359       AbbrevToUse = Abbrev7Bit;
3360 
3361     Vals.push_back(MPSE.getValue().first);
3362 
3363     for (const auto P : MPSE.getKey())
3364       Vals.push_back((unsigned char)P);
3365 
3366     // Emit the finished record.
3367     Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3368 
3369     Vals.clear();
3370     // Emit an optional hash for the module now
3371     auto &Hash = MPSE.getValue().second;
3372     bool AllZero = true; // Detect if the hash is empty, and do not generate it
3373     for (auto Val : Hash) {
3374       if (Val)
3375         AllZero = false;
3376       Vals.push_back(Val);
3377     }
3378     if (!AllZero) {
3379       // Emit the hash record.
3380       Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3381     }
3382 
3383     Vals.clear();
3384   }
3385   Stream.ExitBlock();
3386 }
3387 
3388 /// Write the function type metadata related records that need to appear before
3389 /// a function summary entry (whether per-module or combined).
3390 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3391                                              FunctionSummary *FS) {
3392   if (!FS->type_tests().empty())
3393     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3394 
3395   SmallVector<uint64_t, 64> Record;
3396 
3397   auto WriteVFuncIdVec = [&](uint64_t Ty,
3398                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3399     if (VFs.empty())
3400       return;
3401     Record.clear();
3402     for (auto &VF : VFs) {
3403       Record.push_back(VF.GUID);
3404       Record.push_back(VF.Offset);
3405     }
3406     Stream.EmitRecord(Ty, Record);
3407   };
3408 
3409   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3410                   FS->type_test_assume_vcalls());
3411   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3412                   FS->type_checked_load_vcalls());
3413 
3414   auto WriteConstVCallVec = [&](uint64_t Ty,
3415                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3416     for (auto &VC : VCs) {
3417       Record.clear();
3418       Record.push_back(VC.VFunc.GUID);
3419       Record.push_back(VC.VFunc.Offset);
3420       Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3421       Stream.EmitRecord(Ty, Record);
3422     }
3423   };
3424 
3425   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3426                      FS->type_test_assume_const_vcalls());
3427   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3428                      FS->type_checked_load_const_vcalls());
3429 }
3430 
3431 // Helper to emit a single function summary record.
3432 void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3433     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3434     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3435     const Function &F) {
3436   NameVals.push_back(ValueID);
3437 
3438   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3439   writeFunctionTypeMetadataRecords(Stream, FS);
3440 
3441   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3442   NameVals.push_back(FS->instCount());
3443   NameVals.push_back(FS->refs().size());
3444 
3445   for (auto &RI : FS->refs())
3446     NameVals.push_back(VE.getValueID(RI.getValue()));
3447 
3448   bool HasProfileData = F.getEntryCount().hasValue();
3449   for (auto &ECI : FS->calls()) {
3450     NameVals.push_back(getValueId(ECI.first));
3451     if (HasProfileData)
3452       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3453   }
3454 
3455   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3456   unsigned Code =
3457       (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3458 
3459   // Emit the finished record.
3460   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3461   NameVals.clear();
3462 }
3463 
3464 // Collect the global value references in the given variable's initializer,
3465 // and emit them in a summary record.
3466 void ModuleBitcodeWriter::writeModuleLevelReferences(
3467     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3468     unsigned FSModRefsAbbrev) {
3469   auto Summaries =
3470       Index->findGlobalValueSummaryList(GlobalValue::getGUID(V.getName()));
3471   if (Summaries == Index->end()) {
3472     // Only declarations should not have a summary (a declaration might however
3473     // have a summary if the def was in module level asm).
3474     assert(V.isDeclaration());
3475     return;
3476   }
3477   auto *Summary = Summaries->second.front().get();
3478   NameVals.push_back(VE.getValueID(&V));
3479   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3480   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3481 
3482   unsigned SizeBeforeRefs = NameVals.size();
3483   for (auto &RI : VS->refs())
3484     NameVals.push_back(VE.getValueID(RI.getValue()));
3485   // Sort the refs for determinism output, the vector returned by FS->refs() has
3486   // been initialized from a DenseSet.
3487   std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3488 
3489   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3490                     FSModRefsAbbrev);
3491   NameVals.clear();
3492 }
3493 
3494 // Current version for the summary.
3495 // This is bumped whenever we introduce changes in the way some record are
3496 // interpreted, like flags for instance.
3497 static const uint64_t INDEX_VERSION = 3;
3498 
3499 /// Emit the per-module summary section alongside the rest of
3500 /// the module's bitcode.
3501 void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3502   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
3503 
3504   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3505 
3506   if (Index->begin() == Index->end()) {
3507     Stream.ExitBlock();
3508     return;
3509   }
3510 
3511   // Abbrev for FS_PERMODULE.
3512   auto Abbv = std::make_shared<BitCodeAbbrev>();
3513   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3514   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3515   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3516   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3517   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3518   // numrefs x valueid, n x (valueid)
3519   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3520   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3521   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3522 
3523   // Abbrev for FS_PERMODULE_PROFILE.
3524   Abbv = std::make_shared<BitCodeAbbrev>();
3525   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3526   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3527   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3528   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3529   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3530   // numrefs x valueid, n x (valueid, hotness)
3531   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3532   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3533   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3534 
3535   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3536   Abbv = std::make_shared<BitCodeAbbrev>();
3537   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3538   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3539   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3540   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3541   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3542   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3543 
3544   // Abbrev for FS_ALIAS.
3545   Abbv = std::make_shared<BitCodeAbbrev>();
3546   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3547   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3548   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3549   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3550   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3551 
3552   SmallVector<uint64_t, 64> NameVals;
3553   // Iterate over the list of functions instead of the Index to
3554   // ensure the ordering is stable.
3555   for (const Function &F : M) {
3556     // Summary emission does not support anonymous functions, they have to
3557     // renamed using the anonymous function renaming pass.
3558     if (!F.hasName())
3559       report_fatal_error("Unexpected anonymous function when writing summary");
3560 
3561     auto Summaries =
3562         Index->findGlobalValueSummaryList(GlobalValue::getGUID(F.getName()));
3563     if (Summaries == Index->end()) {
3564       // Only declarations should not have a summary (a declaration might
3565       // however have a summary if the def was in module level asm).
3566       assert(F.isDeclaration());
3567       continue;
3568     }
3569     auto *Summary = Summaries->second.front().get();
3570     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3571                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
3572   }
3573 
3574   // Capture references from GlobalVariable initializers, which are outside
3575   // of a function scope.
3576   for (const GlobalVariable &G : M.globals())
3577     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3578 
3579   for (const GlobalAlias &A : M.aliases()) {
3580     auto *Aliasee = A.getBaseObject();
3581     if (!Aliasee->hasName())
3582       // Nameless function don't have an entry in the summary, skip it.
3583       continue;
3584     auto AliasId = VE.getValueID(&A);
3585     auto AliaseeId = VE.getValueID(Aliasee);
3586     NameVals.push_back(AliasId);
3587     auto *Summary = Index->getGlobalValueSummary(A);
3588     AliasSummary *AS = cast<AliasSummary>(Summary);
3589     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3590     NameVals.push_back(AliaseeId);
3591     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3592     NameVals.clear();
3593   }
3594 
3595   Stream.ExitBlock();
3596 }
3597 
3598 /// Emit the combined summary section into the combined index file.
3599 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3600   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3601   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3602 
3603   // Abbrev for FS_COMBINED.
3604   auto Abbv = std::make_shared<BitCodeAbbrev>();
3605   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3606   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3607   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3608   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3609   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3610   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3611   // numrefs x valueid, n x (valueid)
3612   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3613   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3614   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3615 
3616   // Abbrev for FS_COMBINED_PROFILE.
3617   Abbv = std::make_shared<BitCodeAbbrev>();
3618   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3619   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3620   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3621   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3622   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3623   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3624   // numrefs x valueid, n x (valueid, hotness)
3625   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3626   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3627   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3628 
3629   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3630   Abbv = std::make_shared<BitCodeAbbrev>();
3631   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3632   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3633   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3634   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3635   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
3636   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3637   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3638 
3639   // Abbrev for FS_COMBINED_ALIAS.
3640   Abbv = std::make_shared<BitCodeAbbrev>();
3641   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3642   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3643   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3644   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3645   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3646   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3647 
3648   // The aliases are emitted as a post-pass, and will point to the value
3649   // id of the aliasee. Save them in a vector for post-processing.
3650   SmallVector<AliasSummary *, 64> Aliases;
3651 
3652   // Save the value id for each summary for alias emission.
3653   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3654 
3655   SmallVector<uint64_t, 64> NameVals;
3656 
3657   // For local linkage, we also emit the original name separately
3658   // immediately after the record.
3659   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3660     if (!GlobalValue::isLocalLinkage(S.linkage()))
3661       return;
3662     NameVals.push_back(S.getOriginalName());
3663     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3664     NameVals.clear();
3665   };
3666 
3667   for (const auto &I : *this) {
3668     GlobalValueSummary *S = I.second;
3669     assert(S);
3670 
3671     assert(hasValueId(I.first));
3672     unsigned ValueId = getValueId(I.first);
3673     SummaryToValueIdMap[S] = ValueId;
3674 
3675     if (auto *AS = dyn_cast<AliasSummary>(S)) {
3676       // Will process aliases as a post-pass because the reader wants all
3677       // global to be loaded first.
3678       Aliases.push_back(AS);
3679       continue;
3680     }
3681 
3682     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3683       NameVals.push_back(ValueId);
3684       NameVals.push_back(Index.getModuleId(VS->modulePath()));
3685       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3686       for (auto &RI : VS->refs()) {
3687         NameVals.push_back(getValueId(RI.getGUID()));
3688       }
3689 
3690       // Emit the finished record.
3691       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3692                         FSModRefsAbbrev);
3693       NameVals.clear();
3694       MaybeEmitOriginalName(*S);
3695       continue;
3696     }
3697 
3698     auto *FS = cast<FunctionSummary>(S);
3699     writeFunctionTypeMetadataRecords(Stream, FS);
3700 
3701     NameVals.push_back(ValueId);
3702     NameVals.push_back(Index.getModuleId(FS->modulePath()));
3703     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3704     NameVals.push_back(FS->instCount());
3705     NameVals.push_back(FS->refs().size());
3706 
3707     for (auto &RI : FS->refs()) {
3708       NameVals.push_back(getValueId(RI.getGUID()));
3709     }
3710 
3711     bool HasProfileData = false;
3712     for (auto &EI : FS->calls()) {
3713       HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3714       if (HasProfileData)
3715         break;
3716     }
3717 
3718     for (auto &EI : FS->calls()) {
3719       // If this GUID doesn't have a value id, it doesn't have a function
3720       // summary and we don't need to record any calls to it.
3721       GlobalValue::GUID GUID = EI.first.getGUID();
3722       if (!hasValueId(GUID)) {
3723         // For SamplePGO, the indirect call targets for local functions will
3724         // have its original name annotated in profile. We try to find the
3725         // corresponding PGOFuncName as the GUID.
3726         GUID = Index.getGUIDFromOriginalID(GUID);
3727         if (GUID == 0 || !hasValueId(GUID))
3728           continue;
3729       }
3730       NameVals.push_back(getValueId(GUID));
3731       if (HasProfileData)
3732         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3733     }
3734 
3735     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3736     unsigned Code =
3737         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3738 
3739     // Emit the finished record.
3740     Stream.EmitRecord(Code, NameVals, FSAbbrev);
3741     NameVals.clear();
3742     MaybeEmitOriginalName(*S);
3743   }
3744 
3745   for (auto *AS : Aliases) {
3746     auto AliasValueId = SummaryToValueIdMap[AS];
3747     assert(AliasValueId);
3748     NameVals.push_back(AliasValueId);
3749     NameVals.push_back(Index.getModuleId(AS->modulePath()));
3750     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3751     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3752     assert(AliaseeValueId);
3753     NameVals.push_back(AliaseeValueId);
3754 
3755     // Emit the finished record.
3756     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3757     NameVals.clear();
3758     MaybeEmitOriginalName(*AS);
3759   }
3760 
3761   Stream.ExitBlock();
3762 }
3763 
3764 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3765 /// current llvm version, and a record for the epoch number.
3766 static void writeIdentificationBlock(BitstreamWriter &Stream) {
3767   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3768 
3769   // Write the "user readable" string identifying the bitcode producer
3770   auto Abbv = std::make_shared<BitCodeAbbrev>();
3771   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3772   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3773   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3774   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3775   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3776                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
3777 
3778   // Write the epoch version
3779   Abbv = std::make_shared<BitCodeAbbrev>();
3780   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3781   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3782   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3783   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3784   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3785   Stream.ExitBlock();
3786 }
3787 
3788 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3789   // Emit the module's hash.
3790   // MODULE_CODE_HASH: [5*i32]
3791   if (GenerateHash) {
3792     SHA1 Hasher;
3793     uint32_t Vals[5];
3794     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3795                                     Buffer.size() - BlockStartPos));
3796     StringRef Hash = Hasher.result();
3797     for (int Pos = 0; Pos < 20; Pos += 4) {
3798       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3799     }
3800 
3801     // Emit the finished record.
3802     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3803 
3804     if (ModHash)
3805       // Save the written hash value.
3806       std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3807   } else if (ModHash)
3808     Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
3809 }
3810 
3811 void ModuleBitcodeWriter::write() {
3812   writeIdentificationBlock(Stream);
3813 
3814   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3815   size_t BlockStartPos = Buffer.size();
3816 
3817   SmallVector<unsigned, 1> Vals;
3818   unsigned CurVersion = 1;
3819   Vals.push_back(CurVersion);
3820   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3821 
3822   // Emit blockinfo, which defines the standard abbreviations etc.
3823   writeBlockInfo();
3824 
3825   // Emit information about attribute groups.
3826   writeAttributeGroupTable();
3827 
3828   // Emit information about parameter attributes.
3829   writeAttributeTable();
3830 
3831   // Emit information describing all of the types in the module.
3832   writeTypeTable();
3833 
3834   writeComdats();
3835 
3836   // Emit top-level description of module, including target triple, inline asm,
3837   // descriptors for global variables, and function prototype info.
3838   writeModuleInfo();
3839 
3840   // Emit constants.
3841   writeModuleConstants();
3842 
3843   // Emit metadata kind names.
3844   writeModuleMetadataKinds();
3845 
3846   // Emit metadata.
3847   writeModuleMetadata();
3848 
3849   // Emit module-level use-lists.
3850   if (VE.shouldPreserveUseListOrder())
3851     writeUseListBlock(nullptr);
3852 
3853   writeOperandBundleTags();
3854 
3855   // Emit function bodies.
3856   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3857   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3858     if (!F->isDeclaration())
3859       writeFunction(*F, FunctionToBitcodeIndex);
3860 
3861   // Need to write after the above call to WriteFunction which populates
3862   // the summary information in the index.
3863   if (Index)
3864     writePerModuleGlobalValueSummary();
3865 
3866   writeValueSymbolTable(M.getValueSymbolTable(),
3867                         /* IsModuleLevel */ true, &FunctionToBitcodeIndex);
3868 
3869   writeModuleHash(BlockStartPos);
3870 
3871   Stream.ExitBlock();
3872 }
3873 
3874 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3875                                uint32_t &Position) {
3876   support::endian::write32le(&Buffer[Position], Value);
3877   Position += 4;
3878 }
3879 
3880 /// If generating a bc file on darwin, we have to emit a
3881 /// header and trailer to make it compatible with the system archiver.  To do
3882 /// this we emit the following header, and then emit a trailer that pads the
3883 /// file out to be a multiple of 16 bytes.
3884 ///
3885 /// struct bc_header {
3886 ///   uint32_t Magic;         // 0x0B17C0DE
3887 ///   uint32_t Version;       // Version, currently always 0.
3888 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3889 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
3890 ///   uint32_t CPUType;       // CPU specifier.
3891 ///   ... potentially more later ...
3892 /// };
3893 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3894                                          const Triple &TT) {
3895   unsigned CPUType = ~0U;
3896 
3897   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3898   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3899   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
3900   // specific constants here because they are implicitly part of the Darwin ABI.
3901   enum {
3902     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
3903     DARWIN_CPU_TYPE_X86        = 7,
3904     DARWIN_CPU_TYPE_ARM        = 12,
3905     DARWIN_CPU_TYPE_POWERPC    = 18
3906   };
3907 
3908   Triple::ArchType Arch = TT.getArch();
3909   if (Arch == Triple::x86_64)
3910     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3911   else if (Arch == Triple::x86)
3912     CPUType = DARWIN_CPU_TYPE_X86;
3913   else if (Arch == Triple::ppc)
3914     CPUType = DARWIN_CPU_TYPE_POWERPC;
3915   else if (Arch == Triple::ppc64)
3916     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3917   else if (Arch == Triple::arm || Arch == Triple::thumb)
3918     CPUType = DARWIN_CPU_TYPE_ARM;
3919 
3920   // Traditional Bitcode starts after header.
3921   assert(Buffer.size() >= BWH_HeaderSize &&
3922          "Expected header size to be reserved");
3923   unsigned BCOffset = BWH_HeaderSize;
3924   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3925 
3926   // Write the magic and version.
3927   unsigned Position = 0;
3928   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3929   writeInt32ToBuffer(0, Buffer, Position); // Version.
3930   writeInt32ToBuffer(BCOffset, Buffer, Position);
3931   writeInt32ToBuffer(BCSize, Buffer, Position);
3932   writeInt32ToBuffer(CPUType, Buffer, Position);
3933 
3934   // If the file is not a multiple of 16 bytes, insert dummy padding.
3935   while (Buffer.size() & 15)
3936     Buffer.push_back(0);
3937 }
3938 
3939 /// Helper to write the header common to all bitcode files.
3940 static void writeBitcodeHeader(BitstreamWriter &Stream) {
3941   // Emit the file header.
3942   Stream.Emit((unsigned)'B', 8);
3943   Stream.Emit((unsigned)'C', 8);
3944   Stream.Emit(0x0, 4);
3945   Stream.Emit(0xC, 4);
3946   Stream.Emit(0xE, 4);
3947   Stream.Emit(0xD, 4);
3948 }
3949 
3950 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3951     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3952   writeBitcodeHeader(*Stream);
3953 }
3954 
3955 BitcodeWriter::~BitcodeWriter() = default;
3956 
3957 void BitcodeWriter::writeModule(const Module *M,
3958                                 bool ShouldPreserveUseListOrder,
3959                                 const ModuleSummaryIndex *Index,
3960                                 bool GenerateHash, ModuleHash *ModHash) {
3961   ModuleBitcodeWriter ModuleWriter(M, Buffer, *Stream,
3962                                    ShouldPreserveUseListOrder, Index,
3963                                    GenerateHash, ModHash);
3964   ModuleWriter.write();
3965 }
3966 
3967 /// WriteBitcodeToFile - Write the specified module to the specified output
3968 /// stream.
3969 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3970                               bool ShouldPreserveUseListOrder,
3971                               const ModuleSummaryIndex *Index,
3972                               bool GenerateHash, ModuleHash *ModHash) {
3973   SmallVector<char, 0> Buffer;
3974   Buffer.reserve(256*1024);
3975 
3976   // If this is darwin or another generic macho target, reserve space for the
3977   // header.
3978   Triple TT(M->getTargetTriple());
3979   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3980     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3981 
3982   BitcodeWriter Writer(Buffer);
3983   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3984                      ModHash);
3985 
3986   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3987     emitDarwinBCHeaderAndTrailer(Buffer, TT);
3988 
3989   // Write the generated bitstream to "Out".
3990   Out.write((char*)&Buffer.front(), Buffer.size());
3991 }
3992 
3993 void IndexBitcodeWriter::write() {
3994   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3995 
3996   SmallVector<unsigned, 1> Vals;
3997   unsigned CurVersion = 1;
3998   Vals.push_back(CurVersion);
3999   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
4000 
4001   // If we have a VST, write the VSTOFFSET record placeholder.
4002   writeValueSymbolTableForwardDecl();
4003 
4004   // Write the module paths in the combined index.
4005   writeModStrings();
4006 
4007   // Write the summary combined index records.
4008   writeCombinedGlobalValueSummary();
4009 
4010   // Need a special VST writer for the combined index (we don't have a
4011   // real VST and real values when this is invoked).
4012   writeCombinedValueSymbolTable();
4013 
4014   Stream.ExitBlock();
4015 }
4016 
4017 // Write the specified module summary index to the given raw output stream,
4018 // where it will be written in a new bitcode block. This is used when
4019 // writing the combined index file for ThinLTO. When writing a subset of the
4020 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4021 void llvm::WriteIndexToFile(
4022     const ModuleSummaryIndex &Index, raw_ostream &Out,
4023     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4024   SmallVector<char, 0> Buffer;
4025   Buffer.reserve(256 * 1024);
4026 
4027   BitstreamWriter Stream(Buffer);
4028   writeBitcodeHeader(Stream);
4029 
4030   IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
4031   IndexWriter.write();
4032 
4033   Out.write((char *)&Buffer.front(), Buffer.size());
4034 }
4035