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