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