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 BitCodeAbbrev *Abbv = new 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(Abbv);
793 // Abbrev for TYPE_CODE_FUNCTION.
794 Abbv = new 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(Abbv);
802 // Abbrev for TYPE_CODE_STRUCT_ANON.
803 Abbv = new 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(Abbv);
811 // Abbrev for TYPE_CODE_STRUCT_NAME.
812 Abbv = new 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(Abbv);
818 // Abbrev for TYPE_CODE_STRUCT_NAMED.
819 Abbv = new 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(Abbv);
827 // Abbrev for TYPE_CODE_ARRAY.
828 Abbv = new 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(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.NoRename; // bool
975 RawFlags |= (Flags.IsNotViableToInline << 1);
976 RawFlags |= (Flags.HasInlineAsmMaybeReferencingInternal << 2);
977 // Linkage don't need to be remapped at that time for the summary. Any future
978 // change to the getEncodedLinkage() function will need to be taken into
979 // account here as well.
980 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
985 static unsigned getEncodedVisibility(const GlobalValue &GV) {
986 switch (GV.getVisibility()) {
987 case GlobalValue::DefaultVisibility: return 0;
988 case GlobalValue::HiddenVisibility: return 1;
989 case GlobalValue::ProtectedVisibility: return 2;
991 llvm_unreachable("Invalid visibility");
994 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
995 switch (GV.getDLLStorageClass()) {
996 case GlobalValue::DefaultStorageClass: return 0;
997 case GlobalValue::DLLImportStorageClass: return 1;
998 case GlobalValue::DLLExportStorageClass: return 2;
1000 llvm_unreachable("Invalid DLL storage class");
1003 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1004 switch (GV.getThreadLocalMode()) {
1005 case GlobalVariable::NotThreadLocal: return 0;
1006 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1007 case GlobalVariable::LocalDynamicTLSModel: return 2;
1008 case GlobalVariable::InitialExecTLSModel: return 3;
1009 case GlobalVariable::LocalExecTLSModel: return 4;
1011 llvm_unreachable("Invalid TLS model");
1014 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1015 switch (C.getSelectionKind()) {
1017 return bitc::COMDAT_SELECTION_KIND_ANY;
1018 case Comdat::ExactMatch:
1019 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1020 case Comdat::Largest:
1021 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1022 case Comdat::NoDuplicates:
1023 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1024 case Comdat::SameSize:
1025 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1027 llvm_unreachable("Invalid selection kind");
1030 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1031 switch (GV.getUnnamedAddr()) {
1032 case GlobalValue::UnnamedAddr::None: return 0;
1033 case GlobalValue::UnnamedAddr::Local: return 2;
1034 case GlobalValue::UnnamedAddr::Global: return 1;
1036 llvm_unreachable("Invalid unnamed_addr");
1039 void ModuleBitcodeWriter::writeComdats() {
1040 SmallVector<unsigned, 64> Vals;
1041 for (const Comdat *C : VE.getComdats()) {
1042 // COMDAT: [selection_kind, name]
1043 Vals.push_back(getEncodedComdatSelectionKind(*C));
1044 size_t Size = C->getName().size();
1045 assert(isUInt<32>(Size));
1046 Vals.push_back(Size);
1047 for (char Chr : C->getName())
1048 Vals.push_back((unsigned char)Chr);
1049 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1054 /// Write a record that will eventually hold the word offset of the
1055 /// module-level VST. For now the offset is 0, which will be backpatched
1056 /// after the real VST is written. Saves the bit offset to backpatch.
1057 void BitcodeWriterBase::writeValueSymbolTableForwardDecl() {
1058 // Write a placeholder value in for the offset of the real VST,
1059 // which is written after the function blocks so that it can include
1060 // the offset of each function. The placeholder offset will be
1061 // updated when the real VST is written.
1062 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1063 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1064 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1065 // hold the real VST offset. Must use fixed instead of VBR as we don't
1066 // know how many VBR chunks to reserve ahead of time.
1067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1068 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
1070 // Emit the placeholder
1071 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1072 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1074 // Compute and save the bit offset to the placeholder, which will be
1075 // patched when the real VST is written. We can simply subtract the 32-bit
1076 // fixed size from the current bit number to get the location to backpatch.
1077 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1080 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1082 /// Determine the encoding to use for the given string name and length.
1083 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
1084 bool isChar6 = true;
1085 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
1087 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1088 if ((unsigned char)*C & 128)
1089 // don't bother scanning the rest.
1098 /// Emit top-level description of module, including target triple, inline asm,
1099 /// descriptors for global variables, and function prototype info.
1100 /// Returns the bit offset to backpatch with the location of the real VST.
1101 void ModuleBitcodeWriter::writeModuleInfo() {
1102 // Emit various pieces of data attached to a module.
1103 if (!M.getTargetTriple().empty())
1104 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1106 const std::string &DL = M.getDataLayoutStr();
1108 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1109 if (!M.getModuleInlineAsm().empty())
1110 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1113 // Emit information about sections and GC, computing how many there are. Also
1114 // compute the maximum alignment value.
1115 std::map<std::string, unsigned> SectionMap;
1116 std::map<std::string, unsigned> GCMap;
1117 unsigned MaxAlignment = 0;
1118 unsigned MaxGlobalType = 0;
1119 for (const GlobalValue &GV : M.globals()) {
1120 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1121 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1122 if (GV.hasSection()) {
1123 // Give section names unique ID's.
1124 unsigned &Entry = SectionMap[GV.getSection()];
1126 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1128 Entry = SectionMap.size();
1132 for (const Function &F : M) {
1133 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1134 if (F.hasSection()) {
1135 // Give section names unique ID's.
1136 unsigned &Entry = SectionMap[F.getSection()];
1138 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1140 Entry = SectionMap.size();
1144 // Same for GC names.
1145 unsigned &Entry = GCMap[F.getGC()];
1147 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1149 Entry = GCMap.size();
1154 // Emit abbrev for globals, now that we know # sections and max alignment.
1155 unsigned SimpleGVarAbbrev = 0;
1156 if (!M.global_empty()) {
1157 // Add an abbrev for common globals with no visibility or thread localness.
1158 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1159 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1161 Log2_32_Ceil(MaxGlobalType+1)));
1162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1163 //| explicitType << 1
1165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1167 if (MaxAlignment == 0) // Alignment.
1168 Abbv->Add(BitCodeAbbrevOp(0));
1170 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1172 Log2_32_Ceil(MaxEncAlignment+1)));
1174 if (SectionMap.empty()) // Section.
1175 Abbv->Add(BitCodeAbbrevOp(0));
1177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1178 Log2_32_Ceil(SectionMap.size()+1)));
1179 // Don't bother emitting vis + thread local.
1180 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
1183 // Emit the global variable information.
1184 SmallVector<unsigned, 64> Vals;
1185 for (const GlobalVariable &GV : M.globals()) {
1186 unsigned AbbrevToUse = 0;
1188 // GLOBALVAR: [type, isconst, initid,
1189 // linkage, alignment, section, visibility, threadlocal,
1190 // unnamed_addr, externally_initialized, dllstorageclass,
1192 Vals.push_back(VE.getTypeID(GV.getValueType()));
1193 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1194 Vals.push_back(GV.isDeclaration() ? 0 :
1195 (VE.getValueID(GV.getInitializer()) + 1));
1196 Vals.push_back(getEncodedLinkage(GV));
1197 Vals.push_back(Log2_32(GV.getAlignment())+1);
1198 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1199 if (GV.isThreadLocal() ||
1200 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1201 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1202 GV.isExternallyInitialized() ||
1203 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1205 Vals.push_back(getEncodedVisibility(GV));
1206 Vals.push_back(getEncodedThreadLocalMode(GV));
1207 Vals.push_back(getEncodedUnnamedAddr(GV));
1208 Vals.push_back(GV.isExternallyInitialized());
1209 Vals.push_back(getEncodedDLLStorageClass(GV));
1210 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1212 AbbrevToUse = SimpleGVarAbbrev;
1215 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1219 // Emit the function proto information.
1220 for (const Function &F : M) {
1221 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
1222 // section, visibility, gc, unnamed_addr, prologuedata,
1223 // dllstorageclass, comdat, prefixdata, personalityfn]
1224 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1225 Vals.push_back(F.getCallingConv());
1226 Vals.push_back(F.isDeclaration());
1227 Vals.push_back(getEncodedLinkage(F));
1228 Vals.push_back(VE.getAttributeID(F.getAttributes()));
1229 Vals.push_back(Log2_32(F.getAlignment())+1);
1230 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1231 Vals.push_back(getEncodedVisibility(F));
1232 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1233 Vals.push_back(getEncodedUnnamedAddr(F));
1234 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1236 Vals.push_back(getEncodedDLLStorageClass(F));
1237 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1238 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1241 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1243 unsigned AbbrevToUse = 0;
1244 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1248 // Emit the alias information.
1249 for (const GlobalAlias &A : M.aliases()) {
1250 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass,
1251 // threadlocal, unnamed_addr]
1252 Vals.push_back(VE.getTypeID(A.getValueType()));
1253 Vals.push_back(A.getType()->getAddressSpace());
1254 Vals.push_back(VE.getValueID(A.getAliasee()));
1255 Vals.push_back(getEncodedLinkage(A));
1256 Vals.push_back(getEncodedVisibility(A));
1257 Vals.push_back(getEncodedDLLStorageClass(A));
1258 Vals.push_back(getEncodedThreadLocalMode(A));
1259 Vals.push_back(getEncodedUnnamedAddr(A));
1260 unsigned AbbrevToUse = 0;
1261 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1265 // Emit the ifunc information.
1266 for (const GlobalIFunc &I : M.ifuncs()) {
1267 // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility]
1268 Vals.push_back(VE.getTypeID(I.getValueType()));
1269 Vals.push_back(I.getType()->getAddressSpace());
1270 Vals.push_back(VE.getValueID(I.getResolver()));
1271 Vals.push_back(getEncodedLinkage(I));
1272 Vals.push_back(getEncodedVisibility(I));
1273 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1277 // Emit the module's source file name.
1279 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1280 M.getSourceFileName().size());
1281 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1282 if (Bits == SE_Char6)
1283 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1284 else if (Bits == SE_Fixed7)
1285 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1287 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1288 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1289 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1291 Abbv->Add(AbbrevOpToUse);
1292 unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv);
1294 for (const auto P : M.getSourceFileName())
1295 Vals.push_back((unsigned char)P);
1297 // Emit the finished record.
1298 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1302 // If we have a VST, write the VSTOFFSET record placeholder.
1303 if (M.getValueSymbolTable().empty())
1305 writeValueSymbolTableForwardDecl();
1308 static uint64_t getOptimizationFlags(const Value *V) {
1311 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1312 if (OBO->hasNoSignedWrap())
1313 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1314 if (OBO->hasNoUnsignedWrap())
1315 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1316 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1318 Flags |= 1 << bitc::PEO_EXACT;
1319 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1320 if (FPMO->hasUnsafeAlgebra())
1321 Flags |= FastMathFlags::UnsafeAlgebra;
1322 if (FPMO->hasNoNaNs())
1323 Flags |= FastMathFlags::NoNaNs;
1324 if (FPMO->hasNoInfs())
1325 Flags |= FastMathFlags::NoInfs;
1326 if (FPMO->hasNoSignedZeros())
1327 Flags |= FastMathFlags::NoSignedZeros;
1328 if (FPMO->hasAllowReciprocal())
1329 Flags |= FastMathFlags::AllowReciprocal;
1335 void ModuleBitcodeWriter::writeValueAsMetadata(
1336 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1337 // Mimic an MDNode with a value as one operand.
1338 Value *V = MD->getValue();
1339 Record.push_back(VE.getTypeID(V->getType()));
1340 Record.push_back(VE.getValueID(V));
1341 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1345 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1346 SmallVectorImpl<uint64_t> &Record,
1348 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1349 Metadata *MD = N->getOperand(i);
1350 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1351 "Unexpected function-local metadata");
1352 Record.push_back(VE.getMetadataOrNullID(MD));
1354 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1355 : bitc::METADATA_NODE,
1360 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1361 // Assume the column is usually under 128, and always output the inlined-at
1362 // location (it's never more expensive than building an array size 1).
1363 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1364 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1370 return Stream.EmitAbbrev(Abbv);
1373 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1374 SmallVectorImpl<uint64_t> &Record,
1377 Abbrev = createDILocationAbbrev();
1379 Record.push_back(N->isDistinct());
1380 Record.push_back(N->getLine());
1381 Record.push_back(N->getColumn());
1382 Record.push_back(VE.getMetadataID(N->getScope()));
1383 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1385 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1389 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1390 // Assume the column is usually under 128, and always output the inlined-at
1391 // location (it's never more expensive than building an array size 1).
1392 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1393 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1394 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1400 return Stream.EmitAbbrev(Abbv);
1403 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1404 SmallVectorImpl<uint64_t> &Record,
1407 Abbrev = createGenericDINodeAbbrev();
1409 Record.push_back(N->isDistinct());
1410 Record.push_back(N->getTag());
1411 Record.push_back(0); // Per-tag version field; unused for now.
1413 for (auto &I : N->operands())
1414 Record.push_back(VE.getMetadataOrNullID(I));
1416 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1420 static uint64_t rotateSign(int64_t I) {
1422 return I < 0 ? ~(U << 1) : U << 1;
1425 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1426 SmallVectorImpl<uint64_t> &Record,
1428 Record.push_back(N->isDistinct());
1429 Record.push_back(N->getCount());
1430 Record.push_back(rotateSign(N->getLowerBound()));
1432 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1436 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1437 SmallVectorImpl<uint64_t> &Record,
1439 Record.push_back(N->isDistinct());
1440 Record.push_back(rotateSign(N->getValue()));
1441 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1443 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1447 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1448 SmallVectorImpl<uint64_t> &Record,
1450 Record.push_back(N->isDistinct());
1451 Record.push_back(N->getTag());
1452 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1453 Record.push_back(N->getSizeInBits());
1454 Record.push_back(N->getAlignInBits());
1455 Record.push_back(N->getEncoding());
1457 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1461 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1462 SmallVectorImpl<uint64_t> &Record,
1464 Record.push_back(N->isDistinct());
1465 Record.push_back(N->getTag());
1466 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1467 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1468 Record.push_back(N->getLine());
1469 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1470 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1471 Record.push_back(N->getSizeInBits());
1472 Record.push_back(N->getAlignInBits());
1473 Record.push_back(N->getOffsetInBits());
1474 Record.push_back(N->getFlags());
1475 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1477 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1481 void ModuleBitcodeWriter::writeDICompositeType(
1482 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1484 const unsigned IsNotUsedInOldTypeRef = 0x2;
1485 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1486 Record.push_back(N->getTag());
1487 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1488 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1489 Record.push_back(N->getLine());
1490 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1491 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1492 Record.push_back(N->getSizeInBits());
1493 Record.push_back(N->getAlignInBits());
1494 Record.push_back(N->getOffsetInBits());
1495 Record.push_back(N->getFlags());
1496 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1497 Record.push_back(N->getRuntimeLang());
1498 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1499 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1500 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1502 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1506 void ModuleBitcodeWriter::writeDISubroutineType(
1507 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1509 const unsigned HasNoOldTypeRefs = 0x2;
1510 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1511 Record.push_back(N->getFlags());
1512 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1513 Record.push_back(N->getCC());
1515 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1519 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1520 SmallVectorImpl<uint64_t> &Record,
1522 Record.push_back(N->isDistinct());
1523 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1524 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1525 Record.push_back(N->getChecksumKind());
1526 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1528 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1532 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1533 SmallVectorImpl<uint64_t> &Record,
1535 assert(N->isDistinct() && "Expected distinct compile units");
1536 Record.push_back(/* IsDistinct */ true);
1537 Record.push_back(N->getSourceLanguage());
1538 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1539 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1540 Record.push_back(N->isOptimized());
1541 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1542 Record.push_back(N->getRuntimeVersion());
1543 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1544 Record.push_back(N->getEmissionKind());
1545 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1546 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1547 Record.push_back(/* subprograms */ 0);
1548 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1549 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1550 Record.push_back(N->getDWOId());
1551 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1552 Record.push_back(N->getSplitDebugInlining());
1554 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1558 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1559 SmallVectorImpl<uint64_t> &Record,
1561 uint64_t HasUnitFlag = 1 << 1;
1562 Record.push_back(N->isDistinct() | HasUnitFlag);
1563 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1564 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1565 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1566 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1567 Record.push_back(N->getLine());
1568 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1569 Record.push_back(N->isLocalToUnit());
1570 Record.push_back(N->isDefinition());
1571 Record.push_back(N->getScopeLine());
1572 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1573 Record.push_back(N->getVirtuality());
1574 Record.push_back(N->getVirtualIndex());
1575 Record.push_back(N->getFlags());
1576 Record.push_back(N->isOptimized());
1577 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1578 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1579 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1580 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1581 Record.push_back(N->getThisAdjustment());
1583 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1587 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1588 SmallVectorImpl<uint64_t> &Record,
1590 Record.push_back(N->isDistinct());
1591 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1592 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1593 Record.push_back(N->getLine());
1594 Record.push_back(N->getColumn());
1596 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1600 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1601 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1603 Record.push_back(N->isDistinct());
1604 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1605 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1606 Record.push_back(N->getDiscriminator());
1608 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1612 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1613 SmallVectorImpl<uint64_t> &Record,
1615 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1616 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1617 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1618 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1619 Record.push_back(N->getLine());
1621 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1625 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1626 SmallVectorImpl<uint64_t> &Record,
1628 Record.push_back(N->isDistinct());
1629 Record.push_back(N->getMacinfoType());
1630 Record.push_back(N->getLine());
1631 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1632 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1634 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1638 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1639 SmallVectorImpl<uint64_t> &Record,
1641 Record.push_back(N->isDistinct());
1642 Record.push_back(N->getMacinfoType());
1643 Record.push_back(N->getLine());
1644 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1645 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1647 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1651 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1652 SmallVectorImpl<uint64_t> &Record,
1654 Record.push_back(N->isDistinct());
1655 for (auto &I : N->operands())
1656 Record.push_back(VE.getMetadataOrNullID(I));
1658 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1662 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1663 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1665 Record.push_back(N->isDistinct());
1666 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1667 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1669 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1673 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1674 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1676 Record.push_back(N->isDistinct());
1677 Record.push_back(N->getTag());
1678 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1679 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1680 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1682 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1686 void ModuleBitcodeWriter::writeDIGlobalVariable(
1687 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1689 const uint64_t Version = 1 << 1;
1690 Record.push_back((uint64_t)N->isDistinct() | Version);
1691 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1692 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1693 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1694 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1695 Record.push_back(N->getLine());
1696 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1697 Record.push_back(N->isLocalToUnit());
1698 Record.push_back(N->isDefinition());
1699 Record.push_back(/* expr */ 0);
1700 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1701 Record.push_back(N->getAlignInBits());
1703 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1707 void ModuleBitcodeWriter::writeDILocalVariable(
1708 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1710 // In order to support all possible bitcode formats in BitcodeReader we need
1711 // to distinguish the following cases:
1712 // 1) Record has no artificial tag (Record[1]),
1713 // has no obsolete inlinedAt field (Record[9]).
1714 // In this case Record size will be 8, HasAlignment flag is false.
1715 // 2) Record has artificial tag (Record[1]),
1716 // has no obsolete inlignedAt field (Record[9]).
1717 // In this case Record size will be 9, HasAlignment flag is false.
1718 // 3) Record has both artificial tag (Record[1]) and
1719 // obsolete inlignedAt field (Record[9]).
1720 // In this case Record size will be 10, HasAlignment flag is false.
1721 // 4) Record has neither artificial tag, nor inlignedAt field, but
1722 // HasAlignment flag is true and Record[8] contains alignment value.
1723 const uint64_t HasAlignmentFlag = 1 << 1;
1724 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1725 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1726 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1727 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1728 Record.push_back(N->getLine());
1729 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1730 Record.push_back(N->getArg());
1731 Record.push_back(N->getFlags());
1732 Record.push_back(N->getAlignInBits());
1734 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1738 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1739 SmallVectorImpl<uint64_t> &Record,
1741 Record.reserve(N->getElements().size() + 1);
1743 const uint64_t HasOpFragmentFlag = 1 << 1;
1744 Record.push_back((uint64_t)N->isDistinct() | HasOpFragmentFlag);
1745 Record.append(N->elements_begin(), N->elements_end());
1747 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1751 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1752 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1754 Record.push_back(N->isDistinct());
1755 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1756 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1758 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1762 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1763 SmallVectorImpl<uint64_t> &Record,
1765 Record.push_back(N->isDistinct());
1766 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1767 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1768 Record.push_back(N->getLine());
1769 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1770 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1771 Record.push_back(N->getAttributes());
1772 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1774 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1778 void ModuleBitcodeWriter::writeDIImportedEntity(
1779 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1781 Record.push_back(N->isDistinct());
1782 Record.push_back(N->getTag());
1783 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1784 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1785 Record.push_back(N->getLine());
1786 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1788 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1792 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1793 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1794 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1797 return Stream.EmitAbbrev(Abbv);
1800 void ModuleBitcodeWriter::writeNamedMetadata(
1801 SmallVectorImpl<uint64_t> &Record) {
1802 if (M.named_metadata_empty())
1805 unsigned Abbrev = createNamedMetadataAbbrev();
1806 for (const NamedMDNode &NMD : M.named_metadata()) {
1808 StringRef Str = NMD.getName();
1809 Record.append(Str.bytes_begin(), Str.bytes_end());
1810 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1813 // Write named metadata operands.
1814 for (const MDNode *N : NMD.operands())
1815 Record.push_back(VE.getMetadataID(N));
1816 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1821 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1822 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1823 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1826 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1827 return Stream.EmitAbbrev(Abbv);
1830 /// Write out a record for MDString.
1832 /// All the metadata strings in a metadata block are emitted in a single
1833 /// record. The sizes and strings themselves are shoved into a blob.
1834 void ModuleBitcodeWriter::writeMetadataStrings(
1835 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1836 if (Strings.empty())
1839 // Start the record with the number of strings.
1840 Record.push_back(bitc::METADATA_STRINGS);
1841 Record.push_back(Strings.size());
1843 // Emit the sizes of the strings in the blob.
1844 SmallString<256> Blob;
1846 BitstreamWriter W(Blob);
1847 for (const Metadata *MD : Strings)
1848 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1852 // Add the offset to the strings to the record.
1853 Record.push_back(Blob.size());
1855 // Add the strings to the blob.
1856 for (const Metadata *MD : Strings)
1857 Blob.append(cast<MDString>(MD)->getString());
1859 // Emit the final record.
1860 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1864 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1865 enum MetadataAbbrev : unsigned {
1866 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1867 #include "llvm/IR/Metadata.def"
1871 void ModuleBitcodeWriter::writeMetadataRecords(
1872 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1873 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1877 // Initialize MDNode abbreviations.
1878 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1879 #include "llvm/IR/Metadata.def"
1881 for (const Metadata *MD : MDs) {
1883 IndexPos->push_back(Stream.GetCurrentBitNo());
1884 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1885 assert(N->isResolved() && "Expected forward references to be resolved");
1887 switch (N->getMetadataID()) {
1889 llvm_unreachable("Invalid MDNode subclass");
1890 #define HANDLE_MDNODE_LEAF(CLASS) \
1891 case Metadata::CLASS##Kind: \
1893 write##CLASS(cast<CLASS>(N), Record, \
1894 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1896 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1898 #include "llvm/IR/Metadata.def"
1901 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1905 void ModuleBitcodeWriter::writeModuleMetadata() {
1906 if (!VE.hasMDs() && M.named_metadata_empty())
1909 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1910 SmallVector<uint64_t, 64> Record;
1912 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1913 // block and load any metadata.
1914 std::vector<unsigned> MDAbbrevs;
1916 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1917 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1918 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1919 createGenericDINodeAbbrev();
1921 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1922 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1923 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1924 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1925 unsigned OffsetAbbrev = Stream.EmitAbbrev(Abbv);
1927 Abbv = new BitCodeAbbrev();
1928 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1931 unsigned IndexAbbrev = Stream.EmitAbbrev(Abbv);
1933 // Emit MDStrings together upfront.
1934 writeMetadataStrings(VE.getMDStrings(), Record);
1936 // We only emit an index for the metadata record if we have more than a given
1937 // (naive) threshold of metadatas, otherwise it is not worth it.
1938 if (VE.getNonMDStrings().size() > IndexThreshold) {
1939 // Write a placeholder value in for the offset of the metadata index,
1940 // which is written after the records, so that it can include
1941 // the offset of each entry. The placeholder offset will be
1942 // updated after all records are emitted.
1943 uint64_t Vals[] = {0, 0};
1944 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1947 // Compute and save the bit offset to the current position, which will be
1948 // patched when we emit the index later. We can simply subtract the 64-bit
1949 // fixed size from the current bit number to get the location to backpatch.
1950 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1952 // This index will contain the bitpos for each individual record.
1953 std::vector<uint64_t> IndexPos;
1954 IndexPos.reserve(VE.getNonMDStrings().size());
1956 // Write all the records
1957 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1959 if (VE.getNonMDStrings().size() > IndexThreshold) {
1960 // Now that we have emitted all the records we will emit the index. But
1962 // backpatch the forward reference so that the reader can skip the records
1964 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1965 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1967 // Delta encode the index.
1968 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1969 for (auto &Elt : IndexPos) {
1970 auto EltDelta = Elt - PreviousValue;
1971 PreviousValue = Elt;
1974 // Emit the index record.
1975 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1979 // Write the named metadata now.
1980 writeNamedMetadata(Record);
1982 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1983 SmallVector<uint64_t, 4> Record;
1984 Record.push_back(VE.getValueID(&GO));
1985 pushGlobalMetadataAttachment(Record, GO);
1986 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1988 for (const Function &F : M)
1989 if (F.isDeclaration() && F.hasMetadata())
1990 AddDeclAttachedMetadata(F);
1991 // FIXME: Only store metadata for declarations here, and move data for global
1992 // variable definitions to a separate block (PR28134).
1993 for (const GlobalVariable &GV : M.globals())
1994 if (GV.hasMetadata())
1995 AddDeclAttachedMetadata(GV);
2000 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2004 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2005 SmallVector<uint64_t, 64> Record;
2006 writeMetadataStrings(VE.getMDStrings(), Record);
2007 writeMetadataRecords(VE.getNonMDStrings(), Record);
2011 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2012 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2013 // [n x [id, mdnode]]
2014 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2015 GO.getAllMetadata(MDs);
2016 for (const auto &I : MDs) {
2017 Record.push_back(I.first);
2018 Record.push_back(VE.getMetadataID(I.second));
2022 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2023 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2025 SmallVector<uint64_t, 64> Record;
2027 if (F.hasMetadata()) {
2028 pushGlobalMetadataAttachment(Record, F);
2029 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2033 // Write metadata attachments
2034 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2035 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2036 for (const BasicBlock &BB : F)
2037 for (const Instruction &I : BB) {
2039 I.getAllMetadataOtherThanDebugLoc(MDs);
2041 // If no metadata, ignore instruction.
2042 if (MDs.empty()) continue;
2044 Record.push_back(VE.getInstructionID(&I));
2046 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2047 Record.push_back(MDs[i].first);
2048 Record.push_back(VE.getMetadataID(MDs[i].second));
2050 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2057 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2058 SmallVector<uint64_t, 64> Record;
2060 // Write metadata kinds
2061 // METADATA_KIND - [n x [id, name]]
2062 SmallVector<StringRef, 8> Names;
2063 M.getMDKindNames(Names);
2065 if (Names.empty()) return;
2067 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2069 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2070 Record.push_back(MDKindID);
2071 StringRef KName = Names[MDKindID];
2072 Record.append(KName.begin(), KName.end());
2074 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2081 void ModuleBitcodeWriter::writeOperandBundleTags() {
2082 // Write metadata kinds
2084 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2086 // OPERAND_BUNDLE_TAG - [strchr x N]
2088 SmallVector<StringRef, 8> Tags;
2089 M.getOperandBundleTags(Tags);
2094 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2096 SmallVector<uint64_t, 64> Record;
2098 for (auto Tag : Tags) {
2099 Record.append(Tag.begin(), Tag.end());
2101 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2108 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2109 if ((int64_t)V >= 0)
2110 Vals.push_back(V << 1);
2112 Vals.push_back((-V << 1) | 1);
2115 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2117 if (FirstVal == LastVal) return;
2119 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2121 unsigned AggregateAbbrev = 0;
2122 unsigned String8Abbrev = 0;
2123 unsigned CString7Abbrev = 0;
2124 unsigned CString6Abbrev = 0;
2125 // If this is a constant pool for the module, emit module-specific abbrevs.
2127 // Abbrev for CST_CODE_AGGREGATE.
2128 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2129 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2132 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
2134 // Abbrev for CST_CODE_STRING.
2135 Abbv = new BitCodeAbbrev();
2136 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2139 String8Abbrev = Stream.EmitAbbrev(Abbv);
2140 // Abbrev for CST_CODE_CSTRING.
2141 Abbv = new BitCodeAbbrev();
2142 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2145 CString7Abbrev = Stream.EmitAbbrev(Abbv);
2146 // Abbrev for CST_CODE_CSTRING.
2147 Abbv = new BitCodeAbbrev();
2148 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2151 CString6Abbrev = Stream.EmitAbbrev(Abbv);
2154 SmallVector<uint64_t, 64> Record;
2156 const ValueEnumerator::ValueList &Vals = VE.getValues();
2157 Type *LastTy = nullptr;
2158 for (unsigned i = FirstVal; i != LastVal; ++i) {
2159 const Value *V = Vals[i].first;
2160 // If we need to switch types, do so now.
2161 if (V->getType() != LastTy) {
2162 LastTy = V->getType();
2163 Record.push_back(VE.getTypeID(LastTy));
2164 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2165 CONSTANTS_SETTYPE_ABBREV);
2169 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2170 Record.push_back(unsigned(IA->hasSideEffects()) |
2171 unsigned(IA->isAlignStack()) << 1 |
2172 unsigned(IA->getDialect()&1) << 2);
2174 // Add the asm string.
2175 const std::string &AsmStr = IA->getAsmString();
2176 Record.push_back(AsmStr.size());
2177 Record.append(AsmStr.begin(), AsmStr.end());
2179 // Add the constraint string.
2180 const std::string &ConstraintStr = IA->getConstraintString();
2181 Record.push_back(ConstraintStr.size());
2182 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2183 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2187 const Constant *C = cast<Constant>(V);
2188 unsigned Code = -1U;
2189 unsigned AbbrevToUse = 0;
2190 if (C->isNullValue()) {
2191 Code = bitc::CST_CODE_NULL;
2192 } else if (isa<UndefValue>(C)) {
2193 Code = bitc::CST_CODE_UNDEF;
2194 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2195 if (IV->getBitWidth() <= 64) {
2196 uint64_t V = IV->getSExtValue();
2197 emitSignedInt64(Record, V);
2198 Code = bitc::CST_CODE_INTEGER;
2199 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2200 } else { // Wide integers, > 64 bits in size.
2201 // We have an arbitrary precision integer value to write whose
2202 // bit width is > 64. However, in canonical unsigned integer
2203 // format it is likely that the high bits are going to be zero.
2204 // So, we only write the number of active words.
2205 unsigned NWords = IV->getValue().getActiveWords();
2206 const uint64_t *RawWords = IV->getValue().getRawData();
2207 for (unsigned i = 0; i != NWords; ++i) {
2208 emitSignedInt64(Record, RawWords[i]);
2210 Code = bitc::CST_CODE_WIDE_INTEGER;
2212 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2213 Code = bitc::CST_CODE_FLOAT;
2214 Type *Ty = CFP->getType();
2215 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2216 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2217 } else if (Ty->isX86_FP80Ty()) {
2218 // api needed to prevent premature destruction
2219 // bits are not in the same order as a normal i80 APInt, compensate.
2220 APInt api = CFP->getValueAPF().bitcastToAPInt();
2221 const uint64_t *p = api.getRawData();
2222 Record.push_back((p[1] << 48) | (p[0] >> 16));
2223 Record.push_back(p[0] & 0xffffLL);
2224 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2225 APInt api = CFP->getValueAPF().bitcastToAPInt();
2226 const uint64_t *p = api.getRawData();
2227 Record.push_back(p[0]);
2228 Record.push_back(p[1]);
2230 assert (0 && "Unknown FP type!");
2232 } else if (isa<ConstantDataSequential>(C) &&
2233 cast<ConstantDataSequential>(C)->isString()) {
2234 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2235 // Emit constant strings specially.
2236 unsigned NumElts = Str->getNumElements();
2237 // If this is a null-terminated string, use the denser CSTRING encoding.
2238 if (Str->isCString()) {
2239 Code = bitc::CST_CODE_CSTRING;
2240 --NumElts; // Don't encode the null, which isn't allowed by char6.
2242 Code = bitc::CST_CODE_STRING;
2243 AbbrevToUse = String8Abbrev;
2245 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2246 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2247 for (unsigned i = 0; i != NumElts; ++i) {
2248 unsigned char V = Str->getElementAsInteger(i);
2249 Record.push_back(V);
2250 isCStr7 &= (V & 128) == 0;
2252 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2256 AbbrevToUse = CString6Abbrev;
2258 AbbrevToUse = CString7Abbrev;
2259 } else if (const ConstantDataSequential *CDS =
2260 dyn_cast<ConstantDataSequential>(C)) {
2261 Code = bitc::CST_CODE_DATA;
2262 Type *EltTy = CDS->getType()->getElementType();
2263 if (isa<IntegerType>(EltTy)) {
2264 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2265 Record.push_back(CDS->getElementAsInteger(i));
2267 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2269 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2271 } else if (isa<ConstantAggregate>(C)) {
2272 Code = bitc::CST_CODE_AGGREGATE;
2273 for (const Value *Op : C->operands())
2274 Record.push_back(VE.getValueID(Op));
2275 AbbrevToUse = AggregateAbbrev;
2276 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2277 switch (CE->getOpcode()) {
2279 if (Instruction::isCast(CE->getOpcode())) {
2280 Code = bitc::CST_CODE_CE_CAST;
2281 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2282 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2283 Record.push_back(VE.getValueID(C->getOperand(0)));
2284 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2286 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2287 Code = bitc::CST_CODE_CE_BINOP;
2288 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2289 Record.push_back(VE.getValueID(C->getOperand(0)));
2290 Record.push_back(VE.getValueID(C->getOperand(1)));
2291 uint64_t Flags = getOptimizationFlags(CE);
2293 Record.push_back(Flags);
2296 case Instruction::GetElementPtr: {
2297 Code = bitc::CST_CODE_CE_GEP;
2298 const auto *GO = cast<GEPOperator>(C);
2299 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2300 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2301 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2302 Record.push_back((*Idx << 1) | GO->isInBounds());
2303 } else if (GO->isInBounds())
2304 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2305 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2306 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2307 Record.push_back(VE.getValueID(C->getOperand(i)));
2311 case Instruction::Select:
2312 Code = bitc::CST_CODE_CE_SELECT;
2313 Record.push_back(VE.getValueID(C->getOperand(0)));
2314 Record.push_back(VE.getValueID(C->getOperand(1)));
2315 Record.push_back(VE.getValueID(C->getOperand(2)));
2317 case Instruction::ExtractElement:
2318 Code = bitc::CST_CODE_CE_EXTRACTELT;
2319 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2320 Record.push_back(VE.getValueID(C->getOperand(0)));
2321 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2322 Record.push_back(VE.getValueID(C->getOperand(1)));
2324 case Instruction::InsertElement:
2325 Code = bitc::CST_CODE_CE_INSERTELT;
2326 Record.push_back(VE.getValueID(C->getOperand(0)));
2327 Record.push_back(VE.getValueID(C->getOperand(1)));
2328 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2329 Record.push_back(VE.getValueID(C->getOperand(2)));
2331 case Instruction::ShuffleVector:
2332 // If the return type and argument types are the same, this is a
2333 // standard shufflevector instruction. If the types are different,
2334 // then the shuffle is widening or truncating the input vectors, and
2335 // the argument type must also be encoded.
2336 if (C->getType() == C->getOperand(0)->getType()) {
2337 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2339 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2340 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2342 Record.push_back(VE.getValueID(C->getOperand(0)));
2343 Record.push_back(VE.getValueID(C->getOperand(1)));
2344 Record.push_back(VE.getValueID(C->getOperand(2)));
2346 case Instruction::ICmp:
2347 case Instruction::FCmp:
2348 Code = bitc::CST_CODE_CE_CMP;
2349 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2350 Record.push_back(VE.getValueID(C->getOperand(0)));
2351 Record.push_back(VE.getValueID(C->getOperand(1)));
2352 Record.push_back(CE->getPredicate());
2355 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2356 Code = bitc::CST_CODE_BLOCKADDRESS;
2357 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2358 Record.push_back(VE.getValueID(BA->getFunction()));
2359 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2364 llvm_unreachable("Unknown constant!");
2366 Stream.EmitRecord(Code, Record, AbbrevToUse);
2373 void ModuleBitcodeWriter::writeModuleConstants() {
2374 const ValueEnumerator::ValueList &Vals = VE.getValues();
2376 // Find the first constant to emit, which is the first non-globalvalue value.
2377 // We know globalvalues have been emitted by WriteModuleInfo.
2378 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2379 if (!isa<GlobalValue>(Vals[i].first)) {
2380 writeConstants(i, Vals.size(), true);
2386 /// pushValueAndType - The file has to encode both the value and type id for
2387 /// many values, because we need to know what type to create for forward
2388 /// references. However, most operands are not forward references, so this type
2389 /// field is not needed.
2391 /// This function adds V's value ID to Vals. If the value ID is higher than the
2392 /// instruction ID, then it is a forward reference, and it also includes the
2393 /// type ID. The value ID that is written is encoded relative to the InstID.
2394 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2395 SmallVectorImpl<unsigned> &Vals) {
2396 unsigned ValID = VE.getValueID(V);
2397 // Make encoding relative to the InstID.
2398 Vals.push_back(InstID - ValID);
2399 if (ValID >= InstID) {
2400 Vals.push_back(VE.getTypeID(V->getType()));
2406 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2408 SmallVector<unsigned, 64> Record;
2409 LLVMContext &C = CS.getInstruction()->getContext();
2411 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2412 const auto &Bundle = CS.getOperandBundleAt(i);
2413 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2415 for (auto &Input : Bundle.Inputs)
2416 pushValueAndType(Input, InstID, Record);
2418 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2423 /// pushValue - Like pushValueAndType, but where the type of the value is
2424 /// omitted (perhaps it was already encoded in an earlier operand).
2425 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2426 SmallVectorImpl<unsigned> &Vals) {
2427 unsigned ValID = VE.getValueID(V);
2428 Vals.push_back(InstID - ValID);
2431 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2432 SmallVectorImpl<uint64_t> &Vals) {
2433 unsigned ValID = VE.getValueID(V);
2434 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2435 emitSignedInt64(Vals, diff);
2438 /// WriteInstruction - Emit an instruction to the specified stream.
2439 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2441 SmallVectorImpl<unsigned> &Vals) {
2443 unsigned AbbrevToUse = 0;
2444 VE.setInstructionID(&I);
2445 switch (I.getOpcode()) {
2447 if (Instruction::isCast(I.getOpcode())) {
2448 Code = bitc::FUNC_CODE_INST_CAST;
2449 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2450 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2451 Vals.push_back(VE.getTypeID(I.getType()));
2452 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2454 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2455 Code = bitc::FUNC_CODE_INST_BINOP;
2456 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2457 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2458 pushValue(I.getOperand(1), InstID, Vals);
2459 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2460 uint64_t Flags = getOptimizationFlags(&I);
2462 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2463 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2464 Vals.push_back(Flags);
2469 case Instruction::GetElementPtr: {
2470 Code = bitc::FUNC_CODE_INST_GEP;
2471 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2472 auto &GEPInst = cast<GetElementPtrInst>(I);
2473 Vals.push_back(GEPInst.isInBounds());
2474 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2475 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2476 pushValueAndType(I.getOperand(i), InstID, Vals);
2479 case Instruction::ExtractValue: {
2480 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2481 pushValueAndType(I.getOperand(0), InstID, Vals);
2482 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2483 Vals.append(EVI->idx_begin(), EVI->idx_end());
2486 case Instruction::InsertValue: {
2487 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2488 pushValueAndType(I.getOperand(0), InstID, Vals);
2489 pushValueAndType(I.getOperand(1), InstID, Vals);
2490 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2491 Vals.append(IVI->idx_begin(), IVI->idx_end());
2494 case Instruction::Select:
2495 Code = bitc::FUNC_CODE_INST_VSELECT;
2496 pushValueAndType(I.getOperand(1), InstID, Vals);
2497 pushValue(I.getOperand(2), InstID, Vals);
2498 pushValueAndType(I.getOperand(0), InstID, Vals);
2500 case Instruction::ExtractElement:
2501 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2502 pushValueAndType(I.getOperand(0), InstID, Vals);
2503 pushValueAndType(I.getOperand(1), InstID, Vals);
2505 case Instruction::InsertElement:
2506 Code = bitc::FUNC_CODE_INST_INSERTELT;
2507 pushValueAndType(I.getOperand(0), InstID, Vals);
2508 pushValue(I.getOperand(1), InstID, Vals);
2509 pushValueAndType(I.getOperand(2), InstID, Vals);
2511 case Instruction::ShuffleVector:
2512 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2513 pushValueAndType(I.getOperand(0), InstID, Vals);
2514 pushValue(I.getOperand(1), InstID, Vals);
2515 pushValue(I.getOperand(2), InstID, Vals);
2517 case Instruction::ICmp:
2518 case Instruction::FCmp: {
2519 // compare returning Int1Ty or vector of Int1Ty
2520 Code = bitc::FUNC_CODE_INST_CMP2;
2521 pushValueAndType(I.getOperand(0), InstID, Vals);
2522 pushValue(I.getOperand(1), InstID, Vals);
2523 Vals.push_back(cast<CmpInst>(I).getPredicate());
2524 uint64_t Flags = getOptimizationFlags(&I);
2526 Vals.push_back(Flags);
2530 case Instruction::Ret:
2532 Code = bitc::FUNC_CODE_INST_RET;
2533 unsigned NumOperands = I.getNumOperands();
2534 if (NumOperands == 0)
2535 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2536 else if (NumOperands == 1) {
2537 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2538 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2540 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2541 pushValueAndType(I.getOperand(i), InstID, Vals);
2545 case Instruction::Br:
2547 Code = bitc::FUNC_CODE_INST_BR;
2548 const BranchInst &II = cast<BranchInst>(I);
2549 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2550 if (II.isConditional()) {
2551 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2552 pushValue(II.getCondition(), InstID, Vals);
2556 case Instruction::Switch:
2558 Code = bitc::FUNC_CODE_INST_SWITCH;
2559 const SwitchInst &SI = cast<SwitchInst>(I);
2560 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2561 pushValue(SI.getCondition(), InstID, Vals);
2562 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2563 for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2564 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2565 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2569 case Instruction::IndirectBr:
2570 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2571 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2572 // Encode the address operand as relative, but not the basic blocks.
2573 pushValue(I.getOperand(0), InstID, Vals);
2574 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2575 Vals.push_back(VE.getValueID(I.getOperand(i)));
2578 case Instruction::Invoke: {
2579 const InvokeInst *II = cast<InvokeInst>(&I);
2580 const Value *Callee = II->getCalledValue();
2581 FunctionType *FTy = II->getFunctionType();
2583 if (II->hasOperandBundles())
2584 writeOperandBundles(II, InstID);
2586 Code = bitc::FUNC_CODE_INST_INVOKE;
2588 Vals.push_back(VE.getAttributeID(II->getAttributes()));
2589 Vals.push_back(II->getCallingConv() | 1 << 13);
2590 Vals.push_back(VE.getValueID(II->getNormalDest()));
2591 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2592 Vals.push_back(VE.getTypeID(FTy));
2593 pushValueAndType(Callee, InstID, Vals);
2595 // Emit value #'s for the fixed parameters.
2596 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2597 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2599 // Emit type/value pairs for varargs params.
2600 if (FTy->isVarArg()) {
2601 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2603 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2607 case Instruction::Resume:
2608 Code = bitc::FUNC_CODE_INST_RESUME;
2609 pushValueAndType(I.getOperand(0), InstID, Vals);
2611 case Instruction::CleanupRet: {
2612 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2613 const auto &CRI = cast<CleanupReturnInst>(I);
2614 pushValue(CRI.getCleanupPad(), InstID, Vals);
2615 if (CRI.hasUnwindDest())
2616 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2619 case Instruction::CatchRet: {
2620 Code = bitc::FUNC_CODE_INST_CATCHRET;
2621 const auto &CRI = cast<CatchReturnInst>(I);
2622 pushValue(CRI.getCatchPad(), InstID, Vals);
2623 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2626 case Instruction::CleanupPad:
2627 case Instruction::CatchPad: {
2628 const auto &FuncletPad = cast<FuncletPadInst>(I);
2629 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2630 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2631 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2633 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2634 Vals.push_back(NumArgOperands);
2635 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2636 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2639 case Instruction::CatchSwitch: {
2640 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2641 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2643 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2645 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2646 Vals.push_back(NumHandlers);
2647 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2648 Vals.push_back(VE.getValueID(CatchPadBB));
2650 if (CatchSwitch.hasUnwindDest())
2651 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2654 case Instruction::Unreachable:
2655 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2656 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2659 case Instruction::PHI: {
2660 const PHINode &PN = cast<PHINode>(I);
2661 Code = bitc::FUNC_CODE_INST_PHI;
2662 // With the newer instruction encoding, forward references could give
2663 // negative valued IDs. This is most common for PHIs, so we use
2665 SmallVector<uint64_t, 128> Vals64;
2666 Vals64.push_back(VE.getTypeID(PN.getType()));
2667 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2668 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2669 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2671 // Emit a Vals64 vector and exit.
2672 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2677 case Instruction::LandingPad: {
2678 const LandingPadInst &LP = cast<LandingPadInst>(I);
2679 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2680 Vals.push_back(VE.getTypeID(LP.getType()));
2681 Vals.push_back(LP.isCleanup());
2682 Vals.push_back(LP.getNumClauses());
2683 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2685 Vals.push_back(LandingPadInst::Catch);
2687 Vals.push_back(LandingPadInst::Filter);
2688 pushValueAndType(LP.getClause(I), InstID, Vals);
2693 case Instruction::Alloca: {
2694 Code = bitc::FUNC_CODE_INST_ALLOCA;
2695 const AllocaInst &AI = cast<AllocaInst>(I);
2696 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2697 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2698 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2699 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2700 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2701 "not enough bits for maximum alignment");
2702 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2703 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2704 AlignRecord |= 1 << 6;
2705 AlignRecord |= AI.isSwiftError() << 7;
2706 Vals.push_back(AlignRecord);
2710 case Instruction::Load:
2711 if (cast<LoadInst>(I).isAtomic()) {
2712 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2713 pushValueAndType(I.getOperand(0), InstID, Vals);
2715 Code = bitc::FUNC_CODE_INST_LOAD;
2716 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2717 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2719 Vals.push_back(VE.getTypeID(I.getType()));
2720 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2721 Vals.push_back(cast<LoadInst>(I).isVolatile());
2722 if (cast<LoadInst>(I).isAtomic()) {
2723 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2724 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2727 case Instruction::Store:
2728 if (cast<StoreInst>(I).isAtomic())
2729 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2731 Code = bitc::FUNC_CODE_INST_STORE;
2732 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2733 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2734 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2735 Vals.push_back(cast<StoreInst>(I).isVolatile());
2736 if (cast<StoreInst>(I).isAtomic()) {
2737 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2738 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2741 case Instruction::AtomicCmpXchg:
2742 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2743 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2744 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2745 pushValue(I.getOperand(2), InstID, Vals); // newval.
2746 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2748 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2750 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2752 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2753 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2755 case Instruction::AtomicRMW:
2756 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2757 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2758 pushValue(I.getOperand(1), InstID, Vals); // val.
2760 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2761 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2762 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2764 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2766 case Instruction::Fence:
2767 Code = bitc::FUNC_CODE_INST_FENCE;
2768 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2769 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2771 case Instruction::Call: {
2772 const CallInst &CI = cast<CallInst>(I);
2773 FunctionType *FTy = CI.getFunctionType();
2775 if (CI.hasOperandBundles())
2776 writeOperandBundles(&CI, InstID);
2778 Code = bitc::FUNC_CODE_INST_CALL;
2780 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2782 unsigned Flags = getOptimizationFlags(&I);
2783 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2784 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2785 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2786 1 << bitc::CALL_EXPLICIT_TYPE |
2787 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2788 unsigned(Flags != 0) << bitc::CALL_FMF);
2790 Vals.push_back(Flags);
2792 Vals.push_back(VE.getTypeID(FTy));
2793 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2795 // Emit value #'s for the fixed parameters.
2796 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2797 // Check for labels (can happen with asm labels).
2798 if (FTy->getParamType(i)->isLabelTy())
2799 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2801 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2804 // Emit type/value pairs for varargs params.
2805 if (FTy->isVarArg()) {
2806 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2808 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2812 case Instruction::VAArg:
2813 Code = bitc::FUNC_CODE_INST_VAARG;
2814 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2815 pushValue(I.getOperand(0), InstID, Vals); // valist.
2816 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2820 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2824 /// Emit names for globals/functions etc. \p IsModuleLevel is true when
2825 /// we are writing the module-level VST, where we are including a function
2826 /// bitcode index and need to backpatch the VST forward declaration record.
2827 void ModuleBitcodeWriter::writeValueSymbolTable(
2828 const ValueSymbolTable &VST, bool IsModuleLevel,
2829 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) {
2831 // writeValueSymbolTableForwardDecl should have returned early as
2832 // well. Ensure this handling remains in sync by asserting that
2833 // the placeholder offset is not set.
2834 assert(!IsModuleLevel || !hasVSTOffsetPlaceholder());
2838 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2839 // Get the offset of the VST we are writing, and backpatch it into
2840 // the VST forward declaration record.
2841 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2842 // The BitcodeStartBit was the stream offset of the identification block.
2843 VSTOffset -= bitcodeStartBit();
2844 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2845 // Note that we add 1 here because the offset is relative to one word
2846 // before the start of the identification block, which was historically
2847 // always the start of the regular bitcode header.
2848 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2851 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2853 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2854 // records, which are not used in the per-function VSTs.
2855 unsigned FnEntry8BitAbbrev;
2856 unsigned FnEntry7BitAbbrev;
2857 unsigned FnEntry6BitAbbrev;
2858 unsigned GUIDEntryAbbrev;
2859 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2860 // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2861 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2862 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2866 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2867 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2869 // 7-bit fixed width VST_CODE_FNENTRY function strings.
2870 Abbv = new BitCodeAbbrev();
2871 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2872 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2873 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2876 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2878 // 6-bit char6 VST_CODE_FNENTRY function strings.
2879 Abbv = new BitCodeAbbrev();
2880 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2884 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2885 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2887 // FIXME: Change the name of this record as it is now used by
2888 // the per-module index as well.
2889 Abbv = new BitCodeAbbrev();
2890 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2892 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2893 GUIDEntryAbbrev = Stream.EmitAbbrev(Abbv);
2896 // FIXME: Set up the abbrev, we know how many values there are!
2897 // FIXME: We know if the type names can use 7-bit ascii.
2898 SmallVector<uint64_t, 64> NameVals;
2900 for (const ValueName &Name : VST) {
2901 // Figure out the encoding to use for the name.
2902 StringEncoding Bits =
2903 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2905 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2906 NameVals.push_back(VE.getValueID(Name.getValue()));
2908 Function *F = dyn_cast<Function>(Name.getValue());
2910 // If value is an alias, need to get the aliased base object to
2911 // see if it is a function.
2912 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2913 if (GA && GA->getBaseObject())
2914 F = dyn_cast<Function>(GA->getBaseObject());
2917 // VST_CODE_ENTRY: [valueid, namechar x N]
2918 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2919 // VST_CODE_BBENTRY: [bbid, namechar x N]
2921 if (isa<BasicBlock>(Name.getValue())) {
2922 Code = bitc::VST_CODE_BBENTRY;
2923 if (Bits == SE_Char6)
2924 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2925 } else if (F && !F->isDeclaration()) {
2926 // Must be the module-level VST, where we pass in the Index and
2927 // have a VSTOffsetPlaceholder. The function-level VST should not
2928 // contain any Function symbols.
2929 assert(FunctionToBitcodeIndex);
2930 assert(hasVSTOffsetPlaceholder());
2932 // Save the word offset of the function (from the start of the
2933 // actual bitcode written to the stream).
2934 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit();
2935 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2936 // Note that we add 1 here because the offset is relative to one word
2937 // before the start of the identification block, which was historically
2938 // always the start of the regular bitcode header.
2939 NameVals.push_back(BitcodeIndex / 32 + 1);
2941 Code = bitc::VST_CODE_FNENTRY;
2942 AbbrevToUse = FnEntry8BitAbbrev;
2943 if (Bits == SE_Char6)
2944 AbbrevToUse = FnEntry6BitAbbrev;
2945 else if (Bits == SE_Fixed7)
2946 AbbrevToUse = FnEntry7BitAbbrev;
2948 Code = bitc::VST_CODE_ENTRY;
2949 if (Bits == SE_Char6)
2950 AbbrevToUse = VST_ENTRY_6_ABBREV;
2951 else if (Bits == SE_Fixed7)
2952 AbbrevToUse = VST_ENTRY_7_ABBREV;
2955 for (const auto P : Name.getKey())
2956 NameVals.push_back((unsigned char)P);
2958 // Emit the finished record.
2959 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2962 // Emit any GUID valueIDs created for indirect call edges into the
2963 // module-level VST.
2964 if (IsModuleLevel && hasVSTOffsetPlaceholder())
2965 for (const auto &GI : valueIds()) {
2966 NameVals.push_back(GI.second);
2967 NameVals.push_back(GI.first);
2968 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals,
2975 /// Emit function names and summary offsets for the combined index
2976 /// used by ThinLTO.
2977 void IndexBitcodeWriter::writeCombinedValueSymbolTable() {
2978 assert(hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder");
2979 // Get the offset of the VST we are writing, and backpatch it into
2980 // the VST forward declaration record.
2981 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2982 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2983 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2985 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2987 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2988 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2991 unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
2993 SmallVector<uint64_t, 64> NameVals;
2994 for (const auto &GVI : valueIds()) {
2995 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2996 NameVals.push_back(GVI.second);
2997 NameVals.push_back(GVI.first);
2999 // Emit the finished record.
3000 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
3006 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3007 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3009 if (isa<BasicBlock>(Order.V))
3010 Code = bitc::USELIST_CODE_BB;
3012 Code = bitc::USELIST_CODE_DEFAULT;
3014 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3015 Record.push_back(VE.getValueID(Order.V));
3016 Stream.EmitRecord(Code, Record);
3019 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3020 assert(VE.shouldPreserveUseListOrder() &&
3021 "Expected to be preserving use-list order");
3023 auto hasMore = [&]() {
3024 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3030 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3032 writeUseList(std::move(VE.UseListOrders.back()));
3033 VE.UseListOrders.pop_back();
3038 /// Emit a function body to the module stream.
3039 void ModuleBitcodeWriter::writeFunction(
3041 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3042 // Save the bitcode index of the start of this function block for recording
3044 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3046 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3047 VE.incorporateFunction(F);
3049 SmallVector<unsigned, 64> Vals;
3051 // Emit the number of basic blocks, so the reader can create them ahead of
3053 Vals.push_back(VE.getBasicBlocks().size());
3054 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3057 // If there are function-local constants, emit them now.
3058 unsigned CstStart, CstEnd;
3059 VE.getFunctionConstantRange(CstStart, CstEnd);
3060 writeConstants(CstStart, CstEnd, false);
3062 // If there is function-local metadata, emit it now.
3063 writeFunctionMetadata(F);
3065 // Keep a running idea of what the instruction ID is.
3066 unsigned InstID = CstEnd;
3068 bool NeedsMetadataAttachment = F.hasMetadata();
3070 DILocation *LastDL = nullptr;
3071 // Finally, emit all the instructions, in order.
3072 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3073 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3075 writeInstruction(*I, InstID, Vals);
3077 if (!I->getType()->isVoidTy())
3080 // If the instruction has metadata, write a metadata attachment later.
3081 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3083 // If the instruction has a debug location, emit it.
3084 DILocation *DL = I->getDebugLoc();
3089 // Just repeat the same debug loc as last time.
3090 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3094 Vals.push_back(DL->getLine());
3095 Vals.push_back(DL->getColumn());
3096 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3097 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3098 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3104 // Emit names for all the instructions etc.
3105 if (auto *Symtab = F.getValueSymbolTable())
3106 writeValueSymbolTable(*Symtab);
3108 if (NeedsMetadataAttachment)
3109 writeFunctionMetadataAttachment(F);
3110 if (VE.shouldPreserveUseListOrder())
3111 writeUseListBlock(&F);
3116 // Emit blockinfo, which defines the standard abbreviations etc.
3117 void ModuleBitcodeWriter::writeBlockInfo() {
3118 // We only want to emit block info records for blocks that have multiple
3119 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3120 // Other blocks can define their abbrevs inline.
3121 Stream.EnterBlockInfoBlock();
3123 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3124 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3129 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3131 llvm_unreachable("Unexpected abbrev ordering!");
3134 { // 7-bit fixed width VST_CODE_ENTRY strings.
3135 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3136 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3140 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3142 llvm_unreachable("Unexpected abbrev ordering!");
3144 { // 6-bit char6 VST_CODE_ENTRY strings.
3145 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3146 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3150 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3152 llvm_unreachable("Unexpected abbrev ordering!");
3154 { // 6-bit char6 VST_CODE_BBENTRY strings.
3155 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3156 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3160 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3161 VST_BBENTRY_6_ABBREV)
3162 llvm_unreachable("Unexpected abbrev ordering!");
3167 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3168 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3169 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3171 VE.computeBitsRequiredForTypeIndicies()));
3172 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3173 CONSTANTS_SETTYPE_ABBREV)
3174 llvm_unreachable("Unexpected abbrev ordering!");
3177 { // INTEGER abbrev for CONSTANTS_BLOCK.
3178 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3179 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3181 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3182 CONSTANTS_INTEGER_ABBREV)
3183 llvm_unreachable("Unexpected abbrev ordering!");
3186 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3187 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3188 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3191 VE.computeBitsRequiredForTypeIndicies()));
3192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3194 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3195 CONSTANTS_CE_CAST_Abbrev)
3196 llvm_unreachable("Unexpected abbrev ordering!");
3198 { // NULL abbrev for CONSTANTS_BLOCK.
3199 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3200 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3201 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3202 CONSTANTS_NULL_Abbrev)
3203 llvm_unreachable("Unexpected abbrev ordering!");
3206 // FIXME: This should only use space for first class types!
3208 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3209 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3210 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3213 VE.computeBitsRequiredForTypeIndicies()));
3214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3216 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3217 FUNCTION_INST_LOAD_ABBREV)
3218 llvm_unreachable("Unexpected abbrev ordering!");
3220 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3221 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3222 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3226 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3227 FUNCTION_INST_BINOP_ABBREV)
3228 llvm_unreachable("Unexpected abbrev ordering!");
3230 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3231 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3232 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3237 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3238 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3239 llvm_unreachable("Unexpected abbrev ordering!");
3241 { // INST_CAST abbrev for FUNCTION_BLOCK.
3242 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3243 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3246 VE.computeBitsRequiredForTypeIndicies()));
3247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3248 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3249 FUNCTION_INST_CAST_ABBREV)
3250 llvm_unreachable("Unexpected abbrev ordering!");
3253 { // INST_RET abbrev for FUNCTION_BLOCK.
3254 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3255 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3256 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3257 FUNCTION_INST_RET_VOID_ABBREV)
3258 llvm_unreachable("Unexpected abbrev ordering!");
3260 { // INST_RET abbrev for FUNCTION_BLOCK.
3261 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3262 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3264 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3265 FUNCTION_INST_RET_VAL_ABBREV)
3266 llvm_unreachable("Unexpected abbrev ordering!");
3268 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3269 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3270 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3271 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3272 FUNCTION_INST_UNREACHABLE_ABBREV)
3273 llvm_unreachable("Unexpected abbrev ordering!");
3276 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3277 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3280 Log2_32_Ceil(VE.getTypes().size() + 1)));
3281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3283 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3284 FUNCTION_INST_GEP_ABBREV)
3285 llvm_unreachable("Unexpected abbrev ordering!");
3291 /// Write the module path strings, currently only used when generating
3292 /// a combined index file.
3293 void IndexBitcodeWriter::writeModStrings() {
3294 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3296 // TODO: See which abbrev sizes we actually need to emit
3298 // 8-bit fixed-width MST_ENTRY strings.
3299 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3300 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3304 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
3306 // 7-bit fixed width MST_ENTRY strings.
3307 Abbv = new BitCodeAbbrev();
3308 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3312 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
3314 // 6-bit char6 MST_ENTRY strings.
3315 Abbv = new BitCodeAbbrev();
3316 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3320 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
3322 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3323 Abbv = new BitCodeAbbrev();
3324 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
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 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3330 unsigned AbbrevHash = Stream.EmitAbbrev(Abbv);
3332 SmallVector<unsigned, 64> Vals;
3333 for (const auto &MPSE : Index.modulePaths()) {
3334 if (!doIncludeModule(MPSE.getKey()))
3336 StringEncoding Bits =
3337 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3338 unsigned AbbrevToUse = Abbrev8Bit;
3339 if (Bits == SE_Char6)
3340 AbbrevToUse = Abbrev6Bit;
3341 else if (Bits == SE_Fixed7)
3342 AbbrevToUse = Abbrev7Bit;
3344 Vals.push_back(MPSE.getValue().first);
3346 for (const auto P : MPSE.getKey())
3347 Vals.push_back((unsigned char)P);
3349 // Emit the finished record.
3350 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3353 // Emit an optional hash for the module now
3354 auto &Hash = MPSE.getValue().second;
3355 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3356 for (auto Val : Hash) {
3359 Vals.push_back(Val);
3362 // Emit the hash record.
3363 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3371 // Helper to emit a single function summary record.
3372 void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3373 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3374 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3375 const Function &F) {
3376 NameVals.push_back(ValueID);
3378 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3379 if (!FS->type_tests().empty())
3380 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3382 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3383 NameVals.push_back(FS->instCount());
3384 NameVals.push_back(FS->refs().size());
3386 for (auto &RI : FS->refs())
3387 NameVals.push_back(VE.getValueID(RI.getValue()));
3389 bool HasProfileData = F.getEntryCount().hasValue();
3390 for (auto &ECI : FS->calls()) {
3391 NameVals.push_back(getValueId(ECI.first));
3393 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3396 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3398 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3400 // Emit the finished record.
3401 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3405 // Collect the global value references in the given variable's initializer,
3406 // and emit them in a summary record.
3407 void ModuleBitcodeWriter::writeModuleLevelReferences(
3408 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3409 unsigned FSModRefsAbbrev) {
3411 Index->findGlobalValueSummaryList(GlobalValue::getGUID(V.getName()));
3412 if (Summaries == Index->end()) {
3413 // Only declarations should not have a summary (a declaration might however
3414 // have a summary if the def was in module level asm).
3415 assert(V.isDeclaration());
3418 auto *Summary = Summaries->second.front().get();
3419 NameVals.push_back(VE.getValueID(&V));
3420 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3421 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3423 unsigned SizeBeforeRefs = NameVals.size();
3424 for (auto &RI : VS->refs())
3425 NameVals.push_back(VE.getValueID(RI.getValue()));
3426 // Sort the refs for determinism output, the vector returned by FS->refs() has
3427 // been initialized from a DenseSet.
3428 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3430 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3435 // Current version for the summary.
3436 // This is bumped whenever we introduce changes in the way some record are
3437 // interpreted, like flags for instance.
3438 static const uint64_t INDEX_VERSION = 2;
3440 /// Emit the per-module summary section alongside the rest of
3441 /// the module's bitcode.
3442 void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3443 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
3445 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3447 if (Index->begin() == Index->end()) {
3452 // Abbrev for FS_PERMODULE.
3453 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3454 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3459 // numrefs x valueid, n x (valueid)
3460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3462 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
3464 // Abbrev for FS_PERMODULE_PROFILE.
3465 Abbv = new BitCodeAbbrev();
3466 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3471 // numrefs x valueid, n x (valueid, hotness)
3472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3474 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
3476 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3477 Abbv = new BitCodeAbbrev();
3478 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3480 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3483 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
3485 // Abbrev for FS_ALIAS.
3486 Abbv = new BitCodeAbbrev();
3487 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3491 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
3493 SmallVector<uint64_t, 64> NameVals;
3494 // Iterate over the list of functions instead of the Index to
3495 // ensure the ordering is stable.
3496 for (const Function &F : M) {
3497 // Summary emission does not support anonymous functions, they have to
3498 // renamed using the anonymous function renaming pass.
3500 report_fatal_error("Unexpected anonymous function when writing summary");
3503 Index->findGlobalValueSummaryList(GlobalValue::getGUID(F.getName()));
3504 if (Summaries == Index->end()) {
3505 // Only declarations should not have a summary (a declaration might
3506 // however have a summary if the def was in module level asm).
3507 assert(F.isDeclaration());
3510 auto *Summary = Summaries->second.front().get();
3511 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3512 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3515 // Capture references from GlobalVariable initializers, which are outside
3516 // of a function scope.
3517 for (const GlobalVariable &G : M.globals())
3518 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3520 for (const GlobalAlias &A : M.aliases()) {
3521 auto *Aliasee = A.getBaseObject();
3522 if (!Aliasee->hasName())
3523 // Nameless function don't have an entry in the summary, skip it.
3525 auto AliasId = VE.getValueID(&A);
3526 auto AliaseeId = VE.getValueID(Aliasee);
3527 NameVals.push_back(AliasId);
3528 auto *Summary = Index->getGlobalValueSummary(A);
3529 AliasSummary *AS = cast<AliasSummary>(Summary);
3530 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3531 NameVals.push_back(AliaseeId);
3532 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3539 /// Emit the combined summary section into the combined index file.
3540 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3541 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3542 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3544 // Abbrev for FS_COMBINED.
3545 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3546 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3550 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3551 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3552 // numrefs x valueid, n x (valueid)
3553 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3554 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3555 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
3557 // Abbrev for FS_COMBINED_PROFILE.
3558 Abbv = new BitCodeAbbrev();
3559 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3560 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3561 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3562 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3563 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3564 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3565 // numrefs x valueid, n x (valueid, hotness)
3566 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3567 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3568 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
3570 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3571 Abbv = new BitCodeAbbrev();
3572 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3573 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3574 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3575 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3576 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3577 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3578 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
3580 // Abbrev for FS_COMBINED_ALIAS.
3581 Abbv = new BitCodeAbbrev();
3582 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3587 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
3589 // The aliases are emitted as a post-pass, and will point to the value
3590 // id of the aliasee. Save them in a vector for post-processing.
3591 SmallVector<AliasSummary *, 64> Aliases;
3593 // Save the value id for each summary for alias emission.
3594 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3596 SmallVector<uint64_t, 64> NameVals;
3598 // For local linkage, we also emit the original name separately
3599 // immediately after the record.
3600 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3601 if (!GlobalValue::isLocalLinkage(S.linkage()))
3603 NameVals.push_back(S.getOriginalName());
3604 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3608 for (const auto &I : *this) {
3609 GlobalValueSummary *S = I.second;
3612 assert(hasValueId(I.first));
3613 unsigned ValueId = getValueId(I.first);
3614 SummaryToValueIdMap[S] = ValueId;
3616 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3617 // Will process aliases as a post-pass because the reader wants all
3618 // global to be loaded first.
3619 Aliases.push_back(AS);
3623 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3624 NameVals.push_back(ValueId);
3625 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3626 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3627 for (auto &RI : VS->refs()) {
3628 NameVals.push_back(getValueId(RI.getGUID()));
3631 // Emit the finished record.
3632 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3635 MaybeEmitOriginalName(*S);
3639 auto *FS = cast<FunctionSummary>(S);
3640 if (!FS->type_tests().empty())
3641 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3643 NameVals.push_back(ValueId);
3644 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3645 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3646 NameVals.push_back(FS->instCount());
3647 NameVals.push_back(FS->refs().size());
3649 for (auto &RI : FS->refs()) {
3650 NameVals.push_back(getValueId(RI.getGUID()));
3653 bool HasProfileData = false;
3654 for (auto &EI : FS->calls()) {
3655 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3660 for (auto &EI : FS->calls()) {
3661 // If this GUID doesn't have a value id, it doesn't have a function
3662 // summary and we don't need to record any calls to it.
3663 if (!hasValueId(EI.first.getGUID()))
3665 NameVals.push_back(getValueId(EI.first.getGUID()));
3667 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3670 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3672 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3674 // Emit the finished record.
3675 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3677 MaybeEmitOriginalName(*S);
3680 for (auto *AS : Aliases) {
3681 auto AliasValueId = SummaryToValueIdMap[AS];
3682 assert(AliasValueId);
3683 NameVals.push_back(AliasValueId);
3684 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3685 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3686 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3687 assert(AliaseeValueId);
3688 NameVals.push_back(AliaseeValueId);
3690 // Emit the finished record.
3691 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3693 MaybeEmitOriginalName(*AS);
3699 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3700 /// current llvm version, and a record for the epoch number.
3701 void writeIdentificationBlock(BitstreamWriter &Stream) {
3702 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3704 // Write the "user readable" string identifying the bitcode producer
3705 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3706 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3709 auto StringAbbrev = Stream.EmitAbbrev(Abbv);
3710 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3711 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
3713 // Write the epoch version
3714 Abbv = new BitCodeAbbrev();
3715 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3717 auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
3718 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3719 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3723 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3724 // Emit the module's hash.
3725 // MODULE_CODE_HASH: [5*i32]
3727 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3728 Buffer.size() - BlockStartPos));
3729 StringRef Hash = Hasher.result();
3731 for (int Pos = 0; Pos < 20; Pos += 4) {
3732 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3735 // Emit the finished record.
3736 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3739 void ModuleBitcodeWriter::write() {
3740 writeIdentificationBlock(Stream);
3742 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3743 size_t BlockStartPos = Buffer.size();
3745 SmallVector<unsigned, 1> Vals;
3746 unsigned CurVersion = 1;
3747 Vals.push_back(CurVersion);
3748 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3750 // Emit blockinfo, which defines the standard abbreviations etc.
3753 // Emit information about attribute groups.
3754 writeAttributeGroupTable();
3756 // Emit information about parameter attributes.
3757 writeAttributeTable();
3759 // Emit information describing all of the types in the module.
3764 // Emit top-level description of module, including target triple, inline asm,
3765 // descriptors for global variables, and function prototype info.
3769 writeModuleConstants();
3771 // Emit metadata kind names.
3772 writeModuleMetadataKinds();
3775 writeModuleMetadata();
3777 // Emit module-level use-lists.
3778 if (VE.shouldPreserveUseListOrder())
3779 writeUseListBlock(nullptr);
3781 writeOperandBundleTags();
3783 // Emit function bodies.
3784 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3785 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3786 if (!F->isDeclaration())
3787 writeFunction(*F, FunctionToBitcodeIndex);
3789 // Need to write after the above call to WriteFunction which populates
3790 // the summary information in the index.
3792 writePerModuleGlobalValueSummary();
3794 writeValueSymbolTable(M.getValueSymbolTable(),
3795 /* IsModuleLevel */ true, &FunctionToBitcodeIndex);
3798 writeModuleHash(BlockStartPos);
3804 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3805 uint32_t &Position) {
3806 support::endian::write32le(&Buffer[Position], Value);
3810 /// If generating a bc file on darwin, we have to emit a
3811 /// header and trailer to make it compatible with the system archiver. To do
3812 /// this we emit the following header, and then emit a trailer that pads the
3813 /// file out to be a multiple of 16 bytes.
3815 /// struct bc_header {
3816 /// uint32_t Magic; // 0x0B17C0DE
3817 /// uint32_t Version; // Version, currently always 0.
3818 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3819 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
3820 /// uint32_t CPUType; // CPU specifier.
3821 /// ... potentially more later ...
3823 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3825 unsigned CPUType = ~0U;
3827 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3828 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3829 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3830 // specific constants here because they are implicitly part of the Darwin ABI.
3832 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3833 DARWIN_CPU_TYPE_X86 = 7,
3834 DARWIN_CPU_TYPE_ARM = 12,
3835 DARWIN_CPU_TYPE_POWERPC = 18
3838 Triple::ArchType Arch = TT.getArch();
3839 if (Arch == Triple::x86_64)
3840 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3841 else if (Arch == Triple::x86)
3842 CPUType = DARWIN_CPU_TYPE_X86;
3843 else if (Arch == Triple::ppc)
3844 CPUType = DARWIN_CPU_TYPE_POWERPC;
3845 else if (Arch == Triple::ppc64)
3846 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3847 else if (Arch == Triple::arm || Arch == Triple::thumb)
3848 CPUType = DARWIN_CPU_TYPE_ARM;
3850 // Traditional Bitcode starts after header.
3851 assert(Buffer.size() >= BWH_HeaderSize &&
3852 "Expected header size to be reserved");
3853 unsigned BCOffset = BWH_HeaderSize;
3854 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3856 // Write the magic and version.
3857 unsigned Position = 0;
3858 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3859 writeInt32ToBuffer(0, Buffer, Position); // Version.
3860 writeInt32ToBuffer(BCOffset, Buffer, Position);
3861 writeInt32ToBuffer(BCSize, Buffer, Position);
3862 writeInt32ToBuffer(CPUType, Buffer, Position);
3864 // If the file is not a multiple of 16 bytes, insert dummy padding.
3865 while (Buffer.size() & 15)
3866 Buffer.push_back(0);
3869 /// Helper to write the header common to all bitcode files.
3870 static void writeBitcodeHeader(BitstreamWriter &Stream) {
3871 // Emit the file header.
3872 Stream.Emit((unsigned)'B', 8);
3873 Stream.Emit((unsigned)'C', 8);
3874 Stream.Emit(0x0, 4);
3875 Stream.Emit(0xC, 4);
3876 Stream.Emit(0xE, 4);
3877 Stream.Emit(0xD, 4);
3880 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3881 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3882 writeBitcodeHeader(*Stream);
3885 BitcodeWriter::~BitcodeWriter() = default;
3887 void BitcodeWriter::writeModule(const Module *M,
3888 bool ShouldPreserveUseListOrder,
3889 const ModuleSummaryIndex *Index,
3890 bool GenerateHash) {
3891 ModuleBitcodeWriter ModuleWriter(
3892 M, Buffer, *Stream, ShouldPreserveUseListOrder, Index, GenerateHash);
3893 ModuleWriter.write();
3896 /// WriteBitcodeToFile - Write the specified module to the specified output
3898 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3899 bool ShouldPreserveUseListOrder,
3900 const ModuleSummaryIndex *Index,
3901 bool GenerateHash) {
3902 SmallVector<char, 0> Buffer;
3903 Buffer.reserve(256*1024);
3905 // If this is darwin or another generic macho target, reserve space for the
3907 Triple TT(M->getTargetTriple());
3908 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3909 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3911 BitcodeWriter Writer(Buffer);
3912 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash);
3914 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3915 emitDarwinBCHeaderAndTrailer(Buffer, TT);
3917 // Write the generated bitstream to "Out".
3918 Out.write((char*)&Buffer.front(), Buffer.size());
3921 void IndexBitcodeWriter::write() {
3922 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3924 SmallVector<unsigned, 1> Vals;
3925 unsigned CurVersion = 1;
3926 Vals.push_back(CurVersion);
3927 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3929 // If we have a VST, write the VSTOFFSET record placeholder.
3930 writeValueSymbolTableForwardDecl();
3932 // Write the module paths in the combined index.
3935 // Write the summary combined index records.
3936 writeCombinedGlobalValueSummary();
3938 // Need a special VST writer for the combined index (we don't have a
3939 // real VST and real values when this is invoked).
3940 writeCombinedValueSymbolTable();
3945 // Write the specified module summary index to the given raw output stream,
3946 // where it will be written in a new bitcode block. This is used when
3947 // writing the combined index file for ThinLTO. When writing a subset of the
3948 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3949 void llvm::WriteIndexToFile(
3950 const ModuleSummaryIndex &Index, raw_ostream &Out,
3951 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3952 SmallVector<char, 0> Buffer;
3953 Buffer.reserve(256 * 1024);
3955 BitstreamWriter Stream(Buffer);
3956 writeBitcodeHeader(Stream);
3958 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
3959 IndexWriter.write();
3961 Out.write((char *)&Buffer.front(), Buffer.size());