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