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