LLVM  9.0.0svn
BitcodeWriter.cpp
Go to the documentation of this file.
1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Bitcode writer implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "ValueEnumerator.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Bitcode/BitCodes.h"
31 #include "llvm/Config/llvm-config.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalObject.h"
45 #include "llvm/IR/GlobalValue.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/Instruction.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
55 #include "llvm/IR/Operator.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/UseListOrder.h"
58 #include "llvm/IR/Value.h"
61 #include "llvm/Object/IRSymtab.h"
63 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/Endian.h"
66 #include "llvm/Support/Error.h"
69 #include "llvm/Support/SHA1.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstddef>
75 #include <cstdint>
76 #include <iterator>
77 #include <map>
78 #include <memory>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 static cl::opt<unsigned>
86  IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
87  cl::desc("Number of metadatas above which we emit an index "
88  "to enable lazy-loading"));
89 
91  "write-relbf-to-summary", cl::Hidden, cl::init(false),
92  cl::desc("Write relative block frequency to function summary "));
93 
95 
96 namespace {
97 
98 /// These are manifest constants used by the bitcode writer. They do not need to
99 /// be kept in sync with the reader, but need to be consistent within this file.
100 enum {
101  // VALUE_SYMTAB_BLOCK abbrev id's.
102  VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
103  VST_ENTRY_7_ABBREV,
104  VST_ENTRY_6_ABBREV,
105  VST_BBENTRY_6_ABBREV,
106 
107  // CONSTANTS_BLOCK abbrev id's.
108  CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
109  CONSTANTS_INTEGER_ABBREV,
110  CONSTANTS_CE_CAST_Abbrev,
111  CONSTANTS_NULL_Abbrev,
112 
113  // FUNCTION_BLOCK abbrev id's.
114  FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
115  FUNCTION_INST_UNOP_ABBREV,
116  FUNCTION_INST_UNOP_FLAGS_ABBREV,
117  FUNCTION_INST_BINOP_ABBREV,
118  FUNCTION_INST_BINOP_FLAGS_ABBREV,
119  FUNCTION_INST_CAST_ABBREV,
120  FUNCTION_INST_RET_VOID_ABBREV,
121  FUNCTION_INST_RET_VAL_ABBREV,
122  FUNCTION_INST_UNREACHABLE_ABBREV,
123  FUNCTION_INST_GEP_ABBREV,
124 };
125 
126 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
127 /// file type.
128 class BitcodeWriterBase {
129 protected:
130  /// The stream created and owned by the client.
131  BitstreamWriter &Stream;
132 
133  StringTableBuilder &StrtabBuilder;
134 
135 public:
136  /// Constructs a BitcodeWriterBase object that writes to the provided
137  /// \p Stream.
138  BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
139  : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
140 
141 protected:
142  void writeBitcodeHeader();
143  void writeModuleVersion();
144 };
145 
146 void BitcodeWriterBase::writeModuleVersion() {
147  // VERSION: [version#]
148  Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
149 }
150 
151 /// Base class to manage the module bitcode writing, currently subclassed for
152 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
153 class ModuleBitcodeWriterBase : public BitcodeWriterBase {
154 protected:
155  /// The Module to write to bitcode.
156  const Module &M;
157 
158  /// Enumerates ids for all values in the module.
159  ValueEnumerator VE;
160 
161  /// Optional per-module index to write for ThinLTO.
162  const ModuleSummaryIndex *Index;
163 
164  /// Map that holds the correspondence between GUIDs in the summary index,
165  /// that came from indirect call profiles, and a value id generated by this
166  /// class to use in the VST and summary block records.
167  std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
168 
169  /// Tracks the last value id recorded in the GUIDToValueMap.
170  unsigned GlobalValueId;
171 
172  /// Saves the offset of the VSTOffset record that must eventually be
173  /// backpatched with the offset of the actual VST.
174  uint64_t VSTOffsetPlaceholder = 0;
175 
176 public:
177  /// Constructs a ModuleBitcodeWriterBase object for the given Module,
178  /// writing to the provided \p Buffer.
179  ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
180  BitstreamWriter &Stream,
181  bool ShouldPreserveUseListOrder,
182  const ModuleSummaryIndex *Index)
183  : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
184  VE(M, ShouldPreserveUseListOrder), Index(Index) {
185  // Assign ValueIds to any callee values in the index that came from
186  // indirect call profiles and were recorded as a GUID not a Value*
187  // (which would have been assigned an ID by the ValueEnumerator).
188  // The starting ValueId is just after the number of values in the
189  // ValueEnumerator, so that they can be emitted in the VST.
190  GlobalValueId = VE.getValues().size();
191  if (!Index)
192  return;
193  for (const auto &GUIDSummaryLists : *Index)
194  // Examine all summaries for this GUID.
195  for (auto &Summary : GUIDSummaryLists.second.SummaryList)
196  if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
197  // For each call in the function summary, see if the call
198  // is to a GUID (which means it is for an indirect call,
199  // otherwise we would have a Value for it). If so, synthesize
200  // a value id.
201  for (auto &CallEdge : FS->calls())
202  if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
203  assignValueId(CallEdge.first.getGUID());
204  }
205 
206 protected:
207  void writePerModuleGlobalValueSummary();
208 
209 private:
210  void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
211  GlobalValueSummary *Summary,
212  unsigned ValueID,
213  unsigned FSCallsAbbrev,
214  unsigned FSCallsProfileAbbrev,
215  const Function &F);
216  void writeModuleLevelReferences(const GlobalVariable &V,
217  SmallVector<uint64_t, 64> &NameVals,
218  unsigned FSModRefsAbbrev);
219 
220  void assignValueId(GlobalValue::GUID ValGUID) {
221  GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
222  }
223 
224  unsigned getValueId(GlobalValue::GUID ValGUID) {
225  const auto &VMI = GUIDToValueIdMap.find(ValGUID);
226  // Expect that any GUID value had a value Id assigned by an
227  // earlier call to assignValueId.
228  assert(VMI != GUIDToValueIdMap.end() &&
229  "GUID does not have assigned value Id");
230  return VMI->second;
231  }
232 
233  // Helper to get the valueId for the type of value recorded in VI.
234  unsigned getValueId(ValueInfo VI) {
235  if (!VI.haveGVs() || !VI.getValue())
236  return getValueId(VI.getGUID());
237  return VE.getValueID(VI.getValue());
238  }
239 
240  std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
241 };
242 
243 /// Class to manage the bitcode writing for a module.
244 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
245  /// Pointer to the buffer allocated by caller for bitcode writing.
246  const SmallVectorImpl<char> &Buffer;
247 
248  /// True if a module hash record should be written.
249  bool GenerateHash;
250 
251  /// If non-null, when GenerateHash is true, the resulting hash is written
252  /// into ModHash.
253  ModuleHash *ModHash;
254 
255  SHA1 Hasher;
256 
257  /// The start bit of the identification block.
258  uint64_t BitcodeStartBit;
259 
260 public:
261  /// Constructs a ModuleBitcodeWriter object for the given Module,
262  /// writing to the provided \p Buffer.
263  ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
264  StringTableBuilder &StrtabBuilder,
265  BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
266  const ModuleSummaryIndex *Index, bool GenerateHash,
267  ModuleHash *ModHash = nullptr)
268  : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
269  ShouldPreserveUseListOrder, Index),
270  Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
271  BitcodeStartBit(Stream.GetCurrentBitNo()) {}
272 
273  /// Emit the current module to the bitstream.
274  void write();
275 
276 private:
277  uint64_t bitcodeStartBit() { return BitcodeStartBit; }
278 
279  size_t addToStrtab(StringRef Str);
280 
281  void writeAttributeGroupTable();
282  void writeAttributeTable();
283  void writeTypeTable();
284  void writeComdats();
285  void writeValueSymbolTableForwardDecl();
286  void writeModuleInfo();
287  void writeValueAsMetadata(const ValueAsMetadata *MD,
290  unsigned Abbrev);
291  unsigned createDILocationAbbrev();
293  unsigned &Abbrev);
294  unsigned createGenericDINodeAbbrev();
295  void writeGenericDINode(const GenericDINode *N,
296  SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
298  unsigned Abbrev);
299  void writeDIEnumerator(const DIEnumerator *N,
300  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
302  unsigned Abbrev);
303  void writeDIDerivedType(const DIDerivedType *N,
304  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
306  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
309  unsigned Abbrev);
311  unsigned Abbrev);
312  void writeDICompileUnit(const DICompileUnit *N,
313  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
314  void writeDISubprogram(const DISubprogram *N,
315  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
317  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
320  unsigned Abbrev);
322  unsigned Abbrev);
324  unsigned Abbrev);
326  unsigned Abbrev);
328  unsigned Abbrev);
331  unsigned Abbrev);
334  unsigned Abbrev);
337  unsigned Abbrev);
339  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
340  void writeDILabel(const DILabel *N,
341  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
342  void writeDIExpression(const DIExpression *N,
343  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
346  unsigned Abbrev);
348  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
351  unsigned Abbrev);
352  unsigned createNamedMetadataAbbrev();
353  void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
354  unsigned createMetadataStringsAbbrev();
355  void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
357  void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
359  std::vector<unsigned> *MDAbbrevs = nullptr,
360  std::vector<uint64_t> *IndexPos = nullptr);
361  void writeModuleMetadata();
362  void writeFunctionMetadata(const Function &F);
363  void writeFunctionMetadataAttachment(const Function &F);
364  void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
365  void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
366  const GlobalObject &GO);
367  void writeModuleMetadataKinds();
368  void writeOperandBundleTags();
369  void writeSyncScopeNames();
370  void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
371  void writeModuleConstants();
372  bool pushValueAndType(const Value *V, unsigned InstID,
374  void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
375  void pushValue(const Value *V, unsigned InstID,
377  void pushValueSigned(const Value *V, unsigned InstID,
379  void writeInstruction(const Instruction &I, unsigned InstID,
381  void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
382  void writeGlobalValueSymbolTable(
383  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
384  void writeUseList(UseListOrder &&Order);
385  void writeUseListBlock(const Function *F);
386  void
387  writeFunction(const Function &F,
388  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
389  void writeBlockInfo();
390  void writeModuleHash(size_t BlockStartPos);
391 
392  unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
393  return unsigned(SSID);
394  }
395 };
396 
397 /// Class to manage the bitcode writing for a combined index.
398 class IndexBitcodeWriter : public BitcodeWriterBase {
399  /// The combined index to write to bitcode.
400  const ModuleSummaryIndex &Index;
401 
402  /// When writing a subset of the index for distributed backends, client
403  /// provides a map of modules to the corresponding GUIDs/summaries to write.
404  const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
405 
406  /// Map that holds the correspondence between the GUID used in the combined
407  /// index and a value id generated by this class to use in references.
408  std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
409 
410  /// Tracks the last value id recorded in the GUIDToValueMap.
411  unsigned GlobalValueId = 0;
412 
413 public:
414  /// Constructs a IndexBitcodeWriter object for the given combined index,
415  /// writing to the provided \p Buffer. When writing a subset of the index
416  /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
417  IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
418  const ModuleSummaryIndex &Index,
419  const std::map<std::string, GVSummaryMapTy>
420  *ModuleToSummariesForIndex = nullptr)
421  : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
422  ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
423  // Assign unique value ids to all summaries to be written, for use
424  // in writing out the call graph edges. Save the mapping from GUID
425  // to the new global value id to use when writing those edges, which
426  // are currently saved in the index in terms of GUID.
427  forEachSummary([&](GVInfo I, bool) {
428  GUIDToValueIdMap[I.first] = ++GlobalValueId;
429  });
430  }
431 
432  /// The below iterator returns the GUID and associated summary.
433  using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
434 
435  /// Calls the callback for each value GUID and summary to be written to
436  /// bitcode. This hides the details of whether they are being pulled from the
437  /// entire index or just those in a provided ModuleToSummariesForIndex map.
438  template<typename Functor>
439  void forEachSummary(Functor Callback) {
440  if (ModuleToSummariesForIndex) {
441  for (auto &M : *ModuleToSummariesForIndex)
442  for (auto &Summary : M.second) {
443  Callback(Summary, false);
444  // Ensure aliasee is handled, e.g. for assigning a valueId,
445  // even if we are not importing the aliasee directly (the
446  // imported alias will contain a copy of aliasee).
447  if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
448  Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
449  }
450  } else {
451  for (auto &Summaries : Index)
452  for (auto &Summary : Summaries.second.SummaryList)
453  Callback({Summaries.first, Summary.get()}, false);
454  }
455  }
456 
457  /// Calls the callback for each entry in the modulePaths StringMap that
458  /// should be written to the module path string table. This hides the details
459  /// of whether they are being pulled from the entire index or just those in a
460  /// provided ModuleToSummariesForIndex map.
461  template <typename Functor> void forEachModule(Functor Callback) {
462  if (ModuleToSummariesForIndex) {
463  for (const auto &M : *ModuleToSummariesForIndex) {
464  const auto &MPI = Index.modulePaths().find(M.first);
465  if (MPI == Index.modulePaths().end()) {
466  // This should only happen if the bitcode file was empty, in which
467  // case we shouldn't be importing (the ModuleToSummariesForIndex
468  // would only include the module we are writing and index for).
469  assert(ModuleToSummariesForIndex->size() == 1);
470  continue;
471  }
472  Callback(*MPI);
473  }
474  } else {
475  for (const auto &MPSE : Index.modulePaths())
476  Callback(MPSE);
477  }
478  }
479 
480  /// Main entry point for writing a combined index to bitcode.
481  void write();
482 
483 private:
484  void writeModStrings();
485  void writeCombinedGlobalValueSummary();
486 
487  Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
488  auto VMI = GUIDToValueIdMap.find(ValGUID);
489  if (VMI == GUIDToValueIdMap.end())
490  return None;
491  return VMI->second;
492  }
493 
494  std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
495 };
496 
497 } // end anonymous namespace
498 
499 static unsigned getEncodedCastOpcode(unsigned Opcode) {
500  switch (Opcode) {
501  default: llvm_unreachable("Unknown cast instruction!");
502  case Instruction::Trunc : return bitc::CAST_TRUNC;
503  case Instruction::ZExt : return bitc::CAST_ZEXT;
504  case Instruction::SExt : return bitc::CAST_SEXT;
505  case Instruction::FPToUI : return bitc::CAST_FPTOUI;
506  case Instruction::FPToSI : return bitc::CAST_FPTOSI;
507  case Instruction::UIToFP : return bitc::CAST_UITOFP;
508  case Instruction::SIToFP : return bitc::CAST_SITOFP;
509  case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
510  case Instruction::FPExt : return bitc::CAST_FPEXT;
511  case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
512  case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
513  case Instruction::BitCast : return bitc::CAST_BITCAST;
514  case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
515  }
516 }
517 
518 static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
519  switch (Opcode) {
520  default: llvm_unreachable("Unknown binary instruction!");
521  case Instruction::FNeg: return bitc::UNOP_NEG;
522  }
523 }
524 
525 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
526  switch (Opcode) {
527  default: llvm_unreachable("Unknown binary instruction!");
528  case Instruction::Add:
529  case Instruction::FAdd: return bitc::BINOP_ADD;
530  case Instruction::Sub:
531  case Instruction::FSub: return bitc::BINOP_SUB;
532  case Instruction::Mul:
533  case Instruction::FMul: return bitc::BINOP_MUL;
534  case Instruction::UDiv: return bitc::BINOP_UDIV;
535  case Instruction::FDiv:
536  case Instruction::SDiv: return bitc::BINOP_SDIV;
537  case Instruction::URem: return bitc::BINOP_UREM;
538  case Instruction::FRem:
539  case Instruction::SRem: return bitc::BINOP_SREM;
540  case Instruction::Shl: return bitc::BINOP_SHL;
541  case Instruction::LShr: return bitc::BINOP_LSHR;
542  case Instruction::AShr: return bitc::BINOP_ASHR;
543  case Instruction::And: return bitc::BINOP_AND;
544  case Instruction::Or: return bitc::BINOP_OR;
545  case Instruction::Xor: return bitc::BINOP_XOR;
546  }
547 }
548 
550  switch (Op) {
551  default: llvm_unreachable("Unknown RMW operation!");
552  case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
553  case AtomicRMWInst::Add: return bitc::RMW_ADD;
554  case AtomicRMWInst::Sub: return bitc::RMW_SUB;
555  case AtomicRMWInst::And: return bitc::RMW_AND;
556  case AtomicRMWInst::Nand: return bitc::RMW_NAND;
557  case AtomicRMWInst::Or: return bitc::RMW_OR;
558  case AtomicRMWInst::Xor: return bitc::RMW_XOR;
559  case AtomicRMWInst::Max: return bitc::RMW_MAX;
560  case AtomicRMWInst::Min: return bitc::RMW_MIN;
561  case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
562  case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
563  }
564 }
565 
566 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
567  switch (Ordering) {
575  }
576  llvm_unreachable("Invalid ordering");
577 }
578 
579 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
580  StringRef Str, unsigned AbbrevToUse) {
582 
583  // Code: [strchar x N]
584  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
585  if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
586  AbbrevToUse = 0;
587  Vals.push_back(Str[i]);
588  }
589 
590  // Emit the finished record.
591  Stream.EmitRecord(Code, Vals, AbbrevToUse);
592 }
593 
595  switch (Kind) {
596  case Attribute::Alignment:
598  case Attribute::AllocSize:
600  case Attribute::AlwaysInline:
602  case Attribute::ArgMemOnly:
604  case Attribute::Builtin:
606  case Attribute::ByVal:
607  return bitc::ATTR_KIND_BY_VAL;
610  case Attribute::InAlloca:
612  case Attribute::Cold:
613  return bitc::ATTR_KIND_COLD;
614  case Attribute::InaccessibleMemOnly:
616  case Attribute::InaccessibleMemOrArgMemOnly:
618  case Attribute::InlineHint:
620  case Attribute::InReg:
621  return bitc::ATTR_KIND_IN_REG;
624  case Attribute::MinSize:
626  case Attribute::Naked:
627  return bitc::ATTR_KIND_NAKED;
628  case Attribute::Nest:
629  return bitc::ATTR_KIND_NEST;
630  case Attribute::NoAlias:
632  case Attribute::NoBuiltin:
634  case Attribute::NoCapture:
636  case Attribute::NoDuplicate:
638  case Attribute::NoImplicitFloat:
640  case Attribute::NoInline:
642  case Attribute::NoRecurse:
644  case Attribute::NonLazyBind:
646  case Attribute::NonNull:
648  case Attribute::Dereferenceable:
650  case Attribute::DereferenceableOrNull:
652  case Attribute::NoRedZone:
654  case Attribute::NoReturn:
656  case Attribute::NoCfCheck:
658  case Attribute::NoUnwind:
660  case Attribute::OptForFuzzing:
662  case Attribute::OptimizeForSize:
664  case Attribute::OptimizeNone:
666  case Attribute::ReadNone:
668  case Attribute::ReadOnly:
670  case Attribute::Returned:
672  case Attribute::ReturnsTwice:
674  case Attribute::SExt:
675  return bitc::ATTR_KIND_S_EXT;
676  case Attribute::Speculatable:
678  case Attribute::StackAlignment:
680  case Attribute::StackProtect:
682  case Attribute::StackProtectReq:
684  case Attribute::StackProtectStrong:
686  case Attribute::SafeStack:
688  case Attribute::ShadowCallStack:
690  case Attribute::StrictFP:
692  case Attribute::StructRet:
694  case Attribute::SanitizeAddress:
696  case Attribute::SanitizeHWAddress:
698  case Attribute::SanitizeThread:
700  case Attribute::SanitizeMemory:
702  case Attribute::SpeculativeLoadHardening:
704  case Attribute::SwiftError:
706  case Attribute::SwiftSelf:
708  case Attribute::UWTable:
710  case Attribute::WriteOnly:
712  case Attribute::ZExt:
713  return bitc::ATTR_KIND_Z_EXT;
715  llvm_unreachable("Can not encode end-attribute kinds marker.");
716  case Attribute::None:
717  llvm_unreachable("Can not encode none-attribute.");
718  }
719 
720  llvm_unreachable("Trying to encode unknown attribute");
721 }
722 
723 void ModuleBitcodeWriter::writeAttributeGroupTable() {
724  const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
725  VE.getAttributeGroups();
726  if (AttrGrps.empty()) return;
727 
729 
731  for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
732  unsigned AttrListIndex = Pair.first;
733  AttributeSet AS = Pair.second;
734  Record.push_back(VE.getAttributeGroupID(Pair));
735  Record.push_back(AttrListIndex);
736 
737  for (Attribute Attr : AS) {
738  if (Attr.isEnumAttribute()) {
739  Record.push_back(0);
740  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
741  } else if (Attr.isIntAttribute()) {
742  Record.push_back(1);
743  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
744  Record.push_back(Attr.getValueAsInt());
745  } else {
746  StringRef Kind = Attr.getKindAsString();
747  StringRef Val = Attr.getValueAsString();
748 
749  Record.push_back(Val.empty() ? 3 : 4);
750  Record.append(Kind.begin(), Kind.end());
751  Record.push_back(0);
752  if (!Val.empty()) {
753  Record.append(Val.begin(), Val.end());
754  Record.push_back(0);
755  }
756  }
757  }
758 
760  Record.clear();
761  }
762 
763  Stream.ExitBlock();
764 }
765 
766 void ModuleBitcodeWriter::writeAttributeTable() {
767  const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
768  if (Attrs.empty()) return;
769 
771 
773  for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
774  AttributeList AL = Attrs[i];
775  for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
776  AttributeSet AS = AL.getAttributes(i);
777  if (AS.hasAttributes())
778  Record.push_back(VE.getAttributeGroupID({i, AS}));
779  }
780 
781  Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
782  Record.clear();
783  }
784 
785  Stream.ExitBlock();
786 }
787 
788 /// WriteTypeTable - Write out the type table for a module.
789 void ModuleBitcodeWriter::writeTypeTable() {
790  const ValueEnumerator::TypeList &TypeList = VE.getTypes();
791 
792  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
793  SmallVector<uint64_t, 64> TypeVals;
794 
795  uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
796 
797  // Abbrev for TYPE_CODE_POINTER.
798  auto Abbv = std::make_shared<BitCodeAbbrev>();
800  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
801  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
802  unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
803 
804  // Abbrev for TYPE_CODE_FUNCTION.
805  Abbv = std::make_shared<BitCodeAbbrev>();
807  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
809  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
810  unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
811 
812  // Abbrev for TYPE_CODE_STRUCT_ANON.
813  Abbv = std::make_shared<BitCodeAbbrev>();
815  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
817  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
818  unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
819 
820  // Abbrev for TYPE_CODE_STRUCT_NAME.
821  Abbv = std::make_shared<BitCodeAbbrev>();
825  unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
826 
827  // Abbrev for TYPE_CODE_STRUCT_NAMED.
828  Abbv = std::make_shared<BitCodeAbbrev>();
830  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
832  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
833  unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
834 
835  // Abbrev for TYPE_CODE_ARRAY.
836  Abbv = std::make_shared<BitCodeAbbrev>();
838  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
839  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
840  unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
841 
842  // Emit an entry count so the reader can reserve space.
843  TypeVals.push_back(TypeList.size());
844  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
845  TypeVals.clear();
846 
847  // Loop over all of the types, emitting each in turn.
848  for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
849  Type *T = TypeList[i];
850  int AbbrevToUse = 0;
851  unsigned Code = 0;
852 
853  switch (T->getTypeID()) {
854  case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
855  case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
856  case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
857  case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
858  case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
859  case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
861  case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
862  case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
863  case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
864  case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
865  case Type::IntegerTyID:
866  // INTEGER: [width]
868  TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
869  break;
870  case Type::PointerTyID: {
871  PointerType *PTy = cast<PointerType>(T);
872  // POINTER: [pointee type, address space]
874  TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
875  unsigned AddressSpace = PTy->getAddressSpace();
876  TypeVals.push_back(AddressSpace);
877  if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
878  break;
879  }
880  case Type::FunctionTyID: {
881  FunctionType *FT = cast<FunctionType>(T);
882  // FUNCTION: [isvararg, retty, paramty x N]
884  TypeVals.push_back(FT->isVarArg());
885  TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
886  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
887  TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
888  AbbrevToUse = FunctionAbbrev;
889  break;
890  }
891  case Type::StructTyID: {
892  StructType *ST = cast<StructType>(T);
893  // STRUCT: [ispacked, eltty x N]
894  TypeVals.push_back(ST->isPacked());
895  // Output all of the element types.
897  E = ST->element_end(); I != E; ++I)
898  TypeVals.push_back(VE.getTypeID(*I));
899 
900  if (ST->isLiteral()) {
902  AbbrevToUse = StructAnonAbbrev;
903  } else {
904  if (ST->isOpaque()) {
905  Code = bitc::TYPE_CODE_OPAQUE;
906  } else {
908  AbbrevToUse = StructNamedAbbrev;
909  }
910 
911  // Emit the name if it is present.
912  if (!ST->getName().empty())
914  StructNameAbbrev);
915  }
916  break;
917  }
918  case Type::ArrayTyID: {
919  ArrayType *AT = cast<ArrayType>(T);
920  // ARRAY: [numelts, eltty]
921  Code = bitc::TYPE_CODE_ARRAY;
922  TypeVals.push_back(AT->getNumElements());
923  TypeVals.push_back(VE.getTypeID(AT->getElementType()));
924  AbbrevToUse = ArrayAbbrev;
925  break;
926  }
927  case Type::VectorTyID: {
928  VectorType *VT = cast<VectorType>(T);
929  // VECTOR [numelts, eltty]
930  Code = bitc::TYPE_CODE_VECTOR;
931  TypeVals.push_back(VT->getNumElements());
932  TypeVals.push_back(VE.getTypeID(VT->getElementType()));
933  break;
934  }
935  }
936 
937  // Emit the finished record.
938  Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
939  TypeVals.clear();
940  }
941 
942  Stream.ExitBlock();
943 }
944 
945 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
946  switch (Linkage) {
948  return 0;
950  return 16;
952  return 2;
954  return 3;
956  return 18;
958  return 7;
960  return 8;
962  return 9;
964  return 17;
966  return 19;
968  return 12;
969  }
970  llvm_unreachable("Invalid linkage");
971 }
972 
973 static unsigned getEncodedLinkage(const GlobalValue &GV) {
974  return getEncodedLinkage(GV.getLinkage());
975 }
976 
978  uint64_t RawFlags = 0;
979  RawFlags |= Flags.ReadNone;
980  RawFlags |= (Flags.ReadOnly << 1);
981  RawFlags |= (Flags.NoRecurse << 2);
982  RawFlags |= (Flags.ReturnDoesNotAlias << 3);
983  RawFlags |= (Flags.NoInline << 4);
984  return RawFlags;
985 }
986 
987 // Decode the flags for GlobalValue in the summary
989  uint64_t RawFlags = 0;
990 
991  RawFlags |= Flags.NotEligibleToImport; // bool
992  RawFlags |= (Flags.Live << 1);
993  RawFlags |= (Flags.DSOLocal << 2);
994 
995  // Linkage don't need to be remapped at that time for the summary. Any future
996  // change to the getEncodedLinkage() function will need to be taken into
997  // account here as well.
998  RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
999 
1000  return RawFlags;
1001 }
1002 
1004  uint64_t RawFlags = Flags.ReadOnly;
1005  return RawFlags;
1006 }
1007 
1008 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1009  switch (GV.getVisibility()) {
1010  case GlobalValue::DefaultVisibility: return 0;
1011  case GlobalValue::HiddenVisibility: return 1;
1012  case GlobalValue::ProtectedVisibility: return 2;
1013  }
1014  llvm_unreachable("Invalid visibility");
1015 }
1016 
1017 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1018  switch (GV.getDLLStorageClass()) {
1019  case GlobalValue::DefaultStorageClass: return 0;
1020  case GlobalValue::DLLImportStorageClass: return 1;
1021  case GlobalValue::DLLExportStorageClass: return 2;
1022  }
1023  llvm_unreachable("Invalid DLL storage class");
1024 }
1025 
1026 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1027  switch (GV.getThreadLocalMode()) {
1028  case GlobalVariable::NotThreadLocal: return 0;
1030  case GlobalVariable::LocalDynamicTLSModel: return 2;
1031  case GlobalVariable::InitialExecTLSModel: return 3;
1032  case GlobalVariable::LocalExecTLSModel: return 4;
1033  }
1034  llvm_unreachable("Invalid TLS model");
1035 }
1036 
1037 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1038  switch (C.getSelectionKind()) {
1039  case Comdat::Any:
1041  case Comdat::ExactMatch:
1043  case Comdat::Largest:
1045  case Comdat::NoDuplicates:
1047  case Comdat::SameSize:
1049  }
1050  llvm_unreachable("Invalid selection kind");
1051 }
1052 
1053 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1054  switch (GV.getUnnamedAddr()) {
1055  case GlobalValue::UnnamedAddr::None: return 0;
1056  case GlobalValue::UnnamedAddr::Local: return 2;
1057  case GlobalValue::UnnamedAddr::Global: return 1;
1058  }
1059  llvm_unreachable("Invalid unnamed_addr");
1060 }
1061 
1062 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1063  if (GenerateHash)
1064  Hasher.update(Str);
1065  return StrtabBuilder.add(Str);
1066 }
1067 
1068 void ModuleBitcodeWriter::writeComdats() {
1070  for (const Comdat *C : VE.getComdats()) {
1071  // COMDAT: [strtab offset, strtab size, selection_kind]
1072  Vals.push_back(addToStrtab(C->getName()));
1073  Vals.push_back(C->getName().size());
1075  Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1076  Vals.clear();
1077  }
1078 }
1079 
1080 /// Write a record that will eventually hold the word offset of the
1081 /// module-level VST. For now the offset is 0, which will be backpatched
1082 /// after the real VST is written. Saves the bit offset to backpatch.
1083 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1084  // Write a placeholder value in for the offset of the real VST,
1085  // which is written after the function blocks so that it can include
1086  // the offset of each function. The placeholder offset will be
1087  // updated when the real VST is written.
1088  auto Abbv = std::make_shared<BitCodeAbbrev>();
1090  // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1091  // hold the real VST offset. Must use fixed instead of VBR as we don't
1092  // know how many VBR chunks to reserve ahead of time.
1093  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1094  unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1095 
1096  // Emit the placeholder
1097  uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1098  Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1099 
1100  // Compute and save the bit offset to the placeholder, which will be
1101  // patched when the real VST is written. We can simply subtract the 32-bit
1102  // fixed size from the current bit number to get the location to backpatch.
1103  VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1104 }
1105 
1107 
1108 /// Determine the encoding to use for the given string name and length.
1110  bool isChar6 = true;
1111  for (char C : Str) {
1112  if (isChar6)
1113  isChar6 = BitCodeAbbrevOp::isChar6(C);
1114  if ((unsigned char)C & 128)
1115  // don't bother scanning the rest.
1116  return SE_Fixed8;
1117  }
1118  if (isChar6)
1119  return SE_Char6;
1120  return SE_Fixed7;
1121 }
1122 
1123 /// Emit top-level description of module, including target triple, inline asm,
1124 /// descriptors for global variables, and function prototype info.
1125 /// Returns the bit offset to backpatch with the location of the real VST.
1126 void ModuleBitcodeWriter::writeModuleInfo() {
1127  // Emit various pieces of data attached to a module.
1128  if (!M.getTargetTriple().empty())
1130  0 /*TODO*/);
1131  const std::string &DL = M.getDataLayoutStr();
1132  if (!DL.empty())
1133  writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1134  if (!M.getModuleInlineAsm().empty())
1136  0 /*TODO*/);
1137 
1138  // Emit information about sections and GC, computing how many there are. Also
1139  // compute the maximum alignment value.
1140  std::map<std::string, unsigned> SectionMap;
1141  std::map<std::string, unsigned> GCMap;
1142  unsigned MaxAlignment = 0;
1143  unsigned MaxGlobalType = 0;
1144  for (const GlobalValue &GV : M.globals()) {
1145  MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1146  MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1147  if (GV.hasSection()) {
1148  // Give section names unique ID's.
1149  unsigned &Entry = SectionMap[GV.getSection()];
1150  if (!Entry) {
1151  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1152  0 /*TODO*/);
1153  Entry = SectionMap.size();
1154  }
1155  }
1156  }
1157  for (const Function &F : M) {
1158  MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1159  if (F.hasSection()) {
1160  // Give section names unique ID's.
1161  unsigned &Entry = SectionMap[F.getSection()];
1162  if (!Entry) {
1163  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1164  0 /*TODO*/);
1165  Entry = SectionMap.size();
1166  }
1167  }
1168  if (F.hasGC()) {
1169  // Same for GC names.
1170  unsigned &Entry = GCMap[F.getGC()];
1171  if (!Entry) {
1172  writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1173  0 /*TODO*/);
1174  Entry = GCMap.size();
1175  }
1176  }
1177  }
1178 
1179  // Emit abbrev for globals, now that we know # sections and max alignment.
1180  unsigned SimpleGVarAbbrev = 0;
1181  if (!M.global_empty()) {
1182  // Add an abbrev for common globals with no visibility or thread localness.
1183  auto Abbv = std::make_shared<BitCodeAbbrev>();
1185  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1186  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1188  Log2_32_Ceil(MaxGlobalType+1)));
1189  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1190  //| explicitType << 1
1191  //| constant
1192  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1193  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1194  if (MaxAlignment == 0) // Alignment.
1195  Abbv->Add(BitCodeAbbrevOp(0));
1196  else {
1197  unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1199  Log2_32_Ceil(MaxEncAlignment+1)));
1200  }
1201  if (SectionMap.empty()) // Section.
1202  Abbv->Add(BitCodeAbbrevOp(0));
1203  else
1205  Log2_32_Ceil(SectionMap.size()+1)));
1206  // Don't bother emitting vis + thread local.
1207  SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1208  }
1209 
1211  // Emit the module's source file name.
1212  {
1213  StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1215  if (Bits == SE_Char6)
1216  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1217  else if (Bits == SE_Fixed7)
1218  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1219 
1220  // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1221  auto Abbv = std::make_shared<BitCodeAbbrev>();
1224  Abbv->Add(AbbrevOpToUse);
1225  unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1226 
1227  for (const auto P : M.getSourceFileName())
1228  Vals.push_back((unsigned char)P);
1229 
1230  // Emit the finished record.
1231  Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1232  Vals.clear();
1233  }
1234 
1235  // Emit the global variable information.
1236  for (const GlobalVariable &GV : M.globals()) {
1237  unsigned AbbrevToUse = 0;
1238 
1239  // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1240  // linkage, alignment, section, visibility, threadlocal,
1241  // unnamed_addr, externally_initialized, dllstorageclass,
1242  // comdat, attributes, DSO_Local]
1243  Vals.push_back(addToStrtab(GV.getName()));
1244  Vals.push_back(GV.getName().size());
1245  Vals.push_back(VE.getTypeID(GV.getValueType()));
1246  Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1247  Vals.push_back(GV.isDeclaration() ? 0 :
1248  (VE.getValueID(GV.getInitializer()) + 1));
1249  Vals.push_back(getEncodedLinkage(GV));
1250  Vals.push_back(Log2_32(GV.getAlignment())+1);
1251  Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1252  if (GV.isThreadLocal() ||
1253  GV.getVisibility() != GlobalValue::DefaultVisibility ||
1254  GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1255  GV.isExternallyInitialized() ||
1256  GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1257  GV.hasComdat() ||
1258  GV.hasAttributes() ||
1259  GV.isDSOLocal()) {
1260  Vals.push_back(getEncodedVisibility(GV));
1262  Vals.push_back(getEncodedUnnamedAddr(GV));
1263  Vals.push_back(GV.isExternallyInitialized());
1265  Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1266 
1267  auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1268  Vals.push_back(VE.getAttributeListID(AL));
1269 
1270  Vals.push_back(GV.isDSOLocal());
1271  } else {
1272  AbbrevToUse = SimpleGVarAbbrev;
1273  }
1274 
1275  Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1276  Vals.clear();
1277  }
1278 
1279  // Emit the function proto information.
1280  for (const Function &F : M) {
1281  // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1282  // linkage, paramattrs, alignment, section, visibility, gc,
1283  // unnamed_addr, prologuedata, dllstorageclass, comdat,
1284  // prefixdata, personalityfn, DSO_Local, addrspace]
1285  Vals.push_back(addToStrtab(F.getName()));
1286  Vals.push_back(F.getName().size());
1287  Vals.push_back(VE.getTypeID(F.getFunctionType()));
1288  Vals.push_back(F.getCallingConv());
1289  Vals.push_back(F.isDeclaration());
1290  Vals.push_back(getEncodedLinkage(F));
1291  Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1292  Vals.push_back(Log2_32(F.getAlignment())+1);
1293  Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1295  Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1297  Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1298  : 0);
1300  Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1301  Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1302  : 0);
1303  Vals.push_back(
1304  F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1305 
1306  Vals.push_back(F.isDSOLocal());
1307  Vals.push_back(F.getAddressSpace());
1308 
1309  unsigned AbbrevToUse = 0;
1310  Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1311  Vals.clear();
1312  }
1313 
1314  // Emit the alias information.
1315  for (const GlobalAlias &A : M.aliases()) {
1316  // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1317  // visibility, dllstorageclass, threadlocal, unnamed_addr,
1318  // DSO_Local]
1319  Vals.push_back(addToStrtab(A.getName()));
1320  Vals.push_back(A.getName().size());
1321  Vals.push_back(VE.getTypeID(A.getValueType()));
1322  Vals.push_back(A.getType()->getAddressSpace());
1323  Vals.push_back(VE.getValueID(A.getAliasee()));
1324  Vals.push_back(getEncodedLinkage(A));
1329  Vals.push_back(A.isDSOLocal());
1330 
1331  unsigned AbbrevToUse = 0;
1332  Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1333  Vals.clear();
1334  }
1335 
1336  // Emit the ifunc information.
1337  for (const GlobalIFunc &I : M.ifuncs()) {
1338  // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1339  // val#, linkage, visibility, DSO_Local]
1340  Vals.push_back(addToStrtab(I.getName()));
1341  Vals.push_back(I.getName().size());
1342  Vals.push_back(VE.getTypeID(I.getValueType()));
1343  Vals.push_back(I.getType()->getAddressSpace());
1344  Vals.push_back(VE.getValueID(I.getResolver()));
1345  Vals.push_back(getEncodedLinkage(I));
1347  Vals.push_back(I.isDSOLocal());
1348  Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1349  Vals.clear();
1350  }
1351 
1352  writeValueSymbolTableForwardDecl();
1353 }
1354 
1355 static uint64_t getOptimizationFlags(const Value *V) {
1356  uint64_t Flags = 0;
1357 
1358  if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1359  if (OBO->hasNoSignedWrap())
1360  Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1361  if (OBO->hasNoUnsignedWrap())
1362  Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1363  } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1364  if (PEO->isExact())
1365  Flags |= 1 << bitc::PEO_EXACT;
1366  } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1367  if (FPMO->hasAllowReassoc())
1368  Flags |= bitc::AllowReassoc;
1369  if (FPMO->hasNoNaNs())
1370  Flags |= bitc::NoNaNs;
1371  if (FPMO->hasNoInfs())
1372  Flags |= bitc::NoInfs;
1373  if (FPMO->hasNoSignedZeros())
1374  Flags |= bitc::NoSignedZeros;
1375  if (FPMO->hasAllowReciprocal())
1376  Flags |= bitc::AllowReciprocal;
1377  if (FPMO->hasAllowContract())
1378  Flags |= bitc::AllowContract;
1379  if (FPMO->hasApproxFunc())
1380  Flags |= bitc::ApproxFunc;
1381  }
1382 
1383  return Flags;
1384 }
1385 
1386 void ModuleBitcodeWriter::writeValueAsMetadata(
1388  // Mimic an MDNode with a value as one operand.
1389  Value *V = MD->getValue();
1390  Record.push_back(VE.getTypeID(V->getType()));
1391  Record.push_back(VE.getValueID(V));
1392  Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1393  Record.clear();
1394 }
1395 
1397  SmallVectorImpl<uint64_t> &Record,
1398  unsigned Abbrev) {
1399  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1400  Metadata *MD = N->getOperand(i);
1401  assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1402  "Unexpected function-local metadata");
1403  Record.push_back(VE.getMetadataOrNullID(MD));
1404  }
1407  Record, Abbrev);
1408  Record.clear();
1409 }
1410 
1411 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1412  // Assume the column is usually under 128, and always output the inlined-at
1413  // location (it's never more expensive than building an array size 1).
1414  auto Abbv = std::make_shared<BitCodeAbbrev>();
1416  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1417  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1418  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1419  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1420  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1421  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1422  return Stream.EmitAbbrev(std::move(Abbv));
1423 }
1424 
1426  SmallVectorImpl<uint64_t> &Record,
1427  unsigned &Abbrev) {
1428  if (!Abbrev)
1429  Abbrev = createDILocationAbbrev();
1430 
1431  Record.push_back(N->isDistinct());
1432  Record.push_back(N->getLine());
1433  Record.push_back(N->getColumn());
1434  Record.push_back(VE.getMetadataID(N->getScope()));
1435  Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1436  Record.push_back(N->isImplicitCode());
1437 
1438  Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1439  Record.clear();
1440 }
1441 
1442 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1443  // Assume the column is usually under 128, and always output the inlined-at
1444  // location (it's never more expensive than building an array size 1).
1445  auto Abbv = std::make_shared<BitCodeAbbrev>();
1447  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1448  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1449  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1450  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1452  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1453  return Stream.EmitAbbrev(std::move(Abbv));
1454 }
1455 
1457  SmallVectorImpl<uint64_t> &Record,
1458  unsigned &Abbrev) {
1459  if (!Abbrev)
1460  Abbrev = createGenericDINodeAbbrev();
1461 
1462  Record.push_back(N->isDistinct());
1463  Record.push_back(N->getTag());
1464  Record.push_back(0); // Per-tag version field; unused for now.
1465 
1466  for (auto &I : N->operands())
1467  Record.push_back(VE.getMetadataOrNullID(I));
1468 
1469  Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1470  Record.clear();
1471 }
1472 
1473 static uint64_t rotateSign(int64_t I) {
1474  uint64_t U = I;
1475  return I < 0 ? ~(U << 1) : U << 1;
1476 }
1477 
1479  SmallVectorImpl<uint64_t> &Record,
1480  unsigned Abbrev) {
1481  const uint64_t Version = 1 << 1;
1482  Record.push_back((uint64_t)N->isDistinct() | Version);
1483  Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1484  Record.push_back(rotateSign(N->getLowerBound()));
1485 
1486  Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1487  Record.clear();
1488 }
1489 
1491  SmallVectorImpl<uint64_t> &Record,
1492  unsigned Abbrev) {
1493  Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
1494  Record.push_back(rotateSign(N->getValue()));
1495  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1496 
1497  Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1498  Record.clear();
1499 }
1500 
1502  SmallVectorImpl<uint64_t> &Record,
1503  unsigned Abbrev) {
1504  Record.push_back(N->isDistinct());
1505  Record.push_back(N->getTag());
1506  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1507  Record.push_back(N->getSizeInBits());
1508  Record.push_back(N->getAlignInBits());
1509  Record.push_back(N->getEncoding());
1510  Record.push_back(N->getFlags());
1511 
1512  Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1513  Record.clear();
1514 }
1515 
1517  SmallVectorImpl<uint64_t> &Record,
1518  unsigned Abbrev) {
1519  Record.push_back(N->isDistinct());
1520  Record.push_back(N->getTag());
1521  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1522  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1523  Record.push_back(N->getLine());
1524  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1525  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1526  Record.push_back(N->getSizeInBits());
1527  Record.push_back(N->getAlignInBits());
1528  Record.push_back(N->getOffsetInBits());
1529  Record.push_back(N->getFlags());
1530  Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1531 
1532  // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1533  // that there is no DWARF address space associated with DIDerivedType.
1534  if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1535  Record.push_back(*DWARFAddressSpace + 1);
1536  else
1537  Record.push_back(0);
1538 
1539  Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1540  Record.clear();
1541 }
1542 
1544  const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1545  unsigned Abbrev) {
1546  const unsigned IsNotUsedInOldTypeRef = 0x2;
1547  Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1548  Record.push_back(N->getTag());
1549  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1550  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1551  Record.push_back(N->getLine());
1552  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1553  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1554  Record.push_back(N->getSizeInBits());
1555  Record.push_back(N->getAlignInBits());
1556  Record.push_back(N->getOffsetInBits());
1557  Record.push_back(N->getFlags());
1558  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1559  Record.push_back(N->getRuntimeLang());
1561  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1564 
1565  Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1566  Record.clear();
1567 }
1568 
1570  const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1571  unsigned Abbrev) {
1572  const unsigned HasNoOldTypeRefs = 0x2;
1573  Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1574  Record.push_back(N->getFlags());
1575  Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1576  Record.push_back(N->getCC());
1577 
1578  Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1579  Record.clear();
1580 }
1581 
1583  SmallVectorImpl<uint64_t> &Record,
1584  unsigned Abbrev) {
1585  Record.push_back(N->isDistinct());
1586  Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1587  Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1588  if (N->getRawChecksum()) {
1589  Record.push_back(N->getRawChecksum()->Kind);
1590  Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1591  } else {
1592  // Maintain backwards compatibility with the old internal representation of
1593  // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1594  Record.push_back(0);
1595  Record.push_back(VE.getMetadataOrNullID(nullptr));
1596  }
1597  auto Source = N->getRawSource();
1598  if (Source)
1599  Record.push_back(VE.getMetadataOrNullID(*Source));
1600 
1601  Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1602  Record.clear();
1603 }
1604 
1606  SmallVectorImpl<uint64_t> &Record,
1607  unsigned Abbrev) {
1608  assert(N->isDistinct() && "Expected distinct compile units");
1609  Record.push_back(/* IsDistinct */ true);
1610  Record.push_back(N->getSourceLanguage());
1611  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1612  Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1613  Record.push_back(N->isOptimized());
1614  Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1615  Record.push_back(N->getRuntimeVersion());
1617  Record.push_back(N->getEmissionKind());
1618  Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1619  Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1620  Record.push_back(/* subprograms */ 0);
1621  Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1622  Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1623  Record.push_back(N->getDWOId());
1624  Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1625  Record.push_back(N->getSplitDebugInlining());
1626  Record.push_back(N->getDebugInfoForProfiling());
1627  Record.push_back((unsigned)N->getNameTableKind());
1628 
1629  Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1630  Record.clear();
1631 }
1632 
1634  SmallVectorImpl<uint64_t> &Record,
1635  unsigned Abbrev) {
1636  const uint64_t HasUnitFlag = 1 << 1;
1637  const uint64_t HasSPFlagsFlag = 1 << 2;
1638  Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1639  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1640  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1641  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1642  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1643  Record.push_back(N->getLine());
1644  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1645  Record.push_back(N->getScopeLine());
1646  Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1647  Record.push_back(N->getSPFlags());
1648  Record.push_back(N->getVirtualIndex());
1649  Record.push_back(N->getFlags());
1650  Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1651  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1652  Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1653  Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1654  Record.push_back(N->getThisAdjustment());
1655  Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1656 
1657  Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1658  Record.clear();
1659 }
1660 
1662  SmallVectorImpl<uint64_t> &Record,
1663  unsigned Abbrev) {
1664  Record.push_back(N->isDistinct());
1665  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1666  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1667  Record.push_back(N->getLine());
1668  Record.push_back(N->getColumn());
1669 
1670  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1671  Record.clear();
1672 }
1673 
1676  unsigned Abbrev) {
1677  Record.push_back(N->isDistinct());
1678  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1679  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1680  Record.push_back(N->getDiscriminator());
1681 
1682  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1683  Record.clear();
1684 }
1685 
1687  SmallVectorImpl<uint64_t> &Record,
1688  unsigned Abbrev) {
1689  Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1690  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1691  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1692 
1693  Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1694  Record.clear();
1695 }
1696 
1698  SmallVectorImpl<uint64_t> &Record,
1699  unsigned Abbrev) {
1700  Record.push_back(N->isDistinct());
1701  Record.push_back(N->getMacinfoType());
1702  Record.push_back(N->getLine());
1703  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1704  Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1705 
1706  Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1707  Record.clear();
1708 }
1709 
1711  SmallVectorImpl<uint64_t> &Record,
1712  unsigned Abbrev) {
1713  Record.push_back(N->isDistinct());
1714  Record.push_back(N->getMacinfoType());
1715  Record.push_back(N->getLine());
1716  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1717  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1718 
1719  Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1720  Record.clear();
1721 }
1722 
1724  SmallVectorImpl<uint64_t> &Record,
1725  unsigned Abbrev) {
1726  Record.push_back(N->isDistinct());
1727  for (auto &I : N->operands())
1728  Record.push_back(VE.getMetadataOrNullID(I));
1729 
1730  Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1731  Record.clear();
1732 }
1733 
1736  unsigned Abbrev) {
1737  Record.push_back(N->isDistinct());
1738  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1739  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1740 
1741  Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1742  Record.clear();
1743 }
1744 
1747  unsigned Abbrev) {
1748  Record.push_back(N->isDistinct());
1749  Record.push_back(N->getTag());
1750  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1751  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1752  Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1753 
1754  Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1755  Record.clear();
1756 }
1757 
1759  const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1760  unsigned Abbrev) {
1761  const uint64_t Version = 2 << 1;
1762  Record.push_back((uint64_t)N->isDistinct() | Version);
1763  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1764  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1766  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1767  Record.push_back(N->getLine());
1768  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1769  Record.push_back(N->isLocalToUnit());
1770  Record.push_back(N->isDefinition());
1773  Record.push_back(N->getAlignInBits());
1774 
1775  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1776  Record.clear();
1777 }
1778 
1780  const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1781  unsigned Abbrev) {
1782  // In order to support all possible bitcode formats in BitcodeReader we need
1783  // to distinguish the following cases:
1784  // 1) Record has no artificial tag (Record[1]),
1785  // has no obsolete inlinedAt field (Record[9]).
1786  // In this case Record size will be 8, HasAlignment flag is false.
1787  // 2) Record has artificial tag (Record[1]),
1788  // has no obsolete inlignedAt field (Record[9]).
1789  // In this case Record size will be 9, HasAlignment flag is false.
1790  // 3) Record has both artificial tag (Record[1]) and
1791  // obsolete inlignedAt field (Record[9]).
1792  // In this case Record size will be 10, HasAlignment flag is false.
1793  // 4) Record has neither artificial tag, nor inlignedAt field, but
1794  // HasAlignment flag is true and Record[8] contains alignment value.
1795  const uint64_t HasAlignmentFlag = 1 << 1;
1796  Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1797  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1798  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1799  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1800  Record.push_back(N->getLine());
1801  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1802  Record.push_back(N->getArg());
1803  Record.push_back(N->getFlags());
1804  Record.push_back(N->getAlignInBits());
1805 
1806  Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1807  Record.clear();
1808 }
1809 
1811  const DILabel *N, SmallVectorImpl<uint64_t> &Record,
1812  unsigned Abbrev) {
1813  Record.push_back((uint64_t)N->isDistinct());
1814  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1815  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1816  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1817  Record.push_back(N->getLine());
1818 
1819  Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
1820  Record.clear();
1821 }
1822 
1824  SmallVectorImpl<uint64_t> &Record,
1825  unsigned Abbrev) {
1826  Record.reserve(N->getElements().size() + 1);
1827  const uint64_t Version = 3 << 1;
1828  Record.push_back((uint64_t)N->isDistinct() | Version);
1829  Record.append(N->elements_begin(), N->elements_end());
1830 
1831  Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1832  Record.clear();
1833 }
1834 
1837  unsigned Abbrev) {
1838  Record.push_back(N->isDistinct());
1839  Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1840  Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1841 
1842  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1843  Record.clear();
1844 }
1845 
1847  SmallVectorImpl<uint64_t> &Record,
1848  unsigned Abbrev) {
1849  Record.push_back(N->isDistinct());
1850  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1851  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1852  Record.push_back(N->getLine());
1855  Record.push_back(N->getAttributes());
1856  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1857 
1858  Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1859  Record.clear();
1860 }
1861 
1863  const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1864  unsigned Abbrev) {
1865  Record.push_back(N->isDistinct());
1866  Record.push_back(N->getTag());
1867  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1868  Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1869  Record.push_back(N->getLine());
1870  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1871  Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
1872 
1873  Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1874  Record.clear();
1875 }
1876 
1877 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1878  auto Abbv = std::make_shared<BitCodeAbbrev>();
1881  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1882  return Stream.EmitAbbrev(std::move(Abbv));
1883 }
1884 
1885 void ModuleBitcodeWriter::writeNamedMetadata(
1886  SmallVectorImpl<uint64_t> &Record) {
1887  if (M.named_metadata_empty())
1888  return;
1889 
1890  unsigned Abbrev = createNamedMetadataAbbrev();
1891  for (const NamedMDNode &NMD : M.named_metadata()) {
1892  // Write name.
1893  StringRef Str = NMD.getName();
1894  Record.append(Str.bytes_begin(), Str.bytes_end());
1895  Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1896  Record.clear();
1897 
1898  // Write named metadata operands.
1899  for (const MDNode *N : NMD.operands())
1900  Record.push_back(VE.getMetadataID(N));
1901  Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1902  Record.clear();
1903  }
1904 }
1905 
1906 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1907  auto Abbv = std::make_shared<BitCodeAbbrev>();
1909  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1910  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1912  return Stream.EmitAbbrev(std::move(Abbv));
1913 }
1914 
1915 /// Write out a record for MDString.
1916 ///
1917 /// All the metadata strings in a metadata block are emitted in a single
1918 /// record. The sizes and strings themselves are shoved into a blob.
1919 void ModuleBitcodeWriter::writeMetadataStrings(
1921  if (Strings.empty())
1922  return;
1923 
1924  // Start the record with the number of strings.
1926  Record.push_back(Strings.size());
1927 
1928  // Emit the sizes of the strings in the blob.
1929  SmallString<256> Blob;
1930  {
1931  BitstreamWriter W(Blob);
1932  for (const Metadata *MD : Strings)
1933  W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1934  W.FlushToWord();
1935  }
1936 
1937  // Add the offset to the strings to the record.
1938  Record.push_back(Blob.size());
1939 
1940  // Add the strings to the blob.
1941  for (const Metadata *MD : Strings)
1942  Blob.append(cast<MDString>(MD)->getString());
1943 
1944  // Emit the final record.
1945  Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1946  Record.clear();
1947 }
1948 
1949 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1950 enum MetadataAbbrev : unsigned {
1951 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1952 #include "llvm/IR/Metadata.def"
1954 };
1955 
1956 void ModuleBitcodeWriter::writeMetadataRecords(
1958  std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1959  if (MDs.empty())
1960  return;
1961 
1962  // Initialize MDNode abbreviations.
1963 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1964 #include "llvm/IR/Metadata.def"
1965 
1966  for (const Metadata *MD : MDs) {
1967  if (IndexPos)
1968  IndexPos->push_back(Stream.GetCurrentBitNo());
1969  if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1970  assert(N->isResolved() && "Expected forward references to be resolved");
1971 
1972  switch (N->getMetadataID()) {
1973  default:
1974  llvm_unreachable("Invalid MDNode subclass");
1975 #define HANDLE_MDNODE_LEAF(CLASS) \
1976  case Metadata::CLASS##Kind: \
1977  if (MDAbbrevs) \
1978  write##CLASS(cast<CLASS>(N), Record, \
1979  (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1980  else \
1981  write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1982  continue;
1983 #include "llvm/IR/Metadata.def"
1984  }
1985  }
1986  writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1987  }
1988 }
1989 
1990 void ModuleBitcodeWriter::writeModuleMetadata() {
1991  if (!VE.hasMDs() && M.named_metadata_empty())
1992  return;
1993 
1996 
1997  // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1998  // block and load any metadata.
1999  std::vector<unsigned> MDAbbrevs;
2000 
2002  MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2003  MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2004  createGenericDINodeAbbrev();
2005 
2006  auto Abbv = std::make_shared<BitCodeAbbrev>();
2008  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2009  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2010  unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2011 
2012  Abbv = std::make_shared<BitCodeAbbrev>();
2015  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2016  unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2017 
2018  // Emit MDStrings together upfront.
2019  writeMetadataStrings(VE.getMDStrings(), Record);
2020 
2021  // We only emit an index for the metadata record if we have more than a given
2022  // (naive) threshold of metadatas, otherwise it is not worth it.
2023  if (VE.getNonMDStrings().size() > IndexThreshold) {
2024  // Write a placeholder value in for the offset of the metadata index,
2025  // which is written after the records, so that it can include
2026  // the offset of each entry. The placeholder offset will be
2027  // updated after all records are emitted.
2028  uint64_t Vals[] = {0, 0};
2029  Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2030  }
2031 
2032  // Compute and save the bit offset to the current position, which will be
2033  // patched when we emit the index later. We can simply subtract the 64-bit
2034  // fixed size from the current bit number to get the location to backpatch.
2035  uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2036 
2037  // This index will contain the bitpos for each individual record.
2038  std::vector<uint64_t> IndexPos;
2039  IndexPos.reserve(VE.getNonMDStrings().size());
2040 
2041  // Write all the records
2042  writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2043 
2044  if (VE.getNonMDStrings().size() > IndexThreshold) {
2045  // Now that we have emitted all the records we will emit the index. But
2046  // first
2047  // backpatch the forward reference so that the reader can skip the records
2048  // efficiently.
2049  Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2050  Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2051 
2052  // Delta encode the index.
2053  uint64_t PreviousValue = IndexOffsetRecordBitPos;
2054  for (auto &Elt : IndexPos) {
2055  auto EltDelta = Elt - PreviousValue;
2056  PreviousValue = Elt;
2057  Elt = EltDelta;
2058  }
2059  // Emit the index record.
2060  Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2061  IndexPos.clear();
2062  }
2063 
2064  // Write the named metadata now.
2065  writeNamedMetadata(Record);
2066 
2067  auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2068  SmallVector<uint64_t, 4> Record;
2069  Record.push_back(VE.getValueID(&GO));
2070  pushGlobalMetadataAttachment(Record, GO);
2072  };
2073  for (const Function &F : M)
2074  if (F.isDeclaration() && F.hasMetadata())
2075  AddDeclAttachedMetadata(F);
2076  // FIXME: Only store metadata for declarations here, and move data for global
2077  // variable definitions to a separate block (PR28134).
2078  for (const GlobalVariable &GV : M.globals())
2079  if (GV.hasMetadata())
2080  AddDeclAttachedMetadata(GV);
2081 
2082  Stream.ExitBlock();
2083 }
2084 
2085 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2086  if (!VE.hasMDs())
2087  return;
2088 
2091  writeMetadataStrings(VE.getMDStrings(), Record);
2092  writeMetadataRecords(VE.getNonMDStrings(), Record);
2093  Stream.ExitBlock();
2094 }
2095 
2096 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2097  SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2098  // [n x [id, mdnode]]
2100  GO.getAllMetadata(MDs);
2101  for (const auto &I : MDs) {
2102  Record.push_back(I.first);
2103  Record.push_back(VE.getMetadataID(I.second));
2104  }
2105 }
2106 
2107 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2109 
2111 
2112  if (F.hasMetadata()) {
2113  pushGlobalMetadataAttachment(Record, F);
2114  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2115  Record.clear();
2116  }
2117 
2118  // Write metadata attachments
2119  // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2121  for (const BasicBlock &BB : F)
2122  for (const Instruction &I : BB) {
2123  MDs.clear();
2124  I.getAllMetadataOtherThanDebugLoc(MDs);
2125 
2126  // If no metadata, ignore instruction.
2127  if (MDs.empty()) continue;
2128 
2129  Record.push_back(VE.getInstructionID(&I));
2130 
2131  for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2132  Record.push_back(MDs[i].first);
2133  Record.push_back(VE.getMetadataID(MDs[i].second));
2134  }
2135  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2136  Record.clear();
2137  }
2138 
2139  Stream.ExitBlock();
2140 }
2141 
2142 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2144 
2145  // Write metadata kinds
2146  // METADATA_KIND - [n x [id, name]]
2148  M.getMDKindNames(Names);
2149 
2150  if (Names.empty()) return;
2151 
2153 
2154  for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2155  Record.push_back(MDKindID);
2156  StringRef KName = Names[MDKindID];
2157  Record.append(KName.begin(), KName.end());
2158 
2159  Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2160  Record.clear();
2161  }
2162 
2163  Stream.ExitBlock();
2164 }
2165 
2166 void ModuleBitcodeWriter::writeOperandBundleTags() {
2167  // Write metadata kinds
2168  //
2169  // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2170  //
2171  // OPERAND_BUNDLE_TAG - [strchr x N]
2172 
2174  M.getOperandBundleTags(Tags);
2175 
2176  if (Tags.empty())
2177  return;
2178 
2180 
2182 
2183  for (auto Tag : Tags) {
2184  Record.append(Tag.begin(), Tag.end());
2185 
2186  Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2187  Record.clear();
2188  }
2189 
2190  Stream.ExitBlock();
2191 }
2192 
2193 void ModuleBitcodeWriter::writeSyncScopeNames() {
2195  M.getContext().getSyncScopeNames(SSNs);
2196  if (SSNs.empty())
2197  return;
2198 
2200 
2202  for (auto SSN : SSNs) {
2203  Record.append(SSN.begin(), SSN.end());
2204  Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2205  Record.clear();
2206  }
2207 
2208  Stream.ExitBlock();
2209 }
2210 
2211 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2212  if ((int64_t)V >= 0)
2213  Vals.push_back(V << 1);
2214  else
2215  Vals.push_back((-V << 1) | 1);
2216 }
2217 
2218 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2219  bool isGlobal) {
2220  if (FirstVal == LastVal) return;
2221 
2223 
2224  unsigned AggregateAbbrev = 0;
2225  unsigned String8Abbrev = 0;
2226  unsigned CString7Abbrev = 0;
2227  unsigned CString6Abbrev = 0;
2228  // If this is a constant pool for the module, emit module-specific abbrevs.
2229  if (isGlobal) {
2230  // Abbrev for CST_CODE_AGGREGATE.
2231  auto Abbv = std::make_shared<BitCodeAbbrev>();
2234  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2235  AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2236 
2237  // Abbrev for CST_CODE_STRING.
2238  Abbv = std::make_shared<BitCodeAbbrev>();
2241  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2242  String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2243  // Abbrev for CST_CODE_CSTRING.
2244  Abbv = std::make_shared<BitCodeAbbrev>();
2247  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2248  CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2249  // Abbrev for CST_CODE_CSTRING.
2250  Abbv = std::make_shared<BitCodeAbbrev>();
2254  CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2255  }
2256 
2258 
2259  const ValueEnumerator::ValueList &Vals = VE.getValues();
2260  Type *LastTy = nullptr;
2261  for (unsigned i = FirstVal; i != LastVal; ++i) {
2262  const Value *V = Vals[i].first;
2263  // If we need to switch types, do so now.
2264  if (V->getType() != LastTy) {
2265  LastTy = V->getType();
2266  Record.push_back(VE.getTypeID(LastTy));
2267  Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2268  CONSTANTS_SETTYPE_ABBREV);
2269  Record.clear();
2270  }
2271 
2272  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2273  Record.push_back(unsigned(IA->hasSideEffects()) |
2274  unsigned(IA->isAlignStack()) << 1 |
2275  unsigned(IA->getDialect()&1) << 2);
2276 
2277  // Add the asm string.
2278  const std::string &AsmStr = IA->getAsmString();
2279  Record.push_back(AsmStr.size());
2280  Record.append(AsmStr.begin(), AsmStr.end());
2281 
2282  // Add the constraint string.
2283  const std::string &ConstraintStr = IA->getConstraintString();
2284  Record.push_back(ConstraintStr.size());
2285  Record.append(ConstraintStr.begin(), ConstraintStr.end());
2286  Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2287  Record.clear();
2288  continue;
2289  }
2290  const Constant *C = cast<Constant>(V);
2291  unsigned Code = -1U;
2292  unsigned AbbrevToUse = 0;
2293  if (C->isNullValue()) {
2294  Code = bitc::CST_CODE_NULL;
2295  } else if (isa<UndefValue>(C)) {
2296  Code = bitc::CST_CODE_UNDEF;
2297  } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2298  if (IV->getBitWidth() <= 64) {
2299  uint64_t V = IV->getSExtValue();
2300  emitSignedInt64(Record, V);
2301  Code = bitc::CST_CODE_INTEGER;
2302  AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2303  } else { // Wide integers, > 64 bits in size.
2304  // We have an arbitrary precision integer value to write whose
2305  // bit width is > 64. However, in canonical unsigned integer
2306  // format it is likely that the high bits are going to be zero.
2307  // So, we only write the number of active words.
2308  unsigned NWords = IV->getValue().getActiveWords();
2309  const uint64_t *RawWords = IV->getValue().getRawData();
2310  for (unsigned i = 0; i != NWords; ++i) {
2311  emitSignedInt64(Record, RawWords[i]);
2312  }
2314  }
2315  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2316  Code = bitc::CST_CODE_FLOAT;
2317  Type *Ty = CFP->getType();
2318  if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2319  Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2320  } else if (Ty->isX86_FP80Ty()) {
2321  // api needed to prevent premature destruction
2322  // bits are not in the same order as a normal i80 APInt, compensate.
2323  APInt api = CFP->getValueAPF().bitcastToAPInt();
2324  const uint64_t *p = api.getRawData();
2325  Record.push_back((p[1] << 48) | (p[0] >> 16));
2326  Record.push_back(p[0] & 0xffffLL);
2327  } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2328  APInt api = CFP->getValueAPF().bitcastToAPInt();
2329  const uint64_t *p = api.getRawData();
2330  Record.push_back(p[0]);
2331  Record.push_back(p[1]);
2332  } else {
2333  assert(0 && "Unknown FP type!");
2334  }
2335  } else if (isa<ConstantDataSequential>(C) &&
2336  cast<ConstantDataSequential>(C)->isString()) {
2337  const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2338  // Emit constant strings specially.
2339  unsigned NumElts = Str->getNumElements();
2340  // If this is a null-terminated string, use the denser CSTRING encoding.
2341  if (Str->isCString()) {
2342  Code = bitc::CST_CODE_CSTRING;
2343  --NumElts; // Don't encode the null, which isn't allowed by char6.
2344  } else {
2345  Code = bitc::CST_CODE_STRING;
2346  AbbrevToUse = String8Abbrev;
2347  }
2348  bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2349  bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2350  for (unsigned i = 0; i != NumElts; ++i) {
2351  unsigned char V = Str->getElementAsInteger(i);
2352  Record.push_back(V);
2353  isCStr7 &= (V & 128) == 0;
2354  if (isCStrChar6)
2355  isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2356  }
2357 
2358  if (isCStrChar6)
2359  AbbrevToUse = CString6Abbrev;
2360  else if (isCStr7)
2361  AbbrevToUse = CString7Abbrev;
2362  } else if (const ConstantDataSequential *CDS =
2363  dyn_cast<ConstantDataSequential>(C)) {
2364  Code = bitc::CST_CODE_DATA;
2365  Type *EltTy = CDS->getType()->getElementType();
2366  if (isa<IntegerType>(EltTy)) {
2367  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2368  Record.push_back(CDS->getElementAsInteger(i));
2369  } else {
2370  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2371  Record.push_back(
2372  CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2373  }
2374  } else if (isa<ConstantAggregate>(C)) {
2375  Code = bitc::CST_CODE_AGGREGATE;
2376  for (const Value *Op : C->operands())
2377  Record.push_back(VE.getValueID(Op));
2378  AbbrevToUse = AggregateAbbrev;
2379  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2380  switch (CE->getOpcode()) {
2381  default:
2382  if (Instruction::isCast(CE->getOpcode())) {
2383  Code = bitc::CST_CODE_CE_CAST;
2384  Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2385  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2386  Record.push_back(VE.getValueID(C->getOperand(0)));
2387  AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2388  } else {
2389  assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2390  Code = bitc::CST_CODE_CE_BINOP;
2391  Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2392  Record.push_back(VE.getValueID(C->getOperand(0)));
2393  Record.push_back(VE.getValueID(C->getOperand(1)));
2394  uint64_t Flags = getOptimizationFlags(CE);
2395  if (Flags != 0)
2396  Record.push_back(Flags);
2397  }
2398  break;
2399  case Instruction::FNeg: {
2400  assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2401  Code = bitc::CST_CODE_CE_UNOP;
2402  Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2403  Record.push_back(VE.getValueID(C->getOperand(0)));
2404  uint64_t Flags = getOptimizationFlags(CE);
2405  if (Flags != 0)
2406  Record.push_back(Flags);
2407  break;
2408  }
2409  case Instruction::GetElementPtr: {
2410  Code = bitc::CST_CODE_CE_GEP;
2411  const auto *GO = cast<GEPOperator>(C);
2412  Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2413  if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2415  Record.push_back((*Idx << 1) | GO->isInBounds());
2416  } else if (GO->isInBounds())
2418  for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2419  Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2420  Record.push_back(VE.getValueID(C->getOperand(i)));
2421  }
2422  break;
2423  }
2424  case Instruction::Select:
2425  Code = bitc::CST_CODE_CE_SELECT;
2426  Record.push_back(VE.getValueID(C->getOperand(0)));
2427  Record.push_back(VE.getValueID(C->getOperand(1)));
2428  Record.push_back(VE.getValueID(C->getOperand(2)));
2429  break;
2430  case Instruction::ExtractElement:
2432  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2433  Record.push_back(VE.getValueID(C->getOperand(0)));
2434  Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2435  Record.push_back(VE.getValueID(C->getOperand(1)));
2436  break;
2437  case Instruction::InsertElement:
2439  Record.push_back(VE.getValueID(C->getOperand(0)));
2440  Record.push_back(VE.getValueID(C->getOperand(1)));
2441  Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2442  Record.push_back(VE.getValueID(C->getOperand(2)));
2443  break;
2444  case Instruction::ShuffleVector:
2445  // If the return type and argument types are the same, this is a
2446  // standard shufflevector instruction. If the types are different,
2447  // then the shuffle is widening or truncating the input vectors, and
2448  // the argument type must also be encoded.
2449  if (C->getType() == C->getOperand(0)->getType()) {
2451  } else {
2453  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2454  }
2455  Record.push_back(VE.getValueID(C->getOperand(0)));
2456  Record.push_back(VE.getValueID(C->getOperand(1)));
2457  Record.push_back(VE.getValueID(C->getOperand(2)));
2458  break;
2459  case Instruction::ICmp:
2460  case Instruction::FCmp:
2461  Code = bitc::CST_CODE_CE_CMP;
2462  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2463  Record.push_back(VE.getValueID(C->getOperand(0)));
2464  Record.push_back(VE.getValueID(C->getOperand(1)));
2465  Record.push_back(CE->getPredicate());
2466  break;
2467  }
2468  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2470  Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2471  Record.push_back(VE.getValueID(BA->getFunction()));
2472  Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2473  } else {
2474 #ifndef NDEBUG
2475  C->dump();
2476 #endif
2477  llvm_unreachable("Unknown constant!");
2478  }
2479  Stream.EmitRecord(Code, Record, AbbrevToUse);
2480  Record.clear();
2481  }
2482 
2483  Stream.ExitBlock();
2484 }
2485 
2486 void ModuleBitcodeWriter::writeModuleConstants() {
2487  const ValueEnumerator::ValueList &Vals = VE.getValues();
2488 
2489  // Find the first constant to emit, which is the first non-globalvalue value.
2490  // We know globalvalues have been emitted by WriteModuleInfo.
2491  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2492  if (!isa<GlobalValue>(Vals[i].first)) {
2493  writeConstants(i, Vals.size(), true);
2494  return;
2495  }
2496  }
2497 }
2498 
2499 /// pushValueAndType - The file has to encode both the value and type id for
2500 /// many values, because we need to know what type to create for forward
2501 /// references. However, most operands are not forward references, so this type
2502 /// field is not needed.
2503 ///
2504 /// This function adds V's value ID to Vals. If the value ID is higher than the
2505 /// instruction ID, then it is a forward reference, and it also includes the
2506 /// type ID. The value ID that is written is encoded relative to the InstID.
2507 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2508  SmallVectorImpl<unsigned> &Vals) {
2509  unsigned ValID = VE.getValueID(V);
2510  // Make encoding relative to the InstID.
2511  Vals.push_back(InstID - ValID);
2512  if (ValID >= InstID) {
2513  Vals.push_back(VE.getTypeID(V->getType()));
2514  return true;
2515  }
2516  return false;
2517 }
2518 
2519 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2520  unsigned InstID) {
2523 
2524  for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2525  const auto &Bundle = CS.getOperandBundleAt(i);
2526  Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2527 
2528  for (auto &Input : Bundle.Inputs)
2529  pushValueAndType(Input, InstID, Record);
2530 
2532  Record.clear();
2533  }
2534 }
2535 
2536 /// pushValue - Like pushValueAndType, but where the type of the value is
2537 /// omitted (perhaps it was already encoded in an earlier operand).
2538 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2539  SmallVectorImpl<unsigned> &Vals) {
2540  unsigned ValID = VE.getValueID(V);
2541  Vals.push_back(InstID - ValID);
2542 }
2543 
2544 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2545  SmallVectorImpl<uint64_t> &Vals) {
2546  unsigned ValID = VE.getValueID(V);
2547  int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2548  emitSignedInt64(Vals, diff);
2549 }
2550 
2551 /// WriteInstruction - Emit an instruction to the specified stream.
2552 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2553  unsigned InstID,
2554  SmallVectorImpl<unsigned> &Vals) {
2555  unsigned Code = 0;
2556  unsigned AbbrevToUse = 0;
2557  VE.setInstructionID(&I);
2558  switch (I.getOpcode()) {
2559  default:
2560  if (Instruction::isCast(I.getOpcode())) {
2562  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2563  AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2564  Vals.push_back(VE.getTypeID(I.getType()));
2566  } else {
2567  assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2569  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2570  AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2571  pushValue(I.getOperand(1), InstID, Vals);
2573  uint64_t Flags = getOptimizationFlags(&I);
2574  if (Flags != 0) {
2575  if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2576  AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2577  Vals.push_back(Flags);
2578  }
2579  }
2580  break;
2581  case Instruction::FNeg: {
2583  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2584  AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2586  uint64_t Flags = getOptimizationFlags(&I);
2587  if (Flags != 0) {
2588  if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2589  AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2590  Vals.push_back(Flags);
2591  }
2592  break;
2593  }
2594  case Instruction::GetElementPtr: {
2595  Code = bitc::FUNC_CODE_INST_GEP;
2596  AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2597  auto &GEPInst = cast<GetElementPtrInst>(I);
2598  Vals.push_back(GEPInst.isInBounds());
2599  Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2600  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2601  pushValueAndType(I.getOperand(i), InstID, Vals);
2602  break;
2603  }
2604  case Instruction::ExtractValue: {
2606  pushValueAndType(I.getOperand(0), InstID, Vals);
2607  const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2608  Vals.append(EVI->idx_begin(), EVI->idx_end());
2609  break;
2610  }
2611  case Instruction::InsertValue: {
2613  pushValueAndType(I.getOperand(0), InstID, Vals);
2614  pushValueAndType(I.getOperand(1), InstID, Vals);
2615  const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2616  Vals.append(IVI->idx_begin(), IVI->idx_end());
2617  break;
2618  }
2619  case Instruction::Select:
2621  pushValueAndType(I.getOperand(1), InstID, Vals);
2622  pushValue(I.getOperand(2), InstID, Vals);
2623  pushValueAndType(I.getOperand(0), InstID, Vals);
2624  break;
2625  case Instruction::ExtractElement:
2627  pushValueAndType(I.getOperand(0), InstID, Vals);
2628  pushValueAndType(I.getOperand(1), InstID, Vals);
2629  break;
2630  case Instruction::InsertElement:
2632  pushValueAndType(I.getOperand(0), InstID, Vals);
2633  pushValue(I.getOperand(1), InstID, Vals);
2634  pushValueAndType(I.getOperand(2), InstID, Vals);
2635  break;
2636  case Instruction::ShuffleVector:
2638  pushValueAndType(I.getOperand(0), InstID, Vals);
2639  pushValue(I.getOperand(1), InstID, Vals);
2640  pushValue(I.getOperand(2), InstID, Vals);
2641  break;
2642  case Instruction::ICmp:
2643  case Instruction::FCmp: {
2644  // compare returning Int1Ty or vector of Int1Ty
2646  pushValueAndType(I.getOperand(0), InstID, Vals);
2647  pushValue(I.getOperand(1), InstID, Vals);
2648  Vals.push_back(cast<CmpInst>(I).getPredicate());
2649  uint64_t Flags = getOptimizationFlags(&I);
2650  if (Flags != 0)
2651  Vals.push_back(Flags);
2652  break;
2653  }
2654 
2655  case Instruction::Ret:
2656  {
2657  Code = bitc::FUNC_CODE_INST_RET;
2658  unsigned NumOperands = I.getNumOperands();
2659  if (NumOperands == 0)
2660  AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2661  else if (NumOperands == 1) {
2662  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2663  AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2664  } else {
2665  for (unsigned i = 0, e = NumOperands; i != e; ++i)
2666  pushValueAndType(I.getOperand(i), InstID, Vals);
2667  }
2668  }
2669  break;
2670  case Instruction::Br:
2671  {
2672  Code = bitc::FUNC_CODE_INST_BR;
2673  const BranchInst &II = cast<BranchInst>(I);
2674  Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2675  if (II.isConditional()) {
2676  Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2677  pushValue(II.getCondition(), InstID, Vals);
2678  }
2679  }
2680  break;
2681  case Instruction::Switch:
2682  {
2684  const SwitchInst &SI = cast<SwitchInst>(I);
2685  Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2686  pushValue(SI.getCondition(), InstID, Vals);
2687  Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2688  for (auto Case : SI.cases()) {
2689  Vals.push_back(VE.getValueID(Case.getCaseValue()));
2690  Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2691  }
2692  }
2693  break;
2694  case Instruction::IndirectBr:
2696  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2697  // Encode the address operand as relative, but not the basic blocks.
2698  pushValue(I.getOperand(0), InstID, Vals);
2699  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2700  Vals.push_back(VE.getValueID(I.getOperand(i)));
2701  break;
2702 
2703  case Instruction::Invoke: {
2704  const InvokeInst *II = cast<InvokeInst>(&I);
2705  const Value *Callee = II->getCalledValue();
2706  FunctionType *FTy = II->getFunctionType();
2707 
2708  if (II->hasOperandBundles())
2709  writeOperandBundles(II, InstID);
2710 
2712 
2713  Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2714  Vals.push_back(II->getCallingConv() | 1 << 13);
2715  Vals.push_back(VE.getValueID(II->getNormalDest()));
2716  Vals.push_back(VE.getValueID(II->getUnwindDest()));
2717  Vals.push_back(VE.getTypeID(FTy));
2718  pushValueAndType(Callee, InstID, Vals);
2719 
2720  // Emit value #'s for the fixed parameters.
2721  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2722  pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2723 
2724  // Emit type/value pairs for varargs params.
2725  if (FTy->isVarArg()) {
2726  for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2727  i != e; ++i)
2728  pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2729  }
2730  break;
2731  }
2732  case Instruction::Resume:
2734  pushValueAndType(I.getOperand(0), InstID, Vals);
2735  break;
2736  case Instruction::CleanupRet: {
2738  const auto &CRI = cast<CleanupReturnInst>(I);
2739  pushValue(CRI.getCleanupPad(), InstID, Vals);
2740  if (CRI.hasUnwindDest())
2741  Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2742  break;
2743  }
2744  case Instruction::CatchRet: {
2746  const auto &CRI = cast<CatchReturnInst>(I);
2747  pushValue(CRI.getCatchPad(), InstID, Vals);
2748  Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2749  break;
2750  }
2751  case Instruction::CleanupPad:
2752  case Instruction::CatchPad: {
2753  const auto &FuncletPad = cast<FuncletPadInst>(I);
2754  Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2756  pushValue(FuncletPad.getParentPad(), InstID, Vals);
2757 
2758  unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2759  Vals.push_back(NumArgOperands);
2760  for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2761  pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2762  break;
2763  }
2764  case Instruction::CatchSwitch: {
2766  const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2767 
2768  pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2769 
2770  unsigned NumHandlers = CatchSwitch.getNumHandlers();
2771  Vals.push_back(NumHandlers);
2772  for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2773  Vals.push_back(VE.getValueID(CatchPadBB));
2774 
2775  if (CatchSwitch.hasUnwindDest())
2776  Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2777  break;
2778  }
2779  case Instruction::Unreachable:
2781  AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2782  break;
2783 
2784  case Instruction::PHI: {
2785  const PHINode &PN = cast<PHINode>(I);
2786  Code = bitc::FUNC_CODE_INST_PHI;
2787  // With the newer instruction encoding, forward references could give
2788  // negative valued IDs. This is most common for PHIs, so we use
2789  // signed VBRs.
2791  Vals64.push_back(VE.getTypeID(PN.getType()));
2792  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2793  pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2794  Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2795  }
2796  // Emit a Vals64 vector and exit.
2797  Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2798  Vals64.clear();
2799  return;
2800  }
2801 
2802  case Instruction::LandingPad: {
2803  const LandingPadInst &LP = cast<LandingPadInst>(I);
2805  Vals.push_back(VE.getTypeID(LP.getType()));
2806  Vals.push_back(LP.isCleanup());
2807  Vals.push_back(LP.getNumClauses());
2808  for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2809  if (LP.isCatch(I))
2811  else
2813  pushValueAndType(LP.getClause(I), InstID, Vals);
2814  }
2815  break;
2816  }
2817 
2818  case Instruction::Alloca: {
2820  const AllocaInst &AI = cast<AllocaInst>(I);
2821  Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2822  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2823  Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2824  unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2825  assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2826  "not enough bits for maximum alignment");
2827  assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2828  AlignRecord |= AI.isUsedWithInAlloca() << 5;
2829  AlignRecord |= 1 << 6;
2830  AlignRecord |= AI.isSwiftError() << 7;
2831  Vals.push_back(AlignRecord);
2832  break;
2833  }
2834 
2835  case Instruction::Load:
2836  if (cast<LoadInst>(I).isAtomic()) {
2838  pushValueAndType(I.getOperand(0), InstID, Vals);
2839  } else {
2841  if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2842  AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2843  }
2844  Vals.push_back(VE.getTypeID(I.getType()));
2845  Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2846  Vals.push_back(cast<LoadInst>(I).isVolatile());
2847  if (cast<LoadInst>(I).isAtomic()) {
2848  Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2849  Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
2850  }
2851  break;
2852  case Instruction::Store:
2853  if (cast<StoreInst>(I).isAtomic())
2855  else
2857  pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2858  pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2859  Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2860  Vals.push_back(cast<StoreInst>(I).isVolatile());
2861  if (cast<StoreInst>(I).isAtomic()) {
2862  Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2863  Vals.push_back(
2864  getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
2865  }
2866  break;
2867  case Instruction::AtomicCmpXchg:
2869  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2870  pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2871  pushValue(I.getOperand(2), InstID, Vals); // newval.
2872  Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2873  Vals.push_back(
2874  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2875  Vals.push_back(
2876  getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
2877  Vals.push_back(
2878  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2879  Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2880  break;
2881  case Instruction::AtomicRMW:
2883  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2884  pushValue(I.getOperand(1), InstID, Vals); // val.
2885  Vals.push_back(
2886  getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2887  Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2888  Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2889  Vals.push_back(
2890  getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
2891  break;
2892  case Instruction::Fence:
2894  Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2895  Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
2896  break;
2897  case Instruction::Call: {
2898  const CallInst &CI = cast<CallInst>(I);
2899  FunctionType *FTy = CI.getFunctionType();
2900 
2901  if (CI.hasOperandBundles())
2902  writeOperandBundles(&CI, InstID);
2903 
2905 
2907 
2908  unsigned Flags = getOptimizationFlags(&I);
2911  unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2913  unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2914  unsigned(Flags != 0) << bitc::CALL_FMF);
2915  if (Flags != 0)
2916  Vals.push_back(Flags);
2917 
2918  Vals.push_back(VE.getTypeID(FTy));
2919  pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2920 
2921  // Emit value #'s for the fixed parameters.
2922  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2923  // Check for labels (can happen with asm labels).
2924  if (FTy->getParamType(i)->isLabelTy())
2925  Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2926  else
2927  pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2928  }
2929 
2930  // Emit type/value pairs for varargs params.
2931  if (FTy->isVarArg()) {
2932  for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2933  i != e; ++i)
2934  pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2935  }
2936  break;
2937  }
2938  case Instruction::VAArg:
2940  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2941  pushValue(I.getOperand(0), InstID, Vals); // valist.
2942  Vals.push_back(VE.getTypeID(I.getType())); // restype.
2943  break;
2944  }
2945 
2946  Stream.EmitRecord(Code, Vals, AbbrevToUse);
2947  Vals.clear();
2948 }
2949 
2950 /// Write a GlobalValue VST to the module. The purpose of this data structure is
2951 /// to allow clients to efficiently find the function body.
2952 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2953  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2954  // Get the offset of the VST we are writing, and backpatch it into
2955  // the VST forward declaration record.
2956  uint64_t VSTOffset = Stream.GetCurrentBitNo();
2957  // The BitcodeStartBit was the stream offset of the identification block.
2958  VSTOffset -= bitcodeStartBit();
2959  assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2960  // Note that we add 1 here because the offset is relative to one word
2961  // before the start of the identification block, which was historically
2962  // always the start of the regular bitcode header.
2963  Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2964 
2966 
2967  auto Abbv = std::make_shared<BitCodeAbbrev>();
2969  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2970  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2971  unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2972 
2973  for (const Function &F : M) {
2974  uint64_t Record[2];
2975 
2976  if (F.isDeclaration())
2977  continue;
2978 
2979  Record[0] = VE.getValueID(&F);
2980 
2981  // Save the word offset of the function (from the start of the
2982  // actual bitcode written to the stream).
2983  uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2984  assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2985  // Note that we add 1 here because the offset is relative to one word
2986  // before the start of the identification block, which was historically
2987  // always the start of the regular bitcode header.
2988  Record[1] = BitcodeIndex / 32 + 1;
2989 
2990  Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
2991  }
2992 
2993  Stream.ExitBlock();
2994 }
2995 
2996 /// Emit names for arguments, instructions and basic blocks in a function.
2997 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2998  const ValueSymbolTable &VST) {
2999  if (VST.empty())
3000  return;
3001 
3003 
3004  // FIXME: Set up the abbrev, we know how many values there are!
3005  // FIXME: We know if the type names can use 7-bit ascii.
3006  SmallVector<uint64_t, 64> NameVals;
3007 
3008  for (const ValueName &Name : VST) {
3009  // Figure out the encoding to use for the name.
3011 
3012  unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3013  NameVals.push_back(VE.getValueID(Name.getValue()));
3014 
3015  // VST_CODE_ENTRY: [valueid, namechar x N]
3016  // VST_CODE_BBENTRY: [bbid, namechar x N]
3017  unsigned Code;
3018  if (isa<BasicBlock>(Name.getValue())) {
3019  Code = bitc::VST_CODE_BBENTRY;
3020  if (Bits == SE_Char6)
3021  AbbrevToUse = VST_BBENTRY_6_ABBREV;
3022  } else {
3023  Code = bitc::VST_CODE_ENTRY;
3024  if (Bits == SE_Char6)
3025  AbbrevToUse = VST_ENTRY_6_ABBREV;
3026  else if (Bits == SE_Fixed7)
3027  AbbrevToUse = VST_ENTRY_7_ABBREV;
3028  }
3029 
3030  for (const auto P : Name.getKey())
3031  NameVals.push_back((unsigned char)P);
3032 
3033  // Emit the finished record.
3034  Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3035  NameVals.clear();
3036  }
3037 
3038  Stream.ExitBlock();
3039 }
3040 
3041 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3042  assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3043  unsigned Code;
3044  if (isa<BasicBlock>(Order.V))
3045  Code = bitc::USELIST_CODE_BB;
3046  else
3048 
3049  SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3050  Record.push_back(VE.getValueID(Order.V));
3051  Stream.EmitRecord(Code, Record);
3052 }
3053 
3054 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3056  "Expected to be preserving use-list order");
3057 
3058  auto hasMore = [&]() {
3059  return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3060  };
3061  if (!hasMore())
3062  // Nothing to do.
3063  return;
3064 
3066  while (hasMore()) {
3067  writeUseList(std::move(VE.UseListOrders.back()));
3068  VE.UseListOrders.pop_back();
3069  }
3070  Stream.ExitBlock();
3071 }
3072 
3073 /// Emit a function body to the module stream.
3074 void ModuleBitcodeWriter::writeFunction(
3075  const Function &F,
3076  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3077  // Save the bitcode index of the start of this function block for recording
3078  // in the VST.
3079  FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3080 
3082  VE.incorporateFunction(F);
3083 
3085 
3086  // Emit the number of basic blocks, so the reader can create them ahead of
3087  // time.
3088  Vals.push_back(VE.getBasicBlocks().size());
3090  Vals.clear();
3091 
3092  // If there are function-local constants, emit them now.
3093  unsigned CstStart, CstEnd;
3094  VE.getFunctionConstantRange(CstStart, CstEnd);
3095  writeConstants(CstStart, CstEnd, false);
3096 
3097  // If there is function-local metadata, emit it now.
3098  writeFunctionMetadata(F);
3099 
3100  // Keep a running idea of what the instruction ID is.
3101  unsigned InstID = CstEnd;
3102 
3103  bool NeedsMetadataAttachment = F.hasMetadata();
3104 
3105  DILocation *LastDL = nullptr;
3106  // Finally, emit all the instructions, in order.
3107  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3108  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3109  I != E; ++I) {
3110  writeInstruction(*I, InstID, Vals);
3111 
3112  if (!I->getType()->isVoidTy())
3113  ++InstID;
3114 
3115  // If the instruction has metadata, write a metadata attachment later.
3116  NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3117 
3118  // If the instruction has a debug location, emit it.
3119  DILocation *DL = I->getDebugLoc();
3120  if (!DL)
3121  continue;
3122 
3123  if (DL == LastDL) {
3124  // Just repeat the same debug loc as last time.
3126  continue;
3127  }
3128 
3129  Vals.push_back(DL->getLine());
3130  Vals.push_back(DL->getColumn());
3131  Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3132  Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3133  Vals.push_back(DL->isImplicitCode());
3134  Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3135  Vals.clear();
3136 
3137  LastDL = DL;
3138  }
3139 
3140  // Emit names for all the instructions etc.
3141  if (auto *Symtab = F.getValueSymbolTable())
3142  writeFunctionLevelValueSymbolTable(*Symtab);
3143 
3144  if (NeedsMetadataAttachment)
3145  writeFunctionMetadataAttachment(F);
3146  if (VE.shouldPreserveUseListOrder())
3147  writeUseListBlock(&F);
3148  VE.purgeFunction();
3149  Stream.ExitBlock();
3150 }
3151 
3152 // Emit blockinfo, which defines the standard abbreviations etc.
3153 void ModuleBitcodeWriter::writeBlockInfo() {
3154  // We only want to emit block info records for blocks that have multiple
3155  // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3156  // Other blocks can define their abbrevs inline.
3157  Stream.EnterBlockInfoBlock();
3158 
3159  { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3160  auto Abbv = std::make_shared<BitCodeAbbrev>();
3161  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3162  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3164  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3166  VST_ENTRY_8_ABBREV)
3167  llvm_unreachable("Unexpected abbrev ordering!");
3168  }
3169 
3170  { // 7-bit fixed width VST_CODE_ENTRY strings.
3171  auto Abbv = std::make_shared<BitCodeAbbrev>();
3173  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3175  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3177  VST_ENTRY_7_ABBREV)
3178  llvm_unreachable("Unexpected abbrev ordering!");
3179  }
3180  { // 6-bit char6 VST_CODE_ENTRY strings.
3181  auto Abbv = std::make_shared<BitCodeAbbrev>();
3183  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3187  VST_ENTRY_6_ABBREV)
3188  llvm_unreachable("Unexpected abbrev ordering!");
3189  }
3190  { // 6-bit char6 VST_CODE_BBENTRY strings.
3191  auto Abbv = std::make_shared<BitCodeAbbrev>();
3193  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3197  VST_BBENTRY_6_ABBREV)
3198  llvm_unreachable("Unexpected abbrev ordering!");
3199  }
3200 
3201  { // SETTYPE abbrev for CONSTANTS_BLOCK.
3202  auto Abbv = std::make_shared<BitCodeAbbrev>();
3206  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3207  CONSTANTS_SETTYPE_ABBREV)
3208  llvm_unreachable("Unexpected abbrev ordering!");
3209  }
3210 
3211  { // INTEGER abbrev for CONSTANTS_BLOCK.
3212  auto Abbv = std::make_shared<BitCodeAbbrev>();
3214  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3215  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3216  CONSTANTS_INTEGER_ABBREV)
3217  llvm_unreachable("Unexpected abbrev ordering!");
3218  }
3219 
3220  { // CE_CAST abbrev for CONSTANTS_BLOCK.
3221  auto Abbv = std::make_shared<BitCodeAbbrev>();
3223  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3224  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3226  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3227 
3228  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3229  CONSTANTS_CE_CAST_Abbrev)
3230  llvm_unreachable("Unexpected abbrev ordering!");
3231  }
3232  { // NULL abbrev for CONSTANTS_BLOCK.
3233  auto Abbv = std::make_shared<BitCodeAbbrev>();
3235  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3236  CONSTANTS_NULL_Abbrev)
3237  llvm_unreachable("Unexpected abbrev ordering!");
3238  }
3239 
3240  // FIXME: This should only use space for first class types!
3241 
3242  { // INST_LOAD abbrev for FUNCTION_BLOCK.
3243  auto Abbv = std::make_shared<BitCodeAbbrev>();
3245  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3246  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3248  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3249  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3250  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3251  FUNCTION_INST_LOAD_ABBREV)
3252  llvm_unreachable("Unexpected abbrev ordering!");
3253  }
3254  { // INST_UNOP abbrev for FUNCTION_BLOCK.
3255  auto Abbv = std::make_shared<BitCodeAbbrev>();
3257  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3258  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3259  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3260  FUNCTION_INST_UNOP_ABBREV)
3261  llvm_unreachable("Unexpected abbrev ordering!");
3262  }
3263  { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3264  auto Abbv = std::make_shared<BitCodeAbbrev>();
3266  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3267  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3268  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3269  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3270  FUNCTION_INST_UNOP_FLAGS_ABBREV)
3271  llvm_unreachable("Unexpected abbrev ordering!");
3272  }
3273  { // INST_BINOP abbrev for FUNCTION_BLOCK.
3274  auto Abbv = std::make_shared<BitCodeAbbrev>();
3276  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3277  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3278  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3279  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3280  FUNCTION_INST_BINOP_ABBREV)
3281  llvm_unreachable("Unexpected abbrev ordering!");
3282  }
3283  { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3284  auto Abbv = std::make_shared<BitCodeAbbrev>();
3286  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3287  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3288  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3289  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3290  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3291  FUNCTION_INST_BINOP_FLAGS_ABBREV)
3292  llvm_unreachable("Unexpected abbrev ordering!");
3293  }
3294  { // INST_CAST abbrev for FUNCTION_BLOCK.
3295  auto Abbv = std::make_shared<BitCodeAbbrev>();
3297  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3298  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3300  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3301  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3302  FUNCTION_INST_CAST_ABBREV)
3303  llvm_unreachable("Unexpected abbrev ordering!");
3304  }
3305 
3306  { // INST_RET abbrev for FUNCTION_BLOCK.
3307  auto Abbv = std::make_shared<BitCodeAbbrev>();
3309  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3310  FUNCTION_INST_RET_VOID_ABBREV)
3311  llvm_unreachable("Unexpected abbrev ordering!");
3312  }
3313  { // INST_RET abbrev for FUNCTION_BLOCK.
3314  auto Abbv = std::make_shared<BitCodeAbbrev>();
3316  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3317  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3318  FUNCTION_INST_RET_VAL_ABBREV)
3319  llvm_unreachable("Unexpected abbrev ordering!");
3320  }
3321  { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3322  auto Abbv = std::make_shared<BitCodeAbbrev>();
3324  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3325  FUNCTION_INST_UNREACHABLE_ABBREV)
3326  llvm_unreachable("Unexpected abbrev ordering!");
3327  }
3328  {
3329  auto Abbv = std::make_shared<BitCodeAbbrev>();
3331  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3332  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3333  Log2_32_Ceil(VE.getTypes().size() + 1)));
3335  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3336  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3337  FUNCTION_INST_GEP_ABBREV)
3338  llvm_unreachable("Unexpected abbrev ordering!");
3339  }
3340 
3341  Stream.ExitBlock();
3342 }
3343 
3344 /// Write the module path strings, currently only used when generating
3345 /// a combined index file.
3346 void IndexBitcodeWriter::writeModStrings() {
3348 
3349  // TODO: See which abbrev sizes we actually need to emit
3350 
3351  // 8-bit fixed-width MST_ENTRY strings.
3352  auto Abbv = std::make_shared<BitCodeAbbrev>();
3354  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3356  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3357  unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3358 
3359  // 7-bit fixed width MST_ENTRY strings.
3360  Abbv = std::make_shared<BitCodeAbbrev>();
3362  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3364  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3365  unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3366 
3367  // 6-bit char6 MST_ENTRY strings.
3368  Abbv = std::make_shared<BitCodeAbbrev>();
3370  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3373  unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3374 
3375  // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3376  Abbv = std::make_shared<BitCodeAbbrev>();
3378  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3379  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3380  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3381  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3382  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3383  unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3384 
3386  forEachModule(
3387  [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3388  StringRef Key = MPSE.getKey();
3389  const auto &Value = MPSE.getValue();
3391  unsigned AbbrevToUse = Abbrev8Bit;
3392  if (Bits == SE_Char6)
3393  AbbrevToUse = Abbrev6Bit;
3394  else if (Bits == SE_Fixed7)
3395  AbbrevToUse = Abbrev7Bit;
3396 
3397  Vals.push_back(Value.first);
3398  Vals.append(Key.begin(), Key.end());
3399 
3400  // Emit the finished record.
3401  Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3402 
3403  // Emit an optional hash for the module now
3404  const auto &Hash = Value.second;
3405  if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3406  Vals.assign(Hash.begin(), Hash.end());
3407  // Emit the hash record.
3408  Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3409  }
3410 
3411  Vals.clear();
3412  });
3413  Stream.ExitBlock();
3414 }
3415 
3416 /// Write the function type metadata related records that need to appear before
3417 /// a function summary entry (whether per-module or combined).
3419  FunctionSummary *FS) {
3420  if (!FS->type_tests().empty())
3421  Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3422 
3424 
3425  auto WriteVFuncIdVec = [&](uint64_t Ty,
3427  if (VFs.empty())
3428  return;
3429  Record.clear();
3430  for (auto &VF : VFs) {
3431  Record.push_back(VF.GUID);
3432  Record.push_back(VF.Offset);
3433  }
3434  Stream.EmitRecord(Ty, Record);
3435  };
3436 
3437  WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3438  FS->type_test_assume_vcalls());
3439  WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3440  FS->type_checked_load_vcalls());
3441 
3442  auto WriteConstVCallVec = [&](uint64_t Ty,
3444  for (auto &VC : VCs) {
3445  Record.clear();
3446  Record.push_back(VC.VFunc.GUID);
3447  Record.push_back(VC.VFunc.Offset);
3448  Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3449  Stream.EmitRecord(Ty, Record);
3450  }
3451  };
3452 
3453  WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3455  WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3457 }
3458 
3459 /// Collect type IDs from type tests used by function.
3460 static void
3462  std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3463  if (!FS->type_tests().empty())
3464  for (auto &TT : FS->type_tests())
3465  ReferencedTypeIds.insert(TT);
3466 
3467  auto GetReferencedTypesFromVFuncIdVec =
3469  for (auto &VF : VFs)
3470  ReferencedTypeIds.insert(VF.GUID);
3471  };
3472 
3473  GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3474  GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3475 
3476  auto GetReferencedTypesFromConstVCallVec =
3478  for (auto &VC : VCs)
3479  ReferencedTypeIds.insert(VC.VFunc.GUID);
3480  };
3481 
3482  GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3483  GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3484 }
3485 
3487  SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3488  const WholeProgramDevirtResolution::ByArg &ByArg) {
3489  NameVals.push_back(args.size());
3490  NameVals.insert(NameVals.end(), args.begin(), args.end());
3491 
3492  NameVals.push_back(ByArg.TheKind);
3493  NameVals.push_back(ByArg.Info);
3494  NameVals.push_back(ByArg.Byte);
3495  NameVals.push_back(ByArg.Bit);
3496 }
3497 
3499  SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3500  uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3501  NameVals.push_back(Id);
3502 
3503  NameVals.push_back(Wpd.TheKind);
3504  NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3505  NameVals.push_back(Wpd.SingleImplName.size());
3506 
3507  NameVals.push_back(Wpd.ResByArg.size());
3508  for (auto &A : Wpd.ResByArg)
3509  writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3510 }
3511 
3513  StringTableBuilder &StrtabBuilder,
3514  const std::string &Id,
3515  const TypeIdSummary &Summary) {
3516  NameVals.push_back(StrtabBuilder.add(Id));
3517  NameVals.push_back(Id.size());
3518 
3519  NameVals.push_back(Summary.TTRes.TheKind);
3520  NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3521  NameVals.push_back(Summary.TTRes.AlignLog2);
3522  NameVals.push_back(Summary.TTRes.SizeM1);
3523  NameVals.push_back(Summary.TTRes.BitMask);
3524  NameVals.push_back(Summary.TTRes.InlineBits);
3525 
3526  for (auto &W : Summary.WPDRes)
3527  writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3528  W.second);
3529 }
3530 
3531 // Helper to emit a single function summary record.
3532 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3533  SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3534  unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3535  const Function &F) {
3536  NameVals.push_back(ValueID);
3537 
3538  FunctionSummary *FS = cast<FunctionSummary>(Summary);
3540 
3541  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3542  NameVals.push_back(FS->instCount());
3543  NameVals.push_back(getEncodedFFlags(FS->fflags()));
3544  NameVals.push_back(FS->refs().size());
3545  NameVals.push_back(FS->immutableRefCount());
3546 
3547  for (auto &RI : FS->refs())
3548  NameVals.push_back(VE.getValueID(RI.getValue()));
3549 
3550  bool HasProfileData =
3551  F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3552  for (auto &ECI : FS->calls()) {
3553  NameVals.push_back(getValueId(ECI.first));
3554  if (HasProfileData)
3555  NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3556  else if (WriteRelBFToSummary)
3557  NameVals.push_back(ECI.second.RelBlockFreq);
3558  }
3559 
3560  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3561  unsigned Code =
3562  (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3564  : bitc::FS_PERMODULE));
3565 
3566  // Emit the finished record.
3567  Stream.EmitRecord(Code, NameVals, FSAbbrev);
3568  NameVals.clear();
3569 }
3570 
3571 // Collect the global value references in the given variable's initializer,
3572 // and emit them in a summary record.
3573 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3574  const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3575  unsigned FSModRefsAbbrev) {
3576  auto VI = Index->getValueInfo(V.getGUID());
3577  if (!VI || VI.getSummaryList().empty()) {
3578  // Only declarations should not have a summary (a declaration might however
3579  // have a summary if the def was in module level asm).
3580  assert(V.isDeclaration());
3581  return;
3582  }
3583  auto *Summary = VI.getSummaryList()[0].get();
3584  NameVals.push_back(VE.getValueID(&V));
3585  GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3586  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3587  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3588 
3589  unsigned SizeBeforeRefs = NameVals.size();
3590  for (auto &RI : VS->refs())
3591  NameVals.push_back(VE.getValueID(RI.getValue()));
3592  // Sort the refs for determinism output, the vector returned by FS->refs() has
3593  // been initialized from a DenseSet.
3594  llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3595 
3597  FSModRefsAbbrev);
3598  NameVals.clear();
3599 }
3600 
3601 // Current version for the summary.
3602 // This is bumped whenever we introduce changes in the way some record are
3603 // interpreted, like flags for instance.
3604 static const uint64_t INDEX_VERSION = 6;
3605 
3606 /// Emit the per-module summary section alongside the rest of
3607 /// the module's bitcode.
3608 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3609  // By default we compile with ThinLTO if the module has a summary, but the
3610  // client can request full LTO with a module flag.
3611  bool IsThinLTO = true;
3612  if (auto *MD =
3613  mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3614  IsThinLTO = MD->getZExtValue();
3617  4);
3618 
3619  Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3620 
3621  // Write the index flags.
3622  uint64_t Flags = 0;
3623  // Bits 1-3 are set only in the combined index, skip them.
3624  if (Index->enableSplitLTOUnit())
3625  Flags |= 0x8;
3627 
3628  if (Index->begin() == Index->end()) {
3629  Stream.ExitBlock();
3630  return;
3631  }
3632 
3633  for (const auto &GVI : valueIds()) {
3635  ArrayRef<uint64_t>{GVI.second, GVI.first});
3636  }
3637 
3638  // Abbrev for FS_PERMODULE_PROFILE.
3639  auto Abbv = std::make_shared<BitCodeAbbrev>();
3641  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3642  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3643  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3644  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3645  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3646  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3647  // numrefs x valueid, n x (valueid, hotness)
3649  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3650  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3651 
3652  // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3653  Abbv = std::make_shared<BitCodeAbbrev>();
3654  if (WriteRelBFToSummary)
3656  else
3657  Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3658  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3659  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3660  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3661  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3662  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3663  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3664  // numrefs x valueid, n x (valueid [, rel_block_freq])
3666  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3667  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3668 
3669  // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3670  Abbv = std::make_shared<BitCodeAbbrev>();
3672  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3673  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3674  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3675  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3676  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3677 
3678  // Abbrev for FS_ALIAS.
3679  Abbv = std::make_shared<BitCodeAbbrev>();
3680  Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3681  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3682  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3683  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3684  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3685 
3686  SmallVector<uint64_t, 64> NameVals;
3687  // Iterate over the list of functions instead of the Index to
3688  // ensure the ordering is stable.
3689  for (const Function &F : M) {
3690  // Summary emission does not support anonymous functions, they have to
3691  // renamed using the anonymous function renaming pass.
3692  if (!F.hasName())
3693  report_fatal_error("Unexpected anonymous function when writing summary");
3694 
3695  ValueInfo VI = Index->getValueInfo(F.getGUID());
3696  if (!VI || VI.getSummaryList().empty()) {
3697  // Only declarations should not have a summary (a declaration might
3698  // however have a summary if the def was in module level asm).
3699  assert(F.isDeclaration());
3700  continue;
3701  }
3702  auto *Summary = VI.getSummaryList()[0].get();
3703  writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3704  FSCallsAbbrev, FSCallsProfileAbbrev, F);
3705  }
3706 
3707  // Capture references from GlobalVariable initializers, which are outside
3708  // of a function scope.
3709  for (const GlobalVariable &G : M.globals())
3710  writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3711 
3712  for (const GlobalAlias &A : M.aliases()) {
3713  auto *Aliasee = A.getBaseObject();
3714  if (!Aliasee->hasName())
3715  // Nameless function don't have an entry in the summary, skip it.
3716  continue;
3717  auto AliasId = VE.getValueID(&A);
3718  auto AliaseeId = VE.getValueID(Aliasee);
3719  NameVals.push_back(AliasId);
3720  auto *Summary = Index->getGlobalValueSummary(A);
3721  AliasSummary *AS = cast<AliasSummary>(Summary);
3722  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3723  NameVals.push_back(AliaseeId);
3724  Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3725  NameVals.clear();
3726  }
3727 
3728  Stream.ExitBlock();
3729 }
3730 
3731 /// Emit the combined summary section into the combined index file.
3732 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3734  Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3735 
3736  // Write the index flags.
3737  uint64_t Flags = 0;
3738  if (Index.withGlobalValueDeadStripping())
3739  Flags |= 0x1;
3740  if (Index.skipModuleByDistributedBackend())
3741  Flags |= 0x2;
3742  if (Index.hasSyntheticEntryCounts())
3743  Flags |= 0x4;
3744  if (Index.enableSplitLTOUnit())
3745  Flags |= 0x8;
3746  if (Index.partiallySplitLTOUnits())
3747  Flags |= 0x10;
3749 
3750  for (const auto &GVI : valueIds()) {
3752  ArrayRef<uint64_t>{GVI.second, GVI.first});
3753  }
3754 
3755  // Abbrev for FS_COMBINED.
3756  auto Abbv = std::make_shared<BitCodeAbbrev>();
3757  Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3758  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3759  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3760  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3761  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3762  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3763  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
3764  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3765  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3766  // numrefs x valueid, n x (valueid)
3768  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3769  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3770 
3771  // Abbrev for FS_COMBINED_PROFILE.
3772  Abbv = std::make_shared<BitCodeAbbrev>();
3774  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3775  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3776  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3777  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3778  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3779  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3780  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
3781  // numrefs x valueid, n x (valueid, hotness)
3783  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3784  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3785 
3786  // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3787  Abbv = std::make_shared<BitCodeAbbrev>();
3789  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3790  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3791  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3792  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3793  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3794  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3795 
3796  // Abbrev for FS_COMBINED_ALIAS.
3797  Abbv = std::make_shared<BitCodeAbbrev>();
3799  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3800  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3801  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3802  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3803  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3804 
3805  // The aliases are emitted as a post-pass, and will point to the value
3806  // id of the aliasee. Save them in a vector for post-processing.
3808 
3809  // Save the value id for each summary for alias emission.
3811 
3812  SmallVector<uint64_t, 64> NameVals;
3813 
3814  // Set that will be populated during call to writeFunctionTypeMetadataRecords
3815  // with the type ids referenced by this index file.
3816  std::set<GlobalValue::GUID> ReferencedTypeIds;
3817 
3818  // For local linkage, we also emit the original name separately
3819  // immediately after the record.
3820  auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3821  if (!GlobalValue::isLocalLinkage(S.linkage()))
3822  return;
3823  NameVals.push_back(S.getOriginalName());
3824  Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3825  NameVals.clear();
3826  };
3827 
3828  forEachSummary([&](GVInfo I, bool IsAliasee) {
3829  GlobalValueSummary *S = I.second;
3830  assert(S);
3831 
3832  auto ValueId = getValueId(I.first);
3833  assert(ValueId);
3834  SummaryToValueIdMap[S] = *ValueId;
3835 
3836  // If this is invoked for an aliasee, we want to record the above
3837  // mapping, but then not emit a summary entry (if the aliasee is
3838  // to be imported, we will invoke this separately with IsAliasee=false).
3839  if (IsAliasee)
3840  return;
3841 
3842  if (auto *AS = dyn_cast<AliasSummary>(S)) {
3843  // Will process aliases as a post-pass because the reader wants all
3844  // global to be loaded first.
3845  Aliases.push_back(AS);
3846  return;
3847  }
3848 
3849  if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3850  NameVals.push_back(*ValueId);
3851  NameVals.push_back(Index.getModuleId(VS->modulePath()));
3852  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3853  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3854  for (auto &RI : VS->refs()) {
3855  auto RefValueId = getValueId(RI.getGUID());
3856  if (!RefValueId)
3857  continue;
3858  NameVals.push_back(*RefValueId);
3859  }
3860 
3861  // Emit the finished record.
3863  FSModRefsAbbrev);
3864  NameVals.clear();
3865  MaybeEmitOriginalName(*S);
3866  return;
3867  }
3868 
3869  auto *FS = cast<FunctionSummary>(S);
3871  getReferencedTypeIds(FS, ReferencedTypeIds);
3872 
3873  NameVals.push_back(*ValueId);
3874  NameVals.push_back(Index.getModuleId(FS->modulePath()));
3875  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3876  NameVals.push_back(FS->instCount());
3877  NameVals.push_back(getEncodedFFlags(FS->fflags()));
3878  NameVals.push_back(FS->entryCount());
3879 
3880  // Fill in below
3881  NameVals.push_back(0); // numrefs
3882  NameVals.push_back(0); // immutablerefcnt
3883 
3884  unsigned Count = 0, ImmutableRefCnt = 0;
3885  for (auto &RI : FS->refs()) {
3886  auto RefValueId = getValueId(RI.getGUID());
3887  if (!RefValueId)
3888  continue;
3889  NameVals.push_back(*RefValueId);
3890  if (RI.isReadOnly())
3891  ImmutableRefCnt++;
3892  Count++;
3893  }
3894  NameVals[6] = Count;
3895  NameVals[7] = ImmutableRefCnt;
3896 
3897  bool HasProfileData = false;
3898  for (auto &EI : FS->calls()) {
3899  HasProfileData |=
3900  EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
3901  if (HasProfileData)
3902  break;
3903  }
3904 
3905  for (auto &EI : FS->calls()) {
3906  // If this GUID doesn't have a value id, it doesn't have a function
3907  // summary and we don't need to record any calls to it.
3908  GlobalValue::GUID GUID = EI.first.getGUID();
3909  auto CallValueId = getValueId(GUID);
3910  if (!CallValueId) {
3911  // For SamplePGO, the indirect call targets for local functions will
3912  // have its original name annotated in profile. We try to find the
3913  // corresponding PGOFuncName as the GUID.
3914  GUID = Index.getGUIDFromOriginalID(GUID);
3915  if (GUID == 0)
3916  continue;
3917  CallValueId = getValueId(GUID);
3918  if (!CallValueId)
3919  continue;
3920  // The mapping from OriginalId to GUID may return a GUID
3921  // that corresponds to a static variable. Filter it out here.
3922  // This can happen when
3923  // 1) There is a call to a library function which does not have
3924  // a CallValidId;
3925  // 2) There is a static variable with the OriginalGUID identical
3926  // to the GUID of the library function in 1);
3927  // When this happens, the logic for SamplePGO kicks in and
3928  // the static variable in 2) will be found, which needs to be
3929  // filtered out.
3930  auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3931  if (GVSum &&
3932  GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3933  continue;
3934  }
3935  NameVals.push_back(*CallValueId);
3936  if (HasProfileData)
3937  NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3938  }
3939 
3940  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3941  unsigned Code =
3942  (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3943 
3944  // Emit the finished record.
3945  Stream.EmitRecord(Code, NameVals, FSAbbrev);
3946  NameVals.clear();
3947  MaybeEmitOriginalName(*S);
3948  });
3949 
3950  for (auto *AS : Aliases) {
3951  auto AliasValueId = SummaryToValueIdMap[AS];
3952  assert(AliasValueId);
3953  NameVals.push_back(AliasValueId);
3954  NameVals.push_back(Index.getModuleId(AS->modulePath()));
3955  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3956  auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3957  assert(AliaseeValueId);
3958  NameVals.push_back(AliaseeValueId);
3959 
3960  // Emit the finished record.
3961  Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3962  NameVals.clear();
3963  MaybeEmitOriginalName(*AS);
3964 
3965  if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
3966  getReferencedTypeIds(FS, ReferencedTypeIds);
3967  }
3968 
3969  if (!Index.cfiFunctionDefs().empty()) {
3970  for (auto &S : Index.cfiFunctionDefs()) {
3971  NameVals.push_back(StrtabBuilder.add(S));
3972  NameVals.push_back(S.size());
3973  }
3974  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3975  NameVals.clear();
3976  }
3977 
3978  if (!Index.cfiFunctionDecls().empty()) {
3979  for (auto &S : Index.cfiFunctionDecls()) {
3980  NameVals.push_back(StrtabBuilder.add(S));
3981  NameVals.push_back(S.size());
3982  }
3983  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3984  NameVals.clear();
3985  }
3986 
3987  // Walk the GUIDs that were referenced, and write the
3988  // corresponding type id records.
3989  for (auto &T : ReferencedTypeIds) {
3990  auto TidIter = Index.typeIds().equal_range(T);
3991  for (auto It = TidIter.first; It != TidIter.second; ++It) {
3992  writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
3993  It->second.second);
3994  Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
3995  NameVals.clear();
3996  }
3997  }
3998 
3999  Stream.ExitBlock();
4000 }
4001 
4002 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4003 /// current llvm version, and a record for the epoch number.
4006 
4007  // Write the "user readable" string identifying the bitcode producer
4008  auto Abbv = std::make_shared<BitCodeAbbrev>();
4012  auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4014  "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4015 
4016  // Write the epoch version
4017  Abbv = std::make_shared<BitCodeAbbrev>();
4019  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4020  auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4022  Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4023  Stream.ExitBlock();
4024 }
4025 
4026 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4027  // Emit the module's hash.
4028  // MODULE_CODE_HASH: [5*i32]
4029  if (GenerateHash) {
4030  uint32_t Vals[5];
4031  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4032  Buffer.size() - BlockStartPos));
4033  StringRef Hash = Hasher.result();
4034  for (int Pos = 0; Pos < 20; Pos += 4) {
4035  Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4036  }
4037 
4038  // Emit the finished record.
4039  Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4040 
4041  if (ModHash)
4042  // Save the written hash value.
4043  llvm::copy(Vals, std::begin(*ModHash));
4044  }
4045 }
4046 
4048  writeIdentificationBlock(Stream);
4049 
4051  size_t BlockStartPos = Buffer.size();
4052 
4053  writeModuleVersion();
4054 
4055  // Emit blockinfo, which defines the standard abbreviations etc.
4056  writeBlockInfo();
4057 
4058  // Emit information about attribute groups.
4059  writeAttributeGroupTable();
4060 
4061  // Emit information about parameter attributes.
4062  writeAttributeTable();
4063 
4064  // Emit information describing all of the types in the module.
4065  writeTypeTable();
4066 
4067  writeComdats();
4068 
4069  // Emit top-level description of module, including target triple, inline asm,
4070  // descriptors for global variables, and function prototype info.
4071  writeModuleInfo();
4072 
4073  // Emit constants.
4074  writeModuleConstants();
4075 
4076  // Emit metadata kind names.
4077  writeModuleMetadataKinds();
4078 
4079  // Emit metadata.
4080  writeModuleMetadata();
4081 
4082  // Emit module-level use-lists.
4083  if (VE.shouldPreserveUseListOrder())
4084  writeUseListBlock(nullptr);
4085 
4086  writeOperandBundleTags();
4087  writeSyncScopeNames();
4088 
4089  // Emit function bodies.
4090  DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4091  for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
4092  if (!F->isDeclaration())
4093  writeFunction(*F, FunctionToBitcodeIndex);
4094 
4095  // Need to write after the above call to WriteFunction which populates
4096  // the summary information in the index.
4097  if (Index)
4098  writePerModuleGlobalValueSummary();
4099 
4100  writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4101 
4102  writeModuleHash(BlockStartPos);
4103 
4104  Stream.ExitBlock();
4105 }
4106 
4108  uint32_t &Position) {
4109  support::endian::write32le(&Buffer[Position], Value);
4110  Position += 4;
4111 }
4112 
4113 /// If generating a bc file on darwin, we have to emit a
4114 /// header and trailer to make it compatible with the system archiver. To do
4115 /// this we emit the following header, and then emit a trailer that pads the
4116 /// file out to be a multiple of 16 bytes.
4117 ///
4118 /// struct bc_header {
4119 /// uint32_t Magic; // 0x0B17C0DE
4120 /// uint32_t Version; // Version, currently always 0.
4121 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4122 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4123 /// uint32_t CPUType; // CPU specifier.
4124 /// ... potentially more later ...
4125 /// };
4127  const Triple &TT) {
4128  unsigned CPUType = ~0U;
4129 
4130  // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4131  // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4132  // number from /usr/include/mach/machine.h. It is ok to reproduce the
4133  // specific constants here because they are implicitly part of the Darwin ABI.
4134  enum {
4135  DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4136  DARWIN_CPU_TYPE_X86 = 7,
4137  DARWIN_CPU_TYPE_ARM = 12,
4138  DARWIN_CPU_TYPE_POWERPC = 18
4139  };
4140 
4141  Triple::ArchType Arch = TT.getArch();
4142  if (Arch == Triple::x86_64)
4143  CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4144  else if (Arch == Triple::x86)
4145  CPUType = DARWIN_CPU_TYPE_X86;
4146  else if (Arch == Triple::ppc)
4147  CPUType = DARWIN_CPU_TYPE_POWERPC;
4148  else if (Arch == Triple::ppc64)
4149  CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4150  else if (Arch == Triple::arm || Arch == Triple::thumb)
4151  CPUType = DARWIN_CPU_TYPE_ARM;
4152 
4153  // Traditional Bitcode starts after header.
4154  assert(Buffer.size() >= BWH_HeaderSize &&
4155  "Expected header size to be reserved");
4156  unsigned BCOffset = BWH_HeaderSize;
4157  unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4158 
4159  // Write the magic and version.
4160  unsigned Position = 0;
4161  writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4162  writeInt32ToBuffer(0, Buffer, Position); // Version.
4163  writeInt32ToBuffer(BCOffset, Buffer, Position);
4164  writeInt32ToBuffer(BCSize, Buffer, Position);
4165  writeInt32ToBuffer(CPUType, Buffer, Position);
4166 
4167  // If the file is not a multiple of 16 bytes, insert dummy padding.
4168  while (Buffer.size() & 15)
4169  Buffer.push_back(0);
4170 }
4171 
4172 /// Helper to write the header common to all bitcode files.
4173 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4174  // Emit the file header.
4175  Stream.Emit((unsigned)'B', 8);
4176  Stream.Emit((unsigned)'C', 8);
4177  Stream.Emit(0x0, 4);
4178  Stream.Emit(0xC, 4);
4179  Stream.Emit(0xE, 4);
4180  Stream.Emit(0xD, 4);
4181 }
4182 
4184  : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4185  writeBitcodeHeader(*Stream);
4186 }
4187 
4189 
4190 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4191  Stream->EnterSubblock(Block, 3);
4192 
4193  auto Abbv = std::make_shared<BitCodeAbbrev>();
4194  Abbv->Add(BitCodeAbbrevOp(Record));
4196  auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4197 
4198  Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4199 
4200  Stream->ExitBlock();
4201 }
4202 
4204  assert(!WroteStrtab && !WroteSymtab);
4205 
4206  // If any module has module-level inline asm, we will require a registered asm
4207  // parser for the target so that we can create an accurate symbol table for
4208  // the module.
4209  for (Module *M : Mods) {
4210  if (M->getModuleInlineAsm().empty())
4211  continue;
4212 
4213  std::string Err;
4214  const Triple TT(M->getTargetTriple());
4215  const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4216  if (!T || !T->hasMCAsmParser())
4217  return;
4218  }
4219 
4220  WroteSymtab = true;
4221  SmallVector<char, 0> Symtab;
4222  // The irsymtab::build function may be unable to create a symbol table if the
4223  // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4224  // table is not required for correctness, but we still want to be able to
4225  // write malformed modules to bitcode files, so swallow the error.
4226  if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4227  consumeError(std::move(E));
4228  return;
4229  }
4230 
4232  {Symtab.data(), Symtab.size()});
4233 }
4234 
4236  assert(!WroteStrtab);
4237 
4238  std::vector<char> Strtab;
4239  StrtabBuilder.finalizeInOrder();
4240  Strtab.resize(StrtabBuilder.getSize());
4241  StrtabBuilder.write((uint8_t *)Strtab.data());
4242 
4244  {Strtab.data(), Strtab.size()});
4245 
4246  WroteStrtab = true;
4247 }
4248 
4250  writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4251  WroteStrtab = true;
4252 }
4253 
4255  bool ShouldPreserveUseListOrder,
4256  const ModuleSummaryIndex *Index,
4257  bool GenerateHash, ModuleHash *ModHash) {
4258  assert(!WroteStrtab);
4259 
4260  // The Mods vector is used by irsymtab::build, which requires non-const
4261  // Modules in case it needs to materialize metadata. But the bitcode writer
4262  // requires that the module is materialized, so we can cast to non-const here,
4263  // after checking that it is in fact materialized.
4264  assert(M.isMaterialized());
4265  Mods.push_back(const_cast<Module *>(&M));
4266 
4267  ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4268  ShouldPreserveUseListOrder, Index,
4269  GenerateHash, ModHash);
4270  ModuleWriter.write();
4271 }
4272 
4274  const ModuleSummaryIndex *Index,
4275  const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4276  IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4277  ModuleToSummariesForIndex);
4278  IndexWriter.write();
4279 }
4280 
4281 /// Write the specified module to the specified output stream.
4283  bool ShouldPreserveUseListOrder,
4284  const ModuleSummaryIndex *Index,
4285  bool GenerateHash, ModuleHash *ModHash) {
4286  SmallVector<char, 0> Buffer;
4287  Buffer.reserve(256*1024);
4288 
4289  // If this is darwin or another generic macho target, reserve space for the
4290  // header.
4291  Triple TT(M.getTargetTriple());
4292  if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4293  Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4294 
4295  BitcodeWriter Writer(Buffer);
4296  Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4297  ModHash);
4298  Writer.writeSymtab();
4299  Writer.writeStrtab();
4300 
4301  if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4302  emitDarwinBCHeaderAndTrailer(Buffer, TT);
4303 
4304  // Write the generated bitstream to "Out".
4305  Out.write((char*)&Buffer.front(), Buffer.size());
4306 }
4307 
4310 
4311  writeModuleVersion();
4312 
4313  // Write the module paths in the combined index.
4314  writeModStrings();
4315 
4316  // Write the summary combined index records.
4317  writeCombinedGlobalValueSummary();
4318 
4319  Stream.ExitBlock();
4320 }
4321 
4322 // Write the specified module summary index to the given raw output stream,
4323 // where it will be written in a new bitcode block. This is used when
4324 // writing the combined index file for ThinLTO. When writing a subset of the
4325 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4327  const ModuleSummaryIndex &Index, raw_ostream &Out,
4328  const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4329  SmallVector<char, 0> Buffer;
4330  Buffer.reserve(256 * 1024);
4331 
4332  BitcodeWriter Writer(Buffer);
4333  Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4334  Writer.writeStrtab();
4335 
4336  Out.write((char *)&Buffer.front(), Buffer.size());
4337 }
4338 
4339 namespace {
4340 
4341 /// Class to manage the bitcode writing for a thin link bitcode file.
4342 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4343  /// ModHash is for use in ThinLTO incremental build, generated while writing
4344  /// the module bitcode file.
4345  const ModuleHash *ModHash;
4346 
4347 public:
4348  ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4349  BitstreamWriter &Stream,
4350  const ModuleSummaryIndex &Index,
4351  const ModuleHash &ModHash)
4352  : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4353  /*ShouldPreserveUseListOrder=*/false, &Index),
4354  ModHash(&ModHash) {}
4355 
4356  void write();
4357 
4358 private:
4359  void writeSimplifiedModuleInfo();
4360 };
4361 
4362 } // end anonymous namespace
4363 
4364 // This function writes a simpilified module info for thin link bitcode file.
4365 // It only contains the source file name along with the name(the offset and
4366 // size in strtab) and linkage for global values. For the global value info
4367 // entry, in order to keep linkage at offset 5, there are three zeros used
4368 // as padding.
4369 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4371  // Emit the module's source file name.
4372  {
4375  if (Bits == SE_Char6)
4376  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4377  else if (Bits == SE_Fixed7)
4378  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4379 
4380  // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4381  auto Abbv = std::make_shared<BitCodeAbbrev>();
4384  Abbv->Add(AbbrevOpToUse);
4385  unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4386 
4387  for (const auto P : M.getSourceFileName())
4388  Vals.push_back((unsigned char)P);
4389 
4390  Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4391  Vals.clear();
4392  }
4393 
4394  // Emit the global variable information.
4395  for (const GlobalVariable &GV : M.globals()) {
4396  // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4397  Vals.push_back(StrtabBuilder.add(GV.getName()));
4398  Vals.push_back(GV.getName().size());
4399  Vals.push_back(0);
4400  Vals.push_back(0);
4401  Vals.push_back(0);
4402  Vals.push_back(getEncodedLinkage(GV));
4403 
4405  Vals.clear();
4406  }
4407 
4408  // Emit the function proto information.
4409  for (const Function &F : M) {
4410  // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4411  Vals.push_back(StrtabBuilder.add(F.getName()));
4412  Vals.push_back(F.getName().size());
4413  Vals.push_back(0);
4414  Vals.push_back(0);
4415  Vals.push_back(0);
4416  Vals.push_back(getEncodedLinkage(F));
4417 
4418  Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4419  Vals.clear();
4420  }
4421 
4422  // Emit the alias information.
4423  for (const GlobalAlias &A : M.aliases()) {
4424  // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4425  Vals.push_back(StrtabBuilder.add(A.getName()));
4426  Vals.push_back(A.getName().size());
4427  Vals.push_back(0);
4428  Vals.push_back(0);
4429  Vals.push_back(0);
4430  Vals.push_back(getEncodedLinkage(A));
4431 
4432  Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4433  Vals.clear();
4434  }
4435 
4436  // Emit the ifunc information.
4437  for (const GlobalIFunc &I : M.ifuncs()) {
4438  // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4439  Vals.push_back(StrtabBuilder.add(I.getName()));
4440  Vals.push_back(I.getName().size());
4441  Vals.push_back(0);
4442  Vals.push_back(0);
4443  Vals.push_back(0);
4444  Vals.push_back(getEncodedLinkage(I));
4445 
4446  Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4447  Vals.clear();
4448  }
4449 }
4450 
4453 
4454  writeModuleVersion();
4455 
4456  writeSimplifiedModuleInfo();
4457 
4458  writePerModuleGlobalValueSummary();
4459 
4460  // Write module hash.
4462 
4463  Stream.ExitBlock();
4464 }
4465 
4467  const ModuleSummaryIndex &Index,
4468  const ModuleHash &ModHash) {
4469  assert(!WroteStrtab);
4470 
4471  // The Mods vector is used by irsymtab::build, which requires non-const
4472  // Modules in case it needs to materialize metadata. But the bitcode writer
4473  // requires that the module is materialized, so we can cast to non-const here,
4474  // after checking that it is in fact materialized.
4475  assert(M.isMaterialized());
4476  Mods.push_back(const_cast<Module *>(&M));
4477 
4478  ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4479  ModHash);
4480  ThinLinkWriter.write();
4481 }
4482 
4483 // Write the specified thin link bitcode file to the given raw output stream,
4484 // where it will be written in a new bitcode block. This is used when
4485 // writing the per-module index file for ThinLTO.
4487  const ModuleSummaryIndex &Index,
4488  const ModuleHash &ModHash) {
4489  SmallVector<char, 0> Buffer;
4490  Buffer.reserve(256 * 1024);
4491 
4492  BitcodeWriter Writer(Buffer);
4493  Writer.writeThinLinkBitcode(M, Index, ModHash);
4494  Writer.writeSymtab();
4495  Writer.writeStrtab();
4496 
4497  Out.write((char *)&Buffer.front(), Buffer.size());
4498 }
DIFlags getFlags() const
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
uint64_t CallInst * C
bool hasOperandBundles() const
Return true if this User has any operand bundles.
Definition: InstrTypes.h:1605
MDString * getRawName() const
7: Labels
Definition: Type.h:64
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition: MathExtras.h:552
void writeIndex(const ModuleSummaryIndex *Index, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex)
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:240
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:255
ArrayRef< uint64_t > getElements() const
This class provides a symbol table of name/value pairs.
uint64_t getOffsetInBits() const
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
bool isDistinct() const
Definition: Metadata.h:943
This instruction extracts a struct member or array element value from an aggregate value...
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:55
unsigned getLine() const
*p = old <signed v ? old : v
Definition: Instructions.h:722
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
bool haveGVs() const
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:250
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, TypePrinting *, SlotTracker *, const Module *)
Definition: AsmWriter.cpp:1821
static uint64_t getOptimizationFlags(const Value *V)
unsigned getMetadataOrNullID(const Metadata *MD) const
Atomic ordering constants.
unsigned getValueID(const Value *V) const
const ValueList & getValues() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:493
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:24
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
const unsigned char * bytes_end() const
Definition: StringRef.h:113
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Definition: StringMap.h:126
unsigned getRuntimeVersion() const
unsigned Linkage
The linkage type of the associated global value.
bool hasMetadataOtherThanDebugLoc() const
Return true if this instruction has metadata attached to it other than a debug location.
Definition: Instruction.h:215
MDString * getRawName() const
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
2: 32-bit floating point type
Definition: Type.h:59
MDString * getRawName() const
iterator end()
Definition: Function.h:658
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:54
const GlobalValue * getValue() const
ArrayRef< VFuncId > type_test_assume_vcalls() const
Returns the list of virtual calls made by this function using llvm.assume(llvm.type.test) intrinsics that do not have all constant integer arguments.
Metadata * getRawFile() const
Global variable summary information to aid decisions and implementation of importing.
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
Available for inspection, not emission.
Definition: GlobalValue.h:50
DIFile * getFile() const
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
DITypeRef getBaseType() const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
unsigned getDiscriminator() const
bool isFP128Ty() const
Return true if this is &#39;fp128&#39;.
Definition: Type.h:156
MDString * getRawValue() const
This class represents a function call, abstracting a target machine&#39;s calling convention.
This file contains the declarations for metadata subclasses.
void setInstructionID(const Instruction *I)
Value * getCondition() const
The two locations do not alias at all.
Definition: AliasAnalysis.h:84
bool shouldPreserveUseListOrder() const
StringEncoding
*p = old <unsigned v ? old : v
Definition: Instructions.h:726
void writeSymtab()
Attempt to write a symbol table to the bitcode file.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:136
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
uint64_t Info
Additional information for the resolution:
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
*p = old >unsigned v ? old : v
Definition: Instructions.h:724
Externally visible function.
Definition: GlobalValue.h:49
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:39
DICompositeTypeArray getEnumTypes() const
const std::string & getDataLayoutStr() const
Get the data layout string for the module&#39;s target platform.
Definition: Module.h:231
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, TypePrinting *TypePrinter, SlotTracker *Machine, const Module *Context)
Definition: AsmWriter.cpp:2017
uint64_t getDWOId() const
BasicBlock * getSuccessor(unsigned i) const
void write32le(void *P, uint32_t V)
Definition: Endian.h:404
13: Structures
Definition: Type.h:73
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
Metadata node.
Definition: Metadata.h:864
F(f)
4: 80-bit floating point type (X87)
Definition: Type.h:61
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1069
A class that wrap the SHA1 algorithm.
Definition: SHA1.h:29
1: 16-bit floating point type
Definition: Type.h:58
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Definition: DerivedTypes.h:269
Value * getCondition() const
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
unsigned index_end() const
Definition: Attributes.h:644
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
15: Pointers
Definition: Type.h:75
static void writeDILocation(raw_ostream &Out, const DILocation *DL, TypePrinting *TypePrinter, SlotTracker *Machine, const Module *Context)
Definition: AsmWriter.cpp:1777
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, TypePrinting *TypePrinter, SlotTracker *Machine, const Module *Context)
Definition: AsmWriter.cpp:2042
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
Definition: Metadata.cpp:1417
void reserve(size_type N)
Definition: SmallVector.h:376
bool hasMDs() const
Check whether the current block has any metadata to emit.