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