LLVM  15.0.0git
BitcodeWriter.cpp
Go to the documentation of this file.
1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Bitcode writer implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "ValueEnumerator.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
34 #include "llvm/Config/llvm-config.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/Comdat.h"
38 #include "llvm/IR/Constant.h"
39 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalAlias.h"
45 #include "llvm/IR/GlobalIFunc.h"
46 #include "llvm/IR/GlobalObject.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Module.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/UseListOrder.h"
60 #include "llvm/IR/Value.h"
63 #include "llvm/MC/TargetRegistry.h"
64 #include "llvm/Object/IRSymtab.h"
66 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/Endian.h"
69 #include "llvm/Support/Error.h"
72 #include "llvm/Support/SHA1.h"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstddef>
77 #include <cstdint>
78 #include <iterator>
79 #include <map>
80 #include <memory>
81 #include <string>
82 #include <utility>
83 #include <vector>
84 
85 using namespace llvm;
86 
87 static cl::opt<unsigned>
88  IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
89  cl::desc("Number of metadatas above which we emit an index "
90  "to enable lazy-loading"));
92  "bitcode-flush-threshold", cl::Hidden, cl::init(512),
93  cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
94 
96  "write-relbf-to-summary", cl::Hidden, cl::init(false),
97  cl::desc("Write relative block frequency to function summary "));
98 
100 
101 namespace {
102 
103 /// These are manifest constants used by the bitcode writer. They do not need to
104 /// be kept in sync with the reader, but need to be consistent within this file.
105 enum {
106  // VALUE_SYMTAB_BLOCK abbrev id's.
107  VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
108  VST_ENTRY_7_ABBREV,
109  VST_ENTRY_6_ABBREV,
110  VST_BBENTRY_6_ABBREV,
111 
112  // CONSTANTS_BLOCK abbrev id's.
113  CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
114  CONSTANTS_INTEGER_ABBREV,
115  CONSTANTS_CE_CAST_Abbrev,
116  CONSTANTS_NULL_Abbrev,
117 
118  // FUNCTION_BLOCK abbrev id's.
119  FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
120  FUNCTION_INST_UNOP_ABBREV,
121  FUNCTION_INST_UNOP_FLAGS_ABBREV,
122  FUNCTION_INST_BINOP_ABBREV,
123  FUNCTION_INST_BINOP_FLAGS_ABBREV,
124  FUNCTION_INST_CAST_ABBREV,
125  FUNCTION_INST_RET_VOID_ABBREV,
126  FUNCTION_INST_RET_VAL_ABBREV,
127  FUNCTION_INST_UNREACHABLE_ABBREV,
128  FUNCTION_INST_GEP_ABBREV,
129 };
130 
131 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
132 /// file type.
133 class BitcodeWriterBase {
134 protected:
135  /// The stream created and owned by the client.
137 
138  StringTableBuilder &StrtabBuilder;
139 
140 public:
141  /// Constructs a BitcodeWriterBase object that writes to the provided
142  /// \p Stream.
143  BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
144  : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
145 
146 protected:
147  void writeModuleVersion();
148 };
149 
150 void BitcodeWriterBase::writeModuleVersion() {
151  // VERSION: [version#]
153 }
154 
155 /// Base class to manage the module bitcode writing, currently subclassed for
156 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
157 class ModuleBitcodeWriterBase : public BitcodeWriterBase {
158 protected:
159  /// The Module to write to bitcode.
160  const Module &M;
161 
162  /// Enumerates ids for all values in the module.
163  ValueEnumerator VE;
164 
165  /// Optional per-module index to write for ThinLTO.
166  const ModuleSummaryIndex *Index;
167 
168  /// Map that holds the correspondence between GUIDs in the summary index,
169  /// that came from indirect call profiles, and a value id generated by this
170  /// class to use in the VST and summary block records.
171  std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
172 
173  /// Tracks the last value id recorded in the GUIDToValueMap.
174  unsigned GlobalValueId;
175 
176  /// Saves the offset of the VSTOffset record that must eventually be
177  /// backpatched with the offset of the actual VST.
178  uint64_t VSTOffsetPlaceholder = 0;
179 
180 public:
181  /// Constructs a ModuleBitcodeWriterBase object for the given Module,
182  /// writing to the provided \p Buffer.
183  ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
184  BitstreamWriter &Stream,
185  bool ShouldPreserveUseListOrder,
186  const ModuleSummaryIndex *Index)
187  : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
188  VE(M, ShouldPreserveUseListOrder), Index(Index) {
189  // Assign ValueIds to any callee values in the index that came from
190  // indirect call profiles and were recorded as a GUID not a Value*
191  // (which would have been assigned an ID by the ValueEnumerator).
192  // The starting ValueId is just after the number of values in the
193  // ValueEnumerator, so that they can be emitted in the VST.
194  GlobalValueId = VE.getValues().size();
195  if (!Index)
196  return;
197  for (const auto &GUIDSummaryLists : *Index)
198  // Examine all summaries for this GUID.
199  for (auto &Summary : GUIDSummaryLists.second.SummaryList)
200  if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
201  // For each call in the function summary, see if the call
202  // is to a GUID (which means it is for an indirect call,
203  // otherwise we would have a Value for it). If so, synthesize
204  // a value id.
205  for (auto &CallEdge : FS->calls())
206  if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
207  assignValueId(CallEdge.first.getGUID());
208  }
209 
210 protected:
211  void writePerModuleGlobalValueSummary();
212 
213 private:
214  void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
215  GlobalValueSummary *Summary,
216  unsigned ValueID,
217  unsigned FSCallsAbbrev,
218  unsigned FSCallsProfileAbbrev,
219  const Function &F);
220  void writeModuleLevelReferences(const GlobalVariable &V,
221  SmallVector<uint64_t, 64> &NameVals,
222  unsigned FSModRefsAbbrev,
223  unsigned FSModVTableRefsAbbrev);
224 
225  void assignValueId(GlobalValue::GUID ValGUID) {
226  GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
227  }
228 
229  unsigned getValueId(GlobalValue::GUID ValGUID) {
230  const auto &VMI = GUIDToValueIdMap.find(ValGUID);
231  // Expect that any GUID value had a value Id assigned by an
232  // earlier call to assignValueId.
233  assert(VMI != GUIDToValueIdMap.end() &&
234  "GUID does not have assigned value Id");
235  return VMI->second;
236  }
237 
238  // Helper to get the valueId for the type of value recorded in VI.
239  unsigned getValueId(ValueInfo VI) {
240  if (!VI.haveGVs() || !VI.getValue())
241  return getValueId(VI.getGUID());
242  return VE.getValueID(VI.getValue());
243  }
244 
245  std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
246 };
247 
248 /// Class to manage the bitcode writing for a module.
249 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
250  /// Pointer to the buffer allocated by caller for bitcode writing.
251  const SmallVectorImpl<char> &Buffer;
252 
253  /// True if a module hash record should be written.
254  bool GenerateHash;
255 
256  /// If non-null, when GenerateHash is true, the resulting hash is written
257  /// into ModHash.
258  ModuleHash *ModHash;
259 
260  SHA1 Hasher;
261 
262  /// The start bit of the identification block.
263  uint64_t BitcodeStartBit;
264 
265 public:
266  /// Constructs a ModuleBitcodeWriter object for the given Module,
267  /// writing to the provided \p Buffer.
268  ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
269  StringTableBuilder &StrtabBuilder,
270  BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
271  const ModuleSummaryIndex *Index, bool GenerateHash,
272  ModuleHash *ModHash = nullptr)
273  : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
274  ShouldPreserveUseListOrder, Index),
275  Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
276  BitcodeStartBit(Stream.GetCurrentBitNo()) {}
277 
278  /// Emit the current module to the bitstream.
279  void write();
280 
281 private:
282  uint64_t bitcodeStartBit() { return BitcodeStartBit; }
283 
284  size_t addToStrtab(StringRef Str);
285 
286  void writeAttributeGroupTable();
287  void writeAttributeTable();
288  void writeTypeTable();
289  void writeComdats();
290  void writeValueSymbolTableForwardDecl();
291  void writeModuleInfo();
292  void writeValueAsMetadata(const ValueAsMetadata *MD,
295  unsigned Abbrev);
296  unsigned createDILocationAbbrev();
298  unsigned &Abbrev);
299  unsigned createGenericDINodeAbbrev();
300  void writeGenericDINode(const GenericDINode *N,
301  SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
303  unsigned Abbrev);
306  unsigned Abbrev);
307  void writeDIEnumerator(const DIEnumerator *N,
308  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
310  unsigned Abbrev);
311  void writeDIStringType(const DIStringType *N,
312  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
313  void writeDIDerivedType(const DIDerivedType *N,
314  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
319  unsigned Abbrev);
321  unsigned Abbrev);
322  void writeDICompileUnit(const DICompileUnit *N,
323  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
324  void writeDISubprogram(const DISubprogram *N,
325  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
327  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
330  unsigned Abbrev);
331  void writeDICommonBlock(const DICommonBlock *N,
332  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
334  unsigned Abbrev);
336  unsigned Abbrev);
338  unsigned Abbrev);
340  unsigned Abbrev);
342  unsigned Abbrev);
345  unsigned Abbrev);
348  unsigned Abbrev);
351  unsigned Abbrev);
353  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
354  void writeDILabel(const DILabel *N,
355  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
356  void writeDIExpression(const DIExpression *N,
357  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
360  unsigned Abbrev);
362  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
365  unsigned Abbrev);
366  unsigned createNamedMetadataAbbrev();
367  void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
368  unsigned createMetadataStringsAbbrev();
369  void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
371  void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
373  std::vector<unsigned> *MDAbbrevs = nullptr,
374  std::vector<uint64_t> *IndexPos = nullptr);
375  void writeModuleMetadata();
376  void writeFunctionMetadata(const Function &F);
377  void writeFunctionMetadataAttachment(const Function &F);
378  void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
379  const GlobalObject &GO);
380  void writeModuleMetadataKinds();
381  void writeOperandBundleTags();
382  void writeSyncScopeNames();
383  void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
384  void writeModuleConstants();
385  bool pushValueAndType(const Value *V, unsigned InstID,
387  void writeOperandBundles(const CallBase &CB, unsigned InstID);
388  void pushValue(const Value *V, unsigned InstID,
390  void pushValueSigned(const Value *V, unsigned InstID,
392  void writeInstruction(const Instruction &I, unsigned InstID,
394  void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
395  void writeGlobalValueSymbolTable(
396  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
397  void writeUseList(UseListOrder &&Order);
398  void writeUseListBlock(const Function *F);
399  void
400  writeFunction(const Function &F,
401  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
402  void writeBlockInfo();
403  void writeModuleHash(size_t BlockStartPos);
404 
405  unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
406  return unsigned(SSID);
407  }
408 
409  unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
410 };
411 
412 /// Class to manage the bitcode writing for a combined index.
413 class IndexBitcodeWriter : public BitcodeWriterBase {
414  /// The combined index to write to bitcode.
415  const ModuleSummaryIndex &Index;
416 
417  /// When writing a subset of the index for distributed backends, client
418  /// provides a map of modules to the corresponding GUIDs/summaries to write.
419  const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
420 
421  /// Map that holds the correspondence between the GUID used in the combined
422  /// index and a value id generated by this class to use in references.
423  std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
424 
425  /// Tracks the last value id recorded in the GUIDToValueMap.
426  unsigned GlobalValueId = 0;
427 
428 public:
429  /// Constructs a IndexBitcodeWriter object for the given combined index,
430  /// writing to the provided \p Buffer. When writing a subset of the index
431  /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
432  IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
433  const ModuleSummaryIndex &Index,
434  const std::map<std::string, GVSummaryMapTy>
435  *ModuleToSummariesForIndex = nullptr)
436  : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
437  ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
438  // Assign unique value ids to all summaries to be written, for use
439  // in writing out the call graph edges. Save the mapping from GUID
440  // to the new global value id to use when writing those edges, which
441  // are currently saved in the index in terms of GUID.
442  forEachSummary([&](GVInfo I, bool) {
443  GUIDToValueIdMap[I.first] = ++GlobalValueId;
444  });
445  }
446 
447  /// The below iterator returns the GUID and associated summary.
448  using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
449 
450  /// Calls the callback for each value GUID and summary to be written to
451  /// bitcode. This hides the details of whether they are being pulled from the
452  /// entire index or just those in a provided ModuleToSummariesForIndex map.
453  template<typename Functor>
454  void forEachSummary(Functor Callback) {
455  if (ModuleToSummariesForIndex) {
456  for (auto &M : *ModuleToSummariesForIndex)
457  for (auto &Summary : M.second) {
458  Callback(Summary, false);
459  // Ensure aliasee is handled, e.g. for assigning a valueId,
460  // even if we are not importing the aliasee directly (the
461  // imported alias will contain a copy of aliasee).
462  if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
463  Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
464  }
465  } else {
466  for (auto &Summaries : Index)
467  for (auto &Summary : Summaries.second.SummaryList)
468  Callback({Summaries.first, Summary.get()}, false);
469  }
470  }
471 
472  /// Calls the callback for each entry in the modulePaths StringMap that
473  /// should be written to the module path string table. This hides the details
474  /// of whether they are being pulled from the entire index or just those in a
475  /// provided ModuleToSummariesForIndex map.
476  template <typename Functor> void forEachModule(Functor Callback) {
477  if (ModuleToSummariesForIndex) {
478  for (const auto &M : *ModuleToSummariesForIndex) {
479  const auto &MPI = Index.modulePaths().find(M.first);
480  if (MPI == Index.modulePaths().end()) {
481  // This should only happen if the bitcode file was empty, in which
482  // case we shouldn't be importing (the ModuleToSummariesForIndex
483  // would only include the module we are writing and index for).
484  assert(ModuleToSummariesForIndex->size() == 1);
485  continue;
486  }
487  Callback(*MPI);
488  }
489  } else {
490  for (const auto &MPSE : Index.modulePaths())
491  Callback(MPSE);
492  }
493  }
494 
495  /// Main entry point for writing a combined index to bitcode.
496  void write();
497 
498 private:
499  void writeModStrings();
500  void writeCombinedGlobalValueSummary();
501 
502  Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
503  auto VMI = GUIDToValueIdMap.find(ValGUID);
504  if (VMI == GUIDToValueIdMap.end())
505  return None;
506  return VMI->second;
507  }
508 
509  std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
510 };
511 
512 } // end anonymous namespace
513 
514 static unsigned getEncodedCastOpcode(unsigned Opcode) {
515  switch (Opcode) {
516  default: llvm_unreachable("Unknown cast instruction!");
517  case Instruction::Trunc : return bitc::CAST_TRUNC;
518  case Instruction::ZExt : return bitc::CAST_ZEXT;
519  case Instruction::SExt : return bitc::CAST_SEXT;
520  case Instruction::FPToUI : return bitc::CAST_FPTOUI;
521  case Instruction::FPToSI : return bitc::CAST_FPTOSI;
522  case Instruction::UIToFP : return bitc::CAST_UITOFP;
523  case Instruction::SIToFP : return bitc::CAST_SITOFP;
524  case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
525  case Instruction::FPExt : return bitc::CAST_FPEXT;
526  case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
527  case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
528  case Instruction::BitCast : return bitc::CAST_BITCAST;
529  case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
530  }
531 }
532 
533 static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
534  switch (Opcode) {
535  default: llvm_unreachable("Unknown binary instruction!");
536  case Instruction::FNeg: return bitc::UNOP_FNEG;
537  }
538 }
539 
540 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
541  switch (Opcode) {
542  default: llvm_unreachable("Unknown binary instruction!");
543  case Instruction::Add:
544  case Instruction::FAdd: return bitc::BINOP_ADD;
545  case Instruction::Sub:
546  case Instruction::FSub: return bitc::BINOP_SUB;
547  case Instruction::Mul:
548  case Instruction::FMul: return bitc::BINOP_MUL;
549  case Instruction::UDiv: return bitc::BINOP_UDIV;
550  case Instruction::FDiv:
551  case Instruction::SDiv: return bitc::BINOP_SDIV;
552  case Instruction::URem: return bitc::BINOP_UREM;
553  case Instruction::FRem:
554  case Instruction::SRem: return bitc::BINOP_SREM;
555  case Instruction::Shl: return bitc::BINOP_SHL;
556  case Instruction::LShr: return bitc::BINOP_LSHR;
557  case Instruction::AShr: return bitc::BINOP_ASHR;
558  case Instruction::And: return bitc::BINOP_AND;
559  case Instruction::Or: return bitc::BINOP_OR;
560  case Instruction::Xor: return bitc::BINOP_XOR;
561  }
562 }
563 
565  switch (Op) {
566  default: llvm_unreachable("Unknown RMW operation!");
567  case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
568  case AtomicRMWInst::Add: return bitc::RMW_ADD;
569  case AtomicRMWInst::Sub: return bitc::RMW_SUB;
570  case AtomicRMWInst::And: return bitc::RMW_AND;
571  case AtomicRMWInst::Nand: return bitc::RMW_NAND;
572  case AtomicRMWInst::Or: return bitc::RMW_OR;
573  case AtomicRMWInst::Xor: return bitc::RMW_XOR;
574  case AtomicRMWInst::Max: return bitc::RMW_MAX;
575  case AtomicRMWInst::Min: return bitc::RMW_MIN;
576  case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
577  case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
578  case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
579  case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
580  }
581 }
582 
583 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
584  switch (Ordering) {
592  }
593  llvm_unreachable("Invalid ordering");
594 }
595 
596 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
597  StringRef Str, unsigned AbbrevToUse) {
599 
600  // Code: [strchar x N]
601  for (char C : Str) {
602  if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
603  AbbrevToUse = 0;
604  Vals.push_back(C);
605  }
606 
607  // Emit the finished record.
608  Stream.EmitRecord(Code, Vals, AbbrevToUse);
609 }
610 
612  switch (Kind) {
613  case Attribute::Alignment:
615  case Attribute::AllocAlign:
617  case Attribute::AllocSize:
619  case Attribute::AlwaysInline:
621  case Attribute::ArgMemOnly:
623  case Attribute::Builtin:
625  case Attribute::ByVal:
626  return bitc::ATTR_KIND_BY_VAL;
629  case Attribute::InAlloca:
631  case Attribute::Cold:
632  return bitc::ATTR_KIND_COLD;
633  case Attribute::DisableSanitizerInstrumentation:
635  case Attribute::Hot:
636  return bitc::ATTR_KIND_HOT;
637  case Attribute::ElementType:
639  case Attribute::InaccessibleMemOnly:
641  case Attribute::InaccessibleMemOrArgMemOnly:
643  case Attribute::InlineHint:
645  case Attribute::InReg:
646  return bitc::ATTR_KIND_IN_REG;
649  case Attribute::MinSize:
651  case Attribute::AllocatedPointer:
653  case Attribute::Naked:
654  return bitc::ATTR_KIND_NAKED;
655  case Attribute::Nest:
656  return bitc::ATTR_KIND_NEST;
657  case Attribute::NoAlias:
659  case Attribute::NoBuiltin:
661  case Attribute::NoCallback:
663  case Attribute::NoCapture:
665  case Attribute::NoDuplicate:
667  case Attribute::NoFree:
668  return bitc::ATTR_KIND_NOFREE;
669  case Attribute::NoImplicitFloat:
671  case Attribute::NoInline:
673  case Attribute::NoRecurse:
675  case Attribute::NoMerge:
677  case Attribute::NonLazyBind:
679  case Attribute::NonNull:
681  case Attribute::Dereferenceable:
683  case Attribute::DereferenceableOrNull:
685  case Attribute::NoRedZone:
687  case Attribute::NoReturn:
689  case Attribute::NoSync:
690  return bitc::ATTR_KIND_NOSYNC;
691  case Attribute::NoCfCheck:
693  case Attribute::NoProfile:
695  case Attribute::NoUnwind:
697  case Attribute::NoSanitizeBounds:
699  case Attribute::NoSanitizeCoverage:
701  case Attribute::NullPointerIsValid:
703  case Attribute::OptForFuzzing:
705  case Attribute::OptimizeForSize:
707  case Attribute::OptimizeNone:
709  case Attribute::ReadNone:
711  case Attribute::ReadOnly:
713  case Attribute::Returned:
715  case Attribute::ReturnsTwice:
717  case Attribute::SExt:
718  return bitc::ATTR_KIND_S_EXT;
719  case Attribute::Speculatable:
721  case Attribute::StackAlignment:
723  case Attribute::StackProtect:
725  case Attribute::StackProtectReq:
727  case Attribute::StackProtectStrong:
729  case Attribute::SafeStack:
731  case Attribute::ShadowCallStack:
733  case Attribute::StrictFP:
735  case Attribute::StructRet:
737  case Attribute::SanitizeAddress:
739  case Attribute::SanitizeHWAddress:
741  case Attribute::SanitizeThread:
743  case Attribute::SanitizeMemory:
745  case Attribute::SpeculativeLoadHardening:
747  case Attribute::SwiftError:
749  case Attribute::SwiftSelf:
751  case Attribute::SwiftAsync:
753  case Attribute::UWTable:
755  case Attribute::VScaleRange:
757  case Attribute::WillReturn:
759  case Attribute::WriteOnly:
761  case Attribute::ZExt:
762  return bitc::ATTR_KIND_Z_EXT;
763  case Attribute::ImmArg:
764  return bitc::ATTR_KIND_IMMARG;
765  case Attribute::SanitizeMemTag:
767  case Attribute::Preallocated:
769  case Attribute::NoUndef:
771  case Attribute::ByRef:
772  return bitc::ATTR_KIND_BYREF;
773  case Attribute::MustProgress:
776  llvm_unreachable("Can not encode end-attribute kinds marker.");
777  case Attribute::None:
778  llvm_unreachable("Can not encode none-attribute.");
779  case Attribute::EmptyKey:
781  llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
782  }
783 
784  llvm_unreachable("Trying to encode unknown attribute");
785 }
786 
787 void ModuleBitcodeWriter::writeAttributeGroupTable() {
788  const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
789  VE.getAttributeGroups();
790  if (AttrGrps.empty()) return;
791 
792  Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
793 
795  for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
796  unsigned AttrListIndex = Pair.first;
797  AttributeSet AS = Pair.second;
798  Record.push_back(VE.getAttributeGroupID(Pair));
799  Record.push_back(AttrListIndex);
800 
801  for (Attribute Attr : AS) {
802  if (Attr.isEnumAttribute()) {
803  Record.push_back(0);
804  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
805  } else if (Attr.isIntAttribute()) {
806  Record.push_back(1);
807  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
808  Record.push_back(Attr.getValueAsInt());
809  } else if (Attr.isStringAttribute()) {
810  StringRef Kind = Attr.getKindAsString();
811  StringRef Val = Attr.getValueAsString();
812 
813  Record.push_back(Val.empty() ? 3 : 4);
814  Record.append(Kind.begin(), Kind.end());
815  Record.push_back(0);
816  if (!Val.empty()) {
817  Record.append(Val.begin(), Val.end());
818  Record.push_back(0);
819  }
820  } else {
821  assert(Attr.isTypeAttribute());
822  Type *Ty = Attr.getValueAsType();
823  Record.push_back(Ty ? 6 : 5);
824  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
825  if (Ty)
826  Record.push_back(VE.getTypeID(Attr.getValueAsType()));
827  }
828  }
829 
831  Record.clear();
832  }
833 
834  Stream.ExitBlock();
835 }
836 
837 void ModuleBitcodeWriter::writeAttributeTable() {
838  const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
839  if (Attrs.empty()) return;
840 
841  Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
842 
844  for (const AttributeList &AL : Attrs) {
845  for (unsigned i : AL.indexes()) {
846  AttributeSet AS = AL.getAttributes(i);
847  if (AS.hasAttributes())
848  Record.push_back(VE.getAttributeGroupID({i, AS}));
849  }
850 
852  Record.clear();
853  }
854 
855  Stream.ExitBlock();
856 }
857 
858 /// WriteTypeTable - Write out the type table for a module.
859 void ModuleBitcodeWriter::writeTypeTable() {
860  const ValueEnumerator::TypeList &TypeList = VE.getTypes();
861 
862  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
863  SmallVector<uint64_t, 64> TypeVals;
864 
866 
867  // Abbrev for TYPE_CODE_POINTER.
868  auto Abbv = std::make_shared<BitCodeAbbrev>();
870  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
871  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
872  unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
873 
874  // Abbrev for TYPE_CODE_OPAQUE_POINTER.
875  Abbv = std::make_shared<BitCodeAbbrev>();
877  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
878  unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
879 
880  // Abbrev for TYPE_CODE_FUNCTION.
881  Abbv = std::make_shared<BitCodeAbbrev>();
883  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
885  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
886  unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
887 
888  // Abbrev for TYPE_CODE_STRUCT_ANON.
889  Abbv = std::make_shared<BitCodeAbbrev>();
891  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
893  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
894  unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
895 
896  // Abbrev for TYPE_CODE_STRUCT_NAME.
897  Abbv = std::make_shared<BitCodeAbbrev>();
901  unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
902 
903  // Abbrev for TYPE_CODE_STRUCT_NAMED.
904  Abbv = std::make_shared<BitCodeAbbrev>();
906  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
908  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
909  unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
910 
911  // Abbrev for TYPE_CODE_ARRAY.
912  Abbv = std::make_shared<BitCodeAbbrev>();
914  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
915  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
916  unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
917 
918  // Emit an entry count so the reader can reserve space.
919  TypeVals.push_back(TypeList.size());
920  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
921  TypeVals.clear();
922 
923  // Loop over all of the types, emitting each in turn.
924  for (Type *T : TypeList) {
925  int AbbrevToUse = 0;
926  unsigned Code = 0;
927 
928  switch (T->getTypeID()) {
942  case Type::IntegerTyID:
943  // INTEGER: [width]
945  TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
946  break;
947  case Type::PointerTyID: {
948  PointerType *PTy = cast<PointerType>(T);
949  unsigned AddressSpace = PTy->getAddressSpace();
950  if (PTy->isOpaque()) {
951  // OPAQUE_POINTER: [address space]
953  TypeVals.push_back(AddressSpace);
954  if (AddressSpace == 0)
955  AbbrevToUse = OpaquePtrAbbrev;
956  } else {
957  // POINTER: [pointee type, address space]
959  TypeVals.push_back(VE.getTypeID(PTy->getNonOpaquePointerElementType()));
960  TypeVals.push_back(AddressSpace);
961  if (AddressSpace == 0)
962  AbbrevToUse = PtrAbbrev;
963  }
964  break;
965  }
966  case Type::FunctionTyID: {
967  FunctionType *FT = cast<FunctionType>(T);
968  // FUNCTION: [isvararg, retty, paramty x N]
970  TypeVals.push_back(FT->isVarArg());
971  TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
972  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
973  TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
974  AbbrevToUse = FunctionAbbrev;
975  break;
976  }
977  case Type::StructTyID: {
978  StructType *ST = cast<StructType>(T);
979  // STRUCT: [ispacked, eltty x N]
980  TypeVals.push_back(ST->isPacked());
981  // Output all of the element types.
982  for (Type *ET : ST->elements())
983  TypeVals.push_back(VE.getTypeID(ET));
984 
985  if (ST->isLiteral()) {
987  AbbrevToUse = StructAnonAbbrev;
988  } else {
989  if (ST->isOpaque()) {
991  } else {
993  AbbrevToUse = StructNamedAbbrev;
994  }
995 
996  // Emit the name if it is present.
997  if (!ST->getName().empty())
999  StructNameAbbrev);
1000  }
1001  break;
1002  }
1003  case Type::ArrayTyID: {
1004  ArrayType *AT = cast<ArrayType>(T);
1005  // ARRAY: [numelts, eltty]
1007  TypeVals.push_back(AT->getNumElements());
1008  TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1009  AbbrevToUse = ArrayAbbrev;
1010  break;
1011  }
1012  case Type::FixedVectorTyID:
1013  case Type::ScalableVectorTyID: {
1014  VectorType *VT = cast<VectorType>(T);
1015  // VECTOR [numelts, eltty] or
1016  // [numelts, eltty, scalable]
1018  TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1019  TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1020  if (isa<ScalableVectorType>(VT))
1021  TypeVals.push_back(true);
1022  break;
1023  }
1024  case Type::DXILPointerTyID:
1025  llvm_unreachable("DXIL pointers cannot be added to IR modules");
1026  }
1027 
1028  // Emit the finished record.
1029  Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1030  TypeVals.clear();
1031  }
1032 
1033  Stream.ExitBlock();
1034 }
1035 
1036 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1037  switch (Linkage) {
1039  return 0;
1041  return 16;
1043  return 2;
1045  return 3;
1047  return 18;
1049  return 7;
1051  return 8;
1053  return 9;
1055  return 17;
1057  return 19;
1059  return 12;
1060  }
1061  llvm_unreachable("Invalid linkage");
1062 }
1063 
1064 static unsigned getEncodedLinkage(const GlobalValue &GV) {
1065  return getEncodedLinkage(GV.getLinkage());
1066 }
1067 
1069  uint64_t RawFlags = 0;
1070  RawFlags |= Flags.ReadNone;
1071  RawFlags |= (Flags.ReadOnly << 1);
1072  RawFlags |= (Flags.NoRecurse << 2);
1073  RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1074  RawFlags |= (Flags.NoInline << 4);
1075  RawFlags |= (Flags.AlwaysInline << 5);
1076  RawFlags |= (Flags.NoUnwind << 6);
1077  RawFlags |= (Flags.MayThrow << 7);
1078  RawFlags |= (Flags.HasUnknownCall << 8);
1079  RawFlags |= (Flags.MustBeUnreachable << 9);
1080  return RawFlags;
1081 }
1082 
1083 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1084 // in BitcodeReader.cpp.
1086  uint64_t RawFlags = 0;
1087 
1088  RawFlags |= Flags.NotEligibleToImport; // bool
1089  RawFlags |= (Flags.Live << 1);
1090  RawFlags |= (Flags.DSOLocal << 2);
1091  RawFlags |= (Flags.CanAutoHide << 3);
1092 
1093  // Linkage don't need to be remapped at that time for the summary. Any future
1094  // change to the getEncodedLinkage() function will need to be taken into
1095  // account here as well.
1096  RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1097 
1098  RawFlags |= (Flags.Visibility << 8); // 2 bits
1099 
1100  return RawFlags;
1101 }
1102 
1104  uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1105  (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1106  return RawFlags;
1107 }
1108 
1109 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1110  switch (GV.getVisibility()) {
1111  case GlobalValue::DefaultVisibility: return 0;
1112  case GlobalValue::HiddenVisibility: return 1;
1113  case GlobalValue::ProtectedVisibility: return 2;
1114  }
1115  llvm_unreachable("Invalid visibility");
1116 }
1117 
1118 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1119  switch (GV.getDLLStorageClass()) {
1120  case GlobalValue::DefaultStorageClass: return 0;
1121  case GlobalValue::DLLImportStorageClass: return 1;
1122  case GlobalValue::DLLExportStorageClass: return 2;
1123  }
1124  llvm_unreachable("Invalid DLL storage class");
1125 }
1126 
1127 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1128  switch (GV.getThreadLocalMode()) {
1129  case GlobalVariable::NotThreadLocal: return 0;
1131  case GlobalVariable::LocalDynamicTLSModel: return 2;
1132  case GlobalVariable::InitialExecTLSModel: return 3;
1133  case GlobalVariable::LocalExecTLSModel: return 4;
1134  }
1135  llvm_unreachable("Invalid TLS model");
1136 }
1137 
1138 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1139  switch (C.getSelectionKind()) {
1140  case Comdat::Any:
1142  case Comdat::ExactMatch:
1144  case Comdat::Largest:
1146  case Comdat::NoDeduplicate:
1148  case Comdat::SameSize:
1150  }
1151  llvm_unreachable("Invalid selection kind");
1152 }
1153 
1154 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1155  switch (GV.getUnnamedAddr()) {
1156  case GlobalValue::UnnamedAddr::None: return 0;
1157  case GlobalValue::UnnamedAddr::Local: return 2;
1158  case GlobalValue::UnnamedAddr::Global: return 1;
1159  }
1160  llvm_unreachable("Invalid unnamed_addr");
1161 }
1162 
1163 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1164  if (GenerateHash)
1165  Hasher.update(Str);
1166  return StrtabBuilder.add(Str);
1167 }
1168 
1169 void ModuleBitcodeWriter::writeComdats() {
1171  for (const Comdat *C : VE.getComdats()) {
1172  // COMDAT: [strtab offset, strtab size, selection_kind]
1173  Vals.push_back(addToStrtab(C->getName()));
1174  Vals.push_back(C->getName().size());
1175  Vals.push_back(getEncodedComdatSelectionKind(*C));
1176  Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1177  Vals.clear();
1178  }
1179 }
1180 
1181 /// Write a record that will eventually hold the word offset of the
1182 /// module-level VST. For now the offset is 0, which will be backpatched
1183 /// after the real VST is written. Saves the bit offset to backpatch.
1184 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1185  // Write a placeholder value in for the offset of the real VST,
1186  // which is written after the function blocks so that it can include
1187  // the offset of each function. The placeholder offset will be
1188  // updated when the real VST is written.
1189  auto Abbv = std::make_shared<BitCodeAbbrev>();
1191  // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1192  // hold the real VST offset. Must use fixed instead of VBR as we don't
1193  // know how many VBR chunks to reserve ahead of time.
1194  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1195  unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1196 
1197  // Emit the placeholder
1198  uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1199  Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1200 
1201  // Compute and save the bit offset to the placeholder, which will be
1202  // patched when the real VST is written. We can simply subtract the 32-bit
1203  // fixed size from the current bit number to get the location to backpatch.
1204  VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1205 }
1206 
1208 
1209 /// Determine the encoding to use for the given string name and length.
1211  bool isChar6 = true;
1212  for (char C : Str) {
1213  if (isChar6)
1214  isChar6 = BitCodeAbbrevOp::isChar6(C);
1215  if ((unsigned char)C & 128)
1216  // don't bother scanning the rest.
1217  return SE_Fixed8;
1218  }
1219  if (isChar6)
1220  return SE_Char6;
1221  return SE_Fixed7;
1222 }
1223 
1224 /// Emit top-level description of module, including target triple, inline asm,
1225 /// descriptors for global variables, and function prototype info.
1226 /// Returns the bit offset to backpatch with the location of the real VST.
1227 void ModuleBitcodeWriter::writeModuleInfo() {
1228  // Emit various pieces of data attached to a module.
1229  if (!M.getTargetTriple().empty())
1230  writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1231  0 /*TODO*/);
1232  const std::string &DL = M.getDataLayoutStr();
1233  if (!DL.empty())
1234  writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1235  if (!M.getModuleInlineAsm().empty())
1236  writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1237  0 /*TODO*/);
1238 
1239  // Emit information about sections and GC, computing how many there are. Also
1240  // compute the maximum alignment value.
1241  std::map<std::string, unsigned> SectionMap;
1242  std::map<std::string, unsigned> GCMap;
1243  MaybeAlign MaxAlignment;
1244  unsigned MaxGlobalType = 0;
1245  const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1246  if (A)
1247  MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1248  };
1249  for (const GlobalVariable &GV : M.globals()) {
1250  UpdateMaxAlignment(GV.getAlign());
1251  MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1252  if (GV.hasSection()) {
1253  // Give section names unique ID's.
1254  unsigned &Entry = SectionMap[std::string(GV.getSection())];
1255  if (!Entry) {
1256  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1257  0 /*TODO*/);
1258  Entry = SectionMap.size();
1259  }
1260  }
1261  }
1262  for (const Function &F : M) {
1263  UpdateMaxAlignment(F.getAlign());
1264  if (F.hasSection()) {
1265  // Give section names unique ID's.
1266  unsigned &Entry = SectionMap[std::string(F.getSection())];
1267  if (!Entry) {
1268  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1269  0 /*TODO*/);
1270  Entry = SectionMap.size();
1271  }
1272  }
1273  if (F.hasGC()) {
1274  // Same for GC names.
1275  unsigned &Entry = GCMap[F.getGC()];
1276  if (!Entry) {
1277  writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1278  0 /*TODO*/);
1279  Entry = GCMap.size();
1280  }
1281  }
1282  }
1283 
1284  // Emit abbrev for globals, now that we know # sections and max alignment.
1285  unsigned SimpleGVarAbbrev = 0;
1286  if (!M.global_empty()) {
1287  // Add an abbrev for common globals with no visibility or thread localness.
1288  auto Abbv = std::make_shared<BitCodeAbbrev>();
1290  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1291  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1293  Log2_32_Ceil(MaxGlobalType+1)));
1294  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1295  //| explicitType << 1
1296  //| constant
1297  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1298  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1299  if (!MaxAlignment) // Alignment.
1300  Abbv->Add(BitCodeAbbrevOp(0));
1301  else {
1302  unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1304  Log2_32_Ceil(MaxEncAlignment+1)));
1305  }
1306  if (SectionMap.empty()) // Section.
1307  Abbv->Add(BitCodeAbbrevOp(0));
1308  else
1310  Log2_32_Ceil(SectionMap.size()+1)));
1311  // Don't bother emitting vis + thread local.
1312  SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1313  }
1314 
1316  // Emit the module's source file name.
1317  {
1318  StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1320  if (Bits == SE_Char6)
1321  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1322  else if (Bits == SE_Fixed7)
1323  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1324 
1325  // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1326  auto Abbv = std::make_shared<BitCodeAbbrev>();
1329  Abbv->Add(AbbrevOpToUse);
1330  unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1331 
1332  for (const auto P : M.getSourceFileName())
1333  Vals.push_back((unsigned char)P);
1334 
1335  // Emit the finished record.
1336  Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1337  Vals.clear();
1338  }
1339 
1340  // Emit the global variable information.
1341  for (const GlobalVariable &GV : M.globals()) {
1342  unsigned AbbrevToUse = 0;
1343 
1344  // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1345  // linkage, alignment, section, visibility, threadlocal,
1346  // unnamed_addr, externally_initialized, dllstorageclass,
1347  // comdat, attributes, DSO_Local]
1348  Vals.push_back(addToStrtab(GV.getName()));
1349  Vals.push_back(GV.getName().size());
1350  Vals.push_back(VE.getTypeID(GV.getValueType()));
1351  Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1352  Vals.push_back(GV.isDeclaration() ? 0 :
1353  (VE.getValueID(GV.getInitializer()) + 1));
1354  Vals.push_back(getEncodedLinkage(GV));
1355  Vals.push_back(getEncodedAlign(GV.getAlign()));
1356  Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1357  : 0);
1358  if (GV.isThreadLocal() ||
1359  GV.getVisibility() != GlobalValue::DefaultVisibility ||
1360  GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1361  GV.isExternallyInitialized() ||
1362  GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1363  GV.hasComdat() ||
1364  GV.hasAttributes() ||
1365  GV.isDSOLocal() ||
1366  GV.hasPartition()) {
1367  Vals.push_back(getEncodedVisibility(GV));
1368  Vals.push_back(getEncodedThreadLocalMode(GV));
1369  Vals.push_back(getEncodedUnnamedAddr(GV));
1370  Vals.push_back(GV.isExternallyInitialized());
1371  Vals.push_back(getEncodedDLLStorageClass(GV));
1372  Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1373 
1374  auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1375  Vals.push_back(VE.getAttributeListID(AL));
1376 
1377  Vals.push_back(GV.isDSOLocal());
1378  Vals.push_back(addToStrtab(GV.getPartition()));
1379  Vals.push_back(GV.getPartition().size());
1380  } else {
1381  AbbrevToUse = SimpleGVarAbbrev;
1382  }
1383 
1384  Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1385  Vals.clear();
1386  }
1387 
1388  // Emit the function proto information.
1389  for (const Function &F : M) {
1390  // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1391  // linkage, paramattrs, alignment, section, visibility, gc,
1392  // unnamed_addr, prologuedata, dllstorageclass, comdat,
1393  // prefixdata, personalityfn, DSO_Local, addrspace]
1394  Vals.push_back(addToStrtab(F.getName()));
1395  Vals.push_back(F.getName().size());
1396  Vals.push_back(VE.getTypeID(F.getFunctionType()));
1397  Vals.push_back(F.getCallingConv());
1398  Vals.push_back(F.isDeclaration());
1399  Vals.push_back(getEncodedLinkage(F));
1400  Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1401  Vals.push_back(getEncodedAlign(F.getAlign()));
1402  Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1403  : 0);
1404  Vals.push_back(getEncodedVisibility(F));
1405  Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1406  Vals.push_back(getEncodedUnnamedAddr(F));
1407  Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1408  : 0);
1409  Vals.push_back(getEncodedDLLStorageClass(F));
1410  Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1411  Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1412  : 0);
1413  Vals.push_back(
1414  F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1415 
1416  Vals.push_back(F.isDSOLocal());
1417  Vals.push_back(F.getAddressSpace());
1418  Vals.push_back(addToStrtab(F.getPartition()));
1419  Vals.push_back(F.getPartition().size());
1420 
1421  unsigned AbbrevToUse = 0;
1422  Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1423  Vals.clear();
1424  }
1425 
1426  // Emit the alias information.
1427  for (const GlobalAlias &A : M.aliases()) {
1428  // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1429  // visibility, dllstorageclass, threadlocal, unnamed_addr,
1430  // DSO_Local]
1431  Vals.push_back(addToStrtab(A.getName()));
1432  Vals.push_back(A.getName().size());
1433  Vals.push_back(VE.getTypeID(A.getValueType()));
1434  Vals.push_back(A.getType()->getAddressSpace());
1435  Vals.push_back(VE.getValueID(A.getAliasee()));
1436  Vals.push_back(getEncodedLinkage(A));
1437  Vals.push_back(getEncodedVisibility(A));
1438  Vals.push_back(getEncodedDLLStorageClass(A));
1439  Vals.push_back(getEncodedThreadLocalMode(A));
1440  Vals.push_back(getEncodedUnnamedAddr(A));
1441  Vals.push_back(A.isDSOLocal());
1442  Vals.push_back(addToStrtab(A.getPartition()));
1443  Vals.push_back(A.getPartition().size());
1444 
1445  unsigned AbbrevToUse = 0;
1446  Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1447  Vals.clear();
1448  }
1449 
1450  // Emit the ifunc information.
1451  for (const GlobalIFunc &I : M.ifuncs()) {
1452  // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1453  // val#, linkage, visibility, DSO_Local]
1454  Vals.push_back(addToStrtab(I.getName()));
1455  Vals.push_back(I.getName().size());
1456  Vals.push_back(VE.getTypeID(I.getValueType()));
1457  Vals.push_back(I.getType()->getAddressSpace());
1458  Vals.push_back(VE.getValueID(I.getResolver()));
1459  Vals.push_back(getEncodedLinkage(I));
1460  Vals.push_back(getEncodedVisibility(I));
1461  Vals.push_back(I.isDSOLocal());
1462  Vals.push_back(addToStrtab(I.getPartition()));
1463  Vals.push_back(I.getPartition().size());
1464  Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1465  Vals.clear();
1466  }
1467 
1468  writeValueSymbolTableForwardDecl();
1469 }
1470 
1472  uint64_t Flags = 0;
1473 
1474  if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1475  if (OBO->hasNoSignedWrap())
1476  Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1477  if (OBO->hasNoUnsignedWrap())
1478  Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1479  } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1480  if (PEO->isExact())
1481  Flags |= 1 << bitc::PEO_EXACT;
1482  } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1483  if (FPMO->hasAllowReassoc())
1484  Flags |= bitc::AllowReassoc;
1485  if (FPMO->hasNoNaNs())
1486  Flags |= bitc::NoNaNs;
1487  if (FPMO->hasNoInfs())
1488  Flags |= bitc::NoInfs;
1489  if (FPMO->hasNoSignedZeros())
1490  Flags |= bitc::NoSignedZeros;
1491  if (FPMO->hasAllowReciprocal())
1492  Flags |= bitc::AllowReciprocal;
1493  if (FPMO->hasAllowContract())
1494  Flags |= bitc::AllowContract;
1495  if (FPMO->hasApproxFunc())
1496  Flags |= bitc::ApproxFunc;
1497  }
1498 
1499  return Flags;
1500 }
1501 
1502 void ModuleBitcodeWriter::writeValueAsMetadata(
1504  // Mimic an MDNode with a value as one operand.
1505  Value *V = MD->getValue();
1506  Record.push_back(VE.getTypeID(V->getType()));
1507  Record.push_back(VE.getValueID(V));
1508  Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1509  Record.clear();
1510 }
1511 
1514  unsigned Abbrev) {
1515  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1516  Metadata *MD = N->getOperand(i);
1517  assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1518  "Unexpected function-local metadata");
1519  Record.push_back(VE.getMetadataOrNullID(MD));
1520  }
1521  Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1523  Record, Abbrev);
1524  Record.clear();
1525 }
1526 
1527 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1528  // Assume the column is usually under 128, and always output the inlined-at
1529  // location (it's never more expensive than building an array size 1).
1530  auto Abbv = std::make_shared<BitCodeAbbrev>();
1532  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1533  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1534  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1535  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1536  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1537  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1538  return Stream.EmitAbbrev(std::move(Abbv));
1539 }
1540 
1543  unsigned &Abbrev) {
1544  if (!Abbrev)
1545  Abbrev = createDILocationAbbrev();
1546 
1547  Record.push_back(N->isDistinct());
1548  Record.push_back(N->getLine());
1549  Record.push_back(N->getColumn());
1550  Record.push_back(VE.getMetadataID(N->getScope()));
1551  Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1552  Record.push_back(N->isImplicitCode());
1553 
1554  Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1555  Record.clear();
1556 }
1557 
1558 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1559  // Assume the column is usually under 128, and always output the inlined-at
1560  // location (it's never more expensive than building an array size 1).
1561  auto Abbv = std::make_shared<BitCodeAbbrev>();
1563  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1564  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1565  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1566  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1568  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1569  return Stream.EmitAbbrev(std::move(Abbv));
1570 }
1571 
1574  unsigned &Abbrev) {
1575  if (!Abbrev)
1576  Abbrev = createGenericDINodeAbbrev();
1577 
1578  Record.push_back(N->isDistinct());
1579  Record.push_back(N->getTag());
1580  Record.push_back(0); // Per-tag version field; unused for now.
1581 
1582  for (auto &I : N->operands())
1583  Record.push_back(VE.getMetadataOrNullID(I));
1584 
1585  Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1586  Record.clear();
1587 }
1588 
1591  unsigned Abbrev) {
1592  const uint64_t Version = 2 << 1;
1593  Record.push_back((uint64_t)N->isDistinct() | Version);
1594  Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1595  Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1596  Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1597  Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1598 
1599  Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1600  Record.clear();
1601 }
1602 
1605  unsigned Abbrev) {
1606  Record.push_back((uint64_t)N->isDistinct());
1607  Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1608  Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1609  Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1610  Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1611 
1612  Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1613  Record.clear();
1614 }
1615 
1617  if ((int64_t)V >= 0)
1618  Vals.push_back(V << 1);
1619  else
1620  Vals.push_back((-V << 1) | 1);
1621 }
1622 
1623 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
1624  // We have an arbitrary precision integer value to write whose
1625  // bit width is > 64. However, in canonical unsigned integer
1626  // format it is likely that the high bits are going to be zero.
1627  // So, we only write the number of active words.
1628  unsigned NumWords = A.getActiveWords();
1629  const uint64_t *RawData = A.getRawData();
1630  for (unsigned i = 0; i < NumWords; i++)
1631  emitSignedInt64(Vals, RawData[i]);
1632 }
1633 
1636  unsigned Abbrev) {
1637  const uint64_t IsBigInt = 1 << 2;
1638  Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1639  Record.push_back(N->getValue().getBitWidth());
1640  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1641  emitWideAPInt(Record, N->getValue());
1642 
1643  Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1644  Record.clear();
1645 }
1646 
1649  unsigned Abbrev) {
1650  Record.push_back(N->isDistinct());
1651  Record.push_back(N->getTag());
1652  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1653  Record.push_back(N->getSizeInBits());
1654  Record.push_back(N->getAlignInBits());
1655  Record.push_back(N->getEncoding());
1656  Record.push_back(N->getFlags());
1657 
1658  Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1659  Record.clear();
1660 }
1661 
1664  unsigned Abbrev) {
1665  Record.push_back(N->isDistinct());
1666  Record.push_back(N->getTag());
1667  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1668  Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1669  Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1670  Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1671  Record.push_back(N->getSizeInBits());
1672  Record.push_back(N->getAlignInBits());
1673  Record.push_back(N->getEncoding());
1674 
1675  Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1676  Record.clear();
1677 }
1678 
1681  unsigned Abbrev) {
1682  Record.push_back(N->isDistinct());
1683  Record.push_back(N->getTag());
1684  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1685  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1686  Record.push_back(N->getLine());
1687  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1688  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1689  Record.push_back(N->getSizeInBits());
1690  Record.push_back(N->getAlignInBits());
1691  Record.push_back(N->getOffsetInBits());
1692  Record.push_back(N->getFlags());
1693  Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1694 
1695  // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1696  // that there is no DWARF address space associated with DIDerivedType.
1697  if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1698  Record.push_back(*DWARFAddressSpace + 1);
1699  else
1700  Record.push_back(0);
1701 
1702  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1703 
1704  Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1705  Record.clear();
1706 }
1707 
1710  unsigned Abbrev) {
1711  const unsigned IsNotUsedInOldTypeRef = 0x2;
1712  Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1713  Record.push_back(N->getTag());
1714  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1715  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1716  Record.push_back(N->getLine());
1717  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1718  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1719  Record.push_back(N->getSizeInBits());
1720  Record.push_back(N->getAlignInBits());
1721  Record.push_back(N->getOffsetInBits());
1722  Record.push_back(N->getFlags());
1723  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1724  Record.push_back(N->getRuntimeLang());
1725  Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1726  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1727  Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1728  Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1729  Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1730  Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1731  Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1732  Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1733  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1734 
1735  Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1736  Record.clear();
1737 }
1738 
1741  unsigned Abbrev) {
1742  const unsigned HasNoOldTypeRefs = 0x2;
1743  Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1744  Record.push_back(N->getFlags());
1745  Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1746  Record.push_back(N->getCC());
1747 
1748  Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1749  Record.clear();
1750 }
1751 
1754  unsigned Abbrev) {
1755  Record.push_back(N->isDistinct());
1756  Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1757  Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1758  if (N->getRawChecksum()) {
1759  Record.push_back(N->getRawChecksum()->Kind);
1760  Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1761  } else {
1762  // Maintain backwards compatibility with the old internal representation of
1763  // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1764  Record.push_back(0);
1765  Record.push_back(VE.getMetadataOrNullID(nullptr));
1766  }
1767  auto Source = N->getRawSource();
1768  if (Source)
1769  Record.push_back(VE.getMetadataOrNullID(*Source));
1770 
1771  Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1772  Record.clear();
1773 }
1774 
1777  unsigned Abbrev) {
1778  assert(N->isDistinct() && "Expected distinct compile units");
1779  Record.push_back(/* IsDistinct */ true);
1780  Record.push_back(N->getSourceLanguage());
1781  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1782  Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1783  Record.push_back(N->isOptimized());
1784  Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1785  Record.push_back(N->getRuntimeVersion());
1786  Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1787  Record.push_back(N->getEmissionKind());
1788  Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1789  Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1790  Record.push_back(/* subprograms */ 0);
1791  Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1792  Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1793  Record.push_back(N->getDWOId());
1794  Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1795  Record.push_back(N->getSplitDebugInlining());
1796  Record.push_back(N->getDebugInfoForProfiling());
1797  Record.push_back((unsigned)N->getNameTableKind());
1798  Record.push_back(N->getRangesBaseAddress());
1799  Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1800  Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1801 
1802  Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1803  Record.clear();
1804 }
1805 
1808  unsigned Abbrev) {
1809  const uint64_t HasUnitFlag = 1 << 1;
1810  const uint64_t HasSPFlagsFlag = 1 << 2;
1811  Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1812  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1813  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1814  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1815  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1816  Record.push_back(N->getLine());
1817  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1818  Record.push_back(N->getScopeLine());
1819  Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1820  Record.push_back(N->getSPFlags());
1821  Record.push_back(N->getVirtualIndex());
1822  Record.push_back(N->getFlags());
1823  Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1824  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1825  Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1826  Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1827  Record.push_back(N->getThisAdjustment());
1828  Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1829  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1830  Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
1831 
1832  Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1833  Record.clear();
1834 }
1835 
1838  unsigned Abbrev) {
1839  Record.push_back(N->isDistinct());
1840  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1841  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1842  Record.push_back(N->getLine());
1843  Record.push_back(N->getColumn());
1844 
1845  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1846  Record.clear();
1847 }
1848 
1851  unsigned Abbrev) {
1852  Record.push_back(N->isDistinct());
1853  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1854  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1855  Record.push_back(N->getDiscriminator());
1856 
1857  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1858  Record.clear();
1859 }
1860 
1863  unsigned Abbrev) {
1864  Record.push_back(N->isDistinct());
1865  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1866  Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1867  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1868  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1869  Record.push_back(N->getLineNo());
1870 
1871  Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
1872  Record.clear();
1873 }
1874 
1877  unsigned Abbrev) {
1878  Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1879  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1880  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1881 
1882  Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1883  Record.clear();
1884 }
1885 
1888  unsigned Abbrev) {
1889  Record.push_back(N->isDistinct());
1890  Record.push_back(N->getMacinfoType());
1891  Record.push_back(N->getLine());
1892  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1893  Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1894 
1895  Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1896  Record.clear();
1897 }
1898 
1901  unsigned Abbrev) {
1902  Record.push_back(N->isDistinct());
1903  Record.push_back(N->getMacinfoType());
1904  Record.push_back(N->getLine());
1905  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1906  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1907 
1908  Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1909  Record.clear();
1910 }
1911 
1914  unsigned Abbrev) {
1915  Record.reserve(N->getArgs().size());
1916  for (ValueAsMetadata *MD : N->getArgs())
1917  Record.push_back(VE.getMetadataID(MD));
1918 
1919  Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);
1920  Record.clear();
1921 }
1922 
1925  unsigned Abbrev) {
1926  Record.push_back(N->isDistinct());
1927  for (auto &I : N->operands())
1928  Record.push_back(VE.getMetadataOrNullID(I));
1929  Record.push_back(N->getLineNo());
1930  Record.push_back(N->getIsDecl());
1931 
1932  Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1933  Record.clear();
1934 }
1935 
1938  unsigned Abbrev) {
1939  Record.push_back(N->isDistinct());
1940  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1941  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1942  Record.push_back(N->isDefault());
1943 
1944  Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1945  Record.clear();
1946 }
1947 
1950  unsigned Abbrev) {
1951  Record.push_back(N->isDistinct());
1952  Record.push_back(N->getTag());
1953  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1954  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1955  Record.push_back(N->isDefault());
1956  Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1957 
1958  Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1959  Record.clear();
1960 }
1961 
1964  unsigned Abbrev) {
1965  const uint64_t Version = 2 << 1;
1966  Record.push_back((uint64_t)N->isDistinct() | Version);
1967  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1968  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1969  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1970  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1971  Record.push_back(N->getLine());
1972  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1973  Record.push_back(N->isLocalToUnit());
1974  Record.push_back(N->isDefinition());
1975  Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1976  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1977  Record.push_back(N->getAlignInBits());
1978  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1979 
1980  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1981  Record.clear();
1982 }
1983 
1986  unsigned Abbrev) {
1987  // In order to support all possible bitcode formats in BitcodeReader we need
1988  // to distinguish the following cases:
1989  // 1) Record has no artificial tag (Record[1]),
1990  // has no obsolete inlinedAt field (Record[9]).
1991  // In this case Record size will be 8, HasAlignment flag is false.
1992  // 2) Record has artificial tag (Record[1]),
1993  // has no obsolete inlignedAt field (Record[9]).
1994  // In this case Record size will be 9, HasAlignment flag is false.
1995  // 3) Record has both artificial tag (Record[1]) and
1996  // obsolete inlignedAt field (Record[9]).
1997  // In this case Record size will be 10, HasAlignment flag is false.
1998  // 4) Record has neither artificial tag, nor inlignedAt field, but
1999  // HasAlignment flag is true and Record[8] contains alignment value.
2000  const uint64_t HasAlignmentFlag = 1 << 1;
2001  Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2002  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2003  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2004  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2005  Record.push_back(N->getLine());
2006  Record.push_back(VE.getMetadataOrNullID(N->getType()));
2007  Record.push_back(N->getArg());
2008  Record.push_back(N->getFlags());
2009  Record.push_back(N->getAlignInBits());
2010  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2011 
2012  Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2013  Record.clear();
2014 }
2015 
2018  unsigned Abbrev) {
2019  Record.push_back((uint64_t)N->isDistinct());
2020  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2021  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2022  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2023  Record.push_back(N->getLine());
2024 
2025  Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2026  Record.clear();
2027 }
2028 
2031  unsigned Abbrev) {
2032  Record.reserve(N->getElements().size() + 1);
2033  const uint64_t Version = 3 << 1;
2034  Record.push_back((uint64_t)N->isDistinct() | Version);
2035  Record.append(N->elements_begin(), N->elements_end());
2036 
2037  Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2038  Record.clear();
2039 }
2040 
2043  unsigned Abbrev) {
2044  Record.push_back(N->isDistinct());
2045  Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2046  Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2047 
2048  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2049  Record.clear();
2050 }
2051 
2054  unsigned Abbrev) {
2055  Record.push_back(N->isDistinct());
2056  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2057  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2058  Record.push_back(N->getLine());
2059  Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2060  Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2061  Record.push_back(N->getAttributes());
2062  Record.push_back(VE.getMetadataOrNullID(N->getType()));
2063 
2064  Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2065  Record.clear();
2066 }
2067 
2070  unsigned Abbrev) {
2071  Record.push_back(N->isDistinct());
2072  Record.push_back(N->getTag());
2073  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2074  Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2075  Record.push_back(N->getLine());
2076  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2077  Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2078  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2079 
2080  Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2081  Record.clear();
2082 }
2083 
2084 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2085  auto Abbv = std::make_shared<BitCodeAbbrev>();
2088  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2089  return Stream.EmitAbbrev(std::move(Abbv));
2090 }
2091 
2092 void ModuleBitcodeWriter::writeNamedMetadata(
2094  if (M.named_metadata_empty())
2095  return;
2096 
2097  unsigned Abbrev = createNamedMetadataAbbrev();
2098  for (const NamedMDNode &NMD : M.named_metadata()) {
2099  // Write name.
2100  StringRef Str = NMD.getName();
2101  Record.append(Str.bytes_begin(), Str.bytes_end());
2102  Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2103  Record.clear();
2104 
2105  // Write named metadata operands.
2106  for (const MDNode *N : NMD.operands())
2107  Record.push_back(VE.getMetadataID(N));
2108  Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2109  Record.clear();
2110  }
2111 }
2112 
2113 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2114  auto Abbv = std::make_shared<BitCodeAbbrev>();
2116  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2117  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2119  return Stream.EmitAbbrev(std::move(Abbv));
2120 }
2121 
2122 /// Write out a record for MDString.
2123 ///
2124 /// All the metadata strings in a metadata block are emitted in a single
2125 /// record. The sizes and strings themselves are shoved into a blob.
2126 void ModuleBitcodeWriter::writeMetadataStrings(
2128  if (Strings.empty())
2129  return;
2130 
2131  // Start the record with the number of strings.
2132  Record.push_back(bitc::METADATA_STRINGS);
2133  Record.push_back(Strings.size());
2134 
2135  // Emit the sizes of the strings in the blob.
2136  SmallString<256> Blob;
2137  {
2138  BitstreamWriter W(Blob);
2139  for (const Metadata *MD : Strings)
2140  W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2141  W.FlushToWord();
2142  }
2143 
2144  // Add the offset to the strings to the record.
2145  Record.push_back(Blob.size());
2146 
2147  // Add the strings to the blob.
2148  for (const Metadata *MD : Strings)
2149  Blob.append(cast<MDString>(MD)->getString());
2150 
2151  // Emit the final record.
2152  Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2153  Record.clear();
2154 }
2155 
2156 // Generates an enum to use as an index in the Abbrev array of Metadata record.
2157 enum MetadataAbbrev : unsigned {
2158 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2159 #include "llvm/IR/Metadata.def"
2161 };
2162 
2163 void ModuleBitcodeWriter::writeMetadataRecords(
2165  std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2166  if (MDs.empty())
2167  return;
2168 
2169  // Initialize MDNode abbreviations.
2170 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2171 #include "llvm/IR/Metadata.def"
2172 
2173  for (const Metadata *MD : MDs) {
2174  if (IndexPos)
2175  IndexPos->push_back(Stream.GetCurrentBitNo());
2176  if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2177  assert(N->isResolved() && "Expected forward references to be resolved");
2178 
2179  switch (N->getMetadataID()) {
2180  default:
2181  llvm_unreachable("Invalid MDNode subclass");
2182 #define HANDLE_MDNODE_LEAF(CLASS) \
2183  case Metadata::CLASS##Kind: \
2184  if (MDAbbrevs) \
2185  write##CLASS(cast<CLASS>(N), Record, \
2186  (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2187  else \
2188  write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2189  continue;
2190 #include "llvm/IR/Metadata.def"
2191  }
2192  }
2193  writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2194  }
2195 }
2196 
2197 void ModuleBitcodeWriter::writeModuleMetadata() {
2198  if (!VE.hasMDs() && M.named_metadata_empty())
2199  return;
2200 
2201  Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
2203 
2204  // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2205  // block and load any metadata.
2206  std::vector<unsigned> MDAbbrevs;
2207 
2208  MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2209  MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2210  MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2211  createGenericDINodeAbbrev();
2212 
2213  auto Abbv = std::make_shared<BitCodeAbbrev>();
2215  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2216  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2217  unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2218 
2219  Abbv = std::make_shared<BitCodeAbbrev>();
2222  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2223  unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2224 
2225  // Emit MDStrings together upfront.
2226  writeMetadataStrings(VE.getMDStrings(), Record);
2227 
2228  // We only emit an index for the metadata record if we have more than a given
2229  // (naive) threshold of metadatas, otherwise it is not worth it.
2230  if (VE.getNonMDStrings().size() > IndexThreshold) {
2231  // Write a placeholder value in for the offset of the metadata index,
2232  // which is written after the records, so that it can include
2233  // the offset of each entry. The placeholder offset will be
2234  // updated after all records are emitted.
2235  uint64_t Vals[] = {0, 0};
2236  Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2237  }
2238 
2239  // Compute and save the bit offset to the current position, which will be
2240  // patched when we emit the index later. We can simply subtract the 64-bit
2241  // fixed size from the current bit number to get the location to backpatch.
2242  uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2243 
2244  // This index will contain the bitpos for each individual record.
2245  std::vector<uint64_t> IndexPos;
2246  IndexPos.reserve(VE.getNonMDStrings().size());
2247 
2248  // Write all the records
2249  writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2250 
2251  if (VE.getNonMDStrings().size() > IndexThreshold) {
2252  // Now that we have emitted all the records we will emit the index. But
2253  // first
2254  // backpatch the forward reference so that the reader can skip the records
2255  // efficiently.
2256  Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2257  Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2258 
2259  // Delta encode the index.
2260  uint64_t PreviousValue = IndexOffsetRecordBitPos;
2261  for (auto &Elt : IndexPos) {
2262  auto EltDelta = Elt - PreviousValue;
2263  PreviousValue = Elt;
2264  Elt = EltDelta;
2265  }
2266  // Emit the index record.
2267  Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2268  IndexPos.clear();
2269  }
2270 
2271  // Write the named metadata now.
2272  writeNamedMetadata(Record);
2273 
2274  auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2276  Record.push_back(VE.getValueID(&GO));
2277  pushGlobalMetadataAttachment(Record, GO);
2279  };
2280  for (const Function &F : M)
2281  if (F.isDeclaration() && F.hasMetadata())
2282  AddDeclAttachedMetadata(F);
2283  // FIXME: Only store metadata for declarations here, and move data for global
2284  // variable definitions to a separate block (PR28134).
2285  for (const GlobalVariable &GV : M.globals())
2286  if (GV.hasMetadata())
2287  AddDeclAttachedMetadata(GV);
2288 
2289  Stream.ExitBlock();
2290 }
2291 
2292 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2293  if (!VE.hasMDs())
2294  return;
2295 
2296  Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2298  writeMetadataStrings(VE.getMDStrings(), Record);
2299  writeMetadataRecords(VE.getNonMDStrings(), Record);
2300  Stream.ExitBlock();
2301 }
2302 
2303 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2305  // [n x [id, mdnode]]
2307  GO.getAllMetadata(MDs);
2308  for (const auto &I : MDs) {
2309  Record.push_back(I.first);
2310  Record.push_back(VE.getMetadataID(I.second));
2311  }
2312 }
2313 
2314 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2315  Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2316 
2318 
2319  if (F.hasMetadata()) {
2320  pushGlobalMetadataAttachment(Record, F);
2321  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2322  Record.clear();
2323  }
2324 
2325  // Write metadata attachments
2326  // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2328  for (const BasicBlock &BB : F)
2329  for (const Instruction &I : BB) {
2330  MDs.clear();
2331  I.getAllMetadataOtherThanDebugLoc(MDs);
2332 
2333  // If no metadata, ignore instruction.
2334  if (MDs.empty()) continue;
2335 
2336  Record.push_back(VE.getInstructionID(&I));
2337 
2338  for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2339  Record.push_back(MDs[i].first);
2340  Record.push_back(VE.getMetadataID(MDs[i].second));
2341  }
2342  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2343  Record.clear();
2344  }
2345 
2346  Stream.ExitBlock();
2347 }
2348 
2349 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2351 
2352  // Write metadata kinds
2353  // METADATA_KIND - [n x [id, name]]
2355  M.getMDKindNames(Names);
2356 
2357  if (Names.empty()) return;
2358 
2359  Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2360 
2361  for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2362  Record.push_back(MDKindID);
2363  StringRef KName = Names[MDKindID];
2364  Record.append(KName.begin(), KName.end());
2365 
2366  Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2367  Record.clear();
2368  }
2369 
2370  Stream.ExitBlock();
2371 }
2372 
2373 void ModuleBitcodeWriter::writeOperandBundleTags() {
2374  // Write metadata kinds
2375  //
2376  // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2377  //
2378  // OPERAND_BUNDLE_TAG - [strchr x N]
2379 
2381  M.getOperandBundleTags(Tags);
2382 
2383  if (Tags.empty())
2384  return;
2385 
2386  Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2387 
2389 
2390  for (auto Tag : Tags) {
2391  Record.append(Tag.begin(), Tag.end());
2392 
2393  Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2394  Record.clear();
2395  }
2396 
2397  Stream.ExitBlock();
2398 }
2399 
2400 void ModuleBitcodeWriter::writeSyncScopeNames() {
2402  M.getContext().getSyncScopeNames(SSNs);
2403  if (SSNs.empty())
2404  return;
2405 
2406  Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2407 
2409  for (auto SSN : SSNs) {
2410  Record.append(SSN.begin(), SSN.end());
2411  Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2412  Record.clear();
2413  }
2414 
2415  Stream.ExitBlock();
2416 }
2417 
2418 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2419  bool isGlobal) {
2420  if (FirstVal == LastVal) return;
2421 
2422  Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2423 
2424  unsigned AggregateAbbrev = 0;
2425  unsigned String8Abbrev = 0;
2426  unsigned CString7Abbrev = 0;
2427  unsigned CString6Abbrev = 0;
2428  // If this is a constant pool for the module, emit module-specific abbrevs.
2429  if (isGlobal) {
2430  // Abbrev for CST_CODE_AGGREGATE.
2431  auto Abbv = std::make_shared<BitCodeAbbrev>();
2434  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2435  AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2436 
2437  // Abbrev for CST_CODE_STRING.
2438  Abbv = std::make_shared<BitCodeAbbrev>();
2441  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2442  String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2443  // Abbrev for CST_CODE_CSTRING.
2444  Abbv = std::make_shared<BitCodeAbbrev>();
2447  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2448  CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2449  // Abbrev for CST_CODE_CSTRING.
2450  Abbv = std::make_shared<BitCodeAbbrev>();
2454  CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2455  }
2456 
2458 
2459  const ValueEnumerator::ValueList &Vals = VE.getValues();
2460  Type *LastTy = nullptr;
2461  for (unsigned i = FirstVal; i != LastVal; ++i) {
2462  const Value *V = Vals[i].first;
2463  // If we need to switch types, do so now.
2464  if (V->getType() != LastTy) {
2465  LastTy = V->getType();
2466  Record.push_back(VE.getTypeID(LastTy));
2467  Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2468  CONSTANTS_SETTYPE_ABBREV);
2469  Record.clear();
2470  }
2471 
2472  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2473  Record.push_back(VE.getTypeID(IA->getFunctionType()));
2474  Record.push_back(
2475  unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2476  unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2477 
2478  // Add the asm string.
2479  const std::string &AsmStr = IA->getAsmString();
2480  Record.push_back(AsmStr.size());
2481  Record.append(AsmStr.begin(), AsmStr.end());
2482 
2483  // Add the constraint string.
2484  const std::string &ConstraintStr = IA->getConstraintString();
2485  Record.push_back(ConstraintStr.size());
2486  Record.append(ConstraintStr.begin(), ConstraintStr.end());
2487  Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2488  Record.clear();
2489  continue;
2490  }
2491  const Constant *C = cast<Constant>(V);
2492  unsigned Code = -1U;
2493  unsigned AbbrevToUse = 0;
2494  if (C->isNullValue()) {
2496  } else if (isa<PoisonValue>(C)) {
2498  } else if (isa<UndefValue>(C)) {
2500  } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2501  if (IV->getBitWidth() <= 64) {
2502  uint64_t V = IV->getSExtValue();
2503  emitSignedInt64(Record, V);
2505  AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2506  } else { // Wide integers, > 64 bits in size.
2507  emitWideAPInt(Record, IV->getValue());
2509  }
2510  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2512  Type *Ty = CFP->getType();
2513  if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2514  Ty->isDoubleTy()) {
2515  Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2516  } else if (Ty->isX86_FP80Ty()) {
2517  // api needed to prevent premature destruction
2518  // bits are not in the same order as a normal i80 APInt, compensate.
2519  APInt api = CFP->getValueAPF().bitcastToAPInt();
2520  const uint64_t *p = api.getRawData();
2521  Record.push_back((p[1] << 48) | (p[0] >> 16));
2522  Record.push_back(p[0] & 0xffffLL);
2523  } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2524  APInt api = CFP->getValueAPF().bitcastToAPInt();
2525  const uint64_t *p = api.getRawData();
2526  Record.push_back(p[0]);
2527  Record.push_back(p[1]);
2528  } else {
2529  assert(0 && "Unknown FP type!");
2530  }
2531  } else if (isa<ConstantDataSequential>(C) &&
2532  cast<ConstantDataSequential>(C)->isString()) {
2533  const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2534  // Emit constant strings specially.
2535  unsigned NumElts = Str->getNumElements();
2536  // If this is a null-terminated string, use the denser CSTRING encoding.
2537  if (Str->isCString()) {
2539  --NumElts; // Don't encode the null, which isn't allowed by char6.
2540  } else {
2542  AbbrevToUse = String8Abbrev;
2543  }
2544  bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2545  bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2546  for (unsigned i = 0; i != NumElts; ++i) {
2547  unsigned char V = Str->getElementAsInteger(i);
2548  Record.push_back(V);
2549  isCStr7 &= (V & 128) == 0;
2550  if (isCStrChar6)
2551  isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2552  }
2553 
2554  if (isCStrChar6)
2555  AbbrevToUse = CString6Abbrev;
2556  else if (isCStr7)
2557  AbbrevToUse = CString7Abbrev;
2558  } else if (const ConstantDataSequential *CDS =
2559  dyn_cast<ConstantDataSequential>(C)) {
2561  Type *EltTy = CDS->getElementType();
2562  if (isa<IntegerType>(EltTy)) {
2563  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2564  Record.push_back(CDS->getElementAsInteger(i));
2565  } else {
2566  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2567  Record.push_back(
2568  CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2569  }
2570  } else if (isa<ConstantAggregate>(C)) {
2572  for (const Value *Op : C->operands())
2573  Record.push_back(VE.getValueID(Op));
2574  AbbrevToUse = AggregateAbbrev;
2575  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2576  switch (CE->getOpcode()) {
2577  default:
2578  if (Instruction::isCast(CE->getOpcode())) {
2580  Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2581  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2582  Record.push_back(VE.getValueID(C->getOperand(0)));
2583  AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2584  } else {
2585  assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2587  Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2588  Record.push_back(VE.getValueID(C->getOperand(0)));
2589  Record.push_back(VE.getValueID(C->getOperand(1)));
2590  uint64_t Flags = getOptimizationFlags(CE);
2591  if (Flags != 0)
2592  Record.push_back(Flags);
2593  }
2594  break;
2595  case Instruction::FNeg: {
2596  assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2598  Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2599  Record.push_back(VE.getValueID(C->getOperand(0)));
2600  uint64_t Flags = getOptimizationFlags(CE);
2601  if (Flags != 0)
2602  Record.push_back(Flags);
2603  break;
2604  }
2605  case Instruction::GetElementPtr: {
2607  const auto *GO = cast<GEPOperator>(C);
2608  Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2609  if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2611  Record.push_back((*Idx << 1) | GO->isInBounds());
2612  } else if (GO->isInBounds())
2614  for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2615  Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2616  Record.push_back(VE.getValueID(C->getOperand(i)));
2617  }
2618  break;
2619  }
2620  case Instruction::Select:
2622  Record.push_back(VE.getValueID(C->getOperand(0)));
2623  Record.push_back(VE.getValueID(C->getOperand(1)));
2624  Record.push_back(VE.getValueID(C->getOperand(2)));
2625  break;
2626  case Instruction::ExtractElement:
2628  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2629  Record.push_back(VE.getValueID(C->getOperand(0)));
2630  Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2631  Record.push_back(VE.getValueID(C->getOperand(1)));
2632  break;
2633  case Instruction::InsertElement:
2635  Record.push_back(VE.getValueID(C->getOperand(0)));
2636  Record.push_back(VE.getValueID(C->getOperand(1)));
2637  Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2638  Record.push_back(VE.getValueID(C->getOperand(2)));
2639  break;
2640  case Instruction::ShuffleVector:
2641  // If the return type and argument types are the same, this is a
2642  // standard shufflevector instruction. If the types are different,
2643  // then the shuffle is widening or truncating the input vectors, and
2644  // the argument type must also be encoded.
2645  if (C->getType() == C->getOperand(0)->getType()) {
2647  } else {
2649  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2650  }
2651  Record.push_back(VE.getValueID(C->getOperand(0)));
2652  Record.push_back(VE.getValueID(C->getOperand(1)));
2653  Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2654  break;
2655  case Instruction::ICmp:
2656  case Instruction::FCmp:
2658  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2659  Record.push_back(VE.getValueID(C->getOperand(0)));
2660  Record.push_back(VE.getValueID(C->getOperand(1)));
2661  Record.push_back(CE->getPredicate());
2662  break;
2663  case Instruction::ExtractValue:
2664  case Instruction::InsertValue:
2665  report_fatal_error("extractvalue/insertvalue constexprs not supported");
2666  break;
2667  }
2668  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2670  Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2671  Record.push_back(VE.getValueID(BA->getFunction()));
2672  Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2673  } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2675  Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2676  Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2677  } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2679  Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2680  Record.push_back(VE.getValueID(NC->getGlobalValue()));
2681  } else {
2682 #ifndef NDEBUG
2683  C->dump();
2684 #endif
2685  llvm_unreachable("Unknown constant!");
2686  }
2687  Stream.EmitRecord(Code, Record, AbbrevToUse);
2688  Record.clear();
2689  }
2690 
2691  Stream.ExitBlock();
2692 }
2693 
2694 void ModuleBitcodeWriter::writeModuleConstants() {
2695  const ValueEnumerator::ValueList &Vals = VE.getValues();
2696 
2697  // Find the first constant to emit, which is the first non-globalvalue value.
2698  // We know globalvalues have been emitted by WriteModuleInfo.
2699  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2700  if (!isa<GlobalValue>(Vals[i].first)) {
2701  writeConstants(i, Vals.size(), true);
2702  return;
2703  }
2704  }
2705 }
2706 
2707 /// pushValueAndType - The file has to encode both the value and type id for
2708 /// many values, because we need to know what type to create for forward
2709 /// references. However, most operands are not forward references, so this type
2710 /// field is not needed.
2711 ///
2712 /// This function adds V's value ID to Vals. If the value ID is higher than the
2713 /// instruction ID, then it is a forward reference, and it also includes the
2714 /// type ID. The value ID that is written is encoded relative to the InstID.
2715 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2716  SmallVectorImpl<unsigned> &Vals) {
2717  unsigned ValID = VE.getValueID(V);
2718  // Make encoding relative to the InstID.
2719  Vals.push_back(InstID - ValID);
2720  if (ValID >= InstID) {
2721  Vals.push_back(VE.getTypeID(V->getType()));
2722  return true;
2723  }
2724  return false;
2725 }
2726 
2727 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2728  unsigned InstID) {
2730  LLVMContext &C = CS.getContext();
2731 
2732  for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2733  const auto &Bundle = CS.getOperandBundleAt(i);
2734  Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2735 
2736  for (auto &Input : Bundle.Inputs)
2737  pushValueAndType(Input, InstID, Record);
2738 
2740  Record.clear();
2741  }
2742 }
2743 
2744 /// pushValue - Like pushValueAndType, but where the type of the value is
2745 /// omitted (perhaps it was already encoded in an earlier operand).
2746 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2747  SmallVectorImpl<unsigned> &Vals) {
2748  unsigned ValID = VE.getValueID(V);
2749  Vals.push_back(InstID - ValID);
2750 }
2751 
2752 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2753  SmallVectorImpl<uint64_t> &Vals) {
2754  unsigned ValID = VE.getValueID(V);
2755  int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2756  emitSignedInt64(Vals, diff);
2757 }
2758 
2759 /// WriteInstruction - Emit an instruction to the specified stream.
2760 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2761  unsigned InstID,
2762  SmallVectorImpl<unsigned> &Vals) {
2763  unsigned Code = 0;
2764  unsigned AbbrevToUse = 0;
2765  VE.setInstructionID(&I);
2766  switch (I.getOpcode()) {
2767  default:
2768  if (Instruction::isCast(I.getOpcode())) {
2770  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2771  AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2772  Vals.push_back(VE.getTypeID(I.getType()));
2773  Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2774  } else {
2775  assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2777  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2778  AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2779  pushValue(I.getOperand(1), InstID, Vals);
2780  Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2781  uint64_t Flags = getOptimizationFlags(&I);
2782  if (Flags != 0) {
2783  if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2784  AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2785  Vals.push_back(Flags);
2786  }
2787  }
2788  break;
2789  case Instruction::FNeg: {
2791  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2792  AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2793  Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2794  uint64_t Flags = getOptimizationFlags(&I);
2795  if (Flags != 0) {
2796  if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2797  AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2798  Vals.push_back(Flags);
2799  }
2800  break;
2801  }
2802  case Instruction::GetElementPtr: {
2804  AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2805  auto &GEPInst = cast<GetElementPtrInst>(I);
2806  Vals.push_back(GEPInst.isInBounds());
2807  Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2808  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2809  pushValueAndType(I.getOperand(i), InstID, Vals);
2810  break;
2811  }
2812  case Instruction::ExtractValue: {
2814  pushValueAndType(I.getOperand(0), InstID, Vals);
2815  const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2816  Vals.append(EVI->idx_begin(), EVI->idx_end());
2817  break;
2818  }
2819  case Instruction::InsertValue: {
2821  pushValueAndType(I.getOperand(0), InstID, Vals);
2822  pushValueAndType(I.getOperand(1), InstID, Vals);
2823  const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2824  Vals.append(IVI->idx_begin(), IVI->idx_end());
2825  break;
2826  }
2827  case Instruction::Select: {
2829  pushValueAndType(I.getOperand(1), InstID, Vals);
2830  pushValue(I.getOperand(2), InstID, Vals);
2831  pushValueAndType(I.getOperand(0), InstID, Vals);
2832  uint64_t Flags = getOptimizationFlags(&I);
2833  if (Flags != 0)
2834  Vals.push_back(Flags);
2835  break;
2836  }
2837  case Instruction::ExtractElement:
2839  pushValueAndType(I.getOperand(0), InstID, Vals);
2840  pushValueAndType(I.getOperand(1), InstID, Vals);
2841  break;
2842  case Instruction::InsertElement:
2844  pushValueAndType(I.getOperand(0), InstID, Vals);
2845  pushValue(I.getOperand(1), InstID, Vals);
2846  pushValueAndType(I.getOperand(2), InstID, Vals);
2847  break;
2848  case Instruction::ShuffleVector:
2850  pushValueAndType(I.getOperand(0), InstID, Vals);
2851  pushValue(I.getOperand(1), InstID, Vals);
2852  pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2853  Vals);
2854  break;
2855  case Instruction::ICmp:
2856  case Instruction::FCmp: {
2857  // compare returning Int1Ty or vector of Int1Ty
2859  pushValueAndType(I.getOperand(0), InstID, Vals);
2860  pushValue(I.getOperand(1), InstID, Vals);
2861  Vals.push_back(cast<CmpInst>(I).getPredicate());
2862  uint64_t Flags = getOptimizationFlags(&I);
2863  if (Flags != 0)
2864  Vals.push_back(Flags);
2865  break;
2866  }
2867 
2868  case Instruction::Ret:
2869  {
2871  unsigned NumOperands = I.getNumOperands();
2872  if (NumOperands == 0)
2873  AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2874  else if (NumOperands == 1) {
2875  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2876  AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2877  } else {
2878  for (unsigned i = 0, e = NumOperands; i != e; ++i)
2879  pushValueAndType(I.getOperand(i), InstID, Vals);
2880  }
2881  }
2882  break;
2883  case Instruction::Br:
2884  {
2886  const BranchInst &II = cast<BranchInst>(I);
2887  Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2888  if (II.isConditional()) {
2889  Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2890  pushValue(II.getCondition(), InstID, Vals);
2891  }
2892  }
2893  break;
2894  case Instruction::Switch:
2895  {
2897  const SwitchInst &SI = cast<SwitchInst>(I);
2898  Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2899  pushValue(SI.getCondition(), InstID, Vals);
2900  Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2901  for (auto Case : SI.cases()) {
2902  Vals.push_back(VE.getValueID(Case.getCaseValue()));
2903  Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2904  }
2905  }
2906  break;
2907  case Instruction::IndirectBr:
2909  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2910  // Encode the address operand as relative, but not the basic blocks.
2911  pushValue(I.getOperand(0), InstID, Vals);
2912  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2913  Vals.push_back(VE.getValueID(I.getOperand(i)));
2914  break;
2915 
2916  case Instruction::Invoke: {
2917  const InvokeInst *II = cast<InvokeInst>(&I);
2918  const Value *Callee = II->getCalledOperand();
2919  FunctionType *FTy = II->getFunctionType();
2920 
2921  if (II->hasOperandBundles())
2922  writeOperandBundles(*II, InstID);
2923 
2925 
2926  Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2927  Vals.push_back(II->getCallingConv() | 1 << 13);
2928  Vals.push_back(VE.getValueID(II->getNormalDest()));
2929  Vals.push_back(VE.getValueID(II->getUnwindDest()));
2930  Vals.push_back(VE.getTypeID(FTy));
2931  pushValueAndType(Callee, InstID, Vals);
2932 
2933  // Emit value #'s for the fixed parameters.
2934  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2935  pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2936 
2937  // Emit type/value pairs for varargs params.
2938  if (FTy->isVarArg()) {
2939  for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
2940  pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2941  }
2942  break;
2943  }
2944  case Instruction::Resume:
2946  pushValueAndType(I.getOperand(0), InstID, Vals);
2947  break;
2948  case Instruction::CleanupRet: {
2950  const auto &CRI = cast<CleanupReturnInst>(I);
2951  pushValue(CRI.getCleanupPad(), InstID, Vals);
2952  if (CRI.hasUnwindDest())
2953  Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2954  break;
2955  }
2956  case Instruction::CatchRet: {
2958  const auto &CRI = cast<CatchReturnInst>(I);
2959  pushValue(CRI.getCatchPad(), InstID, Vals);
2960  Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2961  break;
2962  }
2963  case Instruction::CleanupPad:
2964  case Instruction::CatchPad: {
2965  const auto &FuncletPad = cast<FuncletPadInst>(I);
2966  Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2968  pushValue(FuncletPad.getParentPad(), InstID, Vals);
2969 
2970  unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2971  Vals.push_back(NumArgOperands);
2972  for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2973  pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2974  break;
2975  }
2976  case Instruction::CatchSwitch: {
2978  const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2979 
2980  pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2981 
2982  unsigned NumHandlers = CatchSwitch.getNumHandlers();
2983  Vals.push_back(NumHandlers);
2984  for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2985  Vals.push_back(VE.getValueID(CatchPadBB));
2986 
2987  if (CatchSwitch.hasUnwindDest())
2988  Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2989  break;
2990  }
2991  case Instruction::CallBr: {
2992  const CallBrInst *CBI = cast<CallBrInst>(&I);
2993  const Value *Callee = CBI->getCalledOperand();
2994  FunctionType *FTy = CBI->getFunctionType();
2995 
2996  if (CBI->hasOperandBundles())
2997  writeOperandBundles(*CBI, InstID);
2998 
3000 
3001  Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
3002 
3003  Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
3005 
3006  Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3007  Vals.push_back(CBI->getNumIndirectDests());
3008  for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3009  Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3010 
3011  Vals.push_back(VE.getTypeID(FTy));
3012  pushValueAndType(Callee, InstID, Vals);
3013 
3014  // Emit value #'s for the fixed parameters.
3015  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3016  pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3017 
3018  // Emit type/value pairs for varargs params.
3019  if (FTy->isVarArg()) {
3020  for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3021  pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3022  }
3023  break;
3024  }
3025  case Instruction::Unreachable:
3027  AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3028  break;
3029 
3030  case Instruction::PHI: {
3031  const PHINode &PN = cast<PHINode>(I);
3033  // With the newer instruction encoding, forward references could give
3034  // negative valued IDs. This is most common for PHIs, so we use
3035  // signed VBRs.
3037  Vals64.push_back(VE.getTypeID(PN.getType()));
3038  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3039  pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3040  Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3041  }
3042 
3043  uint64_t Flags = getOptimizationFlags(&I);
3044  if (Flags != 0)
3045  Vals64.push_back(Flags);
3046 
3047  // Emit a Vals64 vector and exit.
3048  Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3049  Vals64.clear();
3050  return;
3051  }
3052 
3053  case Instruction::LandingPad: {
3054  const LandingPadInst &LP = cast<LandingPadInst>(I);
3056  Vals.push_back(VE.getTypeID(LP.getType()));
3057  Vals.push_back(LP.isCleanup());
3058  Vals.push_back(LP.getNumClauses());
3059  for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3060  if (LP.isCatch(I))
3061  Vals.push_back(LandingPadInst::Catch);
3062  else
3063  Vals.push_back(LandingPadInst::Filter);
3064  pushValueAndType(LP.getClause(I), InstID, Vals);
3065  }
3066  break;
3067  }
3068 
3069  case Instruction::Alloca: {
3071  const AllocaInst &AI = cast<AllocaInst>(I);
3072  Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3073  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3074  Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3075  using APV = AllocaPackedValues;
3076  unsigned Record = 0;
3077  unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3078  Bitfield::set<APV::AlignLower>(
3079  Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3080  Bitfield::set<APV::AlignUpper>(Record,
3081  EncodedAlign >> APV::AlignLower::Bits);
3082  Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3083  Bitfield::set<APV::ExplicitType>(Record, true);
3084  Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3085  Vals.push_back(Record);
3086 
3087  unsigned AS = AI.getAddressSpace();
3088  if (AS != M.getDataLayout().getAllocaAddrSpace())
3089  Vals.push_back(AS);
3090  break;
3091  }
3092 
3093  case Instruction::Load:
3094  if (cast<LoadInst>(I).isAtomic()) {
3096  pushValueAndType(I.getOperand(0), InstID, Vals);
3097  } else {
3099  if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3100  AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3101  }
3102  Vals.push_back(VE.getTypeID(I.getType()));
3103  Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3104  Vals.push_back(cast<LoadInst>(I).isVolatile());
3105  if (cast<LoadInst>(I).isAtomic()) {
3106  Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3107  Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3108  }
3109  break;
3110  case Instruction::Store:
3111  if (cast<StoreInst>(I).isAtomic())
3113  else
3115  pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3116  pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3117  Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3118  Vals.push_back(cast<StoreInst>(I).isVolatile());
3119  if (cast<StoreInst>(I).isAtomic()) {
3120  Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3121  Vals.push_back(
3122  getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3123  }
3124  break;
3125  case Instruction::AtomicCmpXchg:
3127  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3128  pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3129  pushValue(I.getOperand(2), InstID, Vals); // newval.
3130  Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3131  Vals.push_back(
3132  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3133  Vals.push_back(
3134  getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3135  Vals.push_back(
3136  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3137  Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3138  Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3139  break;
3140  case Instruction::AtomicRMW:
3142  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3143  pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3144  Vals.push_back(
3145  getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3146  Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3147  Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3148  Vals.push_back(
3149  getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3150  Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3151  break;
3152  case Instruction::Fence:
3154  Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3155  Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3156  break;
3157  case Instruction::Call: {
3158  const CallInst &CI = cast<CallInst>(I);
3159  FunctionType *FTy = CI.getFunctionType();
3160 
3161  if (CI.hasOperandBundles())
3162  writeOperandBundles(CI, InstID);
3163 
3165 
3166  Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3167 
3168  unsigned Flags = getOptimizationFlags(&I);
3169  Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3170  unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3171  unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3173  unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3174  unsigned(Flags != 0) << bitc::CALL_FMF);
3175  if (Flags != 0)
3176  Vals.push_back(Flags);
3177 
3178  Vals.push_back(VE.getTypeID(FTy));
3179  pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3180 
3181  // Emit value #'s for the fixed parameters.
3182  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3183  // Check for labels (can happen with asm labels).
3184  if (FTy->getParamType(i)->isLabelTy())
3185  Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3186  else
3187  pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3188  }
3189 
3190  // Emit type/value pairs for varargs params.
3191  if (FTy->isVarArg()) {
3192  for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3193  pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3194  }
3195  break;
3196  }
3197  case Instruction::VAArg:
3199  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3200  pushValue(I.getOperand(0), InstID, Vals); // valist.
3201  Vals.push_back(VE.getTypeID(I.getType())); // restype.
3202  break;
3203  case Instruction::Freeze:
3205  pushValueAndType(I.getOperand(0), InstID, Vals);
3206  break;
3207  }
3208 
3209  Stream.EmitRecord(Code, Vals, AbbrevToUse);
3210  Vals.clear();
3211 }
3212 
3213 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3214 /// to allow clients to efficiently find the function body.
3215 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3216  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3217  // Get the offset of the VST we are writing, and backpatch it into
3218  // the VST forward declaration record.
3219  uint64_t VSTOffset = Stream.GetCurrentBitNo();
3220  // The BitcodeStartBit was the stream offset of the identification block.
3221  VSTOffset -= bitcodeStartBit();
3222  assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3223  // Note that we add 1 here because the offset is relative to one word
3224  // before the start of the identification block, which was historically
3225  // always the start of the regular bitcode header.
3226  Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3227 
3228  Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3229 
3230  auto Abbv = std::make_shared<BitCodeAbbrev>();
3232  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3233  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3234  unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3235 
3236  for (const Function &F : M) {
3237  uint64_t Record[2];
3238 
3239  if (F.isDeclaration())
3240  continue;
3241 
3242  Record[0] = VE.getValueID(&F);
3243 
3244  // Save the word offset of the function (from the start of the
3245  // actual bitcode written to the stream).
3246  uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3247  assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3248  // Note that we add 1 here because the offset is relative to one word
3249  // before the start of the identification block, which was historically
3250  // always the start of the regular bitcode header.
3251  Record[1] = BitcodeIndex / 32 + 1;
3252 
3253  Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3254  }
3255 
3256  Stream.ExitBlock();
3257 }
3258 
3259 /// Emit names for arguments, instructions and basic blocks in a function.
3260 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3261  const ValueSymbolTable &VST) {
3262  if (VST.empty())
3263  return;
3264 
3265  Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3266 
3267  // FIXME: Set up the abbrev, we know how many values there are!
3268  // FIXME: We know if the type names can use 7-bit ascii.
3269  SmallVector<uint64_t, 64> NameVals;
3270 
3271  for (const ValueName &Name : VST) {
3272  // Figure out the encoding to use for the name.
3274 
3275  unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3276  NameVals.push_back(VE.getValueID(Name.getValue()));
3277 
3278  // VST_CODE_ENTRY: [valueid, namechar x N]
3279  // VST_CODE_BBENTRY: [bbid, namechar x N]
3280  unsigned Code;
3281  if (isa<BasicBlock>(Name.getValue())) {
3283  if (Bits == SE_Char6)
3284  AbbrevToUse = VST_BBENTRY_6_ABBREV;
3285  } else {
3287  if (Bits == SE_Char6)
3288  AbbrevToUse = VST_ENTRY_6_ABBREV;
3289  else if (Bits == SE_Fixed7)
3290  AbbrevToUse = VST_ENTRY_7_ABBREV;
3291  }
3292 
3293  for (const auto P : Name.getKey())
3294  NameVals.push_back((unsigned char)P);
3295 
3296  // Emit the finished record.
3297  Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3298  NameVals.clear();
3299  }
3300 
3301  Stream.ExitBlock();
3302 }
3303 
3304 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3305  assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3306  unsigned Code;
3307  if (isa<BasicBlock>(Order.V))
3309  else
3311 
3312  SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3313  Record.push_back(VE.getValueID(Order.V));
3314  Stream.EmitRecord(Code, Record);
3315 }
3316 
3317 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3319  "Expected to be preserving use-list order");
3320 
3321  auto hasMore = [&]() {
3322  return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3323  };
3324  if (!hasMore())
3325  // Nothing to do.
3326  return;
3327 
3328  Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3329  while (hasMore()) {
3330  writeUseList(std::move(VE.UseListOrders.back()));
3331  VE.UseListOrders.pop_back();
3332  }
3333  Stream.ExitBlock();
3334 }
3335 
3336 /// Emit a function body to the module stream.
3337 void ModuleBitcodeWriter::writeFunction(
3338  const Function &F,
3339  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3340  // Save the bitcode index of the start of this function block for recording
3341  // in the VST.
3342  FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3343 
3344  Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3345  VE.incorporateFunction(F);
3346 
3348 
3349  // Emit the number of basic blocks, so the reader can create them ahead of
3350  // time.
3351  Vals.push_back(VE.getBasicBlocks().size());
3352  Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3353  Vals.clear();
3354 
3355  // If there are function-local constants, emit them now.
3356  unsigned CstStart, CstEnd;
3357  VE.getFunctionConstantRange(CstStart, CstEnd);
3358  writeConstants(CstStart, CstEnd, false);
3359 
3360  // If there is function-local metadata, emit it now.
3361  writeFunctionMetadata(F);
3362 
3363  // Keep a running idea of what the instruction ID is.
3364  unsigned InstID = CstEnd;
3365 
3366  bool NeedsMetadataAttachment = F.hasMetadata();
3367 
3368  DILocation *LastDL = nullptr;
3369  SmallSetVector<Function *, 4> BlockAddressUsers;
3370 
3371  // Finally, emit all the instructions, in order.
3372  for (const BasicBlock &BB : F) {
3373  for (const Instruction &I : BB) {
3374  writeInstruction(I, InstID, Vals);
3375 
3376  if (!I.getType()->isVoidTy())
3377  ++InstID;
3378 
3379  // If the instruction has metadata, write a metadata attachment later.
3380  NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3381 
3382  // If the instruction has a debug location, emit it.
3383  DILocation *DL = I.getDebugLoc();
3384  if (!DL)
3385  continue;
3386 
3387  if (DL == LastDL) {
3388  // Just repeat the same debug loc as last time.
3389  Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3390  continue;
3391  }
3392 
3393  Vals.push_back(DL->getLine());
3394  Vals.push_back(DL->getColumn());
3395  Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3396  Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3397  Vals.push_back(DL->isImplicitCode());
3398  Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3399  Vals.clear();
3400 
3401  LastDL = DL;
3402  }
3403 
3404  if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3405  SmallVector<Value *> Worklist{BA};
3406  SmallPtrSet<Value *, 8> Visited{BA};
3407  while (!Worklist.empty()) {
3408  Value *V = Worklist.pop_back_val();
3409  for (User *U : V->users()) {
3410  if (auto *I = dyn_cast<Instruction>(U)) {
3411  Function *P = I->getFunction();
3412  if (P != &F)
3413  BlockAddressUsers.insert(P);
3414  } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3415  Visited.insert(U).second)
3416  Worklist.push_back(U);
3417  }
3418  }
3419  }
3420  }
3421 
3422  if (!BlockAddressUsers.empty()) {
3423  Vals.resize(BlockAddressUsers.size());
3424  for (auto I : llvm::enumerate(BlockAddressUsers))
3425  Vals[I.index()] = VE.getValueID(I.value());
3426  Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals);
3427  Vals.clear();
3428  }
3429 
3430  // Emit names for all the instructions etc.
3431  if (auto *Symtab = F.getValueSymbolTable())
3432  writeFunctionLevelValueSymbolTable(*Symtab);
3433 
3434  if (NeedsMetadataAttachment)
3435  writeFunctionMetadataAttachment(F);
3436  if (VE.shouldPreserveUseListOrder())
3437  writeUseListBlock(&F);
3438  VE.purgeFunction();
3439  Stream.ExitBlock();
3440 }
3441 
3442 // Emit blockinfo, which defines the standard abbreviations etc.
3443 void ModuleBitcodeWriter::writeBlockInfo() {
3444  // We only want to emit block info records for blocks that have multiple
3445  // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3446  // Other blocks can define their abbrevs inline.
3447  Stream.EnterBlockInfoBlock();
3448 
3449  { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3450  auto Abbv = std::make_shared<BitCodeAbbrev>();
3451  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3452  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3454  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3455  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3456  VST_ENTRY_8_ABBREV)
3457  llvm_unreachable("Unexpected abbrev ordering!");
3458  }
3459 
3460  { // 7-bit fixed width VST_CODE_ENTRY strings.
3461  auto Abbv = std::make_shared<BitCodeAbbrev>();
3463  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3465  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3466  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3467  VST_ENTRY_7_ABBREV)
3468  llvm_unreachable("Unexpected abbrev ordering!");
3469  }
3470  { // 6-bit char6 VST_CODE_ENTRY strings.
3471  auto Abbv = std::make_shared<BitCodeAbbrev>();
3473  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3476  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3477  VST_ENTRY_6_ABBREV)
3478  llvm_unreachable("Unexpected abbrev ordering!");
3479  }
3480  { // 6-bit char6 VST_CODE_BBENTRY strings.
3481  auto Abbv = std::make_shared<BitCodeAbbrev>();
3483  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3486  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3487  VST_BBENTRY_6_ABBREV)
3488  llvm_unreachable("Unexpected abbrev ordering!");
3489  }
3490 
3491  { // SETTYPE abbrev for CONSTANTS_BLOCK.
3492  auto Abbv = std::make_shared<BitCodeAbbrev>();
3496  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3497  CONSTANTS_SETTYPE_ABBREV)
3498  llvm_unreachable("Unexpected abbrev ordering!");
3499  }
3500 
3501  { // INTEGER abbrev for CONSTANTS_BLOCK.
3502  auto Abbv = std::make_shared<BitCodeAbbrev>();
3504  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3505  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3506  CONSTANTS_INTEGER_ABBREV)
3507  llvm_unreachable("Unexpected abbrev ordering!");
3508  }
3509 
3510  { // CE_CAST abbrev for CONSTANTS_BLOCK.
3511  auto Abbv = std::make_shared<BitCodeAbbrev>();
3513  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3514  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3516  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3517 
3518  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3519  CONSTANTS_CE_CAST_Abbrev)
3520  llvm_unreachable("Unexpected abbrev ordering!");
3521  }
3522  { // NULL abbrev for CONSTANTS_BLOCK.
3523  auto Abbv = std::make_shared<BitCodeAbbrev>();
3525  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3526  CONSTANTS_NULL_Abbrev)
3527  llvm_unreachable("Unexpected abbrev ordering!");
3528  }
3529 
3530  // FIXME: This should only use space for first class types!
3531 
3532  { // INST_LOAD abbrev for FUNCTION_BLOCK.
3533  auto Abbv = std::make_shared<BitCodeAbbrev>();
3535  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3536  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3538  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3539  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3540  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3541  FUNCTION_INST_LOAD_ABBREV)
3542  llvm_unreachable("Unexpected abbrev ordering!");
3543  }
3544  { // INST_UNOP abbrev for FUNCTION_BLOCK.
3545  auto Abbv = std::make_shared<BitCodeAbbrev>();
3547  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3548  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3549  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3550  FUNCTION_INST_UNOP_ABBREV)
3551  llvm_unreachable("Unexpected abbrev ordering!");
3552  }
3553  { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3554  auto Abbv = std::make_shared<BitCodeAbbrev>();
3556  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3557  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3558  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3559  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3560  FUNCTION_INST_UNOP_FLAGS_ABBREV)
3561  llvm_unreachable("Unexpected abbrev ordering!");
3562  }
3563  { // INST_BINOP abbrev for FUNCTION_BLOCK.
3564  auto Abbv = std::make_shared<BitCodeAbbrev>();
3566  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3567  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3568  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3569  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3570  FUNCTION_INST_BINOP_ABBREV)
3571  llvm_unreachable("Unexpected abbrev ordering!");
3572  }
3573  { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3574  auto Abbv = std::make_shared<BitCodeAbbrev>();
3576  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3577  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3578  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3579  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3580  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3581  FUNCTION_INST_BINOP_FLAGS_ABBREV)
3582  llvm_unreachable("Unexpected abbrev ordering!");
3583  }
3584  { // INST_CAST abbrev for FUNCTION_BLOCK.
3585  auto Abbv = std::make_shared<BitCodeAbbrev>();
3587  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3588  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3590  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3591  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3592  FUNCTION_INST_CAST_ABBREV)
3593  llvm_unreachable("Unexpected abbrev ordering!");
3594  }
3595 
3596  { // INST_RET abbrev for FUNCTION_BLOCK.
3597  auto Abbv = std::make_shared<BitCodeAbbrev>();
3599  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3600  FUNCTION_INST_RET_VOID_ABBREV)
3601  llvm_unreachable("Unexpected abbrev ordering!");
3602  }
3603  { // INST_RET abbrev for FUNCTION_BLOCK.
3604  auto Abbv = std::make_shared<BitCodeAbbrev>();
3606  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3607  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3608  FUNCTION_INST_RET_VAL_ABBREV)
3609  llvm_unreachable("Unexpected abbrev ordering!");
3610  }
3611  { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3612  auto Abbv = std::make_shared<BitCodeAbbrev>();
3614  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3615  FUNCTION_INST_UNREACHABLE_ABBREV)
3616  llvm_unreachable("Unexpected abbrev ordering!");
3617  }
3618  {
3619  auto Abbv = std::make_shared<BitCodeAbbrev>();
3621  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3622  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3623  Log2_32_Ceil(VE.getTypes().size() + 1)));
3625  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3626  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3627  FUNCTION_INST_GEP_ABBREV)
3628  llvm_unreachable("Unexpected abbrev ordering!");
3629  }
3630 
3631  Stream.ExitBlock();
3632 }
3633 
3634 /// Write the module path strings, currently only used when generating
3635 /// a combined index file.
3636 void IndexBitcodeWriter::writeModStrings() {
3637  Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3638 
3639  // TODO: See which abbrev sizes we actually need to emit
3640 
3641  // 8-bit fixed-width MST_ENTRY strings.
3642  auto Abbv = std::make_shared<BitCodeAbbrev>();
3644  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3646  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3647  unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3648 
3649  // 7-bit fixed width MST_ENTRY strings.
3650  Abbv = std::make_shared<BitCodeAbbrev>();
3652  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3654  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3655  unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3656 
3657  // 6-bit char6 MST_ENTRY strings.
3658  Abbv = std::make_shared<BitCodeAbbrev>();
3660  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3663  unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3664 
3665  // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3666  Abbv = std::make_shared<BitCodeAbbrev>();
3668  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3669  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3670  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3671  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3672  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3673  unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3674 
3676  forEachModule(
3677  [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3678  StringRef Key = MPSE.getKey();
3679  const auto &Value = MPSE.getValue();
3681  unsigned AbbrevToUse = Abbrev8Bit;
3682  if (Bits == SE_Char6)
3683  AbbrevToUse = Abbrev6Bit;
3684  else if (Bits == SE_Fixed7)
3685  AbbrevToUse = Abbrev7Bit;
3686 
3687  Vals.push_back(Value.first);
3688  Vals.append(Key.begin(), Key.end());
3689 
3690  // Emit the finished record.
3691  Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3692 
3693  // Emit an optional hash for the module now
3694  const auto &Hash = Value.second;
3695  if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3696  Vals.assign(Hash.begin(), Hash.end());
3697  // Emit the hash record.
3698  Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3699  }
3700 
3701  Vals.clear();
3702  });
3703  Stream.ExitBlock();
3704 }
3705 
3706 /// Write the function type metadata related records that need to appear before
3707 /// a function summary entry (whether per-module or combined).
3708 template <typename Fn>
3711  Fn GetValueID) {
3712  if (!FS->type_tests().empty())
3713  Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3714 
3716 
3717  auto WriteVFuncIdVec = [&](uint64_t Ty,
3719  if (VFs.empty())
3720  return;
3721  Record.clear();
3722  for (auto &VF : VFs) {
3723  Record.push_back(VF.GUID);
3724  Record.push_back(VF.Offset);
3725  }
3726  Stream.EmitRecord(Ty, Record);
3727  };
3728 
3729  WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3730  FS->type_test_assume_vcalls());
3731  WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3732  FS->type_checked_load_vcalls());
3733 
3734  auto WriteConstVCallVec = [&](uint64_t Ty,
3736  for (auto &VC : VCs) {
3737  Record.clear();
3738  Record.push_back(VC.VFunc.GUID);
3739  Record.push_back(VC.VFunc.Offset);
3740  llvm::append_range(Record, VC.Args);
3741  Stream.EmitRecord(Ty, Record);
3742  }
3743  };
3744 
3745  WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3746  FS->type_test_assume_const_vcalls());
3747  WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3748  FS->type_checked_load_const_vcalls());
3749 
3750  auto WriteRange = [&](ConstantRange Range) {
3751  Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3752  assert(Range.getLower().getNumWords() == 1);
3753  assert(Range.getUpper().getNumWords() == 1);
3754  emitSignedInt64(Record, *Range.getLower().getRawData());
3755  emitSignedInt64(Record, *Range.getUpper().getRawData());
3756  };
3757 
3758  if (!FS->paramAccesses().empty()) {
3759  Record.clear();
3760  for (auto &Arg : FS->paramAccesses()) {
3761  size_t UndoSize = Record.size();
3762  Record.push_back(Arg.ParamNo);
3763  WriteRange(Arg.Use);
3764  Record.push_back(Arg.Calls.size());
3765  for (auto &Call : Arg.Calls) {
3766  Record.push_back(Call.ParamNo);
3767  Optional<unsigned> ValueID = GetValueID(Call.Callee);
3768  if (!ValueID) {
3769  // If ValueID is unknown we can't drop just this call, we must drop
3770  // entire parameter.
3771  Record.resize(UndoSize);
3772  break;
3773  }
3774  Record.push_back(*ValueID);
3775  WriteRange(Call.Offsets);
3776  }
3777  }
3778  if (!Record.empty())
3779  Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
3780  }
3781 }
3782 
3783 /// Collect type IDs from type tests used by function.
3784 static void
3786  std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3787  if (!FS->type_tests().empty())
3788  for (auto &TT : FS->type_tests())
3789  ReferencedTypeIds.insert(TT);
3790 
3791  auto GetReferencedTypesFromVFuncIdVec =
3793  for (auto &VF : VFs)
3794  ReferencedTypeIds.insert(VF.GUID);
3795  };
3796 
3797  GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3798  GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3799 
3800  auto GetReferencedTypesFromConstVCallVec =
3802  for (auto &VC : VCs)
3803  ReferencedTypeIds.insert(VC.VFunc.GUID);
3804  };
3805 
3806  GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3807  GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3808 }
3809 
3811  SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3812  const WholeProgramDevirtResolution::ByArg &ByArg) {
3813  NameVals.push_back(args.size());
3814  llvm::append_range(NameVals, args);
3815 
3816  NameVals.push_back(ByArg.TheKind);
3817  NameVals.push_back(ByArg.Info);
3818  NameVals.push_back(ByArg.Byte);
3819  NameVals.push_back(ByArg.Bit);
3820 }
3821 
3823  SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3825  NameVals.push_back(Id);
3826 
3827  NameVals.push_back(Wpd.TheKind);
3828  NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3829  NameVals.push_back(Wpd.SingleImplName.size());
3830 
3831  NameVals.push_back(Wpd.ResByArg.size());
3832  for (auto &A : Wpd.ResByArg)
3833  writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3834 }
3835 
3837  StringTableBuilder &StrtabBuilder,
3838  const std::string &Id,
3839  const TypeIdSummary &Summary) {
3840  NameVals.push_back(StrtabBuilder.add(Id));
3841  NameVals.push_back(Id.size());
3842 
3843  NameVals.push_back(Summary.TTRes.TheKind);
3844  NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3845  NameVals.push_back(Summary.TTRes.AlignLog2);
3846  NameVals.push_back(Summary.TTRes.SizeM1);
3847  NameVals.push_back(Summary.TTRes.BitMask);
3848  NameVals.push_back(Summary.TTRes.InlineBits);
3849 
3850  for (auto &W : Summary.WPDRes)
3851  writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3852  W.second);
3853 }
3854 
3856  SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3857  const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3858  ValueEnumerator &VE) {
3859  NameVals.push_back(StrtabBuilder.add(Id));
3860  NameVals.push_back(Id.size());
3861 
3862  for (auto &P : Summary) {
3863  NameVals.push_back(P.AddressPointOffset);
3864  NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3865  }
3866 }
3867 
3868 // Helper to emit a single function summary record.
3869 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3870  SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3871  unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3872  const Function &F) {
3873  NameVals.push_back(ValueID);
3874 
3875  FunctionSummary *FS = cast<FunctionSummary>(Summary);
3876 
3878  Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3879  return {VE.getValueID(VI.getValue())};
3880  });
3881 
3882  auto SpecialRefCnts = FS->specialRefCounts();
3883  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3884  NameVals.push_back(FS->instCount());
3885  NameVals.push_back(getEncodedFFlags(FS->fflags()));
3886  NameVals.push_back(FS->refs().size());
3887  NameVals.push_back(SpecialRefCnts.first); // rorefcnt
3888  NameVals.push_back(SpecialRefCnts.second); // worefcnt
3889 
3890  for (auto &RI : FS->refs())
3891  NameVals.push_back(VE.getValueID(RI.getValue()));
3892 
3893  bool HasProfileData =
3894  F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3895  for (auto &ECI : FS->calls()) {
3896  NameVals.push_back(getValueId(ECI.first));
3897  if (HasProfileData)
3898  NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3899  else if (WriteRelBFToSummary)
3900  NameVals.push_back(ECI.second.RelBlockFreq);
3901  }
3902 
3903  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3904  unsigned Code =
3905  (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3907  : bitc::FS_PERMODULE));
3908 
3909  // Emit the finished record.
3910  Stream.EmitRecord(Code, NameVals, FSAbbrev);
3911  NameVals.clear();
3912 }
3913 
3914 // Collect the global value references in the given variable's initializer,
3915 // and emit them in a summary record.
3916 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3917  const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3918  unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3919  auto VI = Index->getValueInfo(V.getGUID());
3920  if (!VI || VI.getSummaryList().empty()) {
3921  // Only declarations should not have a summary (a declaration might however
3922  // have a summary if the def was in module level asm).
3923  assert(V.isDeclaration());
3924  return;
3925  }
3926  auto *Summary = VI.getSummaryList()[0].get();
3927  NameVals.push_back(VE.getValueID(&V));
3928  GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3929  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3930  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3931 
3932  auto VTableFuncs = VS->vTableFuncs();
3933  if (!VTableFuncs.empty())
3934  NameVals.push_back(VS->refs().size());
3935 
3936  unsigned SizeBeforeRefs = NameVals.size();
3937  for (auto &RI : VS->refs())
3938  NameVals.push_back(VE.getValueID(RI.getValue()));
3939  // Sort the refs for determinism output, the vector returned by FS->refs() has
3940  // been initialized from a DenseSet.
3941  llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
3942 
3943  if (VTableFuncs.empty())
3944  Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3945  FSModRefsAbbrev);
3946  else {
3947  // VTableFuncs pairs should already be sorted by offset.
3948  for (auto &P : VTableFuncs) {
3949  NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3950  NameVals.push_back(P.VTableOffset);
3951  }
3952 
3954  FSModVTableRefsAbbrev);
3955  }
3956  NameVals.clear();
3957 }
3958 
3959 /// Emit the per-module summary section alongside the rest of
3960 /// the module's bitcode.
3961 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3962  // By default we compile with ThinLTO if the module has a summary, but the
3963  // client can request full LTO with a module flag.
3964  bool IsThinLTO = true;
3965  if (auto *MD =
3966  mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3967  IsThinLTO = MD->getZExtValue();
3968  Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3970  4);
3971 
3972  Stream.EmitRecord(
3975 
3976  // Write the index flags.
3977  uint64_t Flags = 0;
3978  // Bits 1-3 are set only in the combined index, skip them.
3979  if (Index->enableSplitLTOUnit())
3980  Flags |= 0x8;
3981  Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3982 
3983  if (Index->begin() == Index->end()) {
3984  Stream.ExitBlock();
3985  return;
3986  }
3987 
3988  for (const auto &GVI : valueIds()) {
3989  Stream.EmitRecord(bitc::FS_VALUE_GUID,
3990  ArrayRef<uint64_t>{GVI.second, GVI.first});
3991  }
3992 
3993  // Abbrev for FS_PERMODULE_PROFILE.
3994  auto Abbv = std::make_shared<BitCodeAbbrev>();
3996  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3997  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3998  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3999  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4000  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4001  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4002  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4003  // numrefs x valueid, n x (valueid, hotness)
4005  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4006  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4007 
4008  // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
4009  Abbv = std::make_shared<BitCodeAbbrev>();
4010  if (WriteRelBFToSummary)
4012  else
4013  Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
4014  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4015  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4016  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4017  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4018  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4019  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4020  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4021  // numrefs x valueid, n x (valueid [, rel_block_freq])
4023  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4024  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4025 
4026  // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4027  Abbv = std::make_shared<BitCodeAbbrev>();
4029  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4030  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4031  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4032  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4033  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4034 
4035  // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4036  Abbv = std::make_shared<BitCodeAbbrev>();
4038  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4039  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4040  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4041  // numrefs x valueid, n x (valueid , offset)
4043  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4044  unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4045 
4046  // Abbrev for FS_ALIAS.
4047  Abbv = std::make_shared<BitCodeAbbrev>();
4048  Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4049  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4050  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4051  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4052  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4053 
4054  // Abbrev for FS_TYPE_ID_METADATA
4055  Abbv = std::make_shared<BitCodeAbbrev>();
4057  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4058  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4059  // n x (valueid , offset)
4061  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4062  unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4063 
4064  SmallVector<uint64_t, 64> NameVals;
4065  // Iterate over the list of functions instead of the Index to
4066  // ensure the ordering is stable.
4067  for (const Function &F : M) {
4068  // Summary emission does not support anonymous functions, they have to
4069  // renamed using the anonymous function renaming pass.
4070  if (!F.hasName())
4071  report_fatal_error("Unexpected anonymous function when writing summary");
4072 
4073  ValueInfo VI = Index->getValueInfo(F.getGUID());
4074  if (!VI || VI.getSummaryList().empty()) {
4075  // Only declarations should not have a summary (a declaration might
4076  // however have a summary if the def was in module level asm).
4077  assert(F.isDeclaration());
4078  continue;
4079  }
4080  auto *Summary = VI.getSummaryList()[0].get();
4081  writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4082  FSCallsAbbrev, FSCallsProfileAbbrev, F);
4083  }
4084 
4085  // Capture references from GlobalVariable initializers, which are outside
4086  // of a function scope.
4087  for (const GlobalVariable &G : M.globals())
4088  writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4089  FSModVTableRefsAbbrev);
4090 
4091  for (const GlobalAlias &A : M.aliases()) {
4092  auto *Aliasee = A.getAliaseeObject();
4093  if (!Aliasee->hasName())
4094  // Nameless function don't have an entry in the summary, skip it.
4095  continue;
4096  auto AliasId = VE.getValueID(&A);
4097  auto AliaseeId = VE.getValueID(Aliasee);
4098  NameVals.push_back(AliasId);
4099  auto *Summary = Index->getGlobalValueSummary(A);
4100  AliasSummary *AS = cast<AliasSummary>(Summary);
4101  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4102  NameVals.push_back(AliaseeId);
4103  Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4104  NameVals.clear();
4105  }
4106 
4107  for (auto &S : Index->typeIdCompatibleVtableMap()) {
4108  writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4109  S.second, VE);
4110  Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4111  TypeIdCompatibleVtableAbbrev);
4112  NameVals.clear();
4113  }
4114 
4115  Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4116  ArrayRef<uint64_t>{Index->getBlockCount()});
4117 
4118  Stream.ExitBlock();
4119 }
4120 
4121 /// Emit the combined summary section into the combined index file.
4122 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4123  Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
4124  Stream.EmitRecord(
4127 
4128  // Write the index flags.
4129  Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4130 
4131  for (const auto &GVI : valueIds()) {
4132  Stream.EmitRecord(bitc::FS_VALUE_GUID,
4133  ArrayRef<uint64_t>{GVI.second, GVI.first});
4134  }
4135 
4136  // Abbrev for FS_COMBINED.
4137  auto Abbv = std::make_shared<BitCodeAbbrev>();
4138  Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
4139  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4140  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4141  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4142  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4143  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4144  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4145  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4146  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4147  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4148  // numrefs x valueid, n x (valueid)
4150  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4151  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4152 
4153  // Abbrev for FS_COMBINED_PROFILE.
4154  Abbv = std::make_shared<BitCodeAbbrev>();
4156  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4157  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4158  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4159  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4160  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4161  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4162  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4163  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4164  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4165  // numrefs x valueid, n x (valueid, hotness)
4167  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4168  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4169 
4170  // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4171  Abbv = std::make_shared<BitCodeAbbrev>();
4173  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4174  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4175  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4176  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4177  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4178  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4179 
4180  // Abbrev for FS_COMBINED_ALIAS.
4181  Abbv = std::make_shared<BitCodeAbbrev>();
4183  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4184  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4185  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4186  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4187  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4188 
4189  // The aliases are emitted as a post-pass, and will point to the value
4190  // id of the aliasee. Save them in a vector for post-processing.
4192 
4193  // Save the value id for each summary for alias emission.
4195 
4196  SmallVector<uint64_t, 64> NameVals;
4197 
4198  // Set that will be populated during call to writeFunctionTypeMetadataRecords
4199  // with the type ids referenced by this index file.
4200  std::set<GlobalValue::GUID> ReferencedTypeIds;
4201 
4202  // For local linkage, we also emit the original name separately
4203  // immediately after the record.
4204  auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4205  // We don't need to emit the original name if we are writing the index for
4206  // distributed backends (in which case ModuleToSummariesForIndex is
4207  // non-null). The original name is only needed during the thin link, since
4208  // for SamplePGO the indirect call targets for local functions have
4209  // have the original name annotated in profile.
4210  // Continue to emit it when writing out the entire combined index, which is
4211  // used in testing the thin link via llvm-lto.
4212  if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4213  return;
4214  NameVals.push_back(S.getOriginalName());
4215  Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4216  NameVals.clear();
4217  };
4218 
4219  std::set<GlobalValue::GUID> DefOrUseGUIDs;
4220  forEachSummary([&](GVInfo I, bool IsAliasee) {
4221  GlobalValueSummary *S = I.second;
4222  assert(S);
4223  DefOrUseGUIDs.insert(I.first);
4224  for (const ValueInfo &VI : S->refs())
4225  DefOrUseGUIDs.insert(VI.getGUID());
4226 
4227  auto ValueId = getValueId(I.first);
4228  assert(ValueId);
4229  SummaryToValueIdMap[S] = *ValueId;
4230 
4231  // If this is invoked for an aliasee, we want to record the above
4232  // mapping, but then not emit a summary entry (if the aliasee is
4233  // to be imported, we will invoke this separately with IsAliasee=false).
4234  if (IsAliasee)
4235  return;
4236 
4237  if (auto *AS = dyn_cast<AliasSummary>(S)) {
4238  // Will process aliases as a post-pass because the reader wants all
4239  // global to be loaded first.
4240  Aliases.push_back(AS);
4241  return;
4242  }
4243 
4244  if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4245  NameVals.push_back(*ValueId);
4246  NameVals.push_back(Index.getModuleId(VS->modulePath()));
4247  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4248  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4249  for (auto &RI : VS->refs()) {
4250  auto RefValueId = getValueId(RI.getGUID());
4251  if (!RefValueId)
4252  continue;
4253  NameVals.push_back(*RefValueId);
4254  }
4255 
4256  // Emit the finished record.
4257  Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4258  FSModRefsAbbrev);
4259  NameVals.clear();
4260  MaybeEmitOriginalName(*S);
4261  return;
4262  }
4263 
4264  auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4265  return getValueId(VI.getGUID());
4266  };
4267 
4268  auto *FS = cast<FunctionSummary>(S);
4269  writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4270  getReferencedTypeIds(FS, ReferencedTypeIds);
4271 
4272  NameVals.push_back(*ValueId);
4273  NameVals.push_back(Index.getModuleId(FS->modulePath()));
4274  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4275  NameVals.push_back(FS->instCount());
4276  NameVals.push_back(getEncodedFFlags(FS->fflags()));
4277  NameVals.push_back(FS->entryCount());
4278 
4279  // Fill in below
4280  NameVals.push_back(0); // numrefs
4281  NameVals.push_back(0); // rorefcnt
4282  NameVals.push_back(0); // worefcnt
4283 
4284  unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4285  for (auto &RI : FS->refs()) {
4286  auto RefValueId = getValueId(RI.getGUID());
4287  if (!RefValueId)
4288  continue;
4289  NameVals.push_back(*RefValueId);
4290  if (RI.isReadOnly())
4291  RORefCnt++;
4292  else if (RI.isWriteOnly())
4293  WORefCnt++;
4294  Count++;
4295  }
4296  NameVals[6] = Count;
4297  NameVals[7] = RORefCnt;
4298  NameVals[8] = WORefCnt;
4299 
4300  bool HasProfileData = false;
4301  for (auto &EI : FS->calls()) {
4302  HasProfileData |=
4303  EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4304  if (HasProfileData)
4305  break;
4306  }
4307 
4308  for (auto &EI : FS->calls()) {
4309  // If this GUID doesn't have a value id, it doesn't have a function
4310  // summary and we don't need to record any calls to it.
4311  Optional<unsigned> CallValueId = GetValueId(EI.first);
4312  if (!CallValueId)
4313  continue;
4314  NameVals.push_back(*CallValueId);
4315  if (HasProfileData)
4316  NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4317  }
4318 
4319  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4320  unsigned Code =
4321  (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4322 
4323  // Emit the finished record.
4324  Stream.EmitRecord(Code, NameVals, FSAbbrev);
4325  NameVals.clear();
4326  MaybeEmitOriginalName(*S);
4327  });
4328 
4329  for (auto *AS : Aliases) {
4330  auto AliasValueId = SummaryToValueIdMap[AS];
4331  assert(AliasValueId);
4332  NameVals.push_back(AliasValueId);
4333  NameVals.push_back(Index.getModuleId(AS->modulePath()));
4334  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4335  auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4336  assert(AliaseeValueId);
4337  NameVals.push_back(AliaseeValueId);
4338 
4339  // Emit the finished record.
4340  Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4341  NameVals.clear();
4342  MaybeEmitOriginalName(*AS);
4343 
4344  if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4345  getReferencedTypeIds(FS, ReferencedTypeIds);
4346  }
4347 
4348  if (!Index.cfiFunctionDefs().empty()) {
4349  for (auto &S : Index.cfiFunctionDefs()) {
4350  if (DefOrUseGUIDs.count(
4352  NameVals.push_back(StrtabBuilder.add(S));
4353  NameVals.push_back(S.size());
4354  }
4355  }
4356  if (!NameVals.empty()) {
4357  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4358  NameVals.clear();
4359  }
4360  }
4361 
4362  if (!Index.cfiFunctionDecls().empty()) {
4363  for (auto &S : Index.cfiFunctionDecls()) {
4364  if (DefOrUseGUIDs.count(
4366  NameVals.push_back(StrtabBuilder.add(S));
4367  NameVals.push_back(S.size());
4368  }
4369  }
4370  if (!NameVals.empty()) {
4371  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4372  NameVals.clear();
4373  }
4374  }
4375 
4376  // Walk the GUIDs that were referenced, and write the
4377  // corresponding type id records.
4378  for (auto &T : ReferencedTypeIds) {
4379  auto TidIter = Index.typeIds().equal_range(T);
4380  for (auto It = TidIter.first; It != TidIter.second; ++It) {
4381  writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4382  It->second.second);
4383  Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4384  NameVals.clear();
4385  }
4386  }
4387 
4388  Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4389  ArrayRef<uint64_t>{Index.getBlockCount()});
4390 
4391  Stream.ExitBlock();
4392 }
4393 
4394 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4395 /// current llvm version, and a record for the epoch number.
4397  Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4398 
4399  // Write the "user readable" string identifying the bitcode producer
4400  auto Abbv = std::make_shared<BitCodeAbbrev>();
4404  auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4406  "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4407 
4408  // Write the epoch version
4409  Abbv = std::make_shared<BitCodeAbbrev>();
4411  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4412  auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4413  constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4414  Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4415  Stream.ExitBlock();
4416 }
4417 
4418 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4419  // Emit the module's hash.
4420  // MODULE_CODE_HASH: [5*i32]
4421  if (GenerateHash) {
4422  uint32_t Vals[5];
4423  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4424  Buffer.size() - BlockStartPos));
4425  std::array<uint8_t, 20> Hash = Hasher.result();
4426  for (int Pos = 0; Pos < 20; Pos += 4) {
4427  Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4428  }
4429 
4430  // Emit the finished record.
4431  Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4432 
4433  if (ModHash)
4434  // Save the written hash value.
4435  llvm::copy(Vals, std::begin(*ModHash));
4436  }
4437 }
4438 
4440  writeIdentificationBlock(Stream);
4441 
4442  Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4443  size_t BlockStartPos = Buffer.size();
4444 
4445  writeModuleVersion();
4446 
4447  // Emit blockinfo, which defines the standard abbreviations etc.
4448  writeBlockInfo();
4449 
4450  // Emit information describing all of the types in the module.
4451  writeTypeTable();
4452 
4453  // Emit information about attribute groups.
4454  writeAttributeGroupTable();
4455 
4456  // Emit information about parameter attributes.
4457  writeAttributeTable();
4458 
4459  writeComdats();
4460 
4461  // Emit top-level description of module, including target triple, inline asm,
4462  // descriptors for global variables, and function prototype info.
4463  writeModuleInfo();
4464 
4465  // Emit constants.
4466  writeModuleConstants();
4467 
4468  // Emit metadata kind names.
4469  writeModuleMetadataKinds();
4470 
4471  // Emit metadata.
4472  writeModuleMetadata();
4473 
4474  // Emit module-level use-lists.
4475  if (VE.shouldPreserveUseListOrder())
4476  writeUseListBlock(nullptr);
4477 
4478  writeOperandBundleTags();
4479  writeSyncScopeNames();
4480 
4481  // Emit function bodies.
4482  DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4483  for (const Function &F : M)
4484  if (!F.isDeclaration())
4485  writeFunction(F, FunctionToBitcodeIndex);
4486 
4487  // Need to write after the above call to WriteFunction which populates
4488  // the summary information in the index.
4489  if (Index)
4490  writePerModuleGlobalValueSummary();
4491 
4492  writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4493 
4494  writeModuleHash(BlockStartPos);
4495 
4496  Stream.ExitBlock();
4497 }
4498 
4500  uint32_t &Position) {
4501  support::endian::write32le(&Buffer[Position], Value);
4502  Position += 4;
4503 }
4504 
4505 /// If generating a bc file on darwin, we have to emit a
4506 /// header and trailer to make it compatible with the system archiver. To do
4507 /// this we emit the following header, and then emit a trailer that pads the
4508 /// file out to be a multiple of 16 bytes.
4509 ///
4510 /// struct bc_header {
4511 /// uint32_t Magic; // 0x0B17C0DE
4512 /// uint32_t Version; // Version, currently always 0.
4513 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4514 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4515 /// uint32_t CPUType; // CPU specifier.
4516 /// ... potentially more later ...
4517 /// };
4519  const Triple &TT) {
4520  unsigned CPUType = ~0U;
4521 
4522  // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4523  // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4524  // number from /usr/include/mach/machine.h. It is ok to reproduce the
4525  // specific constants here because they are implicitly part of the Darwin ABI.
4526  enum {
4527  DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4528  DARWIN_CPU_TYPE_X86 = 7,
4529  DARWIN_CPU_TYPE_ARM = 12,
4530  DARWIN_CPU_TYPE_POWERPC = 18
4531  };
4532 
4533  Triple::ArchType Arch = TT.getArch();
4534  if (Arch == Triple::x86_64)
4535  CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4536  else if (Arch == Triple::x86)
4537  CPUType = DARWIN_CPU_TYPE_X86;
4538  else if (Arch == Triple::ppc)
4539  CPUType = DARWIN_CPU_TYPE_POWERPC;
4540  else if (Arch == Triple::ppc64)
4541  CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4542  else if (Arch == Triple::arm || Arch == Triple::thumb)
4543  CPUType = DARWIN_CPU_TYPE_ARM;
4544 
4545  // Traditional Bitcode starts after header.
4546  assert(Buffer.size() >= BWH_HeaderSize &&
4547  "Expected header size to be reserved");
4548  unsigned BCOffset = BWH_HeaderSize;
4549  unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4550 
4551  // Write the magic and version.
4552  unsigned Position = 0;
4553  writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4554  writeInt32ToBuffer(0, Buffer, Position); // Version.
4555  writeInt32ToBuffer(BCOffset, Buffer, Position);
4556  writeInt32ToBuffer(BCSize, Buffer, Position);
4557  writeInt32ToBuffer(CPUType, Buffer, Position);
4558 
4559  // If the file is not a multiple of 16 bytes, insert dummy padding.
4560  while (Buffer.size() & 15)
4561  Buffer.push_back(0);
4562 }
4563 
4564 /// Helper to write the header common to all bitcode files.
4565 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4566  // Emit the file header.
4567  Stream.Emit((unsigned)'B', 8);
4568  Stream.Emit((unsigned)'C', 8);
4569  Stream.Emit(0x0, 4);
4570  Stream.Emit(0xC, 4);
4571  Stream.Emit(0xE, 4);
4572  Stream.Emit(0xD, 4);
4573 }
4574 
4576  : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
4577  writeBitcodeHeader(*Stream);
4578 }
4579 
4581 
4582 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4583  Stream->EnterSubblock(Block, 3);
4584 
4585  auto Abbv = std::make_shared<BitCodeAbbrev>();
4586  Abbv->Add(BitCodeAbbrevOp(Record));
4588  auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4589 
4590  Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4591 
4592  Stream->ExitBlock();
4593 }
4594 
4596  assert(!WroteStrtab && !WroteSymtab);
4597 
4598  // If any module has module-level inline asm, we will require a registered asm
4599  // parser for the target so that we can create an accurate symbol table for
4600  // the module.
4601  for (Module *M : Mods) {
4602  if (M->getModuleInlineAsm().empty())
4603  continue;
4604 
4605  std::string Err;
4606  const Triple TT(M->getTargetTriple());
4607  const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4608  if (!T || !T->hasMCAsmParser())
4609  return;
4610  }
4611 
4612  WroteSymtab = true;
4613  SmallVector<char, 0> Symtab;
4614  // The irsymtab::build function may be unable to create a symbol table if the
4615  // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4616  // table is not required for correctness, but we still want to be able to
4617  // write malformed modules to bitcode files, so swallow the error.
4618  if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4620  return;
4621  }
4622 
4624  {Symtab.data(), Symtab.size()});
4625 }
4626 
4628  assert(!WroteStrtab);
4629 
4630  std::vector<char> Strtab;
4631  StrtabBuilder.finalizeInOrder();
4632  Strtab.resize(StrtabBuilder.getSize());
4633  StrtabBuilder.write((uint8_t *)Strtab.data());
4634 
4636  {Strtab.data(), Strtab.size()});
4637 
4638  WroteStrtab = true;
4639 }
4640 
4642  writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4643  WroteStrtab = true;
4644 }
4645 
4647  bool ShouldPreserveUseListOrder,
4648  const ModuleSummaryIndex *Index,
4649  bool GenerateHash, ModuleHash *ModHash) {
4650  assert(!WroteStrtab);
4651 
4652  // The Mods vector is used by irsymtab::build, which requires non-const
4653  // Modules in case it needs to materialize metadata. But the bitcode writer
4654  // requires that the module is materialized, so we can cast to non-const here,
4655  // after checking that it is in fact materialized.
4656  assert(M.isMaterialized());
4657  Mods.push_back(const_cast<Module *>(&M));
4658 
4659  ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4660  ShouldPreserveUseListOrder, Index,
4661  GenerateHash, ModHash);
4662  ModuleWriter.write();
4663 }
4664 
4666  const ModuleSummaryIndex *Index,
4667  const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4668  IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4669  ModuleToSummariesForIndex);
4670  IndexWriter.write();
4671 }
4672 
4673 /// Write the specified module to the specified output stream.
4675  bool ShouldPreserveUseListOrder,
4676  const ModuleSummaryIndex *Index,
4677  bool GenerateHash, ModuleHash *ModHash) {
4678  SmallVector<char, 0> Buffer;
4679  Buffer.reserve(256*1024);
4680 
4681  // If this is darwin or another generic macho target, reserve space for the
4682  // header.
4683  Triple TT(M.getTargetTriple());
4684  if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4685  Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4686 
4687