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 /// The start bit of the identification block.
112 uint64_t BitcodeStartBit;
114 /// Map that holds the correspondence between GUIDs in the summary index,
115 /// that came from indirect call profiles, and a value id generated by this
116 /// class to use in the VST and summary block records.
117 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
119 /// Tracks the last value id recorded in the GUIDToValueMap.
120 unsigned GlobalValueId;
123 /// Constructs a ModuleBitcodeWriter object for the given Module,
124 /// writing to the provided \p Buffer.
125 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
126 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
127 const ModuleSummaryIndex *Index, bool GenerateHash)
128 : BitcodeWriterBase(Stream), Buffer(Buffer), M(*M),
129 VE(*M, ShouldPreserveUseListOrder), Index(Index),
130 GenerateHash(GenerateHash), BitcodeStartBit(Stream.GetCurrentBitNo()) {
131 // Assign ValueIds to any callee values in the index that came from
132 // indirect call profiles and were recorded as a GUID not a Value*
133 // (which would have been assigned an ID by the ValueEnumerator).
134 // The starting ValueId is just after the number of values in the
135 // ValueEnumerator, so that they can be emitted in the VST.
136 GlobalValueId = VE.getValues().size();
139 for (const auto &GUIDSummaryLists : *Index)
140 // Examine all summaries for this GUID.
141 for (auto &Summary : GUIDSummaryLists.second)
142 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
143 // For each call in the function summary, see if the call
144 // is to a GUID (which means it is for an indirect call,
145 // otherwise we would have a Value for it). If so, synthesize
147 for (auto &CallEdge : FS->calls())
148 if (CallEdge.first.isGUID())
149 assignValueId(CallEdge.first.getGUID());
152 /// Emit the current module to the bitstream.
156 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
158 void writeAttributeGroupTable();
159 void writeAttributeTable();
160 void writeTypeTable();
162 void writeModuleInfo();
163 void writeValueAsMetadata(const ValueAsMetadata *MD,
164 SmallVectorImpl<uint64_t> &Record);
165 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
167 unsigned createDILocationAbbrev();
168 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
170 unsigned createGenericDINodeAbbrev();
171 void writeGenericDINode(const GenericDINode *N,
172 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
173 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
175 void writeDIEnumerator(const DIEnumerator *N,
176 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
177 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
179 void writeDIDerivedType(const DIDerivedType *N,
180 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
181 void writeDICompositeType(const DICompositeType *N,
182 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
183 void writeDISubroutineType(const DISubroutineType *N,
184 SmallVectorImpl<uint64_t> &Record,
186 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
188 void writeDICompileUnit(const DICompileUnit *N,
189 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
190 void writeDISubprogram(const DISubprogram *N,
191 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
192 void writeDILexicalBlock(const DILexicalBlock *N,
193 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
194 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
195 SmallVectorImpl<uint64_t> &Record,
197 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
199 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
201 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
203 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
205 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
206 SmallVectorImpl<uint64_t> &Record,
208 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
209 SmallVectorImpl<uint64_t> &Record,
211 void writeDIGlobalVariable(const DIGlobalVariable *N,
212 SmallVectorImpl<uint64_t> &Record,
214 void writeDILocalVariable(const DILocalVariable *N,
215 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
216 void writeDIExpression(const DIExpression *N,
217 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
218 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
219 SmallVectorImpl<uint64_t> &Record,
221 void writeDIObjCProperty(const DIObjCProperty *N,
222 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
223 void writeDIImportedEntity(const DIImportedEntity *N,
224 SmallVectorImpl<uint64_t> &Record,
226 unsigned createNamedMetadataAbbrev();
227 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
228 unsigned createMetadataStringsAbbrev();
229 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
230 SmallVectorImpl<uint64_t> &Record);
231 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
232 SmallVectorImpl<uint64_t> &Record,
233 std::vector<unsigned> *MDAbbrevs = nullptr,
234 std::vector<uint64_t> *IndexPos = nullptr);
235 void writeModuleMetadata();
236 void writeFunctionMetadata(const Function &F);
237 void writeFunctionMetadataAttachment(const Function &F);
238 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
239 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
240 const GlobalObject &GO);
241 void writeModuleMetadataKinds();
242 void writeOperandBundleTags();
243 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
244 void writeModuleConstants();
245 bool pushValueAndType(const Value *V, unsigned InstID,
246 SmallVectorImpl<unsigned> &Vals);
247 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
248 void pushValue(const Value *V, unsigned InstID,
249 SmallVectorImpl<unsigned> &Vals);
250 void pushValueSigned(const Value *V, unsigned InstID,
251 SmallVectorImpl<uint64_t> &Vals);
252 void writeInstruction(const Instruction &I, unsigned InstID,
253 SmallVectorImpl<unsigned> &Vals);
254 void writeValueSymbolTable(
255 const ValueSymbolTable &VST, bool IsModuleLevel = false,
256 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr);
257 void writeUseList(UseListOrder &&Order);
258 void writeUseListBlock(const Function *F);
260 writeFunction(const Function &F,
261 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
262 void writeBlockInfo();
263 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
264 GlobalValueSummary *Summary,
266 unsigned FSCallsAbbrev,
267 unsigned FSCallsProfileAbbrev,
269 void writeModuleLevelReferences(const GlobalVariable &V,
270 SmallVector<uint64_t, 64> &NameVals,
271 unsigned FSModRefsAbbrev);
272 void writePerModuleGlobalValueSummary();
273 void writeModuleHash(size_t BlockStartPos);
275 void assignValueId(GlobalValue::GUID ValGUID) {
276 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
278 unsigned getValueId(GlobalValue::GUID ValGUID) {
279 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
280 // Expect that any GUID value had a value Id assigned by an
281 // earlier call to assignValueId.
282 assert(VMI != GUIDToValueIdMap.end() &&
283 "GUID does not have assigned value Id");
286 // Helper to get the valueId for the type of value recorded in VI.
287 unsigned getValueId(ValueInfo VI) {
289 return getValueId(VI.getGUID());
290 return VE.getValueID(VI.getValue());
292 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
295 /// Class to manage the bitcode writing for a combined index.
296 class IndexBitcodeWriter : public BitcodeWriterBase {
297 /// The combined index to write to bitcode.
298 const ModuleSummaryIndex &Index;
300 /// When writing a subset of the index for distributed backends, client
301 /// provides a map of modules to the corresponding GUIDs/summaries to write.
302 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
304 /// Map that holds the correspondence between the GUID used in the combined
305 /// index and a value id generated by this class to use in references.
306 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
308 /// Tracks the last value id recorded in the GUIDToValueMap.
309 unsigned GlobalValueId = 0;
312 /// Constructs a IndexBitcodeWriter object for the given combined index,
313 /// writing to the provided \p Buffer. When writing a subset of the index
314 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
315 IndexBitcodeWriter(BitstreamWriter &Stream, const ModuleSummaryIndex &Index,
316 const std::map<std::string, GVSummaryMapTy>
317 *ModuleToSummariesForIndex = nullptr)
318 : BitcodeWriterBase(Stream), Index(Index),
319 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
320 // Assign unique value ids to all summaries to be written, for use
321 // in writing out the call graph edges. Save the mapping from GUID
322 // to the new global value id to use when writing those edges, which
323 // are currently saved in the index in terms of GUID.
324 for (const auto &I : *this)
325 GUIDToValueIdMap[I.first] = ++GlobalValueId;
328 /// The below iterator returns the GUID and associated summary.
329 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
331 /// Iterator over the value GUID and summaries to be written to bitcode,
332 /// hides the details of whether they are being pulled from the entire
333 /// index or just those in a provided ModuleToSummariesForIndex map.
335 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
337 /// Enables access to parent class.
338 const IndexBitcodeWriter &Writer;
340 // Iterators used when writing only those summaries in a provided
341 // ModuleToSummariesForIndex map:
343 /// Points to the last element in outer ModuleToSummariesForIndex map.
344 std::map<std::string, GVSummaryMapTy>::const_iterator ModuleSummariesBack;
345 /// Iterator on outer ModuleToSummariesForIndex map.
346 std::map<std::string, GVSummaryMapTy>::const_iterator ModuleSummariesIter;
347 /// Iterator on an inner global variable summary map.
348 GVSummaryMapTy::const_iterator ModuleGVSummariesIter;
350 // Iterators used when writing all summaries in the index:
352 /// Points to the last element in the Index outer GlobalValueMap.
353 const_gvsummary_iterator IndexSummariesBack;
354 /// Iterator on outer GlobalValueMap.
355 const_gvsummary_iterator IndexSummariesIter;
356 /// Iterator on an inner GlobalValueSummaryList.
357 GlobalValueSummaryList::const_iterator IndexGVSummariesIter;
360 /// Construct iterator from parent \p Writer and indicate if we are
361 /// constructing the end iterator.
362 iterator(const IndexBitcodeWriter &Writer, bool IsAtEnd) : Writer(Writer) {
363 // Set up the appropriate set of iterators given whether we are writing
364 // the full index or just a subset.
365 // Can't setup the Back or inner iterators if the corresponding map
366 // is empty. This will be handled specially in operator== as well.
367 if (Writer.ModuleToSummariesForIndex &&
368 !Writer.ModuleToSummariesForIndex->empty()) {
369 for (ModuleSummariesBack = Writer.ModuleToSummariesForIndex->begin();
370 std::next(ModuleSummariesBack) !=
371 Writer.ModuleToSummariesForIndex->end();
372 ModuleSummariesBack++)
374 ModuleSummariesIter = !IsAtEnd
375 ? Writer.ModuleToSummariesForIndex->begin()
376 : ModuleSummariesBack;
377 ModuleGVSummariesIter = !IsAtEnd ? ModuleSummariesIter->second.begin()
378 : ModuleSummariesBack->second.end();
379 } else if (!Writer.ModuleToSummariesForIndex &&
380 Writer.Index.begin() != Writer.Index.end()) {
381 for (IndexSummariesBack = Writer.Index.begin();
382 std::next(IndexSummariesBack) != Writer.Index.end();
383 IndexSummariesBack++)
386 !IsAtEnd ? Writer.Index.begin() : IndexSummariesBack;
387 IndexGVSummariesIter = !IsAtEnd ? IndexSummariesIter->second.begin()
388 : IndexSummariesBack->second.end();
392 /// Increment the appropriate set of iterators.
393 iterator &operator++() {
394 // First the inner iterator is incremented, then if it is at the end
395 // and there are more outer iterations to go, the inner is reset to
396 // the start of the next inner list.
397 if (Writer.ModuleToSummariesForIndex) {
398 ++ModuleGVSummariesIter;
399 if (ModuleGVSummariesIter == ModuleSummariesIter->second.end() &&
400 ModuleSummariesIter != ModuleSummariesBack) {
401 ++ModuleSummariesIter;
402 ModuleGVSummariesIter = ModuleSummariesIter->second.begin();
405 ++IndexGVSummariesIter;
406 if (IndexGVSummariesIter == IndexSummariesIter->second.end() &&
407 IndexSummariesIter != IndexSummariesBack) {
408 ++IndexSummariesIter;
409 IndexGVSummariesIter = IndexSummariesIter->second.begin();
415 /// Access the <GUID,GlobalValueSummary*> pair corresponding to the current
416 /// outer and inner iterator positions.
418 if (Writer.ModuleToSummariesForIndex)
419 return std::make_pair(ModuleGVSummariesIter->first,
420 ModuleGVSummariesIter->second);
421 return std::make_pair(IndexSummariesIter->first,
422 IndexGVSummariesIter->get());
425 /// Checks if the iterators are equal, with special handling for empty
427 bool operator==(const iterator &RHS) const {
428 if (Writer.ModuleToSummariesForIndex) {
429 // First ensure that both are writing the same subset.
430 if (Writer.ModuleToSummariesForIndex !=
431 RHS.Writer.ModuleToSummariesForIndex)
433 // Already determined above that maps are the same, so if one is
434 // empty, they both are.
435 if (Writer.ModuleToSummariesForIndex->empty())
437 // Ensure the ModuleGVSummariesIter are iterating over the same
438 // container before checking them below.
439 if (ModuleSummariesIter != RHS.ModuleSummariesIter)
441 return ModuleGVSummariesIter == RHS.ModuleGVSummariesIter;
443 // First ensure RHS also writing the full index, and that both are
444 // writing the same full index.
445 if (RHS.Writer.ModuleToSummariesForIndex ||
446 &Writer.Index != &RHS.Writer.Index)
448 // Already determined above that maps are the same, so if one is
449 // empty, they both are.
450 if (Writer.Index.begin() == Writer.Index.end())
452 // Ensure the IndexGVSummariesIter are iterating over the same
453 // container before checking them below.
454 if (IndexSummariesIter != RHS.IndexSummariesIter)
456 return IndexGVSummariesIter == RHS.IndexGVSummariesIter;
460 /// Obtain the start iterator over the summaries to be written.
461 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
462 /// Obtain the end iterator over the summaries to be written.
463 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
465 /// Main entry point for writing a combined index to bitcode.
470 void writeModStrings();
471 void writeCombinedValueSymbolTable();
472 void writeCombinedGlobalValueSummary();
474 /// Indicates whether the provided \p ModulePath should be written into
475 /// the module string table, e.g. if full index written or if it is in
476 /// the provided subset.
477 bool doIncludeModule(StringRef ModulePath) {
478 return !ModuleToSummariesForIndex ||
479 ModuleToSummariesForIndex->count(ModulePath);
482 bool hasValueId(GlobalValue::GUID ValGUID) {
483 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
484 return VMI != GUIDToValueIdMap.end();
486 unsigned getValueId(GlobalValue::GUID ValGUID) {
487 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
488 // If this GUID doesn't have an entry, assign one.
489 if (VMI == GUIDToValueIdMap.end()) {
490 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
491 return GlobalValueId;
496 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
498 } // end anonymous namespace
500 static unsigned getEncodedCastOpcode(unsigned Opcode) {
502 default: llvm_unreachable("Unknown cast instruction!");
503 case Instruction::Trunc : return bitc::CAST_TRUNC;
504 case Instruction::ZExt : return bitc::CAST_ZEXT;
505 case Instruction::SExt : return bitc::CAST_SEXT;
506 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
507 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
508 case Instruction::UIToFP : return bitc::CAST_UITOFP;
509 case Instruction::SIToFP : return bitc::CAST_SITOFP;
510 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
511 case Instruction::FPExt : return bitc::CAST_FPEXT;
512 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
513 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
514 case Instruction::BitCast : return bitc::CAST_BITCAST;
515 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
519 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
521 default: llvm_unreachable("Unknown binary instruction!");
522 case Instruction::Add:
523 case Instruction::FAdd: return bitc::BINOP_ADD;
524 case Instruction::Sub:
525 case Instruction::FSub: return bitc::BINOP_SUB;
526 case Instruction::Mul:
527 case Instruction::FMul: return bitc::BINOP_MUL;
528 case Instruction::UDiv: return bitc::BINOP_UDIV;
529 case Instruction::FDiv:
530 case Instruction::SDiv: return bitc::BINOP_SDIV;
531 case Instruction::URem: return bitc::BINOP_UREM;
532 case Instruction::FRem:
533 case Instruction::SRem: return bitc::BINOP_SREM;
534 case Instruction::Shl: return bitc::BINOP_SHL;
535 case Instruction::LShr: return bitc::BINOP_LSHR;
536 case Instruction::AShr: return bitc::BINOP_ASHR;
537 case Instruction::And: return bitc::BINOP_AND;
538 case Instruction::Or: return bitc::BINOP_OR;
539 case Instruction::Xor: return bitc::BINOP_XOR;
543 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
545 default: llvm_unreachable("Unknown RMW operation!");
546 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
547 case AtomicRMWInst::Add: return bitc::RMW_ADD;
548 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
549 case AtomicRMWInst::And: return bitc::RMW_AND;
550 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
551 case AtomicRMWInst::Or: return bitc::RMW_OR;
552 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
553 case AtomicRMWInst::Max: return bitc::RMW_MAX;
554 case AtomicRMWInst::Min: return bitc::RMW_MIN;
555 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
556 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
560 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
562 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
563 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
564 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
565 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
566 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
567 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
568 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
570 llvm_unreachable("Invalid ordering");
573 static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
574 switch (SynchScope) {
575 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
576 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
578 llvm_unreachable("Invalid synch scope");
581 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
582 StringRef Str, unsigned AbbrevToUse) {
583 SmallVector<unsigned, 64> Vals;
585 // Code: [strchar x N]
586 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
587 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
589 Vals.push_back(Str[i]);
592 // Emit the finished record.
593 Stream.EmitRecord(Code, Vals, AbbrevToUse);
596 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
598 case Attribute::Alignment:
599 return bitc::ATTR_KIND_ALIGNMENT;
600 case Attribute::AllocSize:
601 return bitc::ATTR_KIND_ALLOC_SIZE;
602 case Attribute::AlwaysInline:
603 return bitc::ATTR_KIND_ALWAYS_INLINE;
604 case Attribute::ArgMemOnly:
605 return bitc::ATTR_KIND_ARGMEMONLY;
606 case Attribute::Builtin:
607 return bitc::ATTR_KIND_BUILTIN;
608 case Attribute::ByVal:
609 return bitc::ATTR_KIND_BY_VAL;
610 case Attribute::Convergent:
611 return bitc::ATTR_KIND_CONVERGENT;
612 case Attribute::InAlloca:
613 return bitc::ATTR_KIND_IN_ALLOCA;
614 case Attribute::Cold:
615 return bitc::ATTR_KIND_COLD;
616 case Attribute::InaccessibleMemOnly:
617 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
618 case Attribute::InaccessibleMemOrArgMemOnly:
619 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
620 case Attribute::InlineHint:
621 return bitc::ATTR_KIND_INLINE_HINT;
622 case Attribute::InReg:
623 return bitc::ATTR_KIND_IN_REG;
624 case Attribute::JumpTable:
625 return bitc::ATTR_KIND_JUMP_TABLE;
626 case Attribute::MinSize:
627 return bitc::ATTR_KIND_MIN_SIZE;
628 case Attribute::Naked:
629 return bitc::ATTR_KIND_NAKED;
630 case Attribute::Nest:
631 return bitc::ATTR_KIND_NEST;
632 case Attribute::NoAlias:
633 return bitc::ATTR_KIND_NO_ALIAS;
634 case Attribute::NoBuiltin:
635 return bitc::ATTR_KIND_NO_BUILTIN;
636 case Attribute::NoCapture:
637 return bitc::ATTR_KIND_NO_CAPTURE;
638 case Attribute::NoDuplicate:
639 return bitc::ATTR_KIND_NO_DUPLICATE;
640 case Attribute::NoImplicitFloat:
641 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
642 case Attribute::NoInline:
643 return bitc::ATTR_KIND_NO_INLINE;
644 case Attribute::NoRecurse:
645 return bitc::ATTR_KIND_NO_RECURSE;
646 case Attribute::NonLazyBind:
647 return bitc::ATTR_KIND_NON_LAZY_BIND;
648 case Attribute::NonNull:
649 return bitc::ATTR_KIND_NON_NULL;
650 case Attribute::Dereferenceable:
651 return bitc::ATTR_KIND_DEREFERENCEABLE;
652 case Attribute::DereferenceableOrNull:
653 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
654 case Attribute::NoRedZone:
655 return bitc::ATTR_KIND_NO_RED_ZONE;
656 case Attribute::NoReturn:
657 return bitc::ATTR_KIND_NO_RETURN;
658 case Attribute::NoUnwind:
659 return bitc::ATTR_KIND_NO_UNWIND;
660 case Attribute::OptimizeForSize:
661 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
662 case Attribute::OptimizeNone:
663 return bitc::ATTR_KIND_OPTIMIZE_NONE;
664 case Attribute::ReadNone:
665 return bitc::ATTR_KIND_READ_NONE;
666 case Attribute::ReadOnly:
667 return bitc::ATTR_KIND_READ_ONLY;
668 case Attribute::Returned:
669 return bitc::ATTR_KIND_RETURNED;
670 case Attribute::ReturnsTwice:
671 return bitc::ATTR_KIND_RETURNS_TWICE;
672 case Attribute::SExt:
673 return bitc::ATTR_KIND_S_EXT;
674 case Attribute::StackAlignment:
675 return bitc::ATTR_KIND_STACK_ALIGNMENT;
676 case Attribute::StackProtect:
677 return bitc::ATTR_KIND_STACK_PROTECT;
678 case Attribute::StackProtectReq:
679 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
680 case Attribute::StackProtectStrong:
681 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
682 case Attribute::SafeStack:
683 return bitc::ATTR_KIND_SAFESTACK;
684 case Attribute::StructRet:
685 return bitc::ATTR_KIND_STRUCT_RET;
686 case Attribute::SanitizeAddress:
687 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
688 case Attribute::SanitizeThread:
689 return bitc::ATTR_KIND_SANITIZE_THREAD;
690 case Attribute::SanitizeMemory:
691 return bitc::ATTR_KIND_SANITIZE_MEMORY;
692 case Attribute::SwiftError:
693 return bitc::ATTR_KIND_SWIFT_ERROR;
694 case Attribute::SwiftSelf:
695 return bitc::ATTR_KIND_SWIFT_SELF;
696 case Attribute::UWTable:
697 return bitc::ATTR_KIND_UW_TABLE;
698 case Attribute::WriteOnly:
699 return bitc::ATTR_KIND_WRITEONLY;
700 case Attribute::ZExt:
701 return bitc::ATTR_KIND_Z_EXT;
702 case Attribute::EndAttrKinds:
703 llvm_unreachable("Can not encode end-attribute kinds marker.");
704 case Attribute::None:
705 llvm_unreachable("Can not encode none-attribute.");
708 llvm_unreachable("Trying to encode unknown attribute");
711 void ModuleBitcodeWriter::writeAttributeGroupTable() {
712 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
713 if (AttrGrps.empty()) return;
715 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
717 SmallVector<uint64_t, 64> Record;
718 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
719 AttributeSet AS = AttrGrps[i];
720 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
721 AttributeSet A = AS.getSlotAttributes(i);
723 Record.push_back(VE.getAttributeGroupID(A));
724 Record.push_back(AS.getSlotIndex(i));
726 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
729 if (Attr.isEnumAttribute()) {
731 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
732 } else if (Attr.isIntAttribute()) {
734 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
735 Record.push_back(Attr.getValueAsInt());
737 StringRef Kind = Attr.getKindAsString();
738 StringRef Val = Attr.getValueAsString();
740 Record.push_back(Val.empty() ? 3 : 4);
741 Record.append(Kind.begin(), Kind.end());
744 Record.append(Val.begin(), Val.end());
750 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
758 void ModuleBitcodeWriter::writeAttributeTable() {
759 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
760 if (Attrs.empty()) return;
762 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
764 SmallVector<uint64_t, 64> Record;
765 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
766 const AttributeSet &A = Attrs[i];
767 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
768 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
770 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
777 /// WriteTypeTable - Write out the type table for a module.
778 void ModuleBitcodeWriter::writeTypeTable() {
779 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
781 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
782 SmallVector<uint64_t, 64> TypeVals;
784 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
786 // Abbrev for TYPE_CODE_POINTER.
787 auto Abbv = std::make_shared<BitCodeAbbrev>();
788 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
790 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
791 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
793 // Abbrev for TYPE_CODE_FUNCTION.
794 Abbv = std::make_shared<BitCodeAbbrev>();
795 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
800 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
802 // Abbrev for TYPE_CODE_STRUCT_ANON.
803 Abbv = std::make_shared<BitCodeAbbrev>();
804 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
809 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
811 // Abbrev for TYPE_CODE_STRUCT_NAME.
812 Abbv = std::make_shared<BitCodeAbbrev>();
813 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
816 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
818 // Abbrev for TYPE_CODE_STRUCT_NAMED.
819 Abbv = std::make_shared<BitCodeAbbrev>();
820 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
825 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
827 // Abbrev for TYPE_CODE_ARRAY.
828 Abbv = std::make_shared<BitCodeAbbrev>();
829 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
833 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
835 // Emit an entry count so the reader can reserve space.
836 TypeVals.push_back(TypeList.size());
837 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
840 // Loop over all of the types, emitting each in turn.
841 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
842 Type *T = TypeList[i];
846 switch (T->getTypeID()) {
847 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
848 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
849 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
850 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
851 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
852 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
853 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
854 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
855 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
856 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
857 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
858 case Type::IntegerTyID:
860 Code = bitc::TYPE_CODE_INTEGER;
861 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
863 case Type::PointerTyID: {
864 PointerType *PTy = cast<PointerType>(T);
865 // POINTER: [pointee type, address space]
866 Code = bitc::TYPE_CODE_POINTER;
867 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
868 unsigned AddressSpace = PTy->getAddressSpace();
869 TypeVals.push_back(AddressSpace);
870 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
873 case Type::FunctionTyID: {
874 FunctionType *FT = cast<FunctionType>(T);
875 // FUNCTION: [isvararg, retty, paramty x N]
876 Code = bitc::TYPE_CODE_FUNCTION;
877 TypeVals.push_back(FT->isVarArg());
878 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
879 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
880 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
881 AbbrevToUse = FunctionAbbrev;
884 case Type::StructTyID: {
885 StructType *ST = cast<StructType>(T);
886 // STRUCT: [ispacked, eltty x N]
887 TypeVals.push_back(ST->isPacked());
888 // Output all of the element types.
889 for (StructType::element_iterator I = ST->element_begin(),
890 E = ST->element_end(); I != E; ++I)
891 TypeVals.push_back(VE.getTypeID(*I));
893 if (ST->isLiteral()) {
894 Code = bitc::TYPE_CODE_STRUCT_ANON;
895 AbbrevToUse = StructAnonAbbrev;
897 if (ST->isOpaque()) {
898 Code = bitc::TYPE_CODE_OPAQUE;
900 Code = bitc::TYPE_CODE_STRUCT_NAMED;
901 AbbrevToUse = StructNamedAbbrev;
904 // Emit the name if it is present.
905 if (!ST->getName().empty())
906 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
911 case Type::ArrayTyID: {
912 ArrayType *AT = cast<ArrayType>(T);
913 // ARRAY: [numelts, eltty]
914 Code = bitc::TYPE_CODE_ARRAY;
915 TypeVals.push_back(AT->getNumElements());
916 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
917 AbbrevToUse = ArrayAbbrev;
920 case Type::VectorTyID: {
921 VectorType *VT = cast<VectorType>(T);
922 // VECTOR [numelts, eltty]
923 Code = bitc::TYPE_CODE_VECTOR;
924 TypeVals.push_back(VT->getNumElements());
925 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
930 // Emit the finished record.
931 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
938 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
940 case GlobalValue::ExternalLinkage:
942 case GlobalValue::WeakAnyLinkage:
944 case GlobalValue::AppendingLinkage:
946 case GlobalValue::InternalLinkage:
948 case GlobalValue::LinkOnceAnyLinkage:
950 case GlobalValue::ExternalWeakLinkage:
952 case GlobalValue::CommonLinkage:
954 case GlobalValue::PrivateLinkage:
956 case GlobalValue::WeakODRLinkage:
958 case GlobalValue::LinkOnceODRLinkage:
960 case GlobalValue::AvailableExternallyLinkage:
963 llvm_unreachable("Invalid linkage");
966 static unsigned getEncodedLinkage(const GlobalValue &GV) {
967 return getEncodedLinkage(GV.getLinkage());
970 // Decode the flags for GlobalValue in the summary
971 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
972 uint64_t RawFlags = 0;
974 RawFlags |= Flags.NotEligibleToImport; // bool
975 RawFlags |= (Flags.LiveRoot << 1);
976 // Linkage don't need to be remapped at that time for the summary. Any future
977 // change to the getEncodedLinkage() function will need to be taken into
978 // account here as well.
979 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
984 static unsigned getEncodedVisibility(const GlobalValue &GV) {
985 switch (GV.getVisibility()) {
986 case GlobalValue::DefaultVisibility: return 0;
987 case GlobalValue::HiddenVisibility: return 1;
988 case GlobalValue::ProtectedVisibility: return 2;
990 llvm_unreachable("Invalid visibility");
993 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
994 switch (GV.getDLLStorageClass()) {
995 case GlobalValue::DefaultStorageClass: return 0;
996 case GlobalValue::DLLImportStorageClass: return 1;
997 case GlobalValue::DLLExportStorageClass: return 2;
999 llvm_unreachable("Invalid DLL storage class");
1002 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1003 switch (GV.getThreadLocalMode()) {
1004 case GlobalVariable::NotThreadLocal: return 0;
1005 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1006 case GlobalVariable::LocalDynamicTLSModel: return 2;
1007 case GlobalVariable::InitialExecTLSModel: return 3;
1008 case GlobalVariable::LocalExecTLSModel: return 4;
1010 llvm_unreachable("Invalid TLS model");
1013 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1014 switch (C.getSelectionKind()) {
1016 return bitc::COMDAT_SELECTION_KIND_ANY;
1017 case Comdat::ExactMatch:
1018 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1019 case Comdat::Largest:
1020 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1021 case Comdat::NoDuplicates:
1022 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1023 case Comdat::SameSize:
1024 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1026 llvm_unreachable("Invalid selection kind");
1029 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1030 switch (GV.getUnnamedAddr()) {
1031 case GlobalValue::UnnamedAddr::None: return 0;
1032 case GlobalValue::UnnamedAddr::Local: return 2;
1033 case GlobalValue::UnnamedAddr::Global: return 1;
1035 llvm_unreachable("Invalid unnamed_addr");
1038 void ModuleBitcodeWriter::writeComdats() {
1039 SmallVector<unsigned, 64> Vals;
1040 for (const Comdat *C : VE.getComdats()) {
1041 // COMDAT: [selection_kind, name]
1042 Vals.push_back(getEncodedComdatSelectionKind(*C));
1043 size_t Size = C->getName().size();
1044 assert(isUInt<32>(Size));
1045 Vals.push_back(Size);
1046 for (char Chr : C->getName())
1047 Vals.push_back((unsigned char)Chr);
1048 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1053 /// Write a record that will eventually hold the word offset of the
1054 /// module-level VST. For now the offset is 0, which will be backpatched
1055 /// after the real VST is written. Saves the bit offset to backpatch.
1056 void BitcodeWriterBase::writeValueSymbolTableForwardDecl() {
1057 // Write a placeholder value in for the offset of the real VST,
1058 // which is written after the function blocks so that it can include
1059 // the offset of each function. The placeholder offset will be
1060 // updated when the real VST is written.
1061 auto Abbv = std::make_shared<BitCodeAbbrev>();
1062 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1063 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1064 // hold the real VST offset. Must use fixed instead of VBR as we don't
1065 // know how many VBR chunks to reserve ahead of time.
1066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1067 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1069 // Emit the placeholder
1070 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1071 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1073 // Compute and save the bit offset to the placeholder, which will be
1074 // patched when the real VST is written. We can simply subtract the 32-bit
1075 // fixed size from the current bit number to get the location to backpatch.
1076 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1079 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1081 /// Determine the encoding to use for the given string name and length.
1082 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
1083 bool isChar6 = true;
1084 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
1086 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1087 if ((unsigned char)*C & 128)
1088 // don't bother scanning the rest.
1097 /// Emit top-level description of module, including target triple, inline asm,
1098 /// descriptors for global variables, and function prototype info.
1099 /// Returns the bit offset to backpatch with the location of the real VST.
1100 void ModuleBitcodeWriter::writeModuleInfo() {
1101 // Emit various pieces of data attached to a module.
1102 if (!M.getTargetTriple().empty())
1103 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1105 const std::string &DL = M.getDataLayoutStr();
1107 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1108 if (!M.getModuleInlineAsm().empty())
1109 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1112 // Emit information about sections and GC, computing how many there are. Also
1113 // compute the maximum alignment value.
1114 std::map<std::string, unsigned> SectionMap;
1115 std::map<std::string, unsigned> GCMap;
1116 unsigned MaxAlignment = 0;
1117 unsigned MaxGlobalType = 0;
1118 for (const GlobalValue &GV : M.globals()) {
1119 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1120 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1121 if (GV.hasSection()) {
1122 // Give section names unique ID's.
1123 unsigned &Entry = SectionMap[GV.getSection()];
1125 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1127 Entry = SectionMap.size();
1131 for (const Function &F : M) {
1132 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1133 if (F.hasSection()) {
1134 // Give section names unique ID's.
1135 unsigned &Entry = SectionMap[F.getSection()];
1137 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1139 Entry = SectionMap.size();
1143 // Same for GC names.
1144 unsigned &Entry = GCMap[F.getGC()];
1146 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1148 Entry = GCMap.size();
1153 // Emit abbrev for globals, now that we know # sections and max alignment.
1154 unsigned SimpleGVarAbbrev = 0;
1155 if (!M.global_empty()) {
1156 // Add an abbrev for common globals with no visibility or thread localness.
1157 auto Abbv = std::make_shared<BitCodeAbbrev>();
1158 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1160 Log2_32_Ceil(MaxGlobalType+1)));
1161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1162 //| explicitType << 1
1164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1166 if (MaxAlignment == 0) // Alignment.
1167 Abbv->Add(BitCodeAbbrevOp(0));
1169 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1171 Log2_32_Ceil(MaxEncAlignment+1)));
1173 if (SectionMap.empty()) // Section.
1174 Abbv->Add(BitCodeAbbrevOp(0));
1176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1177 Log2_32_Ceil(SectionMap.size()+1)));
1178 // Don't bother emitting vis + thread local.
1179 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1182 // Emit the global variable information.
1183 SmallVector<unsigned, 64> Vals;
1184 for (const GlobalVariable &GV : M.globals()) {
1185 unsigned AbbrevToUse = 0;
1187 // GLOBALVAR: [type, isconst, initid,
1188 // linkage, alignment, section, visibility, threadlocal,
1189 // unnamed_addr, externally_initialized, dllstorageclass,
1191 Vals.push_back(VE.getTypeID(GV.getValueType()));
1192 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1193 Vals.push_back(GV.isDeclaration() ? 0 :
1194 (VE.getValueID(GV.getInitializer()) + 1));
1195 Vals.push_back(getEncodedLinkage(GV));
1196 Vals.push_back(Log2_32(GV.getAlignment())+1);
1197 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1198 if (GV.isThreadLocal() ||
1199 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1200 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1201 GV.isExternallyInitialized() ||
1202 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1204 Vals.push_back(getEncodedVisibility(GV));
1205 Vals.push_back(getEncodedThreadLocalMode(GV));
1206 Vals.push_back(getEncodedUnnamedAddr(GV));
1207 Vals.push_back(GV.isExternallyInitialized());
1208 Vals.push_back(getEncodedDLLStorageClass(GV));
1209 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1211 AbbrevToUse = SimpleGVarAbbrev;
1214 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1218 // Emit the function proto information.
1219 for (const Function &F : M) {
1220 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
1221 // section, visibility, gc, unnamed_addr, prologuedata,
1222 // dllstorageclass, comdat, prefixdata, personalityfn]
1223 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1224 Vals.push_back(F.getCallingConv());
1225 Vals.push_back(F.isDeclaration());
1226 Vals.push_back(getEncodedLinkage(F));
1227 Vals.push_back(VE.getAttributeID(F.getAttributes()));
1228 Vals.push_back(Log2_32(F.getAlignment())+1);
1229 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1230 Vals.push_back(getEncodedVisibility(F));
1231 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1232 Vals.push_back(getEncodedUnnamedAddr(F));
1233 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1235 Vals.push_back(getEncodedDLLStorageClass(F));
1236 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1237 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1240 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1242 unsigned AbbrevToUse = 0;
1243 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1247 // Emit the alias information.
1248 for (const GlobalAlias &A : M.aliases()) {
1249 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass,
1250 // threadlocal, unnamed_addr]
1251 Vals.push_back(VE.getTypeID(A.getValueType()));
1252 Vals.push_back(A.getType()->getAddressSpace());
1253 Vals.push_back(VE.getValueID(A.getAliasee()));
1254 Vals.push_back(getEncodedLinkage(A));
1255 Vals.push_back(getEncodedVisibility(A));
1256 Vals.push_back(getEncodedDLLStorageClass(A));
1257 Vals.push_back(getEncodedThreadLocalMode(A));
1258 Vals.push_back(getEncodedUnnamedAddr(A));
1259 unsigned AbbrevToUse = 0;
1260 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1264 // Emit the ifunc information.
1265 for (const GlobalIFunc &I : M.ifuncs()) {
1266 // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility]
1267 Vals.push_back(VE.getTypeID(I.getValueType()));
1268 Vals.push_back(I.getType()->getAddressSpace());
1269 Vals.push_back(VE.getValueID(I.getResolver()));
1270 Vals.push_back(getEncodedLinkage(I));
1271 Vals.push_back(getEncodedVisibility(I));
1272 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1276 // Emit the module's source file name.
1278 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1279 M.getSourceFileName().size());
1280 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1281 if (Bits == SE_Char6)
1282 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1283 else if (Bits == SE_Fixed7)
1284 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1286 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1287 auto Abbv = std::make_shared<BitCodeAbbrev>();
1288 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1290 Abbv->Add(AbbrevOpToUse);
1291 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1293 for (const auto P : M.getSourceFileName())
1294 Vals.push_back((unsigned char)P);
1296 // Emit the finished record.
1297 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1301 // If we have a VST, write the VSTOFFSET record placeholder.
1302 if (M.getValueSymbolTable().empty())
1304 writeValueSymbolTableForwardDecl();
1307 static uint64_t getOptimizationFlags(const Value *V) {
1310 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1311 if (OBO->hasNoSignedWrap())
1312 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1313 if (OBO->hasNoUnsignedWrap())
1314 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1315 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1317 Flags |= 1 << bitc::PEO_EXACT;
1318 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1319 if (FPMO->hasUnsafeAlgebra())
1320 Flags |= FastMathFlags::UnsafeAlgebra;
1321 if (FPMO->hasNoNaNs())
1322 Flags |= FastMathFlags::NoNaNs;
1323 if (FPMO->hasNoInfs())
1324 Flags |= FastMathFlags::NoInfs;
1325 if (FPMO->hasNoSignedZeros())
1326 Flags |= FastMathFlags::NoSignedZeros;
1327 if (FPMO->hasAllowReciprocal())
1328 Flags |= FastMathFlags::AllowReciprocal;
1334 void ModuleBitcodeWriter::writeValueAsMetadata(
1335 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1336 // Mimic an MDNode with a value as one operand.
1337 Value *V = MD->getValue();
1338 Record.push_back(VE.getTypeID(V->getType()));
1339 Record.push_back(VE.getValueID(V));
1340 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1344 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1345 SmallVectorImpl<uint64_t> &Record,
1347 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1348 Metadata *MD = N->getOperand(i);
1349 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1350 "Unexpected function-local metadata");
1351 Record.push_back(VE.getMetadataOrNullID(MD));
1353 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1354 : bitc::METADATA_NODE,
1359 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1360 // Assume the column is usually under 128, and always output the inlined-at
1361 // location (it's never more expensive than building an array size 1).
1362 auto Abbv = std::make_shared<BitCodeAbbrev>();
1363 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1369 return Stream.EmitAbbrev(std::move(Abbv));
1372 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1373 SmallVectorImpl<uint64_t> &Record,
1376 Abbrev = createDILocationAbbrev();
1378 Record.push_back(N->isDistinct());
1379 Record.push_back(N->getLine());
1380 Record.push_back(N->getColumn());
1381 Record.push_back(VE.getMetadataID(N->getScope()));
1382 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1384 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1388 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1389 // Assume the column is usually under 128, and always output the inlined-at
1390 // location (it's never more expensive than building an array size 1).
1391 auto Abbv = std::make_shared<BitCodeAbbrev>();
1392 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1393 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1394 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1399 return Stream.EmitAbbrev(std::move(Abbv));
1402 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1403 SmallVectorImpl<uint64_t> &Record,
1406 Abbrev = createGenericDINodeAbbrev();
1408 Record.push_back(N->isDistinct());
1409 Record.push_back(N->getTag());
1410 Record.push_back(0); // Per-tag version field; unused for now.
1412 for (auto &I : N->operands())
1413 Record.push_back(VE.getMetadataOrNullID(I));
1415 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1419 static uint64_t rotateSign(int64_t I) {
1421 return I < 0 ? ~(U << 1) : U << 1;
1424 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1425 SmallVectorImpl<uint64_t> &Record,
1427 Record.push_back(N->isDistinct());
1428 Record.push_back(N->getCount());
1429 Record.push_back(rotateSign(N->getLowerBound()));
1431 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1435 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1436 SmallVectorImpl<uint64_t> &Record,
1438 Record.push_back(N->isDistinct());
1439 Record.push_back(rotateSign(N->getValue()));
1440 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1442 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1446 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1447 SmallVectorImpl<uint64_t> &Record,
1449 Record.push_back(N->isDistinct());
1450 Record.push_back(N->getTag());
1451 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1452 Record.push_back(N->getSizeInBits());
1453 Record.push_back(N->getAlignInBits());
1454 Record.push_back(N->getEncoding());
1456 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1460 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1461 SmallVectorImpl<uint64_t> &Record,
1463 Record.push_back(N->isDistinct());
1464 Record.push_back(N->getTag());
1465 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1466 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1467 Record.push_back(N->getLine());
1468 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1469 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1470 Record.push_back(N->getSizeInBits());
1471 Record.push_back(N->getAlignInBits());
1472 Record.push_back(N->getOffsetInBits());
1473 Record.push_back(N->getFlags());
1474 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1476 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1480 void ModuleBitcodeWriter::writeDICompositeType(
1481 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1483 const unsigned IsNotUsedInOldTypeRef = 0x2;
1484 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1485 Record.push_back(N->getTag());
1486 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1487 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1488 Record.push_back(N->getLine());
1489 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1490 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1491 Record.push_back(N->getSizeInBits());
1492 Record.push_back(N->getAlignInBits());
1493 Record.push_back(N->getOffsetInBits());
1494 Record.push_back(N->getFlags());
1495 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1496 Record.push_back(N->getRuntimeLang());
1497 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1498 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1499 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1501 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1505 void ModuleBitcodeWriter::writeDISubroutineType(
1506 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1508 const unsigned HasNoOldTypeRefs = 0x2;
1509 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1510 Record.push_back(N->getFlags());
1511 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1512 Record.push_back(N->getCC());
1514 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1518 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1519 SmallVectorImpl<uint64_t> &Record,
1521 Record.push_back(N->isDistinct());
1522 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1523 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1524 Record.push_back(N->getChecksumKind());
1525 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1527 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1531 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1532 SmallVectorImpl<uint64_t> &Record,
1534 assert(N->isDistinct() && "Expected distinct compile units");
1535 Record.push_back(/* IsDistinct */ true);
1536 Record.push_back(N->getSourceLanguage());
1537 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1538 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1539 Record.push_back(N->isOptimized());
1540 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1541 Record.push_back(N->getRuntimeVersion());
1542 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1543 Record.push_back(N->getEmissionKind());
1544 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1545 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1546 Record.push_back(/* subprograms */ 0);
1547 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1548 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1549 Record.push_back(N->getDWOId());
1550 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1551 Record.push_back(N->getSplitDebugInlining());
1553 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1557 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1558 SmallVectorImpl<uint64_t> &Record,
1560 uint64_t HasUnitFlag = 1 << 1;
1561 Record.push_back(N->isDistinct() | HasUnitFlag);
1562 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1563 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1564 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1565 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1566 Record.push_back(N->getLine());
1567 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1568 Record.push_back(N->isLocalToUnit());
1569 Record.push_back(N->isDefinition());
1570 Record.push_back(N->getScopeLine());
1571 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1572 Record.push_back(N->getVirtuality());
1573 Record.push_back(N->getVirtualIndex());
1574 Record.push_back(N->getFlags());
1575 Record.push_back(N->isOptimized());
1576 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1577 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1578 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1579 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1580 Record.push_back(N->getThisAdjustment());
1582 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1586 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1587 SmallVectorImpl<uint64_t> &Record,
1589 Record.push_back(N->isDistinct());
1590 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1591 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1592 Record.push_back(N->getLine());
1593 Record.push_back(N->getColumn());
1595 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1599 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1600 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1602 Record.push_back(N->isDistinct());
1603 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1604 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1605 Record.push_back(N->getDiscriminator());
1607 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1611 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1612 SmallVectorImpl<uint64_t> &Record,
1614 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1615 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1616 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1617 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1618 Record.push_back(N->getLine());
1620 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1624 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1625 SmallVectorImpl<uint64_t> &Record,
1627 Record.push_back(N->isDistinct());
1628 Record.push_back(N->getMacinfoType());
1629 Record.push_back(N->getLine());
1630 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1631 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1633 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1637 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1638 SmallVectorImpl<uint64_t> &Record,
1640 Record.push_back(N->isDistinct());
1641 Record.push_back(N->getMacinfoType());
1642 Record.push_back(N->getLine());
1643 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1644 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1646 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1650 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1651 SmallVectorImpl<uint64_t> &Record,
1653 Record.push_back(N->isDistinct());
1654 for (auto &I : N->operands())
1655 Record.push_back(VE.getMetadataOrNullID(I));
1657 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1661 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1662 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1664 Record.push_back(N->isDistinct());
1665 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1666 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1668 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1672 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1673 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1675 Record.push_back(N->isDistinct());
1676 Record.push_back(N->getTag());
1677 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1678 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1679 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1681 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1685 void ModuleBitcodeWriter::writeDIGlobalVariable(
1686 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1688 const uint64_t Version = 1 << 1;
1689 Record.push_back((uint64_t)N->isDistinct() | Version);
1690 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1691 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1692 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1693 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1694 Record.push_back(N->getLine());
1695 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1696 Record.push_back(N->isLocalToUnit());
1697 Record.push_back(N->isDefinition());
1698 Record.push_back(/* expr */ 0);
1699 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1700 Record.push_back(N->getAlignInBits());
1702 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1706 void ModuleBitcodeWriter::writeDILocalVariable(
1707 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1709 // In order to support all possible bitcode formats in BitcodeReader we need
1710 // to distinguish the following cases:
1711 // 1) Record has no artificial tag (Record[1]),
1712 // has no obsolete inlinedAt field (Record[9]).
1713 // In this case Record size will be 8, HasAlignment flag is false.
1714 // 2) Record has artificial tag (Record[1]),
1715 // has no obsolete inlignedAt field (Record[9]).
1716 // In this case Record size will be 9, HasAlignment flag is false.
1717 // 3) Record has both artificial tag (Record[1]) and
1718 // obsolete inlignedAt field (Record[9]).
1719 // In this case Record size will be 10, HasAlignment flag is false.
1720 // 4) Record has neither artificial tag, nor inlignedAt field, but
1721 // HasAlignment flag is true and Record[8] contains alignment value.
1722 const uint64_t HasAlignmentFlag = 1 << 1;
1723 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1724 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1725 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1726 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1727 Record.push_back(N->getLine());
1728 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1729 Record.push_back(N->getArg());
1730 Record.push_back(N->getFlags());
1731 Record.push_back(N->getAlignInBits());
1733 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1737 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1738 SmallVectorImpl<uint64_t> &Record,
1740 Record.reserve(N->getElements().size() + 1);
1742 const uint64_t HasOpFragmentFlag = 1 << 1;
1743 Record.push_back((uint64_t)N->isDistinct() | HasOpFragmentFlag);
1744 Record.append(N->elements_begin(), N->elements_end());
1746 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1750 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1751 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1753 Record.push_back(N->isDistinct());
1754 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1755 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1757 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1761 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1762 SmallVectorImpl<uint64_t> &Record,
1764 Record.push_back(N->isDistinct());
1765 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1766 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1767 Record.push_back(N->getLine());
1768 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1769 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1770 Record.push_back(N->getAttributes());
1771 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1773 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1777 void ModuleBitcodeWriter::writeDIImportedEntity(
1778 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1780 Record.push_back(N->isDistinct());
1781 Record.push_back(N->getTag());
1782 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1783 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1784 Record.push_back(N->getLine());
1785 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1787 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1791 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1792 auto Abbv = std::make_shared<BitCodeAbbrev>();
1793 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1796 return Stream.EmitAbbrev(std::move(Abbv));
1799 void ModuleBitcodeWriter::writeNamedMetadata(
1800 SmallVectorImpl<uint64_t> &Record) {
1801 if (M.named_metadata_empty())
1804 unsigned Abbrev = createNamedMetadataAbbrev();
1805 for (const NamedMDNode &NMD : M.named_metadata()) {
1807 StringRef Str = NMD.getName();
1808 Record.append(Str.bytes_begin(), Str.bytes_end());
1809 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1812 // Write named metadata operands.
1813 for (const MDNode *N : NMD.operands())
1814 Record.push_back(VE.getMetadataID(N));
1815 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1820 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1821 auto Abbv = std::make_shared<BitCodeAbbrev>();
1822 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1826 return Stream.EmitAbbrev(std::move(Abbv));
1829 /// Write out a record for MDString.
1831 /// All the metadata strings in a metadata block are emitted in a single
1832 /// record. The sizes and strings themselves are shoved into a blob.
1833 void ModuleBitcodeWriter::writeMetadataStrings(
1834 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1835 if (Strings.empty())
1838 // Start the record with the number of strings.
1839 Record.push_back(bitc::METADATA_STRINGS);
1840 Record.push_back(Strings.size());
1842 // Emit the sizes of the strings in the blob.
1843 SmallString<256> Blob;
1845 BitstreamWriter W(Blob);
1846 for (const Metadata *MD : Strings)
1847 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1851 // Add the offset to the strings to the record.
1852 Record.push_back(Blob.size());
1854 // Add the strings to the blob.
1855 for (const Metadata *MD : Strings)
1856 Blob.append(cast<MDString>(MD)->getString());
1858 // Emit the final record.
1859 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1863 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1864 enum MetadataAbbrev : unsigned {
1865 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1866 #include "llvm/IR/Metadata.def"
1870 void ModuleBitcodeWriter::writeMetadataRecords(
1871 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1872 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1876 // Initialize MDNode abbreviations.
1877 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1878 #include "llvm/IR/Metadata.def"
1880 for (const Metadata *MD : MDs) {
1882 IndexPos->push_back(Stream.GetCurrentBitNo());
1883 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1884 assert(N->isResolved() && "Expected forward references to be resolved");
1886 switch (N->getMetadataID()) {
1888 llvm_unreachable("Invalid MDNode subclass");
1889 #define HANDLE_MDNODE_LEAF(CLASS) \
1890 case Metadata::CLASS##Kind: \
1892 write##CLASS(cast<CLASS>(N), Record, \
1893 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1895 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1897 #include "llvm/IR/Metadata.def"
1900 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1904 void ModuleBitcodeWriter::writeModuleMetadata() {
1905 if (!VE.hasMDs() && M.named_metadata_empty())
1908 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1909 SmallVector<uint64_t, 64> Record;
1911 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1912 // block and load any metadata.
1913 std::vector<unsigned> MDAbbrevs;
1915 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1916 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1917 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1918 createGenericDINodeAbbrev();
1920 auto Abbv = std::make_shared<BitCodeAbbrev>();
1921 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1922 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1923 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1924 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1926 Abbv = std::make_shared<BitCodeAbbrev>();
1927 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1928 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1930 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1932 // Emit MDStrings together upfront.
1933 writeMetadataStrings(VE.getMDStrings(), Record);
1935 // We only emit an index for the metadata record if we have more than a given
1936 // (naive) threshold of metadatas, otherwise it is not worth it.
1937 if (VE.getNonMDStrings().size() > IndexThreshold) {
1938 // Write a placeholder value in for the offset of the metadata index,
1939 // which is written after the records, so that it can include
1940 // the offset of each entry. The placeholder offset will be
1941 // updated after all records are emitted.
1942 uint64_t Vals[] = {0, 0};
1943 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1946 // Compute and save the bit offset to the current position, which will be
1947 // patched when we emit the index later. We can simply subtract the 64-bit
1948 // fixed size from the current bit number to get the location to backpatch.
1949 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1951 // This index will contain the bitpos for each individual record.
1952 std::vector<uint64_t> IndexPos;
1953 IndexPos.reserve(VE.getNonMDStrings().size());
1955 // Write all the records
1956 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1958 if (VE.getNonMDStrings().size() > IndexThreshold) {
1959 // Now that we have emitted all the records we will emit the index. But
1961 // backpatch the forward reference so that the reader can skip the records
1963 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1964 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1966 // Delta encode the index.
1967 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1968 for (auto &Elt : IndexPos) {
1969 auto EltDelta = Elt - PreviousValue;
1970 PreviousValue = Elt;
1973 // Emit the index record.
1974 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1978 // Write the named metadata now.
1979 writeNamedMetadata(Record);
1981 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1982 SmallVector<uint64_t, 4> Record;
1983 Record.push_back(VE.getValueID(&GO));
1984 pushGlobalMetadataAttachment(Record, GO);
1985 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1987 for (const Function &F : M)
1988 if (F.isDeclaration() && F.hasMetadata())
1989 AddDeclAttachedMetadata(F);
1990 // FIXME: Only store metadata for declarations here, and move data for global
1991 // variable definitions to a separate block (PR28134).
1992 for (const GlobalVariable &GV : M.globals())
1993 if (GV.hasMetadata())
1994 AddDeclAttachedMetadata(GV);
1999 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2003 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2004 SmallVector<uint64_t, 64> Record;
2005 writeMetadataStrings(VE.getMDStrings(), Record);
2006 writeMetadataRecords(VE.getNonMDStrings(), Record);
2010 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2011 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2012 // [n x [id, mdnode]]
2013 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2014 GO.getAllMetadata(MDs);
2015 for (const auto &I : MDs) {
2016 Record.push_back(I.first);
2017 Record.push_back(VE.getMetadataID(I.second));
2021 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2022 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2024 SmallVector<uint64_t, 64> Record;
2026 if (F.hasMetadata()) {
2027 pushGlobalMetadataAttachment(Record, F);
2028 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2032 // Write metadata attachments
2033 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2034 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2035 for (const BasicBlock &BB : F)
2036 for (const Instruction &I : BB) {
2038 I.getAllMetadataOtherThanDebugLoc(MDs);
2040 // If no metadata, ignore instruction.
2041 if (MDs.empty()) continue;
2043 Record.push_back(VE.getInstructionID(&I));
2045 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2046 Record.push_back(MDs[i].first);
2047 Record.push_back(VE.getMetadataID(MDs[i].second));
2049 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2056 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2057 SmallVector<uint64_t, 64> Record;
2059 // Write metadata kinds
2060 // METADATA_KIND - [n x [id, name]]
2061 SmallVector<StringRef, 8> Names;
2062 M.getMDKindNames(Names);
2064 if (Names.empty()) return;
2066 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2068 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2069 Record.push_back(MDKindID);
2070 StringRef KName = Names[MDKindID];
2071 Record.append(KName.begin(), KName.end());
2073 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2080 void ModuleBitcodeWriter::writeOperandBundleTags() {
2081 // Write metadata kinds
2083 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2085 // OPERAND_BUNDLE_TAG - [strchr x N]
2087 SmallVector<StringRef, 8> Tags;
2088 M.getOperandBundleTags(Tags);
2093 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2095 SmallVector<uint64_t, 64> Record;
2097 for (auto Tag : Tags) {
2098 Record.append(Tag.begin(), Tag.end());
2100 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2107 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2108 if ((int64_t)V >= 0)
2109 Vals.push_back(V << 1);
2111 Vals.push_back((-V << 1) | 1);
2114 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2116 if (FirstVal == LastVal) return;
2118 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2120 unsigned AggregateAbbrev = 0;
2121 unsigned String8Abbrev = 0;
2122 unsigned CString7Abbrev = 0;
2123 unsigned CString6Abbrev = 0;
2124 // If this is a constant pool for the module, emit module-specific abbrevs.
2126 // Abbrev for CST_CODE_AGGREGATE.
2127 auto Abbv = std::make_shared<BitCodeAbbrev>();
2128 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2131 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2133 // Abbrev for CST_CODE_STRING.
2134 Abbv = std::make_shared<BitCodeAbbrev>();
2135 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2138 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2139 // Abbrev for CST_CODE_CSTRING.
2140 Abbv = std::make_shared<BitCodeAbbrev>();
2141 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2144 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2145 // Abbrev for CST_CODE_CSTRING.
2146 Abbv = std::make_shared<BitCodeAbbrev>();
2147 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2150 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2153 SmallVector<uint64_t, 64> Record;
2155 const ValueEnumerator::ValueList &Vals = VE.getValues();
2156 Type *LastTy = nullptr;
2157 for (unsigned i = FirstVal; i != LastVal; ++i) {
2158 const Value *V = Vals[i].first;
2159 // If we need to switch types, do so now.
2160 if (V->getType() != LastTy) {
2161 LastTy = V->getType();
2162 Record.push_back(VE.getTypeID(LastTy));
2163 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2164 CONSTANTS_SETTYPE_ABBREV);
2168 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2169 Record.push_back(unsigned(IA->hasSideEffects()) |
2170 unsigned(IA->isAlignStack()) << 1 |
2171 unsigned(IA->getDialect()&1) << 2);
2173 // Add the asm string.
2174 const std::string &AsmStr = IA->getAsmString();
2175 Record.push_back(AsmStr.size());
2176 Record.append(AsmStr.begin(), AsmStr.end());
2178 // Add the constraint string.
2179 const std::string &ConstraintStr = IA->getConstraintString();
2180 Record.push_back(ConstraintStr.size());
2181 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2182 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2186 const Constant *C = cast<Constant>(V);
2187 unsigned Code = -1U;
2188 unsigned AbbrevToUse = 0;
2189 if (C->isNullValue()) {
2190 Code = bitc::CST_CODE_NULL;
2191 } else if (isa<UndefValue>(C)) {
2192 Code = bitc::CST_CODE_UNDEF;
2193 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2194 if (IV->getBitWidth() <= 64) {
2195 uint64_t V = IV->getSExtValue();
2196 emitSignedInt64(Record, V);
2197 Code = bitc::CST_CODE_INTEGER;
2198 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2199 } else { // Wide integers, > 64 bits in size.
2200 // We have an arbitrary precision integer value to write whose
2201 // bit width is > 64. However, in canonical unsigned integer
2202 // format it is likely that the high bits are going to be zero.
2203 // So, we only write the number of active words.
2204 unsigned NWords = IV->getValue().getActiveWords();
2205 const uint64_t *RawWords = IV->getValue().getRawData();
2206 for (unsigned i = 0; i != NWords; ++i) {
2207 emitSignedInt64(Record, RawWords[i]);
2209 Code = bitc::CST_CODE_WIDE_INTEGER;
2211 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2212 Code = bitc::CST_CODE_FLOAT;
2213 Type *Ty = CFP->getType();
2214 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2215 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2216 } else if (Ty->isX86_FP80Ty()) {
2217 // api needed to prevent premature destruction
2218 // bits are not in the same order as a normal i80 APInt, compensate.
2219 APInt api = CFP->getValueAPF().bitcastToAPInt();
2220 const uint64_t *p = api.getRawData();
2221 Record.push_back((p[1] << 48) | (p[0] >> 16));
2222 Record.push_back(p[0] & 0xffffLL);
2223 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2224 APInt api = CFP->getValueAPF().bitcastToAPInt();
2225 const uint64_t *p = api.getRawData();
2226 Record.push_back(p[0]);
2227 Record.push_back(p[1]);
2229 assert (0 && "Unknown FP type!");
2231 } else if (isa<ConstantDataSequential>(C) &&
2232 cast<ConstantDataSequential>(C)->isString()) {
2233 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2234 // Emit constant strings specially.
2235 unsigned NumElts = Str->getNumElements();
2236 // If this is a null-terminated string, use the denser CSTRING encoding.
2237 if (Str->isCString()) {
2238 Code = bitc::CST_CODE_CSTRING;
2239 --NumElts; // Don't encode the null, which isn't allowed by char6.
2241 Code = bitc::CST_CODE_STRING;
2242 AbbrevToUse = String8Abbrev;
2244 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2245 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2246 for (unsigned i = 0; i != NumElts; ++i) {
2247 unsigned char V = Str->getElementAsInteger(i);
2248 Record.push_back(V);
2249 isCStr7 &= (V & 128) == 0;
2251 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2255 AbbrevToUse = CString6Abbrev;
2257 AbbrevToUse = CString7Abbrev;
2258 } else if (const ConstantDataSequential *CDS =
2259 dyn_cast<ConstantDataSequential>(C)) {
2260 Code = bitc::CST_CODE_DATA;
2261 Type *EltTy = CDS->getType()->getElementType();
2262 if (isa<IntegerType>(EltTy)) {
2263 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2264 Record.push_back(CDS->getElementAsInteger(i));
2266 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2268 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2270 } else if (isa<ConstantAggregate>(C)) {
2271 Code = bitc::CST_CODE_AGGREGATE;
2272 for (const Value *Op : C->operands())
2273 Record.push_back(VE.getValueID(Op));
2274 AbbrevToUse = AggregateAbbrev;
2275 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2276 switch (CE->getOpcode()) {
2278 if (Instruction::isCast(CE->getOpcode())) {
2279 Code = bitc::CST_CODE_CE_CAST;
2280 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2281 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2282 Record.push_back(VE.getValueID(C->getOperand(0)));
2283 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2285 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2286 Code = bitc::CST_CODE_CE_BINOP;
2287 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2288 Record.push_back(VE.getValueID(C->getOperand(0)));
2289 Record.push_back(VE.getValueID(C->getOperand(1)));
2290 uint64_t Flags = getOptimizationFlags(CE);
2292 Record.push_back(Flags);
2295 case Instruction::GetElementPtr: {
2296 Code = bitc::CST_CODE_CE_GEP;
2297 const auto *GO = cast<GEPOperator>(C);
2298 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2299 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2300 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2301 Record.push_back((*Idx << 1) | GO->isInBounds());
2302 } else if (GO->isInBounds())
2303 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2304 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2305 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2306 Record.push_back(VE.getValueID(C->getOperand(i)));
2310 case Instruction::Select:
2311 Code = bitc::CST_CODE_CE_SELECT;
2312 Record.push_back(VE.getValueID(C->getOperand(0)));
2313 Record.push_back(VE.getValueID(C->getOperand(1)));
2314 Record.push_back(VE.getValueID(C->getOperand(2)));
2316 case Instruction::ExtractElement:
2317 Code = bitc::CST_CODE_CE_EXTRACTELT;
2318 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2319 Record.push_back(VE.getValueID(C->getOperand(0)));
2320 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2321 Record.push_back(VE.getValueID(C->getOperand(1)));
2323 case Instruction::InsertElement:
2324 Code = bitc::CST_CODE_CE_INSERTELT;
2325 Record.push_back(VE.getValueID(C->getOperand(0)));
2326 Record.push_back(VE.getValueID(C->getOperand(1)));
2327 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2328 Record.push_back(VE.getValueID(C->getOperand(2)));
2330 case Instruction::ShuffleVector:
2331 // If the return type and argument types are the same, this is a
2332 // standard shufflevector instruction. If the types are different,
2333 // then the shuffle is widening or truncating the input vectors, and
2334 // the argument type must also be encoded.
2335 if (C->getType() == C->getOperand(0)->getType()) {
2336 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2338 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2339 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2341 Record.push_back(VE.getValueID(C->getOperand(0)));
2342 Record.push_back(VE.getValueID(C->getOperand(1)));
2343 Record.push_back(VE.getValueID(C->getOperand(2)));
2345 case Instruction::ICmp:
2346 case Instruction::FCmp:
2347 Code = bitc::CST_CODE_CE_CMP;
2348 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2349 Record.push_back(VE.getValueID(C->getOperand(0)));
2350 Record.push_back(VE.getValueID(C->getOperand(1)));
2351 Record.push_back(CE->getPredicate());
2354 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2355 Code = bitc::CST_CODE_BLOCKADDRESS;
2356 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2357 Record.push_back(VE.getValueID(BA->getFunction()));
2358 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2363 llvm_unreachable("Unknown constant!");
2365 Stream.EmitRecord(Code, Record, AbbrevToUse);
2372 void ModuleBitcodeWriter::writeModuleConstants() {
2373 const ValueEnumerator::ValueList &Vals = VE.getValues();
2375 // Find the first constant to emit, which is the first non-globalvalue value.
2376 // We know globalvalues have been emitted by WriteModuleInfo.
2377 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2378 if (!isa<GlobalValue>(Vals[i].first)) {
2379 writeConstants(i, Vals.size(), true);
2385 /// pushValueAndType - The file has to encode both the value and type id for
2386 /// many values, because we need to know what type to create for forward
2387 /// references. However, most operands are not forward references, so this type
2388 /// field is not needed.
2390 /// This function adds V's value ID to Vals. If the value ID is higher than the
2391 /// instruction ID, then it is a forward reference, and it also includes the
2392 /// type ID. The value ID that is written is encoded relative to the InstID.
2393 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2394 SmallVectorImpl<unsigned> &Vals) {
2395 unsigned ValID = VE.getValueID(V);
2396 // Make encoding relative to the InstID.
2397 Vals.push_back(InstID - ValID);
2398 if (ValID >= InstID) {
2399 Vals.push_back(VE.getTypeID(V->getType()));
2405 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2407 SmallVector<unsigned, 64> Record;
2408 LLVMContext &C = CS.getInstruction()->getContext();
2410 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2411 const auto &Bundle = CS.getOperandBundleAt(i);
2412 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2414 for (auto &Input : Bundle.Inputs)
2415 pushValueAndType(Input, InstID, Record);
2417 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2422 /// pushValue - Like pushValueAndType, but where the type of the value is
2423 /// omitted (perhaps it was already encoded in an earlier operand).
2424 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2425 SmallVectorImpl<unsigned> &Vals) {
2426 unsigned ValID = VE.getValueID(V);
2427 Vals.push_back(InstID - ValID);
2430 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2431 SmallVectorImpl<uint64_t> &Vals) {
2432 unsigned ValID = VE.getValueID(V);
2433 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2434 emitSignedInt64(Vals, diff);
2437 /// WriteInstruction - Emit an instruction to the specified stream.
2438 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2440 SmallVectorImpl<unsigned> &Vals) {
2442 unsigned AbbrevToUse = 0;
2443 VE.setInstructionID(&I);
2444 switch (I.getOpcode()) {
2446 if (Instruction::isCast(I.getOpcode())) {
2447 Code = bitc::FUNC_CODE_INST_CAST;
2448 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2449 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2450 Vals.push_back(VE.getTypeID(I.getType()));
2451 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2453 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2454 Code = bitc::FUNC_CODE_INST_BINOP;
2455 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2456 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2457 pushValue(I.getOperand(1), InstID, Vals);
2458 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2459 uint64_t Flags = getOptimizationFlags(&I);
2461 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2462 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2463 Vals.push_back(Flags);
2468 case Instruction::GetElementPtr: {
2469 Code = bitc::FUNC_CODE_INST_GEP;
2470 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2471 auto &GEPInst = cast<GetElementPtrInst>(I);
2472 Vals.push_back(GEPInst.isInBounds());
2473 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2474 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2475 pushValueAndType(I.getOperand(i), InstID, Vals);
2478 case Instruction::ExtractValue: {
2479 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2480 pushValueAndType(I.getOperand(0), InstID, Vals);
2481 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2482 Vals.append(EVI->idx_begin(), EVI->idx_end());
2485 case Instruction::InsertValue: {
2486 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2487 pushValueAndType(I.getOperand(0), InstID, Vals);
2488 pushValueAndType(I.getOperand(1), InstID, Vals);
2489 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2490 Vals.append(IVI->idx_begin(), IVI->idx_end());
2493 case Instruction::Select:
2494 Code = bitc::FUNC_CODE_INST_VSELECT;
2495 pushValueAndType(I.getOperand(1), InstID, Vals);
2496 pushValue(I.getOperand(2), InstID, Vals);
2497 pushValueAndType(I.getOperand(0), InstID, Vals);
2499 case Instruction::ExtractElement:
2500 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2501 pushValueAndType(I.getOperand(0), InstID, Vals);
2502 pushValueAndType(I.getOperand(1), InstID, Vals);
2504 case Instruction::InsertElement:
2505 Code = bitc::FUNC_CODE_INST_INSERTELT;
2506 pushValueAndType(I.getOperand(0), InstID, Vals);
2507 pushValue(I.getOperand(1), InstID, Vals);
2508 pushValueAndType(I.getOperand(2), InstID, Vals);
2510 case Instruction::ShuffleVector:
2511 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2512 pushValueAndType(I.getOperand(0), InstID, Vals);
2513 pushValue(I.getOperand(1), InstID, Vals);
2514 pushValue(I.getOperand(2), InstID, Vals);
2516 case Instruction::ICmp:
2517 case Instruction::FCmp: {
2518 // compare returning Int1Ty or vector of Int1Ty
2519 Code = bitc::FUNC_CODE_INST_CMP2;
2520 pushValueAndType(I.getOperand(0), InstID, Vals);
2521 pushValue(I.getOperand(1), InstID, Vals);
2522 Vals.push_back(cast<CmpInst>(I).getPredicate());
2523 uint64_t Flags = getOptimizationFlags(&I);
2525 Vals.push_back(Flags);
2529 case Instruction::Ret:
2531 Code = bitc::FUNC_CODE_INST_RET;
2532 unsigned NumOperands = I.getNumOperands();
2533 if (NumOperands == 0)
2534 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2535 else if (NumOperands == 1) {
2536 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2537 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2539 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2540 pushValueAndType(I.getOperand(i), InstID, Vals);
2544 case Instruction::Br:
2546 Code = bitc::FUNC_CODE_INST_BR;
2547 const BranchInst &II = cast<BranchInst>(I);
2548 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2549 if (II.isConditional()) {
2550 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2551 pushValue(II.getCondition(), InstID, Vals);
2555 case Instruction::Switch:
2557 Code = bitc::FUNC_CODE_INST_SWITCH;
2558 const SwitchInst &SI = cast<SwitchInst>(I);
2559 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2560 pushValue(SI.getCondition(), InstID, Vals);
2561 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2562 for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2563 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2564 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2568 case Instruction::IndirectBr:
2569 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2570 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2571 // Encode the address operand as relative, but not the basic blocks.
2572 pushValue(I.getOperand(0), InstID, Vals);
2573 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2574 Vals.push_back(VE.getValueID(I.getOperand(i)));
2577 case Instruction::Invoke: {
2578 const InvokeInst *II = cast<InvokeInst>(&I);
2579 const Value *Callee = II->getCalledValue();
2580 FunctionType *FTy = II->getFunctionType();
2582 if (II->hasOperandBundles())
2583 writeOperandBundles(II, InstID);
2585 Code = bitc::FUNC_CODE_INST_INVOKE;
2587 Vals.push_back(VE.getAttributeID(II->getAttributes()));
2588 Vals.push_back(II->getCallingConv() | 1 << 13);
2589 Vals.push_back(VE.getValueID(II->getNormalDest()));
2590 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2591 Vals.push_back(VE.getTypeID(FTy));
2592 pushValueAndType(Callee, InstID, Vals);
2594 // Emit value #'s for the fixed parameters.
2595 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2596 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2598 // Emit type/value pairs for varargs params.
2599 if (FTy->isVarArg()) {
2600 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2602 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2606 case Instruction::Resume:
2607 Code = bitc::FUNC_CODE_INST_RESUME;
2608 pushValueAndType(I.getOperand(0), InstID, Vals);
2610 case Instruction::CleanupRet: {
2611 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2612 const auto &CRI = cast<CleanupReturnInst>(I);
2613 pushValue(CRI.getCleanupPad(), InstID, Vals);
2614 if (CRI.hasUnwindDest())
2615 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2618 case Instruction::CatchRet: {
2619 Code = bitc::FUNC_CODE_INST_CATCHRET;
2620 const auto &CRI = cast<CatchReturnInst>(I);
2621 pushValue(CRI.getCatchPad(), InstID, Vals);
2622 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2625 case Instruction::CleanupPad:
2626 case Instruction::CatchPad: {
2627 const auto &FuncletPad = cast<FuncletPadInst>(I);
2628 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2629 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2630 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2632 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2633 Vals.push_back(NumArgOperands);
2634 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2635 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2638 case Instruction::CatchSwitch: {
2639 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2640 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2642 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2644 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2645 Vals.push_back(NumHandlers);
2646 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2647 Vals.push_back(VE.getValueID(CatchPadBB));
2649 if (CatchSwitch.hasUnwindDest())
2650 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2653 case Instruction::Unreachable:
2654 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2655 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2658 case Instruction::PHI: {
2659 const PHINode &PN = cast<PHINode>(I);
2660 Code = bitc::FUNC_CODE_INST_PHI;
2661 // With the newer instruction encoding, forward references could give
2662 // negative valued IDs. This is most common for PHIs, so we use
2664 SmallVector<uint64_t, 128> Vals64;
2665 Vals64.push_back(VE.getTypeID(PN.getType()));
2666 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2667 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2668 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2670 // Emit a Vals64 vector and exit.
2671 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2676 case Instruction::LandingPad: {
2677 const LandingPadInst &LP = cast<LandingPadInst>(I);
2678 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2679 Vals.push_back(VE.getTypeID(LP.getType()));
2680 Vals.push_back(LP.isCleanup());
2681 Vals.push_back(LP.getNumClauses());
2682 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2684 Vals.push_back(LandingPadInst::Catch);
2686 Vals.push_back(LandingPadInst::Filter);
2687 pushValueAndType(LP.getClause(I), InstID, Vals);
2692 case Instruction::Alloca: {
2693 Code = bitc::FUNC_CODE_INST_ALLOCA;
2694 const AllocaInst &AI = cast<AllocaInst>(I);
2695 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2696 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2697 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2698 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2699 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2700 "not enough bits for maximum alignment");
2701 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2702 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2703 AlignRecord |= 1 << 6;
2704 AlignRecord |= AI.isSwiftError() << 7;
2705 Vals.push_back(AlignRecord);
2709 case Instruction::Load:
2710 if (cast<LoadInst>(I).isAtomic()) {
2711 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2712 pushValueAndType(I.getOperand(0), InstID, Vals);
2714 Code = bitc::FUNC_CODE_INST_LOAD;
2715 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2716 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2718 Vals.push_back(VE.getTypeID(I.getType()));
2719 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2720 Vals.push_back(cast<LoadInst>(I).isVolatile());
2721 if (cast<LoadInst>(I).isAtomic()) {
2722 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2723 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2726 case Instruction::Store:
2727 if (cast<StoreInst>(I).isAtomic())
2728 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2730 Code = bitc::FUNC_CODE_INST_STORE;
2731 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2732 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2733 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2734 Vals.push_back(cast<StoreInst>(I).isVolatile());
2735 if (cast<StoreInst>(I).isAtomic()) {
2736 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2737 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2740 case Instruction::AtomicCmpXchg:
2741 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2742 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2743 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2744 pushValue(I.getOperand(2), InstID, Vals); // newval.
2745 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2747 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2749 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2751 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2752 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2754 case Instruction::AtomicRMW:
2755 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2756 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2757 pushValue(I.getOperand(1), InstID, Vals); // val.
2759 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2760 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2761 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2763 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2765 case Instruction::Fence:
2766 Code = bitc::FUNC_CODE_INST_FENCE;
2767 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2768 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2770 case Instruction::Call: {
2771 const CallInst &CI = cast<CallInst>(I);
2772 FunctionType *FTy = CI.getFunctionType();
2774 if (CI.hasOperandBundles())
2775 writeOperandBundles(&CI, InstID);
2777 Code = bitc::FUNC_CODE_INST_CALL;
2779 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2781 unsigned Flags = getOptimizationFlags(&I);
2782 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2783 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2784 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2785 1 << bitc::CALL_EXPLICIT_TYPE |
2786 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2787 unsigned(Flags != 0) << bitc::CALL_FMF);
2789 Vals.push_back(Flags);
2791 Vals.push_back(VE.getTypeID(FTy));
2792 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2794 // Emit value #'s for the fixed parameters.
2795 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2796 // Check for labels (can happen with asm labels).
2797 if (FTy->getParamType(i)->isLabelTy())
2798 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2800 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2803 // Emit type/value pairs for varargs params.
2804 if (FTy->isVarArg()) {
2805 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2807 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2811 case Instruction::VAArg:
2812 Code = bitc::FUNC_CODE_INST_VAARG;
2813 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2814 pushValue(I.getOperand(0), InstID, Vals); // valist.
2815 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2819 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2823 /// Emit names for globals/functions etc. \p IsModuleLevel is true when
2824 /// we are writing the module-level VST, where we are including a function
2825 /// bitcode index and need to backpatch the VST forward declaration record.
2826 void ModuleBitcodeWriter::writeValueSymbolTable(
2827 const ValueSymbolTable &VST, bool IsModuleLevel,
2828 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) {
2830 // writeValueSymbolTableForwardDecl should have returned early as
2831 // well. Ensure this handling remains in sync by asserting that
2832 // the placeholder offset is not set.
2833 assert(!IsModuleLevel || !hasVSTOffsetPlaceholder());
2837 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2838 // Get the offset of the VST we are writing, and backpatch it into
2839 // the VST forward declaration record.
2840 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2841 // The BitcodeStartBit was the stream offset of the identification block.
2842 VSTOffset -= bitcodeStartBit();
2843 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2844 // Note that we add 1 here because the offset is relative to one word
2845 // before the start of the identification block, which was historically
2846 // always the start of the regular bitcode header.
2847 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2850 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2852 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2853 // records, which are not used in the per-function VSTs.
2854 unsigned FnEntry8BitAbbrev;
2855 unsigned FnEntry7BitAbbrev;
2856 unsigned FnEntry6BitAbbrev;
2857 unsigned GUIDEntryAbbrev;
2858 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2859 // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2860 auto Abbv = std::make_shared<BitCodeAbbrev>();
2861 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2862 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2866 FnEntry8BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2868 // 7-bit fixed width VST_CODE_FNENTRY function strings.
2869 Abbv = std::make_shared<BitCodeAbbrev>();
2870 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2871 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2872 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2873 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2875 FnEntry7BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2877 // 6-bit char6 VST_CODE_FNENTRY function strings.
2878 Abbv = std::make_shared<BitCodeAbbrev>();
2879 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2884 FnEntry6BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2886 // FIXME: Change the name of this record as it is now used by
2887 // the per-module index as well.
2888 Abbv = std::make_shared<BitCodeAbbrev>();
2889 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2892 GUIDEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2895 // FIXME: Set up the abbrev, we know how many values there are!
2896 // FIXME: We know if the type names can use 7-bit ascii.
2897 SmallVector<uint64_t, 64> NameVals;
2899 for (const ValueName &Name : VST) {
2900 // Figure out the encoding to use for the name.
2901 StringEncoding Bits =
2902 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2904 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2905 NameVals.push_back(VE.getValueID(Name.getValue()));
2907 Function *F = dyn_cast<Function>(Name.getValue());
2909 // If value is an alias, need to get the aliased base object to
2910 // see if it is a function.
2911 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2912 if (GA && GA->getBaseObject())
2913 F = dyn_cast<Function>(GA->getBaseObject());
2916 // VST_CODE_ENTRY: [valueid, namechar x N]
2917 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2918 // VST_CODE_BBENTRY: [bbid, namechar x N]
2920 if (isa<BasicBlock>(Name.getValue())) {
2921 Code = bitc::VST_CODE_BBENTRY;
2922 if (Bits == SE_Char6)
2923 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2924 } else if (F && !F->isDeclaration()) {
2925 // Must be the module-level VST, where we pass in the Index and
2926 // have a VSTOffsetPlaceholder. The function-level VST should not
2927 // contain any Function symbols.
2928 assert(FunctionToBitcodeIndex);
2929 assert(hasVSTOffsetPlaceholder());
2931 // Save the word offset of the function (from the start of the
2932 // actual bitcode written to the stream).
2933 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit();
2934 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2935 // Note that we add 1 here because the offset is relative to one word
2936 // before the start of the identification block, which was historically
2937 // always the start of the regular bitcode header.
2938 NameVals.push_back(BitcodeIndex / 32 + 1);
2940 Code = bitc::VST_CODE_FNENTRY;
2941 AbbrevToUse = FnEntry8BitAbbrev;
2942 if (Bits == SE_Char6)
2943 AbbrevToUse = FnEntry6BitAbbrev;
2944 else if (Bits == SE_Fixed7)
2945 AbbrevToUse = FnEntry7BitAbbrev;
2947 Code = bitc::VST_CODE_ENTRY;
2948 if (Bits == SE_Char6)
2949 AbbrevToUse = VST_ENTRY_6_ABBREV;
2950 else if (Bits == SE_Fixed7)
2951 AbbrevToUse = VST_ENTRY_7_ABBREV;
2954 for (const auto P : Name.getKey())
2955 NameVals.push_back((unsigned char)P);
2957 // Emit the finished record.
2958 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2961 // Emit any GUID valueIDs created for indirect call edges into the
2962 // module-level VST.
2963 if (IsModuleLevel && hasVSTOffsetPlaceholder())
2964 for (const auto &GI : valueIds()) {
2965 NameVals.push_back(GI.second);
2966 NameVals.push_back(GI.first);
2967 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals,
2974 /// Emit function names and summary offsets for the combined index
2975 /// used by ThinLTO.
2976 void IndexBitcodeWriter::writeCombinedValueSymbolTable() {
2977 assert(hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder");
2978 // Get the offset of the VST we are writing, and backpatch it into
2979 // the VST forward declaration record.
2980 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2981 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2982 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2984 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2986 auto Abbv = std::make_shared<BitCodeAbbrev>();
2987 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2990 unsigned EntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2992 SmallVector<uint64_t, 64> NameVals;
2993 for (const auto &GVI : valueIds()) {
2994 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2995 NameVals.push_back(GVI.second);
2996 NameVals.push_back(GVI.first);
2998 // Emit the finished record.
2999 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
3005 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3006 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3008 if (isa<BasicBlock>(Order.V))
3009 Code = bitc::USELIST_CODE_BB;
3011 Code = bitc::USELIST_CODE_DEFAULT;
3013 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3014 Record.push_back(VE.getValueID(Order.V));
3015 Stream.EmitRecord(Code, Record);
3018 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3019 assert(VE.shouldPreserveUseListOrder() &&
3020 "Expected to be preserving use-list order");
3022 auto hasMore = [&]() {
3023 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3029 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3031 writeUseList(std::move(VE.UseListOrders.back()));
3032 VE.UseListOrders.pop_back();
3037 /// Emit a function body to the module stream.
3038 void ModuleBitcodeWriter::writeFunction(
3040 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3041 // Save the bitcode index of the start of this function block for recording
3043 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3045 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3046 VE.incorporateFunction(F);
3048 SmallVector<unsigned, 64> Vals;
3050 // Emit the number of basic blocks, so the reader can create them ahead of
3052 Vals.push_back(VE.getBasicBlocks().size());
3053 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3056 // If there are function-local constants, emit them now.
3057 unsigned CstStart, CstEnd;
3058 VE.getFunctionConstantRange(CstStart, CstEnd);
3059 writeConstants(CstStart, CstEnd, false);
3061 // If there is function-local metadata, emit it now.
3062 writeFunctionMetadata(F);
3064 // Keep a running idea of what the instruction ID is.
3065 unsigned InstID = CstEnd;
3067 bool NeedsMetadataAttachment = F.hasMetadata();
3069 DILocation *LastDL = nullptr;
3070 // Finally, emit all the instructions, in order.
3071 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3072 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3074 writeInstruction(*I, InstID, Vals);
3076 if (!I->getType()->isVoidTy())
3079 // If the instruction has metadata, write a metadata attachment later.
3080 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3082 // If the instruction has a debug location, emit it.
3083 DILocation *DL = I->getDebugLoc();
3088 // Just repeat the same debug loc as last time.
3089 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3093 Vals.push_back(DL->getLine());
3094 Vals.push_back(DL->getColumn());
3095 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3096 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3097 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3103 // Emit names for all the instructions etc.
3104 if (auto *Symtab = F.getValueSymbolTable())
3105 writeValueSymbolTable(*Symtab);
3107 if (NeedsMetadataAttachment)
3108 writeFunctionMetadataAttachment(F);
3109 if (VE.shouldPreserveUseListOrder())
3110 writeUseListBlock(&F);
3115 // Emit blockinfo, which defines the standard abbreviations etc.
3116 void ModuleBitcodeWriter::writeBlockInfo() {
3117 // We only want to emit block info records for blocks that have multiple
3118 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3119 // Other blocks can define their abbrevs inline.
3120 Stream.EnterBlockInfoBlock();
3122 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3123 auto Abbv = std::make_shared<BitCodeAbbrev>();
3124 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3128 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3130 llvm_unreachable("Unexpected abbrev ordering!");
3133 { // 7-bit fixed width VST_CODE_ENTRY strings.
3134 auto Abbv = std::make_shared<BitCodeAbbrev>();
3135 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3139 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3141 llvm_unreachable("Unexpected abbrev ordering!");
3143 { // 6-bit char6 VST_CODE_ENTRY strings.
3144 auto Abbv = std::make_shared<BitCodeAbbrev>();
3145 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3149 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3151 llvm_unreachable("Unexpected abbrev ordering!");
3153 { // 6-bit char6 VST_CODE_BBENTRY strings.
3154 auto Abbv = std::make_shared<BitCodeAbbrev>();
3155 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3159 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3160 VST_BBENTRY_6_ABBREV)
3161 llvm_unreachable("Unexpected abbrev ordering!");
3166 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3167 auto Abbv = std::make_shared<BitCodeAbbrev>();
3168 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3170 VE.computeBitsRequiredForTypeIndicies()));
3171 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3172 CONSTANTS_SETTYPE_ABBREV)
3173 llvm_unreachable("Unexpected abbrev ordering!");
3176 { // INTEGER abbrev for CONSTANTS_BLOCK.
3177 auto Abbv = std::make_shared<BitCodeAbbrev>();
3178 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3180 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3181 CONSTANTS_INTEGER_ABBREV)
3182 llvm_unreachable("Unexpected abbrev ordering!");
3185 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3186 auto Abbv = std::make_shared<BitCodeAbbrev>();
3187 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3190 VE.computeBitsRequiredForTypeIndicies()));
3191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3193 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3194 CONSTANTS_CE_CAST_Abbrev)
3195 llvm_unreachable("Unexpected abbrev ordering!");
3197 { // NULL abbrev for CONSTANTS_BLOCK.
3198 auto Abbv = std::make_shared<BitCodeAbbrev>();
3199 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3200 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3201 CONSTANTS_NULL_Abbrev)
3202 llvm_unreachable("Unexpected abbrev ordering!");
3205 // FIXME: This should only use space for first class types!
3207 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3208 auto Abbv = std::make_shared<BitCodeAbbrev>();
3209 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3212 VE.computeBitsRequiredForTypeIndicies()));
3213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3215 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3216 FUNCTION_INST_LOAD_ABBREV)
3217 llvm_unreachable("Unexpected abbrev ordering!");
3219 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3220 auto Abbv = std::make_shared<BitCodeAbbrev>();
3221 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3225 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3226 FUNCTION_INST_BINOP_ABBREV)
3227 llvm_unreachable("Unexpected abbrev ordering!");
3229 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3230 auto Abbv = std::make_shared<BitCodeAbbrev>();
3231 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3236 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3237 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3238 llvm_unreachable("Unexpected abbrev ordering!");
3240 { // INST_CAST abbrev for FUNCTION_BLOCK.
3241 auto Abbv = std::make_shared<BitCodeAbbrev>();
3242 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3245 VE.computeBitsRequiredForTypeIndicies()));
3246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3247 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3248 FUNCTION_INST_CAST_ABBREV)
3249 llvm_unreachable("Unexpected abbrev ordering!");
3252 { // INST_RET abbrev for FUNCTION_BLOCK.
3253 auto Abbv = std::make_shared<BitCodeAbbrev>();
3254 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3255 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3256 FUNCTION_INST_RET_VOID_ABBREV)
3257 llvm_unreachable("Unexpected abbrev ordering!");
3259 { // INST_RET abbrev for FUNCTION_BLOCK.
3260 auto Abbv = std::make_shared<BitCodeAbbrev>();
3261 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3263 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3264 FUNCTION_INST_RET_VAL_ABBREV)
3265 llvm_unreachable("Unexpected abbrev ordering!");
3267 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3268 auto Abbv = std::make_shared<BitCodeAbbrev>();
3269 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3270 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3271 FUNCTION_INST_UNREACHABLE_ABBREV)
3272 llvm_unreachable("Unexpected abbrev ordering!");
3275 auto Abbv = std::make_shared<BitCodeAbbrev>();
3276 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3279 Log2_32_Ceil(VE.getTypes().size() + 1)));
3280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3282 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3283 FUNCTION_INST_GEP_ABBREV)
3284 llvm_unreachable("Unexpected abbrev ordering!");
3290 /// Write the module path strings, currently only used when generating
3291 /// a combined index file.
3292 void IndexBitcodeWriter::writeModStrings() {
3293 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3295 // TODO: See which abbrev sizes we actually need to emit
3297 // 8-bit fixed-width MST_ENTRY strings.
3298 auto Abbv = std::make_shared<BitCodeAbbrev>();
3299 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3303 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3305 // 7-bit fixed width MST_ENTRY strings.
3306 Abbv = std::make_shared<BitCodeAbbrev>();
3307 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3311 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3313 // 6-bit char6 MST_ENTRY strings.
3314 Abbv = std::make_shared<BitCodeAbbrev>();
3315 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3319 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3321 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3322 Abbv = std::make_shared<BitCodeAbbrev>();
3323 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3329 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3331 SmallVector<unsigned, 64> Vals;
3332 for (const auto &MPSE : Index.modulePaths()) {
3333 if (!doIncludeModule(MPSE.getKey()))
3335 StringEncoding Bits =
3336 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3337 unsigned AbbrevToUse = Abbrev8Bit;
3338 if (Bits == SE_Char6)
3339 AbbrevToUse = Abbrev6Bit;
3340 else if (Bits == SE_Fixed7)
3341 AbbrevToUse = Abbrev7Bit;
3343 Vals.push_back(MPSE.getValue().first);
3345 for (const auto P : MPSE.getKey())
3346 Vals.push_back((unsigned char)P);
3348 // Emit the finished record.
3349 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3352 // Emit an optional hash for the module now
3353 auto &Hash = MPSE.getValue().second;
3354 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3355 for (auto Val : Hash) {
3358 Vals.push_back(Val);
3361 // Emit the hash record.
3362 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3370 // Helper to emit a single function summary record.
3371 void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3372 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3373 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3374 const Function &F) {
3375 NameVals.push_back(ValueID);
3377 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3378 if (!FS->type_tests().empty())
3379 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3381 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3382 NameVals.push_back(FS->instCount());
3383 NameVals.push_back(FS->refs().size());
3385 for (auto &RI : FS->refs())
3386 NameVals.push_back(VE.getValueID(RI.getValue()));
3388 bool HasProfileData = F.getEntryCount().hasValue();
3389 for (auto &ECI : FS->calls()) {
3390 NameVals.push_back(getValueId(ECI.first));
3392 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3395 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3397 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3399 // Emit the finished record.
3400 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3404 // Collect the global value references in the given variable's initializer,
3405 // and emit them in a summary record.
3406 void ModuleBitcodeWriter::writeModuleLevelReferences(
3407 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3408 unsigned FSModRefsAbbrev) {
3410 Index->findGlobalValueSummaryList(GlobalValue::getGUID(V.getName()));
3411 if (Summaries == Index->end()) {
3412 // Only declarations should not have a summary (a declaration might however
3413 // have a summary if the def was in module level asm).
3414 assert(V.isDeclaration());
3417 auto *Summary = Summaries->second.front().get();
3418 NameVals.push_back(VE.getValueID(&V));
3419 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3420 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3422 unsigned SizeBeforeRefs = NameVals.size();
3423 for (auto &RI : VS->refs())
3424 NameVals.push_back(VE.getValueID(RI.getValue()));
3425 // Sort the refs for determinism output, the vector returned by FS->refs() has
3426 // been initialized from a DenseSet.
3427 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3429 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3434 // Current version for the summary.
3435 // This is bumped whenever we introduce changes in the way some record are
3436 // interpreted, like flags for instance.
3437 static const uint64_t INDEX_VERSION = 3;
3439 /// Emit the per-module summary section alongside the rest of
3440 /// the module's bitcode.
3441 void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3442 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
3444 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3446 if (Index->begin() == Index->end()) {
3451 // Abbrev for FS_PERMODULE.
3452 auto Abbv = std::make_shared<BitCodeAbbrev>();
3453 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3458 // numrefs x valueid, n x (valueid)
3459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3461 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3463 // Abbrev for FS_PERMODULE_PROFILE.
3464 Abbv = std::make_shared<BitCodeAbbrev>();
3465 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3470 // numrefs x valueid, n x (valueid, hotness)
3471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3473 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3475 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3476 Abbv = std::make_shared<BitCodeAbbrev>();
3477 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3480 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3482 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3484 // Abbrev for FS_ALIAS.
3485 Abbv = std::make_shared<BitCodeAbbrev>();
3486 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3490 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3492 SmallVector<uint64_t, 64> NameVals;
3493 // Iterate over the list of functions instead of the Index to
3494 // ensure the ordering is stable.
3495 for (const Function &F : M) {
3496 // Summary emission does not support anonymous functions, they have to
3497 // renamed using the anonymous function renaming pass.
3499 report_fatal_error("Unexpected anonymous function when writing summary");
3502 Index->findGlobalValueSummaryList(GlobalValue::getGUID(F.getName()));
3503 if (Summaries == Index->end()) {
3504 // Only declarations should not have a summary (a declaration might
3505 // however have a summary if the def was in module level asm).
3506 assert(F.isDeclaration());
3509 auto *Summary = Summaries->second.front().get();
3510 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3511 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3514 // Capture references from GlobalVariable initializers, which are outside
3515 // of a function scope.
3516 for (const GlobalVariable &G : M.globals())
3517 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3519 for (const GlobalAlias &A : M.aliases()) {
3520 auto *Aliasee = A.getBaseObject();
3521 if (!Aliasee->hasName())
3522 // Nameless function don't have an entry in the summary, skip it.
3524 auto AliasId = VE.getValueID(&A);
3525 auto AliaseeId = VE.getValueID(Aliasee);
3526 NameVals.push_back(AliasId);
3527 auto *Summary = Index->getGlobalValueSummary(A);
3528 AliasSummary *AS = cast<AliasSummary>(Summary);
3529 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3530 NameVals.push_back(AliaseeId);
3531 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3538 /// Emit the combined summary section into the combined index file.
3539 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3540 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3541 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3543 // Abbrev for FS_COMBINED.
3544 auto Abbv = std::make_shared<BitCodeAbbrev>();
3545 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3546 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3550 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3551 // numrefs x valueid, n x (valueid)
3552 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3553 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3554 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3556 // Abbrev for FS_COMBINED_PROFILE.
3557 Abbv = std::make_shared<BitCodeAbbrev>();
3558 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3559 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3560 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3561 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3562 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3563 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3564 // numrefs x valueid, n x (valueid, hotness)
3565 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3566 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3567 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3569 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3570 Abbv = std::make_shared<BitCodeAbbrev>();
3571 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3572 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3573 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3574 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3575 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3576 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3577 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3579 // Abbrev for FS_COMBINED_ALIAS.
3580 Abbv = std::make_shared<BitCodeAbbrev>();
3581 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3586 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3588 // The aliases are emitted as a post-pass, and will point to the value
3589 // id of the aliasee. Save them in a vector for post-processing.
3590 SmallVector<AliasSummary *, 64> Aliases;
3592 // Save the value id for each summary for alias emission.
3593 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3595 SmallVector<uint64_t, 64> NameVals;
3597 // For local linkage, we also emit the original name separately
3598 // immediately after the record.
3599 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3600 if (!GlobalValue::isLocalLinkage(S.linkage()))
3602 NameVals.push_back(S.getOriginalName());
3603 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3607 for (const auto &I : *this) {
3608 GlobalValueSummary *S = I.second;
3611 assert(hasValueId(I.first));
3612 unsigned ValueId = getValueId(I.first);
3613 SummaryToValueIdMap[S] = ValueId;
3615 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3616 // Will process aliases as a post-pass because the reader wants all
3617 // global to be loaded first.
3618 Aliases.push_back(AS);
3622 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3623 NameVals.push_back(ValueId);
3624 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3625 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3626 for (auto &RI : VS->refs()) {
3627 NameVals.push_back(getValueId(RI.getGUID()));
3630 // Emit the finished record.
3631 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3634 MaybeEmitOriginalName(*S);
3638 auto *FS = cast<FunctionSummary>(S);
3639 if (!FS->type_tests().empty())
3640 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3642 NameVals.push_back(ValueId);
3643 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3644 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3645 NameVals.push_back(FS->instCount());
3646 NameVals.push_back(FS->refs().size());
3648 for (auto &RI : FS->refs()) {
3649 NameVals.push_back(getValueId(RI.getGUID()));
3652 bool HasProfileData = false;
3653 for (auto &EI : FS->calls()) {
3654 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3659 for (auto &EI : FS->calls()) {
3660 // If this GUID doesn't have a value id, it doesn't have a function
3661 // summary and we don't need to record any calls to it.
3662 if (!hasValueId(EI.first.getGUID()))
3664 NameVals.push_back(getValueId(EI.first.getGUID()));
3666 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3669 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3671 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3673 // Emit the finished record.
3674 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3676 MaybeEmitOriginalName(*S);
3679 for (auto *AS : Aliases) {
3680 auto AliasValueId = SummaryToValueIdMap[AS];
3681 assert(AliasValueId);
3682 NameVals.push_back(AliasValueId);
3683 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3684 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3685 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3686 assert(AliaseeValueId);
3687 NameVals.push_back(AliaseeValueId);
3689 // Emit the finished record.
3690 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3692 MaybeEmitOriginalName(*AS);
3698 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3699 /// current llvm version, and a record for the epoch number.
3700 void writeIdentificationBlock(BitstreamWriter &Stream) {
3701 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3703 // Write the "user readable" string identifying the bitcode producer
3704 auto Abbv = std::make_shared<BitCodeAbbrev>();
3705 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3708 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3709 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3710 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
3712 // Write the epoch version
3713 Abbv = std::make_shared<BitCodeAbbrev>();
3714 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3716 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3717 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3718 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3722 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3723 // Emit the module's hash.
3724 // MODULE_CODE_HASH: [5*i32]
3726 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3727 Buffer.size() - BlockStartPos));
3728 StringRef Hash = Hasher.result();
3730 for (int Pos = 0; Pos < 20; Pos += 4) {
3731 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3734 // Emit the finished record.
3735 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3738 void ModuleBitcodeWriter::write() {
3739 writeIdentificationBlock(Stream);
3741 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3742 size_t BlockStartPos = Buffer.size();
3744 SmallVector<unsigned, 1> Vals;
3745 unsigned CurVersion = 1;
3746 Vals.push_back(CurVersion);
3747 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3749 // Emit blockinfo, which defines the standard abbreviations etc.
3752 // Emit information about attribute groups.
3753 writeAttributeGroupTable();
3755 // Emit information about parameter attributes.
3756 writeAttributeTable();
3758 // Emit information describing all of the types in the module.
3763 // Emit top-level description of module, including target triple, inline asm,
3764 // descriptors for global variables, and function prototype info.
3768 writeModuleConstants();
3770 // Emit metadata kind names.
3771 writeModuleMetadataKinds();
3774 writeModuleMetadata();
3776 // Emit module-level use-lists.
3777 if (VE.shouldPreserveUseListOrder())
3778 writeUseListBlock(nullptr);
3780 writeOperandBundleTags();
3782 // Emit function bodies.
3783 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3784 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3785 if (!F->isDeclaration())
3786 writeFunction(*F, FunctionToBitcodeIndex);
3788 // Need to write after the above call to WriteFunction which populates
3789 // the summary information in the index.
3791 writePerModuleGlobalValueSummary();
3793 writeValueSymbolTable(M.getValueSymbolTable(),
3794 /* IsModuleLevel */ true, &FunctionToBitcodeIndex);
3797 writeModuleHash(BlockStartPos);
3803 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3804 uint32_t &Position) {
3805 support::endian::write32le(&Buffer[Position], Value);
3809 /// If generating a bc file on darwin, we have to emit a
3810 /// header and trailer to make it compatible with the system archiver. To do
3811 /// this we emit the following header, and then emit a trailer that pads the
3812 /// file out to be a multiple of 16 bytes.
3814 /// struct bc_header {
3815 /// uint32_t Magic; // 0x0B17C0DE
3816 /// uint32_t Version; // Version, currently always 0.
3817 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3818 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
3819 /// uint32_t CPUType; // CPU specifier.
3820 /// ... potentially more later ...
3822 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3824 unsigned CPUType = ~0U;
3826 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3827 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3828 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3829 // specific constants here because they are implicitly part of the Darwin ABI.
3831 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3832 DARWIN_CPU_TYPE_X86 = 7,
3833 DARWIN_CPU_TYPE_ARM = 12,
3834 DARWIN_CPU_TYPE_POWERPC = 18
3837 Triple::ArchType Arch = TT.getArch();
3838 if (Arch == Triple::x86_64)
3839 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3840 else if (Arch == Triple::x86)
3841 CPUType = DARWIN_CPU_TYPE_X86;
3842 else if (Arch == Triple::ppc)
3843 CPUType = DARWIN_CPU_TYPE_POWERPC;
3844 else if (Arch == Triple::ppc64)
3845 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3846 else if (Arch == Triple::arm || Arch == Triple::thumb)
3847 CPUType = DARWIN_CPU_TYPE_ARM;
3849 // Traditional Bitcode starts after header.
3850 assert(Buffer.size() >= BWH_HeaderSize &&
3851 "Expected header size to be reserved");
3852 unsigned BCOffset = BWH_HeaderSize;
3853 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3855 // Write the magic and version.
3856 unsigned Position = 0;
3857 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3858 writeInt32ToBuffer(0, Buffer, Position); // Version.
3859 writeInt32ToBuffer(BCOffset, Buffer, Position);
3860 writeInt32ToBuffer(BCSize, Buffer, Position);
3861 writeInt32ToBuffer(CPUType, Buffer, Position);
3863 // If the file is not a multiple of 16 bytes, insert dummy padding.
3864 while (Buffer.size() & 15)
3865 Buffer.push_back(0);
3868 /// Helper to write the header common to all bitcode files.
3869 static void writeBitcodeHeader(BitstreamWriter &Stream) {
3870 // Emit the file header.
3871 Stream.Emit((unsigned)'B', 8);
3872 Stream.Emit((unsigned)'C', 8);
3873 Stream.Emit(0x0, 4);
3874 Stream.Emit(0xC, 4);
3875 Stream.Emit(0xE, 4);
3876 Stream.Emit(0xD, 4);
3879 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3880 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3881 writeBitcodeHeader(*Stream);
3884 BitcodeWriter::~BitcodeWriter() = default;
3886 void BitcodeWriter::writeModule(const Module *M,
3887 bool ShouldPreserveUseListOrder,
3888 const ModuleSummaryIndex *Index,
3889 bool GenerateHash) {
3890 ModuleBitcodeWriter ModuleWriter(
3891 M, Buffer, *Stream, ShouldPreserveUseListOrder, Index, GenerateHash);
3892 ModuleWriter.write();
3895 /// WriteBitcodeToFile - Write the specified module to the specified output
3897 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3898 bool ShouldPreserveUseListOrder,
3899 const ModuleSummaryIndex *Index,
3900 bool GenerateHash) {
3901 SmallVector<char, 0> Buffer;
3902 Buffer.reserve(256*1024);
3904 // If this is darwin or another generic macho target, reserve space for the
3906 Triple TT(M->getTargetTriple());
3907 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3908 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3910 BitcodeWriter Writer(Buffer);
3911 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash);
3913 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3914 emitDarwinBCHeaderAndTrailer(Buffer, TT);
3916 // Write the generated bitstream to "Out".
3917 Out.write((char*)&Buffer.front(), Buffer.size());
3920 void IndexBitcodeWriter::write() {
3921 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3923 SmallVector<unsigned, 1> Vals;
3924 unsigned CurVersion = 1;
3925 Vals.push_back(CurVersion);
3926 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3928 // If we have a VST, write the VSTOFFSET record placeholder.
3929 writeValueSymbolTableForwardDecl();
3931 // Write the module paths in the combined index.
3934 // Write the summary combined index records.
3935 writeCombinedGlobalValueSummary();
3937 // Need a special VST writer for the combined index (we don't have a
3938 // real VST and real values when this is invoked).
3939 writeCombinedValueSymbolTable();
3944 // Write the specified module summary index to the given raw output stream,
3945 // where it will be written in a new bitcode block. This is used when
3946 // writing the combined index file for ThinLTO. When writing a subset of the
3947 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3948 void llvm::WriteIndexToFile(
3949 const ModuleSummaryIndex &Index, raw_ostream &Out,
3950 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3951 SmallVector<char, 0> Buffer;
3952 Buffer.reserve(256 * 1024);
3954 BitstreamWriter Stream(Buffer);
3955 writeBitcodeHeader(Stream);
3957 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
3958 IndexWriter.write();
3960 Out.write((char *)&Buffer.front(), Buffer.size());