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