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/MC/StringTableBuilder.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Program.h"
35 #include "llvm/Support/SHA1.h"
36 #include "llvm/Support/raw_ostream.h"
44 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
45 cl::desc("Number of metadatas above which we emit an index "
46 "to enable lazy-loading"));
47 /// These are manifest constants used by the bitcode writer. They do not need to
48 /// be kept in sync with the reader, but need to be consistent within this file.
50 // VALUE_SYMTAB_BLOCK abbrev id's.
51 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
56 // CONSTANTS_BLOCK abbrev id's.
57 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 CONSTANTS_INTEGER_ABBREV,
59 CONSTANTS_CE_CAST_Abbrev,
60 CONSTANTS_NULL_Abbrev,
62 // FUNCTION_BLOCK abbrev id's.
63 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
64 FUNCTION_INST_BINOP_ABBREV,
65 FUNCTION_INST_BINOP_FLAGS_ABBREV,
66 FUNCTION_INST_CAST_ABBREV,
67 FUNCTION_INST_RET_VOID_ABBREV,
68 FUNCTION_INST_RET_VAL_ABBREV,
69 FUNCTION_INST_UNREACHABLE_ABBREV,
70 FUNCTION_INST_GEP_ABBREV,
73 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
75 class BitcodeWriterBase {
77 /// The stream created and owned by the client.
78 BitstreamWriter &Stream;
81 /// Constructs a BitcodeWriterBase object that writes to the provided
83 BitcodeWriterBase(BitstreamWriter &Stream) : Stream(Stream) {}
86 void writeBitcodeHeader();
87 void writeModuleVersion();
90 void BitcodeWriterBase::writeModuleVersion() {
91 // VERSION: [version#]
92 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
95 /// Class to manage the bitcode writing for a module.
96 class ModuleBitcodeWriter : public BitcodeWriterBase {
97 /// Pointer to the buffer allocated by caller for bitcode writing.
98 const SmallVectorImpl<char> &Buffer;
100 StringTableBuilder &StrtabBuilder;
102 /// The Module to write to bitcode.
105 /// Enumerates ids for all values in the module.
108 /// Optional per-module index to write for ThinLTO.
109 const ModuleSummaryIndex *Index;
111 /// True if a module hash record should be written.
114 /// If non-null, when GenerateHash is true, the resulting hash is written
115 /// into ModHash. When GenerateHash is false, that specified value
116 /// is used as the hash instead of computing from the generated bitcode.
117 /// Can be used to produce the same module hash for a minimized bitcode
118 /// used just for the thin link as in the regular full bitcode that will
119 /// be used in the backend.
122 /// The start bit of the identification block.
123 uint64_t BitcodeStartBit;
125 /// Map that holds the correspondence between GUIDs in the summary index,
126 /// that came from indirect call profiles, and a value id generated by this
127 /// class to use in the VST and summary block records.
128 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
130 /// Tracks the last value id recorded in the GUIDToValueMap.
131 unsigned GlobalValueId;
133 /// Saves the offset of the VSTOffset record that must eventually be
134 /// backpatched with the offset of the actual VST.
135 uint64_t VSTOffsetPlaceholder = 0;
138 /// Constructs a ModuleBitcodeWriter object for the given Module,
139 /// writing to the provided \p Buffer.
140 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
141 StringTableBuilder &StrtabBuilder,
142 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
143 const ModuleSummaryIndex *Index, bool GenerateHash,
144 ModuleHash *ModHash = nullptr)
145 : BitcodeWriterBase(Stream), Buffer(Buffer), StrtabBuilder(StrtabBuilder),
146 M(*M), VE(*M, ShouldPreserveUseListOrder), Index(Index),
147 GenerateHash(GenerateHash), ModHash(ModHash),
148 BitcodeStartBit(Stream.GetCurrentBitNo()) {
149 // Assign ValueIds to any callee values in the index that came from
150 // indirect call profiles and were recorded as a GUID not a Value*
151 // (which would have been assigned an ID by the ValueEnumerator).
152 // The starting ValueId is just after the number of values in the
153 // ValueEnumerator, so that they can be emitted in the VST.
154 GlobalValueId = VE.getValues().size();
157 for (const auto &GUIDSummaryLists : *Index)
158 // Examine all summaries for this GUID.
159 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
160 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
161 // For each call in the function summary, see if the call
162 // is to a GUID (which means it is for an indirect call,
163 // otherwise we would have a Value for it). If so, synthesize
165 for (auto &CallEdge : FS->calls())
166 if (!CallEdge.first.getValue())
167 assignValueId(CallEdge.first.getGUID());
170 /// Emit the current module to the bitstream.
174 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
176 void writeAttributeGroupTable();
177 void writeAttributeTable();
178 void writeTypeTable();
180 void writeValueSymbolTableForwardDecl();
181 void writeModuleInfo();
182 void writeValueAsMetadata(const ValueAsMetadata *MD,
183 SmallVectorImpl<uint64_t> &Record);
184 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
186 unsigned createDILocationAbbrev();
187 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
189 unsigned createGenericDINodeAbbrev();
190 void writeGenericDINode(const GenericDINode *N,
191 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
192 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
194 void writeDIEnumerator(const DIEnumerator *N,
195 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
196 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
198 void writeDIDerivedType(const DIDerivedType *N,
199 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
200 void writeDICompositeType(const DICompositeType *N,
201 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
202 void writeDISubroutineType(const DISubroutineType *N,
203 SmallVectorImpl<uint64_t> &Record,
205 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
207 void writeDICompileUnit(const DICompileUnit *N,
208 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
209 void writeDISubprogram(const DISubprogram *N,
210 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
211 void writeDILexicalBlock(const DILexicalBlock *N,
212 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
213 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
214 SmallVectorImpl<uint64_t> &Record,
216 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
218 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
220 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
222 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
224 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
225 SmallVectorImpl<uint64_t> &Record,
227 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
228 SmallVectorImpl<uint64_t> &Record,
230 void writeDIGlobalVariable(const DIGlobalVariable *N,
231 SmallVectorImpl<uint64_t> &Record,
233 void writeDILocalVariable(const DILocalVariable *N,
234 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
235 void writeDIExpression(const DIExpression *N,
236 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
237 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
238 SmallVectorImpl<uint64_t> &Record,
240 void writeDIObjCProperty(const DIObjCProperty *N,
241 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
242 void writeDIImportedEntity(const DIImportedEntity *N,
243 SmallVectorImpl<uint64_t> &Record,
245 unsigned createNamedMetadataAbbrev();
246 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
247 unsigned createMetadataStringsAbbrev();
248 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
249 SmallVectorImpl<uint64_t> &Record);
250 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
251 SmallVectorImpl<uint64_t> &Record,
252 std::vector<unsigned> *MDAbbrevs = nullptr,
253 std::vector<uint64_t> *IndexPos = nullptr);
254 void writeModuleMetadata();
255 void writeFunctionMetadata(const Function &F);
256 void writeFunctionMetadataAttachment(const Function &F);
257 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
258 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
259 const GlobalObject &GO);
260 void writeModuleMetadataKinds();
261 void writeOperandBundleTags();
262 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
263 void writeModuleConstants();
264 bool pushValueAndType(const Value *V, unsigned InstID,
265 SmallVectorImpl<unsigned> &Vals);
266 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
267 void pushValue(const Value *V, unsigned InstID,
268 SmallVectorImpl<unsigned> &Vals);
269 void pushValueSigned(const Value *V, unsigned InstID,
270 SmallVectorImpl<uint64_t> &Vals);
271 void writeInstruction(const Instruction &I, unsigned InstID,
272 SmallVectorImpl<unsigned> &Vals);
273 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
274 void writeGlobalValueSymbolTable(
275 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
276 void writeUseList(UseListOrder &&Order);
277 void writeUseListBlock(const Function *F);
279 writeFunction(const Function &F,
280 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
281 void writeBlockInfo();
282 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
283 GlobalValueSummary *Summary,
285 unsigned FSCallsAbbrev,
286 unsigned FSCallsProfileAbbrev,
288 void writeModuleLevelReferences(const GlobalVariable &V,
289 SmallVector<uint64_t, 64> &NameVals,
290 unsigned FSModRefsAbbrev);
291 void writePerModuleGlobalValueSummary();
292 void writeModuleHash(size_t BlockStartPos);
294 void assignValueId(GlobalValue::GUID ValGUID) {
295 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
297 unsigned getValueId(GlobalValue::GUID ValGUID) {
298 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
299 // Expect that any GUID value had a value Id assigned by an
300 // earlier call to assignValueId.
301 assert(VMI != GUIDToValueIdMap.end() &&
302 "GUID does not have assigned value Id");
305 // Helper to get the valueId for the type of value recorded in VI.
306 unsigned getValueId(ValueInfo VI) {
308 return getValueId(VI.getGUID());
309 return VE.getValueID(VI.getValue());
311 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
314 /// Class to manage the bitcode writing for a combined index.
315 class IndexBitcodeWriter : public BitcodeWriterBase {
316 /// The combined index to write to bitcode.
317 const ModuleSummaryIndex &Index;
319 /// When writing a subset of the index for distributed backends, client
320 /// provides a map of modules to the corresponding GUIDs/summaries to write.
321 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
323 /// Map that holds the correspondence between the GUID used in the combined
324 /// index and a value id generated by this class to use in references.
325 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
327 /// Tracks the last value id recorded in the GUIDToValueMap.
328 unsigned GlobalValueId = 0;
331 /// Constructs a IndexBitcodeWriter object for the given combined index,
332 /// writing to the provided \p Buffer. When writing a subset of the index
333 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
334 IndexBitcodeWriter(BitstreamWriter &Stream, const ModuleSummaryIndex &Index,
335 const std::map<std::string, GVSummaryMapTy>
336 *ModuleToSummariesForIndex = nullptr)
337 : BitcodeWriterBase(Stream), Index(Index),
338 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
339 // Assign unique value ids to all summaries to be written, for use
340 // in writing out the call graph edges. Save the mapping from GUID
341 // to the new global value id to use when writing those edges, which
342 // are currently saved in the index in terms of GUID.
343 forEachSummary([&](GVInfo I) {
344 GUIDToValueIdMap[I.first] = ++GlobalValueId;
348 /// The below iterator returns the GUID and associated summary.
349 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
351 /// Calls the callback for each value GUID and summary to be written to
352 /// bitcode. This hides the details of whether they are being pulled from the
353 /// entire index or just those in a provided ModuleToSummariesForIndex map.
354 void forEachSummary(std::function<void(GVInfo)> Callback) {
355 if (ModuleToSummariesForIndex) {
356 for (auto &M : *ModuleToSummariesForIndex)
357 for (auto &Summary : M.second)
360 for (auto &Summaries : Index)
361 for (auto &Summary : Summaries.second.SummaryList)
362 Callback({Summaries.first, Summary.get()});
366 /// Main entry point for writing a combined index to bitcode.
370 void writeModStrings();
371 void writeCombinedGlobalValueSummary();
373 /// Indicates whether the provided \p ModulePath should be written into
374 /// the module string table, e.g. if full index written or if it is in
375 /// the provided subset.
376 bool doIncludeModule(StringRef ModulePath) {
377 return !ModuleToSummariesForIndex ||
378 ModuleToSummariesForIndex->count(ModulePath);
381 bool hasValueId(GlobalValue::GUID ValGUID) {
382 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
383 return VMI != GUIDToValueIdMap.end();
385 void assignValueId(GlobalValue::GUID ValGUID) {
386 unsigned &ValueId = GUIDToValueIdMap[ValGUID];
388 ValueId = ++GlobalValueId;
390 unsigned getValueId(GlobalValue::GUID ValGUID) {
391 auto VMI = GUIDToValueIdMap.find(ValGUID);
392 assert(VMI != GUIDToValueIdMap.end());
395 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
397 } // end anonymous namespace
399 static unsigned getEncodedCastOpcode(unsigned Opcode) {
401 default: llvm_unreachable("Unknown cast instruction!");
402 case Instruction::Trunc : return bitc::CAST_TRUNC;
403 case Instruction::ZExt : return bitc::CAST_ZEXT;
404 case Instruction::SExt : return bitc::CAST_SEXT;
405 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
406 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
407 case Instruction::UIToFP : return bitc::CAST_UITOFP;
408 case Instruction::SIToFP : return bitc::CAST_SITOFP;
409 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
410 case Instruction::FPExt : return bitc::CAST_FPEXT;
411 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
412 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
413 case Instruction::BitCast : return bitc::CAST_BITCAST;
414 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
418 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
420 default: llvm_unreachable("Unknown binary instruction!");
421 case Instruction::Add:
422 case Instruction::FAdd: return bitc::BINOP_ADD;
423 case Instruction::Sub:
424 case Instruction::FSub: return bitc::BINOP_SUB;
425 case Instruction::Mul:
426 case Instruction::FMul: return bitc::BINOP_MUL;
427 case Instruction::UDiv: return bitc::BINOP_UDIV;
428 case Instruction::FDiv:
429 case Instruction::SDiv: return bitc::BINOP_SDIV;
430 case Instruction::URem: return bitc::BINOP_UREM;
431 case Instruction::FRem:
432 case Instruction::SRem: return bitc::BINOP_SREM;
433 case Instruction::Shl: return bitc::BINOP_SHL;
434 case Instruction::LShr: return bitc::BINOP_LSHR;
435 case Instruction::AShr: return bitc::BINOP_ASHR;
436 case Instruction::And: return bitc::BINOP_AND;
437 case Instruction::Or: return bitc::BINOP_OR;
438 case Instruction::Xor: return bitc::BINOP_XOR;
442 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
444 default: llvm_unreachable("Unknown RMW operation!");
445 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
446 case AtomicRMWInst::Add: return bitc::RMW_ADD;
447 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
448 case AtomicRMWInst::And: return bitc::RMW_AND;
449 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
450 case AtomicRMWInst::Or: return bitc::RMW_OR;
451 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
452 case AtomicRMWInst::Max: return bitc::RMW_MAX;
453 case AtomicRMWInst::Min: return bitc::RMW_MIN;
454 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
455 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
459 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
461 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
462 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
463 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
464 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
465 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
466 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
467 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
469 llvm_unreachable("Invalid ordering");
472 static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
473 switch (SynchScope) {
474 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
475 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
477 llvm_unreachable("Invalid synch scope");
480 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
481 StringRef Str, unsigned AbbrevToUse) {
482 SmallVector<unsigned, 64> Vals;
484 // Code: [strchar x N]
485 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
486 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
488 Vals.push_back(Str[i]);
491 // Emit the finished record.
492 Stream.EmitRecord(Code, Vals, AbbrevToUse);
495 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
497 case Attribute::Alignment:
498 return bitc::ATTR_KIND_ALIGNMENT;
499 case Attribute::AllocSize:
500 return bitc::ATTR_KIND_ALLOC_SIZE;
501 case Attribute::AlwaysInline:
502 return bitc::ATTR_KIND_ALWAYS_INLINE;
503 case Attribute::ArgMemOnly:
504 return bitc::ATTR_KIND_ARGMEMONLY;
505 case Attribute::Builtin:
506 return bitc::ATTR_KIND_BUILTIN;
507 case Attribute::ByVal:
508 return bitc::ATTR_KIND_BY_VAL;
509 case Attribute::Convergent:
510 return bitc::ATTR_KIND_CONVERGENT;
511 case Attribute::InAlloca:
512 return bitc::ATTR_KIND_IN_ALLOCA;
513 case Attribute::Cold:
514 return bitc::ATTR_KIND_COLD;
515 case Attribute::InaccessibleMemOnly:
516 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
517 case Attribute::InaccessibleMemOrArgMemOnly:
518 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
519 case Attribute::InlineHint:
520 return bitc::ATTR_KIND_INLINE_HINT;
521 case Attribute::InReg:
522 return bitc::ATTR_KIND_IN_REG;
523 case Attribute::JumpTable:
524 return bitc::ATTR_KIND_JUMP_TABLE;
525 case Attribute::MinSize:
526 return bitc::ATTR_KIND_MIN_SIZE;
527 case Attribute::Naked:
528 return bitc::ATTR_KIND_NAKED;
529 case Attribute::Nest:
530 return bitc::ATTR_KIND_NEST;
531 case Attribute::NoAlias:
532 return bitc::ATTR_KIND_NO_ALIAS;
533 case Attribute::NoBuiltin:
534 return bitc::ATTR_KIND_NO_BUILTIN;
535 case Attribute::NoCapture:
536 return bitc::ATTR_KIND_NO_CAPTURE;
537 case Attribute::NoDuplicate:
538 return bitc::ATTR_KIND_NO_DUPLICATE;
539 case Attribute::NoImplicitFloat:
540 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
541 case Attribute::NoInline:
542 return bitc::ATTR_KIND_NO_INLINE;
543 case Attribute::NoRecurse:
544 return bitc::ATTR_KIND_NO_RECURSE;
545 case Attribute::NonLazyBind:
546 return bitc::ATTR_KIND_NON_LAZY_BIND;
547 case Attribute::NonNull:
548 return bitc::ATTR_KIND_NON_NULL;
549 case Attribute::Dereferenceable:
550 return bitc::ATTR_KIND_DEREFERENCEABLE;
551 case Attribute::DereferenceableOrNull:
552 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
553 case Attribute::NoRedZone:
554 return bitc::ATTR_KIND_NO_RED_ZONE;
555 case Attribute::NoReturn:
556 return bitc::ATTR_KIND_NO_RETURN;
557 case Attribute::NoUnwind:
558 return bitc::ATTR_KIND_NO_UNWIND;
559 case Attribute::OptimizeForSize:
560 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
561 case Attribute::OptimizeNone:
562 return bitc::ATTR_KIND_OPTIMIZE_NONE;
563 case Attribute::ReadNone:
564 return bitc::ATTR_KIND_READ_NONE;
565 case Attribute::ReadOnly:
566 return bitc::ATTR_KIND_READ_ONLY;
567 case Attribute::Returned:
568 return bitc::ATTR_KIND_RETURNED;
569 case Attribute::ReturnsTwice:
570 return bitc::ATTR_KIND_RETURNS_TWICE;
571 case Attribute::SExt:
572 return bitc::ATTR_KIND_S_EXT;
573 case Attribute::Speculatable:
574 return bitc::ATTR_KIND_SPECULATABLE;
575 case Attribute::StackAlignment:
576 return bitc::ATTR_KIND_STACK_ALIGNMENT;
577 case Attribute::StackProtect:
578 return bitc::ATTR_KIND_STACK_PROTECT;
579 case Attribute::StackProtectReq:
580 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
581 case Attribute::StackProtectStrong:
582 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
583 case Attribute::SafeStack:
584 return bitc::ATTR_KIND_SAFESTACK;
585 case Attribute::StructRet:
586 return bitc::ATTR_KIND_STRUCT_RET;
587 case Attribute::SanitizeAddress:
588 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
589 case Attribute::SanitizeThread:
590 return bitc::ATTR_KIND_SANITIZE_THREAD;
591 case Attribute::SanitizeMemory:
592 return bitc::ATTR_KIND_SANITIZE_MEMORY;
593 case Attribute::SwiftError:
594 return bitc::ATTR_KIND_SWIFT_ERROR;
595 case Attribute::SwiftSelf:
596 return bitc::ATTR_KIND_SWIFT_SELF;
597 case Attribute::UWTable:
598 return bitc::ATTR_KIND_UW_TABLE;
599 case Attribute::WriteOnly:
600 return bitc::ATTR_KIND_WRITEONLY;
601 case Attribute::ZExt:
602 return bitc::ATTR_KIND_Z_EXT;
603 case Attribute::EndAttrKinds:
604 llvm_unreachable("Can not encode end-attribute kinds marker.");
605 case Attribute::None:
606 llvm_unreachable("Can not encode none-attribute.");
609 llvm_unreachable("Trying to encode unknown attribute");
612 void ModuleBitcodeWriter::writeAttributeGroupTable() {
613 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
614 VE.getAttributeGroups();
615 if (AttrGrps.empty()) return;
617 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
619 SmallVector<uint64_t, 64> Record;
620 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
621 unsigned AttrListIndex = Pair.first;
622 AttributeSet AS = Pair.second;
623 Record.push_back(VE.getAttributeGroupID(Pair));
624 Record.push_back(AttrListIndex);
626 for (Attribute Attr : AS) {
627 if (Attr.isEnumAttribute()) {
629 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
630 } else if (Attr.isIntAttribute()) {
632 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
633 Record.push_back(Attr.getValueAsInt());
635 StringRef Kind = Attr.getKindAsString();
636 StringRef Val = Attr.getValueAsString();
638 Record.push_back(Val.empty() ? 3 : 4);
639 Record.append(Kind.begin(), Kind.end());
642 Record.append(Val.begin(), Val.end());
648 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
655 void ModuleBitcodeWriter::writeAttributeTable() {
656 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
657 if (Attrs.empty()) return;
659 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
661 SmallVector<uint64_t, 64> Record;
662 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
663 const AttributeList &A = Attrs[i];
664 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
666 VE.getAttributeGroupID({A.getSlotIndex(i), A.getSlotAttributes(i)}));
668 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
675 /// WriteTypeTable - Write out the type table for a module.
676 void ModuleBitcodeWriter::writeTypeTable() {
677 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
679 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
680 SmallVector<uint64_t, 64> TypeVals;
682 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
684 // Abbrev for TYPE_CODE_POINTER.
685 auto Abbv = std::make_shared<BitCodeAbbrev>();
686 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
688 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
689 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
691 // Abbrev for TYPE_CODE_FUNCTION.
692 Abbv = std::make_shared<BitCodeAbbrev>();
693 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
694 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
695 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
696 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
698 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
700 // Abbrev for TYPE_CODE_STRUCT_ANON.
701 Abbv = std::make_shared<BitCodeAbbrev>();
702 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
703 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
704 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
705 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
707 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
709 // Abbrev for TYPE_CODE_STRUCT_NAME.
710 Abbv = std::make_shared<BitCodeAbbrev>();
711 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
714 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
716 // Abbrev for TYPE_CODE_STRUCT_NAMED.
717 Abbv = std::make_shared<BitCodeAbbrev>();
718 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
721 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
723 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
725 // Abbrev for TYPE_CODE_ARRAY.
726 Abbv = std::make_shared<BitCodeAbbrev>();
727 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
731 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
733 // Emit an entry count so the reader can reserve space.
734 TypeVals.push_back(TypeList.size());
735 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
738 // Loop over all of the types, emitting each in turn.
739 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
740 Type *T = TypeList[i];
744 switch (T->getTypeID()) {
745 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
746 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
747 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
748 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
749 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
750 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
751 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
752 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
753 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
754 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
755 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
756 case Type::IntegerTyID:
758 Code = bitc::TYPE_CODE_INTEGER;
759 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
761 case Type::PointerTyID: {
762 PointerType *PTy = cast<PointerType>(T);
763 // POINTER: [pointee type, address space]
764 Code = bitc::TYPE_CODE_POINTER;
765 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
766 unsigned AddressSpace = PTy->getAddressSpace();
767 TypeVals.push_back(AddressSpace);
768 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
771 case Type::FunctionTyID: {
772 FunctionType *FT = cast<FunctionType>(T);
773 // FUNCTION: [isvararg, retty, paramty x N]
774 Code = bitc::TYPE_CODE_FUNCTION;
775 TypeVals.push_back(FT->isVarArg());
776 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
777 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
778 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
779 AbbrevToUse = FunctionAbbrev;
782 case Type::StructTyID: {
783 StructType *ST = cast<StructType>(T);
784 // STRUCT: [ispacked, eltty x N]
785 TypeVals.push_back(ST->isPacked());
786 // Output all of the element types.
787 for (StructType::element_iterator I = ST->element_begin(),
788 E = ST->element_end(); I != E; ++I)
789 TypeVals.push_back(VE.getTypeID(*I));
791 if (ST->isLiteral()) {
792 Code = bitc::TYPE_CODE_STRUCT_ANON;
793 AbbrevToUse = StructAnonAbbrev;
795 if (ST->isOpaque()) {
796 Code = bitc::TYPE_CODE_OPAQUE;
798 Code = bitc::TYPE_CODE_STRUCT_NAMED;
799 AbbrevToUse = StructNamedAbbrev;
802 // Emit the name if it is present.
803 if (!ST->getName().empty())
804 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
809 case Type::ArrayTyID: {
810 ArrayType *AT = cast<ArrayType>(T);
811 // ARRAY: [numelts, eltty]
812 Code = bitc::TYPE_CODE_ARRAY;
813 TypeVals.push_back(AT->getNumElements());
814 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
815 AbbrevToUse = ArrayAbbrev;
818 case Type::VectorTyID: {
819 VectorType *VT = cast<VectorType>(T);
820 // VECTOR [numelts, eltty]
821 Code = bitc::TYPE_CODE_VECTOR;
822 TypeVals.push_back(VT->getNumElements());
823 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
828 // Emit the finished record.
829 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
836 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
838 case GlobalValue::ExternalLinkage:
840 case GlobalValue::WeakAnyLinkage:
842 case GlobalValue::AppendingLinkage:
844 case GlobalValue::InternalLinkage:
846 case GlobalValue::LinkOnceAnyLinkage:
848 case GlobalValue::ExternalWeakLinkage:
850 case GlobalValue::CommonLinkage:
852 case GlobalValue::PrivateLinkage:
854 case GlobalValue::WeakODRLinkage:
856 case GlobalValue::LinkOnceODRLinkage:
858 case GlobalValue::AvailableExternallyLinkage:
861 llvm_unreachable("Invalid linkage");
864 static unsigned getEncodedLinkage(const GlobalValue &GV) {
865 return getEncodedLinkage(GV.getLinkage());
868 // Decode the flags for GlobalValue in the summary
869 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
870 uint64_t RawFlags = 0;
872 RawFlags |= Flags.NotEligibleToImport; // bool
873 RawFlags |= (Flags.LiveRoot << 1);
874 // Linkage don't need to be remapped at that time for the summary. Any future
875 // change to the getEncodedLinkage() function will need to be taken into
876 // account here as well.
877 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
882 static unsigned getEncodedVisibility(const GlobalValue &GV) {
883 switch (GV.getVisibility()) {
884 case GlobalValue::DefaultVisibility: return 0;
885 case GlobalValue::HiddenVisibility: return 1;
886 case GlobalValue::ProtectedVisibility: return 2;
888 llvm_unreachable("Invalid visibility");
891 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
892 switch (GV.getDLLStorageClass()) {
893 case GlobalValue::DefaultStorageClass: return 0;
894 case GlobalValue::DLLImportStorageClass: return 1;
895 case GlobalValue::DLLExportStorageClass: return 2;
897 llvm_unreachable("Invalid DLL storage class");
900 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
901 switch (GV.getThreadLocalMode()) {
902 case GlobalVariable::NotThreadLocal: return 0;
903 case GlobalVariable::GeneralDynamicTLSModel: return 1;
904 case GlobalVariable::LocalDynamicTLSModel: return 2;
905 case GlobalVariable::InitialExecTLSModel: return 3;
906 case GlobalVariable::LocalExecTLSModel: return 4;
908 llvm_unreachable("Invalid TLS model");
911 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
912 switch (C.getSelectionKind()) {
914 return bitc::COMDAT_SELECTION_KIND_ANY;
915 case Comdat::ExactMatch:
916 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
917 case Comdat::Largest:
918 return bitc::COMDAT_SELECTION_KIND_LARGEST;
919 case Comdat::NoDuplicates:
920 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
921 case Comdat::SameSize:
922 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
924 llvm_unreachable("Invalid selection kind");
927 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
928 switch (GV.getUnnamedAddr()) {
929 case GlobalValue::UnnamedAddr::None: return 0;
930 case GlobalValue::UnnamedAddr::Local: return 2;
931 case GlobalValue::UnnamedAddr::Global: return 1;
933 llvm_unreachable("Invalid unnamed_addr");
936 void ModuleBitcodeWriter::writeComdats() {
937 SmallVector<unsigned, 64> Vals;
938 for (const Comdat *C : VE.getComdats()) {
939 // COMDAT: [strtab offset, strtab size, selection_kind]
940 Vals.push_back(StrtabBuilder.add(C->getName()));
941 Vals.push_back(C->getName().size());
942 Vals.push_back(getEncodedComdatSelectionKind(*C));
943 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
948 /// Write a record that will eventually hold the word offset of the
949 /// module-level VST. For now the offset is 0, which will be backpatched
950 /// after the real VST is written. Saves the bit offset to backpatch.
951 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
952 // Write a placeholder value in for the offset of the real VST,
953 // which is written after the function blocks so that it can include
954 // the offset of each function. The placeholder offset will be
955 // updated when the real VST is written.
956 auto Abbv = std::make_shared<BitCodeAbbrev>();
957 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
958 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
959 // hold the real VST offset. Must use fixed instead of VBR as we don't
960 // know how many VBR chunks to reserve ahead of time.
961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
962 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
964 // Emit the placeholder
965 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
966 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
968 // Compute and save the bit offset to the placeholder, which will be
969 // patched when the real VST is written. We can simply subtract the 32-bit
970 // fixed size from the current bit number to get the location to backpatch.
971 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
974 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
976 /// Determine the encoding to use for the given string name and length.
977 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
979 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
981 isChar6 = BitCodeAbbrevOp::isChar6(*C);
982 if ((unsigned char)*C & 128)
983 // don't bother scanning the rest.
992 /// Emit top-level description of module, including target triple, inline asm,
993 /// descriptors for global variables, and function prototype info.
994 /// Returns the bit offset to backpatch with the location of the real VST.
995 void ModuleBitcodeWriter::writeModuleInfo() {
996 // Emit various pieces of data attached to a module.
997 if (!M.getTargetTriple().empty())
998 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1000 const std::string &DL = M.getDataLayoutStr();
1002 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1003 if (!M.getModuleInlineAsm().empty())
1004 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1007 // Emit information about sections and GC, computing how many there are. Also
1008 // compute the maximum alignment value.
1009 std::map<std::string, unsigned> SectionMap;
1010 std::map<std::string, unsigned> GCMap;
1011 unsigned MaxAlignment = 0;
1012 unsigned MaxGlobalType = 0;
1013 for (const GlobalValue &GV : M.globals()) {
1014 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1015 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1016 if (GV.hasSection()) {
1017 // Give section names unique ID's.
1018 unsigned &Entry = SectionMap[GV.getSection()];
1020 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1022 Entry = SectionMap.size();
1026 for (const Function &F : M) {
1027 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1028 if (F.hasSection()) {
1029 // Give section names unique ID's.
1030 unsigned &Entry = SectionMap[F.getSection()];
1032 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1034 Entry = SectionMap.size();
1038 // Same for GC names.
1039 unsigned &Entry = GCMap[F.getGC()];
1041 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1043 Entry = GCMap.size();
1048 // Emit abbrev for globals, now that we know # sections and max alignment.
1049 unsigned SimpleGVarAbbrev = 0;
1050 if (!M.global_empty()) {
1051 // Add an abbrev for common globals with no visibility or thread localness.
1052 auto Abbv = std::make_shared<BitCodeAbbrev>();
1053 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1057 Log2_32_Ceil(MaxGlobalType+1)));
1058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1059 //| explicitType << 1
1061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1063 if (MaxAlignment == 0) // Alignment.
1064 Abbv->Add(BitCodeAbbrevOp(0));
1066 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1068 Log2_32_Ceil(MaxEncAlignment+1)));
1070 if (SectionMap.empty()) // Section.
1071 Abbv->Add(BitCodeAbbrevOp(0));
1073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1074 Log2_32_Ceil(SectionMap.size()+1)));
1075 // Don't bother emitting vis + thread local.
1076 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1079 SmallVector<unsigned, 64> Vals;
1080 // Emit the module's source file name.
1082 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1083 M.getSourceFileName().size());
1084 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1085 if (Bits == SE_Char6)
1086 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1087 else if (Bits == SE_Fixed7)
1088 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1090 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1091 auto Abbv = std::make_shared<BitCodeAbbrev>();
1092 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1094 Abbv->Add(AbbrevOpToUse);
1095 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1097 for (const auto P : M.getSourceFileName())
1098 Vals.push_back((unsigned char)P);
1100 // Emit the finished record.
1101 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1105 // Emit the global variable information.
1106 for (const GlobalVariable &GV : M.globals()) {
1107 unsigned AbbrevToUse = 0;
1109 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1110 // linkage, alignment, section, visibility, threadlocal,
1111 // unnamed_addr, externally_initialized, dllstorageclass,
1112 // comdat, attributes]
1113 Vals.push_back(StrtabBuilder.add(GV.getName()));
1114 Vals.push_back(GV.getName().size());
1115 Vals.push_back(VE.getTypeID(GV.getValueType()));
1116 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1117 Vals.push_back(GV.isDeclaration() ? 0 :
1118 (VE.getValueID(GV.getInitializer()) + 1));
1119 Vals.push_back(getEncodedLinkage(GV));
1120 Vals.push_back(Log2_32(GV.getAlignment())+1);
1121 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1122 if (GV.isThreadLocal() ||
1123 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1124 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1125 GV.isExternallyInitialized() ||
1126 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1128 GV.hasAttributes()) {
1129 Vals.push_back(getEncodedVisibility(GV));
1130 Vals.push_back(getEncodedThreadLocalMode(GV));
1131 Vals.push_back(getEncodedUnnamedAddr(GV));
1132 Vals.push_back(GV.isExternallyInitialized());
1133 Vals.push_back(getEncodedDLLStorageClass(GV));
1134 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1136 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1137 Vals.push_back(VE.getAttributeListID(AL));
1139 AbbrevToUse = SimpleGVarAbbrev;
1142 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1146 // Emit the function proto information.
1147 for (const Function &F : M) {
1148 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1149 // linkage, paramattrs, alignment, section, visibility, gc,
1150 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1151 // prefixdata, personalityfn]
1152 Vals.push_back(StrtabBuilder.add(F.getName()));
1153 Vals.push_back(F.getName().size());
1154 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1155 Vals.push_back(F.getCallingConv());
1156 Vals.push_back(F.isDeclaration());
1157 Vals.push_back(getEncodedLinkage(F));
1158 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1159 Vals.push_back(Log2_32(F.getAlignment())+1);
1160 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1161 Vals.push_back(getEncodedVisibility(F));
1162 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1163 Vals.push_back(getEncodedUnnamedAddr(F));
1164 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1166 Vals.push_back(getEncodedDLLStorageClass(F));
1167 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1168 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1171 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1173 unsigned AbbrevToUse = 0;
1174 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1178 // Emit the alias information.
1179 for (const GlobalAlias &A : M.aliases()) {
1180 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1181 // visibility, dllstorageclass, threadlocal, unnamed_addr]
1182 Vals.push_back(StrtabBuilder.add(A.getName()));
1183 Vals.push_back(A.getName().size());
1184 Vals.push_back(VE.getTypeID(A.getValueType()));
1185 Vals.push_back(A.getType()->getAddressSpace());
1186 Vals.push_back(VE.getValueID(A.getAliasee()));
1187 Vals.push_back(getEncodedLinkage(A));
1188 Vals.push_back(getEncodedVisibility(A));
1189 Vals.push_back(getEncodedDLLStorageClass(A));
1190 Vals.push_back(getEncodedThreadLocalMode(A));
1191 Vals.push_back(getEncodedUnnamedAddr(A));
1192 unsigned AbbrevToUse = 0;
1193 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1197 // Emit the ifunc information.
1198 for (const GlobalIFunc &I : M.ifuncs()) {
1199 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1200 // val#, linkage, visibility]
1201 Vals.push_back(StrtabBuilder.add(I.getName()));
1202 Vals.push_back(I.getName().size());
1203 Vals.push_back(VE.getTypeID(I.getValueType()));
1204 Vals.push_back(I.getType()->getAddressSpace());
1205 Vals.push_back(VE.getValueID(I.getResolver()));
1206 Vals.push_back(getEncodedLinkage(I));
1207 Vals.push_back(getEncodedVisibility(I));
1208 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1212 writeValueSymbolTableForwardDecl();
1215 static uint64_t getOptimizationFlags(const Value *V) {
1218 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1219 if (OBO->hasNoSignedWrap())
1220 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1221 if (OBO->hasNoUnsignedWrap())
1222 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1223 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1225 Flags |= 1 << bitc::PEO_EXACT;
1226 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1227 if (FPMO->hasUnsafeAlgebra())
1228 Flags |= FastMathFlags::UnsafeAlgebra;
1229 if (FPMO->hasNoNaNs())
1230 Flags |= FastMathFlags::NoNaNs;
1231 if (FPMO->hasNoInfs())
1232 Flags |= FastMathFlags::NoInfs;
1233 if (FPMO->hasNoSignedZeros())
1234 Flags |= FastMathFlags::NoSignedZeros;
1235 if (FPMO->hasAllowReciprocal())
1236 Flags |= FastMathFlags::AllowReciprocal;
1237 if (FPMO->hasAllowContract())
1238 Flags |= FastMathFlags::AllowContract;
1244 void ModuleBitcodeWriter::writeValueAsMetadata(
1245 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1246 // Mimic an MDNode with a value as one operand.
1247 Value *V = MD->getValue();
1248 Record.push_back(VE.getTypeID(V->getType()));
1249 Record.push_back(VE.getValueID(V));
1250 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1254 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1255 SmallVectorImpl<uint64_t> &Record,
1257 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1258 Metadata *MD = N->getOperand(i);
1259 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1260 "Unexpected function-local metadata");
1261 Record.push_back(VE.getMetadataOrNullID(MD));
1263 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1264 : bitc::METADATA_NODE,
1269 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1270 // Assume the column is usually under 128, and always output the inlined-at
1271 // location (it's never more expensive than building an array size 1).
1272 auto Abbv = std::make_shared<BitCodeAbbrev>();
1273 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1274 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1275 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1276 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1279 return Stream.EmitAbbrev(std::move(Abbv));
1282 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1283 SmallVectorImpl<uint64_t> &Record,
1286 Abbrev = createDILocationAbbrev();
1288 Record.push_back(N->isDistinct());
1289 Record.push_back(N->getLine());
1290 Record.push_back(N->getColumn());
1291 Record.push_back(VE.getMetadataID(N->getScope()));
1292 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1294 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1298 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1299 // Assume the column is usually under 128, and always output the inlined-at
1300 // location (it's never more expensive than building an array size 1).
1301 auto Abbv = std::make_shared<BitCodeAbbrev>();
1302 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1307 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1309 return Stream.EmitAbbrev(std::move(Abbv));
1312 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1313 SmallVectorImpl<uint64_t> &Record,
1316 Abbrev = createGenericDINodeAbbrev();
1318 Record.push_back(N->isDistinct());
1319 Record.push_back(N->getTag());
1320 Record.push_back(0); // Per-tag version field; unused for now.
1322 for (auto &I : N->operands())
1323 Record.push_back(VE.getMetadataOrNullID(I));
1325 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1329 static uint64_t rotateSign(int64_t I) {
1331 return I < 0 ? ~(U << 1) : U << 1;
1334 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1335 SmallVectorImpl<uint64_t> &Record,
1337 Record.push_back(N->isDistinct());
1338 Record.push_back(N->getCount());
1339 Record.push_back(rotateSign(N->getLowerBound()));
1341 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1345 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1346 SmallVectorImpl<uint64_t> &Record,
1348 Record.push_back(N->isDistinct());
1349 Record.push_back(rotateSign(N->getValue()));
1350 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1352 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1356 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1357 SmallVectorImpl<uint64_t> &Record,
1359 Record.push_back(N->isDistinct());
1360 Record.push_back(N->getTag());
1361 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1362 Record.push_back(N->getSizeInBits());
1363 Record.push_back(N->getAlignInBits());
1364 Record.push_back(N->getEncoding());
1366 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1370 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1371 SmallVectorImpl<uint64_t> &Record,
1373 Record.push_back(N->isDistinct());
1374 Record.push_back(N->getTag());
1375 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1376 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1377 Record.push_back(N->getLine());
1378 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1379 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1380 Record.push_back(N->getSizeInBits());
1381 Record.push_back(N->getAlignInBits());
1382 Record.push_back(N->getOffsetInBits());
1383 Record.push_back(N->getFlags());
1384 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1386 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1387 // that there is no DWARF address space associated with DIDerivedType.
1388 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1389 Record.push_back(*DWARFAddressSpace + 1);
1391 Record.push_back(0);
1393 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1397 void ModuleBitcodeWriter::writeDICompositeType(
1398 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1400 const unsigned IsNotUsedInOldTypeRef = 0x2;
1401 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1402 Record.push_back(N->getTag());
1403 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1404 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1405 Record.push_back(N->getLine());
1406 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1407 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1408 Record.push_back(N->getSizeInBits());
1409 Record.push_back(N->getAlignInBits());
1410 Record.push_back(N->getOffsetInBits());
1411 Record.push_back(N->getFlags());
1412 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1413 Record.push_back(N->getRuntimeLang());
1414 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1415 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1416 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1418 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1422 void ModuleBitcodeWriter::writeDISubroutineType(
1423 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1425 const unsigned HasNoOldTypeRefs = 0x2;
1426 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1427 Record.push_back(N->getFlags());
1428 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1429 Record.push_back(N->getCC());
1431 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1435 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1436 SmallVectorImpl<uint64_t> &Record,
1438 Record.push_back(N->isDistinct());
1439 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1440 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1441 Record.push_back(N->getChecksumKind());
1442 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1444 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1448 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1449 SmallVectorImpl<uint64_t> &Record,
1451 assert(N->isDistinct() && "Expected distinct compile units");
1452 Record.push_back(/* IsDistinct */ true);
1453 Record.push_back(N->getSourceLanguage());
1454 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1455 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1456 Record.push_back(N->isOptimized());
1457 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1458 Record.push_back(N->getRuntimeVersion());
1459 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1460 Record.push_back(N->getEmissionKind());
1461 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1462 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1463 Record.push_back(/* subprograms */ 0);
1464 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1465 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1466 Record.push_back(N->getDWOId());
1467 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1468 Record.push_back(N->getSplitDebugInlining());
1469 Record.push_back(N->getDebugInfoForProfiling());
1471 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1475 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1476 SmallVectorImpl<uint64_t> &Record,
1478 uint64_t HasUnitFlag = 1 << 1;
1479 Record.push_back(N->isDistinct() | HasUnitFlag);
1480 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1481 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1482 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1483 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1484 Record.push_back(N->getLine());
1485 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1486 Record.push_back(N->isLocalToUnit());
1487 Record.push_back(N->isDefinition());
1488 Record.push_back(N->getScopeLine());
1489 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1490 Record.push_back(N->getVirtuality());
1491 Record.push_back(N->getVirtualIndex());
1492 Record.push_back(N->getFlags());
1493 Record.push_back(N->isOptimized());
1494 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1495 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1496 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1497 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1498 Record.push_back(N->getThisAdjustment());
1499 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1501 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1505 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1506 SmallVectorImpl<uint64_t> &Record,
1508 Record.push_back(N->isDistinct());
1509 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1510 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1511 Record.push_back(N->getLine());
1512 Record.push_back(N->getColumn());
1514 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1518 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1519 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1521 Record.push_back(N->isDistinct());
1522 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1523 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1524 Record.push_back(N->getDiscriminator());
1526 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1530 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1531 SmallVectorImpl<uint64_t> &Record,
1533 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1534 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1535 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1537 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1541 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1542 SmallVectorImpl<uint64_t> &Record,
1544 Record.push_back(N->isDistinct());
1545 Record.push_back(N->getMacinfoType());
1546 Record.push_back(N->getLine());
1547 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1548 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1550 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1554 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1555 SmallVectorImpl<uint64_t> &Record,
1557 Record.push_back(N->isDistinct());
1558 Record.push_back(N->getMacinfoType());
1559 Record.push_back(N->getLine());
1560 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1561 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1563 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1567 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1568 SmallVectorImpl<uint64_t> &Record,
1570 Record.push_back(N->isDistinct());
1571 for (auto &I : N->operands())
1572 Record.push_back(VE.getMetadataOrNullID(I));
1574 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1578 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1579 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1581 Record.push_back(N->isDistinct());
1582 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1583 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1585 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1589 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1590 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1592 Record.push_back(N->isDistinct());
1593 Record.push_back(N->getTag());
1594 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1595 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1596 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1598 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1602 void ModuleBitcodeWriter::writeDIGlobalVariable(
1603 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1605 const uint64_t Version = 1 << 1;
1606 Record.push_back((uint64_t)N->isDistinct() | Version);
1607 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1608 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1609 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1610 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1611 Record.push_back(N->getLine());
1612 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1613 Record.push_back(N->isLocalToUnit());
1614 Record.push_back(N->isDefinition());
1615 Record.push_back(/* expr */ 0);
1616 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1617 Record.push_back(N->getAlignInBits());
1619 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1623 void ModuleBitcodeWriter::writeDILocalVariable(
1624 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1626 // In order to support all possible bitcode formats in BitcodeReader we need
1627 // to distinguish the following cases:
1628 // 1) Record has no artificial tag (Record[1]),
1629 // has no obsolete inlinedAt field (Record[9]).
1630 // In this case Record size will be 8, HasAlignment flag is false.
1631 // 2) Record has artificial tag (Record[1]),
1632 // has no obsolete inlignedAt field (Record[9]).
1633 // In this case Record size will be 9, HasAlignment flag is false.
1634 // 3) Record has both artificial tag (Record[1]) and
1635 // obsolete inlignedAt field (Record[9]).
1636 // In this case Record size will be 10, HasAlignment flag is false.
1637 // 4) Record has neither artificial tag, nor inlignedAt field, but
1638 // HasAlignment flag is true and Record[8] contains alignment value.
1639 const uint64_t HasAlignmentFlag = 1 << 1;
1640 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1641 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1642 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1643 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1644 Record.push_back(N->getLine());
1645 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1646 Record.push_back(N->getArg());
1647 Record.push_back(N->getFlags());
1648 Record.push_back(N->getAlignInBits());
1650 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1654 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1655 SmallVectorImpl<uint64_t> &Record,
1657 Record.reserve(N->getElements().size() + 1);
1658 const uint64_t Version = 2 << 1;
1659 Record.push_back((uint64_t)N->isDistinct() | Version);
1660 Record.append(N->elements_begin(), N->elements_end());
1662 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1666 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1667 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1669 Record.push_back(N->isDistinct());
1670 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1671 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1673 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1677 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1678 SmallVectorImpl<uint64_t> &Record,
1680 Record.push_back(N->isDistinct());
1681 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1682 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1683 Record.push_back(N->getLine());
1684 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1685 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1686 Record.push_back(N->getAttributes());
1687 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1689 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1693 void ModuleBitcodeWriter::writeDIImportedEntity(
1694 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1696 Record.push_back(N->isDistinct());
1697 Record.push_back(N->getTag());
1698 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1699 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1700 Record.push_back(N->getLine());
1701 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1703 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1707 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1708 auto Abbv = std::make_shared<BitCodeAbbrev>();
1709 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1712 return Stream.EmitAbbrev(std::move(Abbv));
1715 void ModuleBitcodeWriter::writeNamedMetadata(
1716 SmallVectorImpl<uint64_t> &Record) {
1717 if (M.named_metadata_empty())
1720 unsigned Abbrev = createNamedMetadataAbbrev();
1721 for (const NamedMDNode &NMD : M.named_metadata()) {
1723 StringRef Str = NMD.getName();
1724 Record.append(Str.bytes_begin(), Str.bytes_end());
1725 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1728 // Write named metadata operands.
1729 for (const MDNode *N : NMD.operands())
1730 Record.push_back(VE.getMetadataID(N));
1731 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1736 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1737 auto Abbv = std::make_shared<BitCodeAbbrev>();
1738 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1739 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1740 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1742 return Stream.EmitAbbrev(std::move(Abbv));
1745 /// Write out a record for MDString.
1747 /// All the metadata strings in a metadata block are emitted in a single
1748 /// record. The sizes and strings themselves are shoved into a blob.
1749 void ModuleBitcodeWriter::writeMetadataStrings(
1750 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1751 if (Strings.empty())
1754 // Start the record with the number of strings.
1755 Record.push_back(bitc::METADATA_STRINGS);
1756 Record.push_back(Strings.size());
1758 // Emit the sizes of the strings in the blob.
1759 SmallString<256> Blob;
1761 BitstreamWriter W(Blob);
1762 for (const Metadata *MD : Strings)
1763 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1767 // Add the offset to the strings to the record.
1768 Record.push_back(Blob.size());
1770 // Add the strings to the blob.
1771 for (const Metadata *MD : Strings)
1772 Blob.append(cast<MDString>(MD)->getString());
1774 // Emit the final record.
1775 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1779 // Generates an enum to use as an index in the Abbrev array of Metadata record.
1780 enum MetadataAbbrev : unsigned {
1781 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1782 #include "llvm/IR/Metadata.def"
1786 void ModuleBitcodeWriter::writeMetadataRecords(
1787 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1788 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1792 // Initialize MDNode abbreviations.
1793 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1794 #include "llvm/IR/Metadata.def"
1796 for (const Metadata *MD : MDs) {
1798 IndexPos->push_back(Stream.GetCurrentBitNo());
1799 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1800 assert(N->isResolved() && "Expected forward references to be resolved");
1802 switch (N->getMetadataID()) {
1804 llvm_unreachable("Invalid MDNode subclass");
1805 #define HANDLE_MDNODE_LEAF(CLASS) \
1806 case Metadata::CLASS##Kind: \
1808 write##CLASS(cast<CLASS>(N), Record, \
1809 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1811 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1813 #include "llvm/IR/Metadata.def"
1816 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1820 void ModuleBitcodeWriter::writeModuleMetadata() {
1821 if (!VE.hasMDs() && M.named_metadata_empty())
1824 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1825 SmallVector<uint64_t, 64> Record;
1827 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1828 // block and load any metadata.
1829 std::vector<unsigned> MDAbbrevs;
1831 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1832 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1833 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1834 createGenericDINodeAbbrev();
1836 auto Abbv = std::make_shared<BitCodeAbbrev>();
1837 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1838 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1840 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1842 Abbv = std::make_shared<BitCodeAbbrev>();
1843 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1844 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1845 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1846 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1848 // Emit MDStrings together upfront.
1849 writeMetadataStrings(VE.getMDStrings(), Record);
1851 // We only emit an index for the metadata record if we have more than a given
1852 // (naive) threshold of metadatas, otherwise it is not worth it.
1853 if (VE.getNonMDStrings().size() > IndexThreshold) {
1854 // Write a placeholder value in for the offset of the metadata index,
1855 // which is written after the records, so that it can include
1856 // the offset of each entry. The placeholder offset will be
1857 // updated after all records are emitted.
1858 uint64_t Vals[] = {0, 0};
1859 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1862 // Compute and save the bit offset to the current position, which will be
1863 // patched when we emit the index later. We can simply subtract the 64-bit
1864 // fixed size from the current bit number to get the location to backpatch.
1865 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1867 // This index will contain the bitpos for each individual record.
1868 std::vector<uint64_t> IndexPos;
1869 IndexPos.reserve(VE.getNonMDStrings().size());
1871 // Write all the records
1872 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1874 if (VE.getNonMDStrings().size() > IndexThreshold) {
1875 // Now that we have emitted all the records we will emit the index. But
1877 // backpatch the forward reference so that the reader can skip the records
1879 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1880 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1882 // Delta encode the index.
1883 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1884 for (auto &Elt : IndexPos) {
1885 auto EltDelta = Elt - PreviousValue;
1886 PreviousValue = Elt;
1889 // Emit the index record.
1890 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1894 // Write the named metadata now.
1895 writeNamedMetadata(Record);
1897 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1898 SmallVector<uint64_t, 4> Record;
1899 Record.push_back(VE.getValueID(&GO));
1900 pushGlobalMetadataAttachment(Record, GO);
1901 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1903 for (const Function &F : M)
1904 if (F.isDeclaration() && F.hasMetadata())
1905 AddDeclAttachedMetadata(F);
1906 // FIXME: Only store metadata for declarations here, and move data for global
1907 // variable definitions to a separate block (PR28134).
1908 for (const GlobalVariable &GV : M.globals())
1909 if (GV.hasMetadata())
1910 AddDeclAttachedMetadata(GV);
1915 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
1919 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1920 SmallVector<uint64_t, 64> Record;
1921 writeMetadataStrings(VE.getMDStrings(), Record);
1922 writeMetadataRecords(VE.getNonMDStrings(), Record);
1926 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1927 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1928 // [n x [id, mdnode]]
1929 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1930 GO.getAllMetadata(MDs);
1931 for (const auto &I : MDs) {
1932 Record.push_back(I.first);
1933 Record.push_back(VE.getMetadataID(I.second));
1937 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
1938 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1940 SmallVector<uint64_t, 64> Record;
1942 if (F.hasMetadata()) {
1943 pushGlobalMetadataAttachment(Record, F);
1944 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1948 // Write metadata attachments
1949 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1950 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1951 for (const BasicBlock &BB : F)
1952 for (const Instruction &I : BB) {
1954 I.getAllMetadataOtherThanDebugLoc(MDs);
1956 // If no metadata, ignore instruction.
1957 if (MDs.empty()) continue;
1959 Record.push_back(VE.getInstructionID(&I));
1961 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1962 Record.push_back(MDs[i].first);
1963 Record.push_back(VE.getMetadataID(MDs[i].second));
1965 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1972 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
1973 SmallVector<uint64_t, 64> Record;
1975 // Write metadata kinds
1976 // METADATA_KIND - [n x [id, name]]
1977 SmallVector<StringRef, 8> Names;
1978 M.getMDKindNames(Names);
1980 if (Names.empty()) return;
1982 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1984 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1985 Record.push_back(MDKindID);
1986 StringRef KName = Names[MDKindID];
1987 Record.append(KName.begin(), KName.end());
1989 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1996 void ModuleBitcodeWriter::writeOperandBundleTags() {
1997 // Write metadata kinds
1999 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2001 // OPERAND_BUNDLE_TAG - [strchr x N]
2003 SmallVector<StringRef, 8> Tags;
2004 M.getOperandBundleTags(Tags);
2009 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2011 SmallVector<uint64_t, 64> Record;
2013 for (auto Tag : Tags) {
2014 Record.append(Tag.begin(), Tag.end());
2016 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2023 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2024 if ((int64_t)V >= 0)
2025 Vals.push_back(V << 1);
2027 Vals.push_back((-V << 1) | 1);
2030 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2032 if (FirstVal == LastVal) return;
2034 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2036 unsigned AggregateAbbrev = 0;
2037 unsigned String8Abbrev = 0;
2038 unsigned CString7Abbrev = 0;
2039 unsigned CString6Abbrev = 0;
2040 // If this is a constant pool for the module, emit module-specific abbrevs.
2042 // Abbrev for CST_CODE_AGGREGATE.
2043 auto Abbv = std::make_shared<BitCodeAbbrev>();
2044 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2045 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2047 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2049 // Abbrev for CST_CODE_STRING.
2050 Abbv = std::make_shared<BitCodeAbbrev>();
2051 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2054 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2055 // Abbrev for CST_CODE_CSTRING.
2056 Abbv = std::make_shared<BitCodeAbbrev>();
2057 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2060 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2061 // Abbrev for CST_CODE_CSTRING.
2062 Abbv = std::make_shared<BitCodeAbbrev>();
2063 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2066 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2069 SmallVector<uint64_t, 64> Record;
2071 const ValueEnumerator::ValueList &Vals = VE.getValues();
2072 Type *LastTy = nullptr;
2073 for (unsigned i = FirstVal; i != LastVal; ++i) {
2074 const Value *V = Vals[i].first;
2075 // If we need to switch types, do so now.
2076 if (V->getType() != LastTy) {
2077 LastTy = V->getType();
2078 Record.push_back(VE.getTypeID(LastTy));
2079 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2080 CONSTANTS_SETTYPE_ABBREV);
2084 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2085 Record.push_back(unsigned(IA->hasSideEffects()) |
2086 unsigned(IA->isAlignStack()) << 1 |
2087 unsigned(IA->getDialect()&1) << 2);
2089 // Add the asm string.
2090 const std::string &AsmStr = IA->getAsmString();
2091 Record.push_back(AsmStr.size());
2092 Record.append(AsmStr.begin(), AsmStr.end());
2094 // Add the constraint string.
2095 const std::string &ConstraintStr = IA->getConstraintString();
2096 Record.push_back(ConstraintStr.size());
2097 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2098 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2102 const Constant *C = cast<Constant>(V);
2103 unsigned Code = -1U;
2104 unsigned AbbrevToUse = 0;
2105 if (C->isNullValue()) {
2106 Code = bitc::CST_CODE_NULL;
2107 } else if (isa<UndefValue>(C)) {
2108 Code = bitc::CST_CODE_UNDEF;
2109 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2110 if (IV->getBitWidth() <= 64) {
2111 uint64_t V = IV->getSExtValue();
2112 emitSignedInt64(Record, V);
2113 Code = bitc::CST_CODE_INTEGER;
2114 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2115 } else { // Wide integers, > 64 bits in size.
2116 // We have an arbitrary precision integer value to write whose
2117 // bit width is > 64. However, in canonical unsigned integer
2118 // format it is likely that the high bits are going to be zero.
2119 // So, we only write the number of active words.
2120 unsigned NWords = IV->getValue().getActiveWords();
2121 const uint64_t *RawWords = IV->getValue().getRawData();
2122 for (unsigned i = 0; i != NWords; ++i) {
2123 emitSignedInt64(Record, RawWords[i]);
2125 Code = bitc::CST_CODE_WIDE_INTEGER;
2127 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2128 Code = bitc::CST_CODE_FLOAT;
2129 Type *Ty = CFP->getType();
2130 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2131 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2132 } else if (Ty->isX86_FP80Ty()) {
2133 // api needed to prevent premature destruction
2134 // bits are not in the same order as a normal i80 APInt, compensate.
2135 APInt api = CFP->getValueAPF().bitcastToAPInt();
2136 const uint64_t *p = api.getRawData();
2137 Record.push_back((p[1] << 48) | (p[0] >> 16));
2138 Record.push_back(p[0] & 0xffffLL);
2139 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2140 APInt api = CFP->getValueAPF().bitcastToAPInt();
2141 const uint64_t *p = api.getRawData();
2142 Record.push_back(p[0]);
2143 Record.push_back(p[1]);
2145 assert (0 && "Unknown FP type!");
2147 } else if (isa<ConstantDataSequential>(C) &&
2148 cast<ConstantDataSequential>(C)->isString()) {
2149 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2150 // Emit constant strings specially.
2151 unsigned NumElts = Str->getNumElements();
2152 // If this is a null-terminated string, use the denser CSTRING encoding.
2153 if (Str->isCString()) {
2154 Code = bitc::CST_CODE_CSTRING;
2155 --NumElts; // Don't encode the null, which isn't allowed by char6.
2157 Code = bitc::CST_CODE_STRING;
2158 AbbrevToUse = String8Abbrev;
2160 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2161 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2162 for (unsigned i = 0; i != NumElts; ++i) {
2163 unsigned char V = Str->getElementAsInteger(i);
2164 Record.push_back(V);
2165 isCStr7 &= (V & 128) == 0;
2167 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2171 AbbrevToUse = CString6Abbrev;
2173 AbbrevToUse = CString7Abbrev;
2174 } else if (const ConstantDataSequential *CDS =
2175 dyn_cast<ConstantDataSequential>(C)) {
2176 Code = bitc::CST_CODE_DATA;
2177 Type *EltTy = CDS->getType()->getElementType();
2178 if (isa<IntegerType>(EltTy)) {
2179 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2180 Record.push_back(CDS->getElementAsInteger(i));
2182 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2184 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2186 } else if (isa<ConstantAggregate>(C)) {
2187 Code = bitc::CST_CODE_AGGREGATE;
2188 for (const Value *Op : C->operands())
2189 Record.push_back(VE.getValueID(Op));
2190 AbbrevToUse = AggregateAbbrev;
2191 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2192 switch (CE->getOpcode()) {
2194 if (Instruction::isCast(CE->getOpcode())) {
2195 Code = bitc::CST_CODE_CE_CAST;
2196 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2197 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2198 Record.push_back(VE.getValueID(C->getOperand(0)));
2199 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2201 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2202 Code = bitc::CST_CODE_CE_BINOP;
2203 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2204 Record.push_back(VE.getValueID(C->getOperand(0)));
2205 Record.push_back(VE.getValueID(C->getOperand(1)));
2206 uint64_t Flags = getOptimizationFlags(CE);
2208 Record.push_back(Flags);
2211 case Instruction::GetElementPtr: {
2212 Code = bitc::CST_CODE_CE_GEP;
2213 const auto *GO = cast<GEPOperator>(C);
2214 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2215 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2216 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2217 Record.push_back((*Idx << 1) | GO->isInBounds());
2218 } else if (GO->isInBounds())
2219 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2220 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2221 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2222 Record.push_back(VE.getValueID(C->getOperand(i)));
2226 case Instruction::Select:
2227 Code = bitc::CST_CODE_CE_SELECT;
2228 Record.push_back(VE.getValueID(C->getOperand(0)));
2229 Record.push_back(VE.getValueID(C->getOperand(1)));
2230 Record.push_back(VE.getValueID(C->getOperand(2)));
2232 case Instruction::ExtractElement:
2233 Code = bitc::CST_CODE_CE_EXTRACTELT;
2234 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2235 Record.push_back(VE.getValueID(C->getOperand(0)));
2236 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2237 Record.push_back(VE.getValueID(C->getOperand(1)));
2239 case Instruction::InsertElement:
2240 Code = bitc::CST_CODE_CE_INSERTELT;
2241 Record.push_back(VE.getValueID(C->getOperand(0)));
2242 Record.push_back(VE.getValueID(C->getOperand(1)));
2243 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2244 Record.push_back(VE.getValueID(C->getOperand(2)));
2246 case Instruction::ShuffleVector:
2247 // If the return type and argument types are the same, this is a
2248 // standard shufflevector instruction. If the types are different,
2249 // then the shuffle is widening or truncating the input vectors, and
2250 // the argument type must also be encoded.
2251 if (C->getType() == C->getOperand(0)->getType()) {
2252 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2254 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2255 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2257 Record.push_back(VE.getValueID(C->getOperand(0)));
2258 Record.push_back(VE.getValueID(C->getOperand(1)));
2259 Record.push_back(VE.getValueID(C->getOperand(2)));
2261 case Instruction::ICmp:
2262 case Instruction::FCmp:
2263 Code = bitc::CST_CODE_CE_CMP;
2264 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2265 Record.push_back(VE.getValueID(C->getOperand(0)));
2266 Record.push_back(VE.getValueID(C->getOperand(1)));
2267 Record.push_back(CE->getPredicate());
2270 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2271 Code = bitc::CST_CODE_BLOCKADDRESS;
2272 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2273 Record.push_back(VE.getValueID(BA->getFunction()));
2274 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2279 llvm_unreachable("Unknown constant!");
2281 Stream.EmitRecord(Code, Record, AbbrevToUse);
2288 void ModuleBitcodeWriter::writeModuleConstants() {
2289 const ValueEnumerator::ValueList &Vals = VE.getValues();
2291 // Find the first constant to emit, which is the first non-globalvalue value.
2292 // We know globalvalues have been emitted by WriteModuleInfo.
2293 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2294 if (!isa<GlobalValue>(Vals[i].first)) {
2295 writeConstants(i, Vals.size(), true);
2301 /// pushValueAndType - The file has to encode both the value and type id for
2302 /// many values, because we need to know what type to create for forward
2303 /// references. However, most operands are not forward references, so this type
2304 /// field is not needed.
2306 /// This function adds V's value ID to Vals. If the value ID is higher than the
2307 /// instruction ID, then it is a forward reference, and it also includes the
2308 /// type ID. The value ID that is written is encoded relative to the InstID.
2309 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2310 SmallVectorImpl<unsigned> &Vals) {
2311 unsigned ValID = VE.getValueID(V);
2312 // Make encoding relative to the InstID.
2313 Vals.push_back(InstID - ValID);
2314 if (ValID >= InstID) {
2315 Vals.push_back(VE.getTypeID(V->getType()));
2321 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2323 SmallVector<unsigned, 64> Record;
2324 LLVMContext &C = CS.getInstruction()->getContext();
2326 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2327 const auto &Bundle = CS.getOperandBundleAt(i);
2328 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2330 for (auto &Input : Bundle.Inputs)
2331 pushValueAndType(Input, InstID, Record);
2333 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2338 /// pushValue - Like pushValueAndType, but where the type of the value is
2339 /// omitted (perhaps it was already encoded in an earlier operand).
2340 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2341 SmallVectorImpl<unsigned> &Vals) {
2342 unsigned ValID = VE.getValueID(V);
2343 Vals.push_back(InstID - ValID);
2346 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2347 SmallVectorImpl<uint64_t> &Vals) {
2348 unsigned ValID = VE.getValueID(V);
2349 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2350 emitSignedInt64(Vals, diff);
2353 /// WriteInstruction - Emit an instruction to the specified stream.
2354 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2356 SmallVectorImpl<unsigned> &Vals) {
2358 unsigned AbbrevToUse = 0;
2359 VE.setInstructionID(&I);
2360 switch (I.getOpcode()) {
2362 if (Instruction::isCast(I.getOpcode())) {
2363 Code = bitc::FUNC_CODE_INST_CAST;
2364 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2365 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2366 Vals.push_back(VE.getTypeID(I.getType()));
2367 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2369 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2370 Code = bitc::FUNC_CODE_INST_BINOP;
2371 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2372 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2373 pushValue(I.getOperand(1), InstID, Vals);
2374 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2375 uint64_t Flags = getOptimizationFlags(&I);
2377 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2378 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2379 Vals.push_back(Flags);
2384 case Instruction::GetElementPtr: {
2385 Code = bitc::FUNC_CODE_INST_GEP;
2386 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2387 auto &GEPInst = cast<GetElementPtrInst>(I);
2388 Vals.push_back(GEPInst.isInBounds());
2389 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2390 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2391 pushValueAndType(I.getOperand(i), InstID, Vals);
2394 case Instruction::ExtractValue: {
2395 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2396 pushValueAndType(I.getOperand(0), InstID, Vals);
2397 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2398 Vals.append(EVI->idx_begin(), EVI->idx_end());
2401 case Instruction::InsertValue: {
2402 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2403 pushValueAndType(I.getOperand(0), InstID, Vals);
2404 pushValueAndType(I.getOperand(1), InstID, Vals);
2405 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2406 Vals.append(IVI->idx_begin(), IVI->idx_end());
2409 case Instruction::Select:
2410 Code = bitc::FUNC_CODE_INST_VSELECT;
2411 pushValueAndType(I.getOperand(1), InstID, Vals);
2412 pushValue(I.getOperand(2), InstID, Vals);
2413 pushValueAndType(I.getOperand(0), InstID, Vals);
2415 case Instruction::ExtractElement:
2416 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2417 pushValueAndType(I.getOperand(0), InstID, Vals);
2418 pushValueAndType(I.getOperand(1), InstID, Vals);
2420 case Instruction::InsertElement:
2421 Code = bitc::FUNC_CODE_INST_INSERTELT;
2422 pushValueAndType(I.getOperand(0), InstID, Vals);
2423 pushValue(I.getOperand(1), InstID, Vals);
2424 pushValueAndType(I.getOperand(2), InstID, Vals);
2426 case Instruction::ShuffleVector:
2427 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2428 pushValueAndType(I.getOperand(0), InstID, Vals);
2429 pushValue(I.getOperand(1), InstID, Vals);
2430 pushValue(I.getOperand(2), InstID, Vals);
2432 case Instruction::ICmp:
2433 case Instruction::FCmp: {
2434 // compare returning Int1Ty or vector of Int1Ty
2435 Code = bitc::FUNC_CODE_INST_CMP2;
2436 pushValueAndType(I.getOperand(0), InstID, Vals);
2437 pushValue(I.getOperand(1), InstID, Vals);
2438 Vals.push_back(cast<CmpInst>(I).getPredicate());
2439 uint64_t Flags = getOptimizationFlags(&I);
2441 Vals.push_back(Flags);
2445 case Instruction::Ret:
2447 Code = bitc::FUNC_CODE_INST_RET;
2448 unsigned NumOperands = I.getNumOperands();
2449 if (NumOperands == 0)
2450 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2451 else if (NumOperands == 1) {
2452 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2453 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2455 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2456 pushValueAndType(I.getOperand(i), InstID, Vals);
2460 case Instruction::Br:
2462 Code = bitc::FUNC_CODE_INST_BR;
2463 const BranchInst &II = cast<BranchInst>(I);
2464 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2465 if (II.isConditional()) {
2466 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2467 pushValue(II.getCondition(), InstID, Vals);
2471 case Instruction::Switch:
2473 Code = bitc::FUNC_CODE_INST_SWITCH;
2474 const SwitchInst &SI = cast<SwitchInst>(I);
2475 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2476 pushValue(SI.getCondition(), InstID, Vals);
2477 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2478 for (auto Case : SI.cases()) {
2479 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2480 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2484 case Instruction::IndirectBr:
2485 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2486 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2487 // Encode the address operand as relative, but not the basic blocks.
2488 pushValue(I.getOperand(0), InstID, Vals);
2489 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2490 Vals.push_back(VE.getValueID(I.getOperand(i)));
2493 case Instruction::Invoke: {
2494 const InvokeInst *II = cast<InvokeInst>(&I);
2495 const Value *Callee = II->getCalledValue();
2496 FunctionType *FTy = II->getFunctionType();
2498 if (II->hasOperandBundles())
2499 writeOperandBundles(II, InstID);
2501 Code = bitc::FUNC_CODE_INST_INVOKE;
2503 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2504 Vals.push_back(II->getCallingConv() | 1 << 13);
2505 Vals.push_back(VE.getValueID(II->getNormalDest()));
2506 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2507 Vals.push_back(VE.getTypeID(FTy));
2508 pushValueAndType(Callee, InstID, Vals);
2510 // Emit value #'s for the fixed parameters.
2511 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2512 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2514 // Emit type/value pairs for varargs params.
2515 if (FTy->isVarArg()) {
2516 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2518 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2522 case Instruction::Resume:
2523 Code = bitc::FUNC_CODE_INST_RESUME;
2524 pushValueAndType(I.getOperand(0), InstID, Vals);
2526 case Instruction::CleanupRet: {
2527 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2528 const auto &CRI = cast<CleanupReturnInst>(I);
2529 pushValue(CRI.getCleanupPad(), InstID, Vals);
2530 if (CRI.hasUnwindDest())
2531 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2534 case Instruction::CatchRet: {
2535 Code = bitc::FUNC_CODE_INST_CATCHRET;
2536 const auto &CRI = cast<CatchReturnInst>(I);
2537 pushValue(CRI.getCatchPad(), InstID, Vals);
2538 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2541 case Instruction::CleanupPad:
2542 case Instruction::CatchPad: {
2543 const auto &FuncletPad = cast<FuncletPadInst>(I);
2544 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2545 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2546 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2548 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2549 Vals.push_back(NumArgOperands);
2550 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2551 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2554 case Instruction::CatchSwitch: {
2555 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2556 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2558 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2560 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2561 Vals.push_back(NumHandlers);
2562 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2563 Vals.push_back(VE.getValueID(CatchPadBB));
2565 if (CatchSwitch.hasUnwindDest())
2566 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2569 case Instruction::Unreachable:
2570 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2571 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2574 case Instruction::PHI: {
2575 const PHINode &PN = cast<PHINode>(I);
2576 Code = bitc::FUNC_CODE_INST_PHI;
2577 // With the newer instruction encoding, forward references could give
2578 // negative valued IDs. This is most common for PHIs, so we use
2580 SmallVector<uint64_t, 128> Vals64;
2581 Vals64.push_back(VE.getTypeID(PN.getType()));
2582 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2583 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2584 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2586 // Emit a Vals64 vector and exit.
2587 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2592 case Instruction::LandingPad: {
2593 const LandingPadInst &LP = cast<LandingPadInst>(I);
2594 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2595 Vals.push_back(VE.getTypeID(LP.getType()));
2596 Vals.push_back(LP.isCleanup());
2597 Vals.push_back(LP.getNumClauses());
2598 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2600 Vals.push_back(LandingPadInst::Catch);
2602 Vals.push_back(LandingPadInst::Filter);
2603 pushValueAndType(LP.getClause(I), InstID, Vals);
2608 case Instruction::Alloca: {
2609 Code = bitc::FUNC_CODE_INST_ALLOCA;
2610 const AllocaInst &AI = cast<AllocaInst>(I);
2611 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2612 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2613 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2614 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2615 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2616 "not enough bits for maximum alignment");
2617 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2618 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2619 AlignRecord |= 1 << 6;
2620 AlignRecord |= AI.isSwiftError() << 7;
2621 Vals.push_back(AlignRecord);
2625 case Instruction::Load:
2626 if (cast<LoadInst>(I).isAtomic()) {
2627 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2628 pushValueAndType(I.getOperand(0), InstID, Vals);
2630 Code = bitc::FUNC_CODE_INST_LOAD;
2631 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2632 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2634 Vals.push_back(VE.getTypeID(I.getType()));
2635 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2636 Vals.push_back(cast<LoadInst>(I).isVolatile());
2637 if (cast<LoadInst>(I).isAtomic()) {
2638 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2639 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2642 case Instruction::Store:
2643 if (cast<StoreInst>(I).isAtomic())
2644 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2646 Code = bitc::FUNC_CODE_INST_STORE;
2647 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2648 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2649 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2650 Vals.push_back(cast<StoreInst>(I).isVolatile());
2651 if (cast<StoreInst>(I).isAtomic()) {
2652 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2653 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2656 case Instruction::AtomicCmpXchg:
2657 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2658 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2659 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2660 pushValue(I.getOperand(2), InstID, Vals); // newval.
2661 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2663 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2665 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2667 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2668 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2670 case Instruction::AtomicRMW:
2671 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2672 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2673 pushValue(I.getOperand(1), InstID, Vals); // val.
2675 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2676 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2677 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2679 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2681 case Instruction::Fence:
2682 Code = bitc::FUNC_CODE_INST_FENCE;
2683 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2684 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2686 case Instruction::Call: {
2687 const CallInst &CI = cast<CallInst>(I);
2688 FunctionType *FTy = CI.getFunctionType();
2690 if (CI.hasOperandBundles())
2691 writeOperandBundles(&CI, InstID);
2693 Code = bitc::FUNC_CODE_INST_CALL;
2695 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2697 unsigned Flags = getOptimizationFlags(&I);
2698 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2699 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2700 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2701 1 << bitc::CALL_EXPLICIT_TYPE |
2702 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2703 unsigned(Flags != 0) << bitc::CALL_FMF);
2705 Vals.push_back(Flags);
2707 Vals.push_back(VE.getTypeID(FTy));
2708 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2710 // Emit value #'s for the fixed parameters.
2711 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2712 // Check for labels (can happen with asm labels).
2713 if (FTy->getParamType(i)->isLabelTy())
2714 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2716 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2719 // Emit type/value pairs for varargs params.
2720 if (FTy->isVarArg()) {
2721 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2723 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2727 case Instruction::VAArg:
2728 Code = bitc::FUNC_CODE_INST_VAARG;
2729 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2730 pushValue(I.getOperand(0), InstID, Vals); // valist.
2731 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2735 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2739 /// Write a GlobalValue VST to the module. The purpose of this data structure is
2740 /// to allow clients to efficiently find the function body.
2741 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2742 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2743 // Get the offset of the VST we are writing, and backpatch it into
2744 // the VST forward declaration record.
2745 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2746 // The BitcodeStartBit was the stream offset of the identification block.
2747 VSTOffset -= bitcodeStartBit();
2748 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2749 // Note that we add 1 here because the offset is relative to one word
2750 // before the start of the identification block, which was historically
2751 // always the start of the regular bitcode header.
2752 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2754 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2756 auto Abbv = std::make_shared<BitCodeAbbrev>();
2757 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2760 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2762 for (const Function &F : M) {
2765 if (F.isDeclaration())
2768 Record[0] = VE.getValueID(&F);
2770 // Save the word offset of the function (from the start of the
2771 // actual bitcode written to the stream).
2772 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2773 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2774 // Note that we add 1 here because the offset is relative to one word
2775 // before the start of the identification block, which was historically
2776 // always the start of the regular bitcode header.
2777 Record[1] = BitcodeIndex / 32 + 1;
2779 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
2785 /// Emit names for arguments, instructions and basic blocks in a function.
2786 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2787 const ValueSymbolTable &VST) {
2791 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2793 // FIXME: Set up the abbrev, we know how many values there are!
2794 // FIXME: We know if the type names can use 7-bit ascii.
2795 SmallVector<uint64_t, 64> NameVals;
2797 for (const ValueName &Name : VST) {
2798 // Figure out the encoding to use for the name.
2799 StringEncoding Bits =
2800 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2802 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2803 NameVals.push_back(VE.getValueID(Name.getValue()));
2805 // VST_CODE_ENTRY: [valueid, namechar x N]
2806 // VST_CODE_BBENTRY: [bbid, namechar x N]
2808 if (isa<BasicBlock>(Name.getValue())) {
2809 Code = bitc::VST_CODE_BBENTRY;
2810 if (Bits == SE_Char6)
2811 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2813 Code = bitc::VST_CODE_ENTRY;
2814 if (Bits == SE_Char6)
2815 AbbrevToUse = VST_ENTRY_6_ABBREV;
2816 else if (Bits == SE_Fixed7)
2817 AbbrevToUse = VST_ENTRY_7_ABBREV;
2820 for (const auto P : Name.getKey())
2821 NameVals.push_back((unsigned char)P);
2823 // Emit the finished record.
2824 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2831 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
2832 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2834 if (isa<BasicBlock>(Order.V))
2835 Code = bitc::USELIST_CODE_BB;
2837 Code = bitc::USELIST_CODE_DEFAULT;
2839 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2840 Record.push_back(VE.getValueID(Order.V));
2841 Stream.EmitRecord(Code, Record);
2844 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
2845 assert(VE.shouldPreserveUseListOrder() &&
2846 "Expected to be preserving use-list order");
2848 auto hasMore = [&]() {
2849 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2855 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2857 writeUseList(std::move(VE.UseListOrders.back()));
2858 VE.UseListOrders.pop_back();
2863 /// Emit a function body to the module stream.
2864 void ModuleBitcodeWriter::writeFunction(
2866 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2867 // Save the bitcode index of the start of this function block for recording
2869 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
2871 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2872 VE.incorporateFunction(F);
2874 SmallVector<unsigned, 64> Vals;
2876 // Emit the number of basic blocks, so the reader can create them ahead of
2878 Vals.push_back(VE.getBasicBlocks().size());
2879 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2882 // If there are function-local constants, emit them now.
2883 unsigned CstStart, CstEnd;
2884 VE.getFunctionConstantRange(CstStart, CstEnd);
2885 writeConstants(CstStart, CstEnd, false);
2887 // If there is function-local metadata, emit it now.
2888 writeFunctionMetadata(F);
2890 // Keep a running idea of what the instruction ID is.
2891 unsigned InstID = CstEnd;
2893 bool NeedsMetadataAttachment = F.hasMetadata();
2895 DILocation *LastDL = nullptr;
2896 // Finally, emit all the instructions, in order.
2897 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2898 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2900 writeInstruction(*I, InstID, Vals);
2902 if (!I->getType()->isVoidTy())
2905 // If the instruction has metadata, write a metadata attachment later.
2906 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2908 // If the instruction has a debug location, emit it.
2909 DILocation *DL = I->getDebugLoc();
2914 // Just repeat the same debug loc as last time.
2915 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2919 Vals.push_back(DL->getLine());
2920 Vals.push_back(DL->getColumn());
2921 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2922 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2923 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2929 // Emit names for all the instructions etc.
2930 if (auto *Symtab = F.getValueSymbolTable())
2931 writeFunctionLevelValueSymbolTable(*Symtab);
2933 if (NeedsMetadataAttachment)
2934 writeFunctionMetadataAttachment(F);
2935 if (VE.shouldPreserveUseListOrder())
2936 writeUseListBlock(&F);
2941 // Emit blockinfo, which defines the standard abbreviations etc.
2942 void ModuleBitcodeWriter::writeBlockInfo() {
2943 // We only want to emit block info records for blocks that have multiple
2944 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2945 // Other blocks can define their abbrevs inline.
2946 Stream.EnterBlockInfoBlock();
2948 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
2949 auto Abbv = std::make_shared<BitCodeAbbrev>();
2950 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2954 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2956 llvm_unreachable("Unexpected abbrev ordering!");
2959 { // 7-bit fixed width VST_CODE_ENTRY strings.
2960 auto Abbv = std::make_shared<BitCodeAbbrev>();
2961 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2965 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2967 llvm_unreachable("Unexpected abbrev ordering!");
2969 { // 6-bit char6 VST_CODE_ENTRY strings.
2970 auto Abbv = std::make_shared<BitCodeAbbrev>();
2971 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2975 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2977 llvm_unreachable("Unexpected abbrev ordering!");
2979 { // 6-bit char6 VST_CODE_BBENTRY strings.
2980 auto Abbv = std::make_shared<BitCodeAbbrev>();
2981 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2983 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2985 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
2986 VST_BBENTRY_6_ABBREV)
2987 llvm_unreachable("Unexpected abbrev ordering!");
2992 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2993 auto Abbv = std::make_shared<BitCodeAbbrev>();
2994 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2996 VE.computeBitsRequiredForTypeIndicies()));
2997 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
2998 CONSTANTS_SETTYPE_ABBREV)
2999 llvm_unreachable("Unexpected abbrev ordering!");
3002 { // INTEGER abbrev for CONSTANTS_BLOCK.
3003 auto Abbv = std::make_shared<BitCodeAbbrev>();
3004 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3006 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3007 CONSTANTS_INTEGER_ABBREV)
3008 llvm_unreachable("Unexpected abbrev ordering!");
3011 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3012 auto Abbv = std::make_shared<BitCodeAbbrev>();
3013 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3014 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3016 VE.computeBitsRequiredForTypeIndicies()));
3017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3019 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3020 CONSTANTS_CE_CAST_Abbrev)
3021 llvm_unreachable("Unexpected abbrev ordering!");
3023 { // NULL abbrev for CONSTANTS_BLOCK.
3024 auto Abbv = std::make_shared<BitCodeAbbrev>();
3025 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3026 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3027 CONSTANTS_NULL_Abbrev)
3028 llvm_unreachable("Unexpected abbrev ordering!");
3031 // FIXME: This should only use space for first class types!
3033 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3034 auto Abbv = std::make_shared<BitCodeAbbrev>();
3035 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3037 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3038 VE.computeBitsRequiredForTypeIndicies()));
3039 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3040 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3041 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3042 FUNCTION_INST_LOAD_ABBREV)
3043 llvm_unreachable("Unexpected abbrev ordering!");
3045 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3046 auto Abbv = std::make_shared<BitCodeAbbrev>();
3047 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3051 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3052 FUNCTION_INST_BINOP_ABBREV)
3053 llvm_unreachable("Unexpected abbrev ordering!");
3055 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3056 auto Abbv = std::make_shared<BitCodeAbbrev>();
3057 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3062 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3063 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3064 llvm_unreachable("Unexpected abbrev ordering!");
3066 { // INST_CAST abbrev for FUNCTION_BLOCK.
3067 auto Abbv = std::make_shared<BitCodeAbbrev>();
3068 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3071 VE.computeBitsRequiredForTypeIndicies()));
3072 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3073 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3074 FUNCTION_INST_CAST_ABBREV)
3075 llvm_unreachable("Unexpected abbrev ordering!");
3078 { // INST_RET abbrev for FUNCTION_BLOCK.
3079 auto Abbv = std::make_shared<BitCodeAbbrev>();
3080 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3081 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3082 FUNCTION_INST_RET_VOID_ABBREV)
3083 llvm_unreachable("Unexpected abbrev ordering!");
3085 { // INST_RET abbrev for FUNCTION_BLOCK.
3086 auto Abbv = std::make_shared<BitCodeAbbrev>();
3087 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3088 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3089 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3090 FUNCTION_INST_RET_VAL_ABBREV)
3091 llvm_unreachable("Unexpected abbrev ordering!");
3093 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3094 auto Abbv = std::make_shared<BitCodeAbbrev>();
3095 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3096 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3097 FUNCTION_INST_UNREACHABLE_ABBREV)
3098 llvm_unreachable("Unexpected abbrev ordering!");
3101 auto Abbv = std::make_shared<BitCodeAbbrev>();
3102 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3103 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3104 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3105 Log2_32_Ceil(VE.getTypes().size() + 1)));
3106 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3108 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3109 FUNCTION_INST_GEP_ABBREV)
3110 llvm_unreachable("Unexpected abbrev ordering!");
3116 /// Write the module path strings, currently only used when generating
3117 /// a combined index file.
3118 void IndexBitcodeWriter::writeModStrings() {
3119 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3121 // TODO: See which abbrev sizes we actually need to emit
3123 // 8-bit fixed-width MST_ENTRY strings.
3124 auto Abbv = std::make_shared<BitCodeAbbrev>();
3125 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3129 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3131 // 7-bit fixed width MST_ENTRY strings.
3132 Abbv = std::make_shared<BitCodeAbbrev>();
3133 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3134 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3137 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3139 // 6-bit char6 MST_ENTRY strings.
3140 Abbv = std::make_shared<BitCodeAbbrev>();
3141 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3145 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3147 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3148 Abbv = std::make_shared<BitCodeAbbrev>();
3149 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3155 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3157 SmallVector<unsigned, 64> Vals;
3158 for (const auto &MPSE : Index.modulePaths()) {
3159 if (!doIncludeModule(MPSE.getKey()))
3161 StringEncoding Bits =
3162 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3163 unsigned AbbrevToUse = Abbrev8Bit;
3164 if (Bits == SE_Char6)
3165 AbbrevToUse = Abbrev6Bit;
3166 else if (Bits == SE_Fixed7)
3167 AbbrevToUse = Abbrev7Bit;
3169 Vals.push_back(MPSE.getValue().first);
3171 for (const auto P : MPSE.getKey())
3172 Vals.push_back((unsigned char)P);
3174 // Emit the finished record.
3175 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3178 // Emit an optional hash for the module now
3179 auto &Hash = MPSE.getValue().second;
3180 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3181 for (auto Val : Hash) {
3184 Vals.push_back(Val);
3187 // Emit the hash record.
3188 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3196 /// Write the function type metadata related records that need to appear before
3197 /// a function summary entry (whether per-module or combined).
3198 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3199 FunctionSummary *FS) {
3200 if (!FS->type_tests().empty())
3201 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3203 SmallVector<uint64_t, 64> Record;
3205 auto WriteVFuncIdVec = [&](uint64_t Ty,
3206 ArrayRef<FunctionSummary::VFuncId> VFs) {
3210 for (auto &VF : VFs) {
3211 Record.push_back(VF.GUID);
3212 Record.push_back(VF.Offset);
3214 Stream.EmitRecord(Ty, Record);
3217 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3218 FS->type_test_assume_vcalls());
3219 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3220 FS->type_checked_load_vcalls());
3222 auto WriteConstVCallVec = [&](uint64_t Ty,
3223 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3224 for (auto &VC : VCs) {
3226 Record.push_back(VC.VFunc.GUID);
3227 Record.push_back(VC.VFunc.Offset);
3228 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3229 Stream.EmitRecord(Ty, Record);
3233 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3234 FS->type_test_assume_const_vcalls());
3235 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3236 FS->type_checked_load_const_vcalls());
3239 // Helper to emit a single function summary record.
3240 void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3241 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3242 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3243 const Function &F) {
3244 NameVals.push_back(ValueID);
3246 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3247 writeFunctionTypeMetadataRecords(Stream, FS);
3249 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3250 NameVals.push_back(FS->instCount());
3251 NameVals.push_back(FS->refs().size());
3253 for (auto &RI : FS->refs())
3254 NameVals.push_back(VE.getValueID(RI.getValue()));
3256 bool HasProfileData = F.getEntryCount().hasValue();
3257 for (auto &ECI : FS->calls()) {
3258 NameVals.push_back(getValueId(ECI.first));
3260 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3263 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3265 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3267 // Emit the finished record.
3268 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3272 // Collect the global value references in the given variable's initializer,
3273 // and emit them in a summary record.
3274 void ModuleBitcodeWriter::writeModuleLevelReferences(
3275 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3276 unsigned FSModRefsAbbrev) {
3277 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3278 if (!VI || VI.getSummaryList().empty()) {
3279 // Only declarations should not have a summary (a declaration might however
3280 // have a summary if the def was in module level asm).
3281 assert(V.isDeclaration());
3284 auto *Summary = VI.getSummaryList()[0].get();
3285 NameVals.push_back(VE.getValueID(&V));
3286 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3287 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3289 unsigned SizeBeforeRefs = NameVals.size();
3290 for (auto &RI : VS->refs())
3291 NameVals.push_back(VE.getValueID(RI.getValue()));
3292 // Sort the refs for determinism output, the vector returned by FS->refs() has
3293 // been initialized from a DenseSet.
3294 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3296 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3301 // Current version for the summary.
3302 // This is bumped whenever we introduce changes in the way some record are
3303 // interpreted, like flags for instance.
3304 static const uint64_t INDEX_VERSION = 3;
3306 /// Emit the per-module summary section alongside the rest of
3307 /// the module's bitcode.
3308 void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3309 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
3311 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3313 if (Index->begin() == Index->end()) {
3318 for (const auto &GVI : valueIds()) {
3319 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3320 ArrayRef<uint64_t>{GVI.second, GVI.first});
3323 // Abbrev for FS_PERMODULE.
3324 auto Abbv = std::make_shared<BitCodeAbbrev>();
3325 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3329 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3330 // numrefs x valueid, n x (valueid)
3331 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3333 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3335 // Abbrev for FS_PERMODULE_PROFILE.
3336 Abbv = std::make_shared<BitCodeAbbrev>();
3337 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3342 // numrefs x valueid, n x (valueid, hotness)
3343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3345 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3347 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3348 Abbv = std::make_shared<BitCodeAbbrev>();
3349 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3354 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3356 // Abbrev for FS_ALIAS.
3357 Abbv = std::make_shared<BitCodeAbbrev>();
3358 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3362 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3364 SmallVector<uint64_t, 64> NameVals;
3365 // Iterate over the list of functions instead of the Index to
3366 // ensure the ordering is stable.
3367 for (const Function &F : M) {
3368 // Summary emission does not support anonymous functions, they have to
3369 // renamed using the anonymous function renaming pass.
3371 report_fatal_error("Unexpected anonymous function when writing summary");
3373 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3374 if (!VI || VI.getSummaryList().empty()) {
3375 // Only declarations should not have a summary (a declaration might
3376 // however have a summary if the def was in module level asm).
3377 assert(F.isDeclaration());
3380 auto *Summary = VI.getSummaryList()[0].get();
3381 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3382 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3385 // Capture references from GlobalVariable initializers, which are outside
3386 // of a function scope.
3387 for (const GlobalVariable &G : M.globals())
3388 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3390 for (const GlobalAlias &A : M.aliases()) {
3391 auto *Aliasee = A.getBaseObject();
3392 if (!Aliasee->hasName())
3393 // Nameless function don't have an entry in the summary, skip it.
3395 auto AliasId = VE.getValueID(&A);
3396 auto AliaseeId = VE.getValueID(Aliasee);
3397 NameVals.push_back(AliasId);
3398 auto *Summary = Index->getGlobalValueSummary(A);
3399 AliasSummary *AS = cast<AliasSummary>(Summary);
3400 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3401 NameVals.push_back(AliaseeId);
3402 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3409 /// Emit the combined summary section into the combined index file.
3410 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3411 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3412 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3414 // Create value IDs for undefined references.
3415 forEachSummary([&](GVInfo I) {
3416 if (auto *VS = dyn_cast<GlobalVarSummary>(I.second)) {
3417 for (auto &RI : VS->refs())
3418 assignValueId(RI.getGUID());
3422 auto *FS = dyn_cast<FunctionSummary>(I.second);
3425 for (auto &RI : FS->refs())
3426 assignValueId(RI.getGUID());
3428 for (auto &EI : FS->calls()) {
3429 GlobalValue::GUID GUID = EI.first.getGUID();
3430 if (!hasValueId(GUID)) {
3431 // For SamplePGO, the indirect call targets for local functions will
3432 // have its original name annotated in profile. We try to find the
3433 // corresponding PGOFuncName as the GUID.
3434 GUID = Index.getGUIDFromOriginalID(GUID);
3435 if (GUID == 0 || !hasValueId(GUID))
3438 assignValueId(GUID);
3442 for (const auto &GVI : valueIds()) {
3443 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3444 ArrayRef<uint64_t>{GVI.second, GVI.first});
3447 // Abbrev for FS_COMBINED.
3448 auto Abbv = std::make_shared<BitCodeAbbrev>();
3449 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3455 // numrefs x valueid, n x (valueid)
3456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3458 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3460 // Abbrev for FS_COMBINED_PROFILE.
3461 Abbv = std::make_shared<BitCodeAbbrev>();
3462 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3468 // numrefs x valueid, n x (valueid, hotness)
3469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3471 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3473 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3474 Abbv = std::make_shared<BitCodeAbbrev>();
3475 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3480 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3481 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3483 // Abbrev for FS_COMBINED_ALIAS.
3484 Abbv = std::make_shared<BitCodeAbbrev>();
3485 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3486 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3490 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3492 // The aliases are emitted as a post-pass, and will point to the value
3493 // id of the aliasee. Save them in a vector for post-processing.
3494 SmallVector<AliasSummary *, 64> Aliases;
3496 // Save the value id for each summary for alias emission.
3497 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3499 SmallVector<uint64_t, 64> NameVals;
3501 // For local linkage, we also emit the original name separately
3502 // immediately after the record.
3503 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3504 if (!GlobalValue::isLocalLinkage(S.linkage()))
3506 NameVals.push_back(S.getOriginalName());
3507 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3511 forEachSummary([&](GVInfo I) {
3512 GlobalValueSummary *S = I.second;
3515 assert(hasValueId(I.first));
3516 unsigned ValueId = getValueId(I.first);
3517 SummaryToValueIdMap[S] = ValueId;
3519 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3520 // Will process aliases as a post-pass because the reader wants all
3521 // global to be loaded first.
3522 Aliases.push_back(AS);
3526 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3527 NameVals.push_back(ValueId);
3528 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3529 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3530 for (auto &RI : VS->refs()) {
3531 NameVals.push_back(getValueId(RI.getGUID()));
3534 // Emit the finished record.
3535 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3538 MaybeEmitOriginalName(*S);
3542 auto *FS = cast<FunctionSummary>(S);
3543 writeFunctionTypeMetadataRecords(Stream, FS);
3545 NameVals.push_back(ValueId);
3546 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3547 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3548 NameVals.push_back(FS->instCount());
3549 NameVals.push_back(FS->refs().size());
3551 for (auto &RI : FS->refs()) {
3552 NameVals.push_back(getValueId(RI.getGUID()));
3555 bool HasProfileData = false;
3556 for (auto &EI : FS->calls()) {
3557 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3562 for (auto &EI : FS->calls()) {
3563 // If this GUID doesn't have a value id, it doesn't have a function
3564 // summary and we don't need to record any calls to it.
3565 GlobalValue::GUID GUID = EI.first.getGUID();
3566 if (!hasValueId(GUID)) {
3567 // For SamplePGO, the indirect call targets for local functions will
3568 // have its original name annotated in profile. We try to find the
3569 // corresponding PGOFuncName as the GUID.
3570 GUID = Index.getGUIDFromOriginalID(GUID);
3571 if (GUID == 0 || !hasValueId(GUID))
3574 NameVals.push_back(getValueId(GUID));
3576 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3579 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3581 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3583 // Emit the finished record.
3584 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3586 MaybeEmitOriginalName(*S);
3589 for (auto *AS : Aliases) {
3590 auto AliasValueId = SummaryToValueIdMap[AS];
3591 assert(AliasValueId);
3592 NameVals.push_back(AliasValueId);
3593 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3594 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3595 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3596 assert(AliaseeValueId);
3597 NameVals.push_back(AliaseeValueId);
3599 // Emit the finished record.
3600 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3602 MaybeEmitOriginalName(*AS);
3608 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3609 /// current llvm version, and a record for the epoch number.
3610 static void writeIdentificationBlock(BitstreamWriter &Stream) {
3611 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3613 // Write the "user readable" string identifying the bitcode producer
3614 auto Abbv = std::make_shared<BitCodeAbbrev>();
3615 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3617 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3618 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3619 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3620 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
3622 // Write the epoch version
3623 Abbv = std::make_shared<BitCodeAbbrev>();
3624 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3625 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3626 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3627 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3628 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3632 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3633 // Emit the module's hash.
3634 // MODULE_CODE_HASH: [5*i32]
3638 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3639 Buffer.size() - BlockStartPos));
3640 StringRef Hash = Hasher.result();
3641 for (int Pos = 0; Pos < 20; Pos += 4) {
3642 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3645 // Emit the finished record.
3646 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3649 // Save the written hash value.
3650 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3652 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
3655 void ModuleBitcodeWriter::write() {
3656 writeIdentificationBlock(Stream);
3658 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3659 size_t BlockStartPos = Buffer.size();
3661 writeModuleVersion();
3663 // Emit blockinfo, which defines the standard abbreviations etc.
3666 // Emit information about attribute groups.
3667 writeAttributeGroupTable();
3669 // Emit information about parameter attributes.
3670 writeAttributeTable();
3672 // Emit information describing all of the types in the module.
3677 // Emit top-level description of module, including target triple, inline asm,
3678 // descriptors for global variables, and function prototype info.
3682 writeModuleConstants();
3684 // Emit metadata kind names.
3685 writeModuleMetadataKinds();
3688 writeModuleMetadata();
3690 // Emit module-level use-lists.
3691 if (VE.shouldPreserveUseListOrder())
3692 writeUseListBlock(nullptr);
3694 writeOperandBundleTags();
3696 // Emit function bodies.
3697 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3698 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3699 if (!F->isDeclaration())
3700 writeFunction(*F, FunctionToBitcodeIndex);
3702 // Need to write after the above call to WriteFunction which populates
3703 // the summary information in the index.
3705 writePerModuleGlobalValueSummary();
3707 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
3709 writeModuleHash(BlockStartPos);
3714 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3715 uint32_t &Position) {
3716 support::endian::write32le(&Buffer[Position], Value);
3720 /// If generating a bc file on darwin, we have to emit a
3721 /// header and trailer to make it compatible with the system archiver. To do
3722 /// this we emit the following header, and then emit a trailer that pads the
3723 /// file out to be a multiple of 16 bytes.
3725 /// struct bc_header {
3726 /// uint32_t Magic; // 0x0B17C0DE
3727 /// uint32_t Version; // Version, currently always 0.
3728 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3729 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
3730 /// uint32_t CPUType; // CPU specifier.
3731 /// ... potentially more later ...
3733 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3735 unsigned CPUType = ~0U;
3737 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3738 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3739 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3740 // specific constants here because they are implicitly part of the Darwin ABI.
3742 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3743 DARWIN_CPU_TYPE_X86 = 7,
3744 DARWIN_CPU_TYPE_ARM = 12,
3745 DARWIN_CPU_TYPE_POWERPC = 18
3748 Triple::ArchType Arch = TT.getArch();
3749 if (Arch == Triple::x86_64)
3750 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3751 else if (Arch == Triple::x86)
3752 CPUType = DARWIN_CPU_TYPE_X86;
3753 else if (Arch == Triple::ppc)
3754 CPUType = DARWIN_CPU_TYPE_POWERPC;
3755 else if (Arch == Triple::ppc64)
3756 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3757 else if (Arch == Triple::arm || Arch == Triple::thumb)
3758 CPUType = DARWIN_CPU_TYPE_ARM;
3760 // Traditional Bitcode starts after header.
3761 assert(Buffer.size() >= BWH_HeaderSize &&
3762 "Expected header size to be reserved");
3763 unsigned BCOffset = BWH_HeaderSize;
3764 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3766 // Write the magic and version.
3767 unsigned Position = 0;
3768 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3769 writeInt32ToBuffer(0, Buffer, Position); // Version.
3770 writeInt32ToBuffer(BCOffset, Buffer, Position);
3771 writeInt32ToBuffer(BCSize, Buffer, Position);
3772 writeInt32ToBuffer(CPUType, Buffer, Position);
3774 // If the file is not a multiple of 16 bytes, insert dummy padding.
3775 while (Buffer.size() & 15)
3776 Buffer.push_back(0);
3779 /// Helper to write the header common to all bitcode files.
3780 static void writeBitcodeHeader(BitstreamWriter &Stream) {
3781 // Emit the file header.
3782 Stream.Emit((unsigned)'B', 8);
3783 Stream.Emit((unsigned)'C', 8);
3784 Stream.Emit(0x0, 4);
3785 Stream.Emit(0xC, 4);
3786 Stream.Emit(0xE, 4);
3787 Stream.Emit(0xD, 4);
3790 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3791 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3792 writeBitcodeHeader(*Stream);
3795 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3797 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3798 Stream->EnterSubblock(Block, 3);
3800 auto Abbv = std::make_shared<BitCodeAbbrev>();
3801 Abbv->Add(BitCodeAbbrevOp(Record));
3802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3803 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3805 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3807 Stream->ExitBlock();
3810 void BitcodeWriter::writeStrtab() {
3811 assert(!WroteStrtab);
3813 std::vector<char> Strtab;
3814 StrtabBuilder.finalizeInOrder();
3815 Strtab.resize(StrtabBuilder.getSize());
3816 StrtabBuilder.write((uint8_t *)Strtab.data());
3818 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3819 {Strtab.data(), Strtab.size()});
3824 void BitcodeWriter::copyStrtab(StringRef Strtab) {
3825 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3829 void BitcodeWriter::writeModule(const Module *M,
3830 bool ShouldPreserveUseListOrder,
3831 const ModuleSummaryIndex *Index,
3832 bool GenerateHash, ModuleHash *ModHash) {
3833 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
3834 ShouldPreserveUseListOrder, Index,
3835 GenerateHash, ModHash);
3836 ModuleWriter.write();
3839 /// WriteBitcodeToFile - Write the specified module to the specified output
3841 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3842 bool ShouldPreserveUseListOrder,
3843 const ModuleSummaryIndex *Index,
3844 bool GenerateHash, ModuleHash *ModHash) {
3845 SmallVector<char, 0> Buffer;
3846 Buffer.reserve(256*1024);
3848 // If this is darwin or another generic macho target, reserve space for the
3850 Triple TT(M->getTargetTriple());
3851 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3852 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3854 BitcodeWriter Writer(Buffer);
3855 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3857 Writer.writeStrtab();
3859 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3860 emitDarwinBCHeaderAndTrailer(Buffer, TT);
3862 // Write the generated bitstream to "Out".
3863 Out.write((char*)&Buffer.front(), Buffer.size());
3866 void IndexBitcodeWriter::write() {
3867 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3869 writeModuleVersion();
3871 // Write the module paths in the combined index.
3874 // Write the summary combined index records.
3875 writeCombinedGlobalValueSummary();
3880 // Write the specified module summary index to the given raw output stream,
3881 // where it will be written in a new bitcode block. This is used when
3882 // writing the combined index file for ThinLTO. When writing a subset of the
3883 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3884 void llvm::WriteIndexToFile(
3885 const ModuleSummaryIndex &Index, raw_ostream &Out,
3886 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3887 SmallVector<char, 0> Buffer;
3888 Buffer.reserve(256 * 1024);
3890 BitstreamWriter Stream(Buffer);
3891 writeBitcodeHeader(Stream);
3893 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
3894 IndexWriter.write();
3896 Out.write((char *)&Buffer.front(), Buffer.size());