33#include "llvm/Config/llvm-config.h"
95 cl::desc(
"Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
99 cl::desc(
"The threshold (unit M) for flushing LLVM bitcode."));
119 cl::desc(
"Preserve use-list order when writing LLVM bitcode."));
130 VST_BBENTRY_6_ABBREV,
134 CONSTANTS_INTEGER_ABBREV,
135 CONSTANTS_BYTE_ABBREV,
136 CONSTANTS_CE_CAST_Abbrev,
137 CONSTANTS_NULL_Abbrev,
141 FUNCTION_INST_STORE_ABBREV,
142 FUNCTION_INST_UNOP_ABBREV,
143 FUNCTION_INST_UNOP_FLAGS_ABBREV,
144 FUNCTION_INST_BINOP_ABBREV,
145 FUNCTION_INST_BINOP_FLAGS_ABBREV,
146 FUNCTION_INST_CAST_ABBREV,
147 FUNCTION_INST_CAST_FLAGS_ABBREV,
148 FUNCTION_INST_RET_VOID_ABBREV,
149 FUNCTION_INST_RET_VAL_ABBREV,
150 FUNCTION_INST_BR_UNCOND_ABBREV,
151 FUNCTION_INST_BR_COND_ABBREV,
152 FUNCTION_INST_UNREACHABLE_ABBREV,
153 FUNCTION_INST_GEP_ABBREV,
154 FUNCTION_INST_CMP_ABBREV,
155 FUNCTION_INST_CMP_FLAGS_ABBREV,
156 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
157 FUNCTION_DEBUG_LOC_ABBREV,
158 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
163class BitcodeWriterBase {
166 BitstreamWriter &Stream;
168 StringTableBuilder &StrtabBuilder;
173 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
174 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
177 void writeModuleVersion();
180void BitcodeWriterBase::writeModuleVersion() {
187class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
196 const ModuleSummaryIndex *Index;
201 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
204 unsigned GlobalValueId;
213 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
214 BitstreamWriter &Stream,
215 bool ShouldPreserveUseListOrder,
216 const ModuleSummaryIndex *Index)
217 : BitcodeWriterBase(Stream, StrtabBuilder),
M(
M),
220 : ShouldPreserveUseListOrder),
231 for (
const auto &GUIDSummaryLists :
232 Index->sortedGlobalValueSummariesRange())
234 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
240 for (auto &CallEdge : FS->calls())
241 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
242 assignValueId(CallEdge.first.getGUID());
248 for (auto &RefEdge : FS->refs())
249 if (!RefEdge.haveGVs() || !RefEdge.getValue())
250 assignValueId(RefEdge.getGUID());
255 void writePerModuleGlobalValueSummary();
256 void writeGUIDList();
259 void writePerModuleFunctionSummaryRecord(
260 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
261 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
262 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
263 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
265 void writeModuleLevelReferences(
const GlobalVariable &V,
266 SmallVector<uint64_t, 64> &NameVals,
267 unsigned FSModRefsAbbrev,
268 unsigned FSModVTableRefsAbbrev);
271 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
275 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
278 assert(VMI != GUIDToValueIdMap.end() &&
279 "GUID does not have assigned value Id");
284 unsigned getValueId(ValueInfo VI) {
285 if (!
VI.haveGVs() || !
VI.getValue())
286 return getValueId(
VI.getGUID());
290 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
294class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
310 unsigned DILocationLayersAbbrev = 0;
315 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
316 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
317 const ModuleSummaryIndex *Index,
bool GenerateHash,
319 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
320 ShouldPreserveUseListOrder,
Index),
321 GenerateHash(GenerateHash), ModHash(ModHash),
322 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
328 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
330 size_t addToStrtab(StringRef Str);
332 void writeAttributeGroupTable();
333 void writeAttributeTable();
334 void writeTypeTable();
336 void writeValueSymbolTableForwardDecl();
337 void writeModuleInfo();
338 void writeValueAsMetadata(
const ValueAsMetadata *MD,
339 SmallVectorImpl<uint64_t> &Record);
340 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
342 unsigned createDILocationAbbrev(
bool WithIRLayers);
343 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
345 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
348 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
349 unsigned createGenericDINodeAbbrev();
351 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
352 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
355 SmallVectorImpl<uint64_t> &Record,
358 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
362 SmallVectorImpl<uint64_t> &Record,
365 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
367 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
369 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
371 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
373 SmallVectorImpl<uint64_t> &Record,
375 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
378 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
380 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
382 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 SmallVectorImpl<uint64_t> &Record,
387 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
390 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
394 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
395 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
397 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
400 SmallVectorImpl<uint64_t> &Record,
403 SmallVectorImpl<uint64_t> &Record,
406 SmallVectorImpl<uint64_t> &Record,
409 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
411 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
413 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
415 SmallVectorImpl<uint64_t> &Record,
418 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
419 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
422 SmallVectorImpl<uint64_t> &Record,
424 unsigned createNamedMetadataAbbrev();
425 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
426 unsigned createMetadataStringsAbbrev();
428 SmallVectorImpl<uint64_t> &Record);
430 SmallVectorImpl<uint64_t> &Record,
431 std::vector<unsigned> *MDAbbrevs =
nullptr,
432 std::vector<uint64_t> *IndexPos =
nullptr);
433 void writeModuleMetadata();
434 void writeFunctionMetadata(
const Function &
F);
435 void writeFunctionMetadataAttachment(
const Function &
F);
436 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
437 const GlobalObject &GO);
438 void writeModuleMetadataKinds();
439 void writeOperandBundleTags();
440 void writeSyncScopeNames();
441 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
442 void writeModuleConstants();
443 bool pushValueAndType(
const Value *V,
unsigned InstID,
444 SmallVectorImpl<unsigned> &Vals);
445 bool pushValueOrMetadata(
const Value *V,
unsigned InstID,
446 SmallVectorImpl<unsigned> &Vals);
447 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
448 void pushValue(
const Value *V,
unsigned InstID,
449 SmallVectorImpl<unsigned> &Vals);
450 void pushValueSigned(
const Value *V,
unsigned InstID,
451 SmallVectorImpl<uint64_t> &Vals);
452 void writeInstruction(
const Instruction &
I,
unsigned InstID,
453 SmallVectorImpl<unsigned> &Vals);
454 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
455 void writeGlobalValueSymbolTable(
456 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
457 void writeUseList(UseListOrder &&Order);
458 void writeUseListBlock(
const Function *
F);
461 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
462 void writeBlockInfo();
463 void writeModuleHash(StringRef View);
466 return unsigned(SSID);
469 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
473class IndexBitcodeWriter :
public BitcodeWriterBase {
475 const ModuleSummaryIndex &
Index;
491 SortedSummariesForIndex;
495 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
499 std::vector<uint64_t> StackIds;
504 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
507 unsigned GlobalValueId = 0;
511 DenseMap<StringRef, uint64_t> ModuleIdMap;
521 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
522 const ModuleSummaryIndex &Index,
525 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
526 DecSummaries(DecSummaries),
527 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
528 if (ModuleToSummariesForIndex) {
529 for (
const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
540 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
545 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
547 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
554 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
555 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
567 for (
auto &CI :
FS->callsites()) {
578 if (CI.StackIdIndices.empty()) {
579 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
582 for (
auto Idx : CI.StackIdIndices)
583 RecordStackIdReference(Idx);
586 for (
auto &AI :
FS->allocs())
587 for (
auto &MIB : AI.MIBs)
588 for (
auto Idx : MIB.StackIdIndices)
589 RecordStackIdReference(Idx);
595 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
600 template<
typename Functor>
601 void forEachSummary(Functor Callback) {
602 if (ModuleToSummariesForIndex) {
603 for (
auto &[GUID, GVS] : SortedSummariesForIndex) {
609 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
613 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
614 for (
auto &Summary : Summaries.second.getSummaryList())
623 template <
typename Functor>
void forEachModule(Functor Callback) {
624 if (ModuleToSummariesForIndex) {
625 for (
const auto &M : *ModuleToSummariesForIndex) {
626 const auto &MPI =
Index.modulePaths().find(
M.first);
627 if (MPI ==
Index.modulePaths().end()) {
631 assert(ModuleToSummariesForIndex->size() == 1);
641 std::vector<StringRef> ModulePaths;
642 for (
auto &[ModPath,
_] :
Index.modulePaths())
643 ModulePaths.push_back(ModPath);
645 for (
auto &ModPath : ModulePaths)
654 void writeModStrings();
655 void writeCombinedGlobalValueSummary();
658 auto VMI = GUIDToValueIdMap.find(ValGUID);
659 if (VMI == GUIDToValueIdMap.end())
664 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
699 case Instruction::Add:
701 case Instruction::Sub:
703 case Instruction::Mul:
706 case Instruction::FDiv:
709 case Instruction::FRem:
721 unsigned Encoding = 0;
722 switch (
I.getOperation()) {
795 if (
I.isElementwise())
830 case Attribute::Alignment:
832 case Attribute::AllocAlign:
834 case Attribute::AllocSize:
836 case Attribute::AlwaysInline:
838 case Attribute::Builtin:
840 case Attribute::ByVal:
842 case Attribute::Convergent:
844 case Attribute::InAlloca:
846 case Attribute::Cold:
848 case Attribute::DisableSanitizerInstrumentation:
850 case Attribute::FnRetThunkExtern:
852 case Attribute::Flatten:
856 case Attribute::ElementType:
858 case Attribute::HybridPatchable:
860 case Attribute::InlineHint:
862 case Attribute::InReg:
864 case Attribute::JumpTable:
866 case Attribute::MinSize:
868 case Attribute::AllocatedPointer:
870 case Attribute::AllocKind:
872 case Attribute::Memory:
874 case Attribute::NoFPClass:
876 case Attribute::Naked:
878 case Attribute::Nest:
880 case Attribute::NoAlias:
882 case Attribute::NoBuiltin:
884 case Attribute::NoCallback:
886 case Attribute::NoDivergenceSource:
888 case Attribute::NoDuplicate:
890 case Attribute::NoFree:
892 case Attribute::NoFreeObj:
894 case Attribute::NoImplicitFloat:
896 case Attribute::NoInline:
898 case Attribute::NoRecurse:
900 case Attribute::NoMerge:
902 case Attribute::NonLazyBind:
904 case Attribute::NonNull:
906 case Attribute::Dereferenceable:
908 case Attribute::DereferenceableOrNull:
910 case Attribute::NoRedZone:
912 case Attribute::NoReturn:
914 case Attribute::NoSync:
916 case Attribute::NoCfCheck:
918 case Attribute::NoProfile:
920 case Attribute::SkipProfile:
922 case Attribute::NoUnwind:
924 case Attribute::NoSanitizeBounds:
926 case Attribute::NoSanitizeCoverage:
928 case Attribute::NullPointerIsValid:
930 case Attribute::OptimizeForDebugging:
932 case Attribute::OptForFuzzing:
934 case Attribute::OptimizeForSize:
936 case Attribute::OptimizeNone:
938 case Attribute::ReadNone:
940 case Attribute::ReadOnly:
942 case Attribute::Returned:
944 case Attribute::ReturnsTwice:
946 case Attribute::SExt:
948 case Attribute::Speculatable:
950 case Attribute::StackAlignment:
952 case Attribute::StackProtect:
954 case Attribute::StackProtectReq:
956 case Attribute::StackProtectStrong:
958 case Attribute::SafeStack:
960 case Attribute::ShadowCallStack:
962 case Attribute::StrictFP:
964 case Attribute::StructRet:
966 case Attribute::SanitizeAddress:
968 case Attribute::SanitizeAllocToken:
970 case Attribute::SanitizeHWAddress:
972 case Attribute::SanitizeThread:
974 case Attribute::SanitizeType:
976 case Attribute::SanitizeMemory:
978 case Attribute::SanitizeNumericalStability:
980 case Attribute::SanitizeRealtime:
982 case Attribute::SanitizeRealtimeBlocking:
984 case Attribute::SpeculativeLoadHardening:
986 case Attribute::SwiftError:
988 case Attribute::SwiftSelf:
990 case Attribute::SwiftAsync:
992 case Attribute::UWTable:
994 case Attribute::VScaleRange:
996 case Attribute::WillReturn:
998 case Attribute::WriteOnly:
1000 case Attribute::ZExt:
1002 case Attribute::ImmArg:
1004 case Attribute::SanitizeMemTag:
1006 case Attribute::Preallocated:
1008 case Attribute::NoUndef:
1010 case Attribute::ByRef:
1012 case Attribute::MustProgress:
1014 case Attribute::PresplitCoroutine:
1016 case Attribute::Writable:
1018 case Attribute::CoroDestroyOnlyWhenComplete:
1020 case Attribute::CoroElideSafe:
1022 case Attribute::DeadOnUnwind:
1024 case Attribute::Range:
1026 case Attribute::Initializes:
1028 case Attribute::NoExt:
1030 case Attribute::Captures:
1032 case Attribute::DeadOnReturn:
1034 case Attribute::NoCreateUndefOrPoison:
1036 case Attribute::DenormalFPEnv:
1038 case Attribute::NoOutline:
1040 case Attribute::NoIPA:
1055 if ((int64_t)V >= 0)
1066 unsigned NumWords =
A.getActiveWords();
1067 const uint64_t *RawData =
A.getRawData();
1068 for (
unsigned i = 0; i < NumWords; i++)
1088void ModuleBitcodeWriter::writeAttributeGroupTable() {
1089 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1091 if (AttrGrps.empty())
return;
1095 SmallVector<uint64_t, 64>
Record;
1097 unsigned AttrListIndex = Pair.first;
1098 AttributeSet AS = Pair.second;
1100 Record.push_back(AttrListIndex);
1103 if (Attr.isEnumAttribute()) {
1106 }
else if (Attr.isIntAttribute()) {
1108 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1110 if (Kind == Attribute::Memory) {
1115 Record.push_back(Attr.getValueAsInt());
1117 }
else if (Attr.isStringAttribute()) {
1118 StringRef
Kind = Attr.getKindAsString();
1119 StringRef Val = Attr.getValueAsString();
1128 }
else if (Attr.isTypeAttribute()) {
1129 Type *Ty = Attr.getValueAsType();
1130 Record.push_back(Ty ? 6 : 5);
1134 }
else if (Attr.isConstantRangeAttribute()) {
1140 assert(Attr.isConstantRangeListAttribute());
1146 for (
auto &CR : Val)
1158void ModuleBitcodeWriter::writeAttributeTable() {
1160 if (
Attrs.empty())
return;
1164 SmallVector<uint64_t, 64>
Record;
1165 for (
const AttributeList &AL : Attrs) {
1166 for (
unsigned i :
AL.indexes()) {
1167 AttributeSet AS =
AL.getAttributes(i);
1180void ModuleBitcodeWriter::writeTypeTable() {
1184 SmallVector<uint64_t, 64> TypeVals;
1189 auto Abbv = std::make_shared<BitCodeAbbrev>();
1191 Abbv->Add(BitCodeAbbrevOp(0));
1192 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1195 Abbv = std::make_shared<BitCodeAbbrev>();
1200 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1203 Abbv = std::make_shared<BitCodeAbbrev>();
1208 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1211 Abbv = std::make_shared<BitCodeAbbrev>();
1215 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1218 Abbv = std::make_shared<BitCodeAbbrev>();
1223 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1226 Abbv = std::make_shared<BitCodeAbbrev>();
1230 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1238 for (
Type *
T : TypeList) {
1239 int AbbrevToUse = 0;
1242 switch (
T->getTypeID()) {
1252 case Type::MetadataTyID:
1257 case Type::ByteTyID:
1262 case Type::IntegerTyID:
1267 case Type::PointerTyID: {
1274 AbbrevToUse = OpaquePtrAbbrev;
1277 case Type::FunctionTyID: {
1283 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1285 AbbrevToUse = FunctionAbbrev;
1288 case Type::StructTyID: {
1293 for (
Type *ET :
ST->elements())
1296 if (
ST->isLiteral()) {
1298 AbbrevToUse = StructAnonAbbrev;
1300 if (
ST->isOpaque()) {
1304 AbbrevToUse = StructNamedAbbrev;
1308 if (!
ST->getName().empty())
1314 case Type::ArrayTyID: {
1318 TypeVals.
push_back(AT->getNumElements());
1320 AbbrevToUse = ArrayAbbrev;
1323 case Type::FixedVectorTyID:
1324 case Type::ScalableVectorTyID: {
1329 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1335 case Type::TargetExtTyID: {
1341 for (
Type *InnerTy :
TET->type_params())
1346 case Type::TypedPointerTyID:
1351 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1392 RawFlags |= Flags.ReadNone;
1393 RawFlags |= (Flags.ReadOnly << 1);
1394 RawFlags |= (Flags.NoRecurse << 2);
1395 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1396 RawFlags |= (Flags.NoInline << 4);
1397 RawFlags |= (Flags.AlwaysInline << 5);
1398 RawFlags |= (Flags.NoUnwind << 6);
1399 RawFlags |= (Flags.MayThrow << 7);
1400 RawFlags |= (Flags.HasUnknownCall << 8);
1401 RawFlags |= (Flags.MustBeUnreachable << 9);
1408 bool ImportAsDecl =
false) {
1411 RawFlags |= Flags.NotEligibleToImport;
1412 RawFlags |= (Flags.Live << 1);
1413 RawFlags |= (Flags.DSOLocal << 2);
1414 RawFlags |= (Flags.CanAutoHide << 3);
1419 RawFlags = (RawFlags << 4) | Flags.Linkage;
1421 RawFlags |= (Flags.Visibility << 8);
1423 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1424 RawFlags |= (ImportType << 10);
1426 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1432 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1433 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1477 switch (
C.getSelectionKind()) {
1501size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1504 return StrtabBuilder.
add(Str);
1507void ModuleBitcodeWriter::writeComdats() {
1522void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1527 auto Abbv = std::make_shared<BitCodeAbbrev>();
1533 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1549 bool isChar6 =
true;
1550 for (
char C : Str) {
1553 if ((
unsigned char)
C & 128)
1562static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1563 "Sanitizer Metadata is too large for naive serialization.");
1566 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1567 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1573void ModuleBitcodeWriter::writeModuleInfo() {
1575 if (!
M.getTargetTriple().empty())
1577 M.getTargetTriple().str(), 0 );
1578 const std::string &
DL =
M.getDataLayoutStr();
1582 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1584 Frag.Props.getAsStrings();
1597 std::map<std::string, unsigned> SectionMap;
1598 std::map<std::string, unsigned> GCMap;
1599 MaybeAlign MaxGVarAlignment;
1600 unsigned MaxGlobalType = 0;
1601 for (
const GlobalVariable &GV :
M.globals()) {
1602 if (MaybeAlign
A = GV.getAlign())
1603 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1604 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1605 if (GV.hasSection()) {
1607 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1611 Entry = SectionMap.size();
1616 if (
F.hasSection()) {
1618 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1622 Entry = SectionMap.size();
1627 unsigned &
Entry = GCMap[
F.getGC()];
1631 Entry = GCMap.size();
1637 unsigned SimpleGVarAbbrev = 0;
1638 if (!
M.global_empty()) {
1640 auto Abbv = std::make_shared<BitCodeAbbrev>();
1651 if (!MaxGVarAlignment)
1652 Abbv->Add(BitCodeAbbrevOp(0));
1654 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1658 if (SectionMap.empty())
1659 Abbv->Add(BitCodeAbbrevOp(0));
1664 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1678 auto Abbv = std::make_shared<BitCodeAbbrev>();
1681 Abbv->Add(AbbrevOpToUse);
1682 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1684 for (
const auto P :
M.getSourceFileName())
1695 for (
const GlobalVariable &GV :
M.globals()) {
1696 unsigned AbbrevToUse = 0;
1702 Vals.
push_back(addToStrtab(GV.getName()));
1705 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1709 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1710 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1712 if (GV.isThreadLocal() ||
1714 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1715 GV.isExternallyInitialized() ||
1717 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1718 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1722 Vals.
push_back(GV.isExternallyInitialized());
1726 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1730 Vals.
push_back(addToStrtab(GV.getPartition()));
1731 Vals.
push_back(GV.getPartition().size());
1734 GV.getSanitizerMetadata())
1738 AbbrevToUse = SimpleGVarAbbrev;
1759 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1760 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1772 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1776 Vals.
push_back(addToStrtab(
F.getPartition()));
1778 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1780 unsigned AbbrevToUse = 0;
1786 for (
const GlobalAlias &
A :
M.aliases()) {
1793 Vals.
push_back(
A.getType()->getAddressSpace());
1801 Vals.
push_back(addToStrtab(
A.getPartition()));
1804 unsigned AbbrevToUse = 0;
1810 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1816 Vals.
push_back(
I.getType()->getAddressSpace());
1821 Vals.
push_back(addToStrtab(
I.getPartition()));
1827 writeValueSymbolTableForwardDecl();
1834 if (OBO->hasNoSignedWrap())
1836 if (OBO->hasNoUnsignedWrap())
1842 if (PDI->isDisjoint())
1845 if (FPMO->hasAllowReassoc())
1847 if (FPMO->hasNoNaNs())
1849 if (FPMO->hasNoInfs())
1851 if (FPMO->hasNoSignedZeros())
1853 if (FPMO->hasAllowReciprocal())
1855 if (FPMO->hasAllowContract())
1857 if (FPMO->hasApproxFunc())
1863 if (NNI->hasNonNeg())
1867 if (NNI->hasNonNeg())
1870 if (TI->hasNoSignedWrap())
1872 if (TI->hasNoUnsignedWrap())
1875 if (
GEP->isInBounds())
1877 if (
GEP->hasNoUnsignedSignedWrap())
1879 if (
GEP->hasNoUnsignedWrap())
1882 if (ICmp->hasSameSign())
1885 if (ASC->hasNonNull())
1892void ModuleBitcodeWriter::writeValueAsMetadata(
1893 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1902void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1903 SmallVectorImpl<uint64_t> &Record,
1905 for (
const MDOperand &MDO :
N->operands()) {
1908 "Unexpected function-local metadata");
1917unsigned ModuleBitcodeWriter::createDILocationAbbrev(
bool WithIRLayers) {
1923 auto Abbv = std::make_shared<BitCodeAbbrev>();
1938void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1939 SmallVectorImpl<uint64_t> &Record,
1942 Abbrev = createDILocationAbbrev(
false);
1944 Record.push_back(
N->isDistinct());
1945 Record.push_back(
N->getLine());
1946 Record.push_back(
N->getColumn());
1949 Record.push_back(
N->isImplicitCode());
1950 Record.push_back(
N->getAtomGroup());
1951 Record.push_back(
N->getAtomRank());
1953 unsigned AbbrevToUse = Abbrev;
1954 if (DILayerLocList *IRLayers =
N->getIRLayers()) {
1955 if (!DILocationLayersAbbrev)
1956 DILocationLayersAbbrev = createDILocationAbbrev(
true);
1957 AbbrevToUse = DILocationLayersAbbrev;
1965void ModuleBitcodeWriter::writeDILayerLoc(
const DILayerLoc *
N,
1966 SmallVectorImpl<uint64_t> &Record,
1968 Record.push_back(
N->isDistinct());
1969 Record.push_back(
N->getLine());
1970 Record.push_back(
N->getColumn());
1977void ModuleBitcodeWriter::writeDILayerLocList(
const DILayerLocList *
N,
1978 SmallVectorImpl<uint64_t> &Record,
1980 Record.push_back(
N->isDistinct());
1981 for (
const MDOperand &
Op :
N->layers())
1987unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1990 auto Abbv = std::make_shared<BitCodeAbbrev>();
2001void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
2002 SmallVectorImpl<uint64_t> &Record,
2005 Abbrev = createGenericDINodeAbbrev();
2007 Record.push_back(
N->isDistinct());
2008 Record.push_back(
N->getTag());
2011 for (
auto &
I :
N->operands())
2018void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
2019 SmallVectorImpl<uint64_t> &Record,
2032void ModuleBitcodeWriter::writeDIGenericSubrange(
2033 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
2045void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
2046 SmallVectorImpl<uint64_t> &Record,
2049 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
2050 Record.push_back(
N->getValue().getBitWidth());
2058void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
2059 SmallVectorImpl<uint64_t> &Record,
2061 const unsigned SizeIsMetadata = 0x2;
2062 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2063 Record.push_back(
N->getTag());
2066 Record.push_back(
N->getAlignInBits());
2067 Record.push_back(
N->getEncoding());
2068 Record.push_back(
N->getFlags());
2069 Record.push_back(
N->getNumExtraInhabitants());
2070 Record.push_back(
N->getDataSizeInBits());
2072 Record.push_back(
N->getLine());
2079void ModuleBitcodeWriter::writeDIFixedPointType(
2080 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2082 const unsigned SizeIsMetadata = 0x2;
2083 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2084 Record.push_back(
N->getTag());
2087 Record.push_back(
N->getAlignInBits());
2088 Record.push_back(
N->getEncoding());
2089 Record.push_back(
N->getFlags());
2090 Record.push_back(
N->getKind());
2091 Record.push_back(
N->getFactorRaw());
2093 auto WriteWideInt = [&](
const APInt &
Value) {
2098 Record.push_back(Encoded);
2102 WriteWideInt(
N->getNumeratorRaw());
2103 WriteWideInt(
N->getDenominatorRaw());
2106 Record.push_back(
N->getLine());
2113void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2114 SmallVectorImpl<uint64_t> &Record,
2116 const unsigned SizeIsMetadata = 0x2;
2117 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2118 Record.push_back(
N->getTag());
2124 Record.push_back(
N->getAlignInBits());
2125 Record.push_back(
N->getEncoding());
2132void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2133 SmallVectorImpl<uint64_t> &Record,
2135 const unsigned SizeIsMetadata = 0x2;
2136 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2137 Record.push_back(
N->getTag());
2140 Record.push_back(
N->getLine());
2144 Record.push_back(
N->getAlignInBits());
2146 Record.push_back(
N->getFlags());
2151 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2152 Record.push_back(*DWARFAddressSpace + 1);
2158 if (
auto PtrAuthData =
N->getPtrAuthData())
2159 Record.push_back(PtrAuthData->RawData);
2167void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2168 SmallVectorImpl<uint64_t> &Record,
2170 const unsigned SizeIsMetadata = 0x2;
2171 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2174 Record.push_back(
N->getLine());
2177 Record.push_back(
N->getAlignInBits());
2178 Record.push_back(
N->getFlags());
2189void ModuleBitcodeWriter::writeDICompositeType(
2190 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2192 const unsigned IsNotUsedInOldTypeRef = 0x2;
2193 const unsigned SizeIsMetadata = 0x4;
2194 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2195 (
unsigned)
N->isDistinct());
2196 Record.push_back(
N->getTag());
2199 Record.push_back(
N->getLine());
2203 Record.push_back(
N->getAlignInBits());
2205 Record.push_back(
N->getFlags());
2207 Record.push_back(
N->getRuntimeLang());
2217 Record.push_back(
N->getNumExtraInhabitants());
2227void ModuleBitcodeWriter::writeDISubroutineType(
2228 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2230 const unsigned HasNoOldTypeRefs = 0x2;
2231 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2232 Record.push_back(
N->getFlags());
2240void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2241 SmallVectorImpl<uint64_t> &Record,
2243 Record.push_back(
N->isDistinct());
2246 if (
N->getRawChecksum()) {
2247 Record.push_back(
N->getRawChecksum()->Kind);
2255 auto Source =
N->getRawSource();
2263void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2264 SmallVectorImpl<uint64_t> &Record,
2266 assert(
N->isDistinct() &&
"Expected distinct compile units");
2269 auto Lang =
N->getSourceLanguage();
2270 Record.push_back(Lang.getName());
2273 if (Lang.hasVersionedName())
2278 Record.push_back(
N->isOptimized());
2280 Record.push_back(
N->getRuntimeVersion());
2282 Record.push_back(
N->getEmissionKind());
2288 Record.push_back(
N->getDWOId());
2290 Record.push_back(
N->getSplitDebugInlining());
2291 Record.push_back(
N->getDebugInfoForProfiling());
2292 Record.push_back((
unsigned)
N->getNameTableKind());
2293 Record.push_back(
N->getRangesBaseAddress());
2296 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2297 Record.push_back(Lang.getDialect());
2303void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2304 SmallVectorImpl<uint64_t> &Record,
2306 const uint64_t HasUnitFlag = 1 << 1;
2307 const uint64_t HasSPFlagsFlag = 1 << 2;
2308 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2313 Record.push_back(
N->getLine());
2315 Record.push_back(
N->getScopeLine());
2317 Record.push_back(
N->getSPFlags());
2318 Record.push_back(
N->getVirtualIndex());
2319 Record.push_back(
N->getFlags());
2324 Record.push_back(
N->getThisAdjustment());
2328 Record.push_back(
N->getKeyInstructionsEnabled());
2334void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2335 SmallVectorImpl<uint64_t> &Record,
2337 Record.push_back(
N->isDistinct());
2340 Record.push_back(
N->getLine());
2341 Record.push_back(
N->getColumn());
2347void ModuleBitcodeWriter::writeDILexicalBlockFile(
2348 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2350 Record.push_back(
N->isDistinct());
2353 Record.push_back(
N->getDiscriminator());
2359void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2360 SmallVectorImpl<uint64_t> &Record,
2362 Record.push_back(
N->isDistinct());
2367 Record.push_back(
N->getLineNo());
2373void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2374 SmallVectorImpl<uint64_t> &Record,
2376 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2384void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2385 SmallVectorImpl<uint64_t> &Record,
2387 Record.push_back(
N->isDistinct());
2388 Record.push_back(
N->getMacinfoType());
2389 Record.push_back(
N->getLine());
2397void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2398 SmallVectorImpl<uint64_t> &Record,
2400 Record.push_back(
N->isDistinct());
2401 Record.push_back(
N->getMacinfoType());
2402 Record.push_back(
N->getLine());
2410void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2411 SmallVectorImpl<uint64_t> &Record) {
2412 Record.reserve(
N->getArgs().size());
2413 for (ValueAsMetadata *MD :
N->getArgs())
2420void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2421 SmallVectorImpl<uint64_t> &Record,
2423 Record.push_back(
N->isDistinct());
2424 for (
auto &
I :
N->operands())
2426 Record.push_back(
N->getLineNo());
2427 Record.push_back(
N->getIsDecl());
2433void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2434 SmallVectorImpl<uint64_t> &Record,
2437 Record.push_back(
N->isDistinct());
2442void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2443 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2445 Record.push_back(
N->isDistinct());
2448 Record.push_back(
N->isDefault());
2454void ModuleBitcodeWriter::writeDITemplateValueParameter(
2455 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2457 Record.push_back(
N->isDistinct());
2458 Record.push_back(
N->getTag());
2461 Record.push_back(
N->isDefault());
2468void ModuleBitcodeWriter::writeDIGlobalVariable(
2469 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2477 Record.push_back(
N->getLine());
2479 Record.push_back(
N->isLocalToUnit());
2480 Record.push_back(
N->isDefinition());
2483 Record.push_back(
N->getAlignInBits());
2490void ModuleBitcodeWriter::writeDILocalVariable(
2491 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2506 const uint64_t HasAlignmentFlag = 1 << 1;
2511 Record.push_back(
N->getLine());
2513 Record.push_back(
N->getArg());
2514 Record.push_back(
N->getFlags());
2515 Record.push_back(
N->getAlignInBits());
2522void ModuleBitcodeWriter::writeDILabel(
2523 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2530 Record.push_back(
N->getLine());
2531 Record.push_back(
N->getColumn());
2532 Record.push_back(
N->getCoroSuspendIdx().has_value()
2533 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2534 : std::numeric_limits<uint64_t>::max());
2540void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2541 SmallVectorImpl<uint64_t> &Record,
2543 Record.reserve(
N->getElements().size() + 1);
2546 Record.append(
N->elements_begin(),
N->elements_end());
2552void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2553 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2555 Record.push_back(
N->isDistinct());
2563void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2564 SmallVectorImpl<uint64_t> &Record,
2566 Record.push_back(
N->isDistinct());
2569 Record.push_back(
N->getLine());
2572 Record.push_back(
N->getAttributes());
2579void ModuleBitcodeWriter::writeDIProperty(
const DIProperty *
N,
2580 SmallVectorImpl<uint64_t> &Record,
2582 Record.push_back(
N->isDistinct());
2585 Record.push_back(
N->getLine());
2593void ModuleBitcodeWriter::writeDIImportedEntity(
2594 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2596 Record.push_back(
N->isDistinct());
2597 Record.push_back(
N->getTag());
2600 Record.push_back(
N->getLine());
2609unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2610 auto Abbv = std::make_shared<BitCodeAbbrev>();
2617void ModuleBitcodeWriter::writeNamedMetadata(
2618 SmallVectorImpl<uint64_t> &Record) {
2619 if (
M.named_metadata_empty())
2622 unsigned Abbrev = createNamedMetadataAbbrev();
2623 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2625 StringRef Str = NMD.getName();
2626 Record.append(Str.bytes_begin(), Str.bytes_end());
2631 for (
const MDNode *
N : NMD.operands())
2638unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2639 auto Abbv = std::make_shared<BitCodeAbbrev>();
2651void ModuleBitcodeWriter::writeMetadataStrings(
2653 if (Strings.
empty())
2661 SmallString<256> Blob;
2663 BitstreamWriter
W(Blob);
2683#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2684#include "llvm/IR/Metadata.def"
2688void ModuleBitcodeWriter::writeMetadataRecords(
2690 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2695#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2696#include "llvm/IR/Metadata.def"
2702 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2704 switch (
N->getMetadataID()) {
2707#define HANDLE_MDNODE_LEAF(CLASS) \
2708 case Metadata::CLASS##Kind: \
2710 write##CLASS(cast<CLASS>(N), Record, \
2711 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2713 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2715#include "llvm/IR/Metadata.def"
2726void ModuleBitcodeWriter::writeModuleMetadata() {
2727 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2731 SmallVector<uint64_t, 64>
Record;
2735 std::vector<unsigned> MDAbbrevs;
2738 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2739 createDILocationAbbrev(
false);
2740 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2741 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2742 createGenericDINodeAbbrev();
2744 auto Abbv = std::make_shared<BitCodeAbbrev>();
2748 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2750 Abbv = std::make_shared<BitCodeAbbrev>();
2754 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2776 std::vector<uint64_t> IndexPos;
2780 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2791 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2792 for (
auto &Elt : IndexPos) {
2793 auto EltDelta = Elt - PreviousValue;
2794 PreviousValue = Elt;
2803 writeNamedMetadata(Record);
2805 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2806 SmallVector<uint64_t, 4>
Record;
2808 pushGlobalMetadataAttachment(Record, GO);
2812 if (
F.isDeclaration() &&
F.hasMetadata())
2813 AddDeclAttachedMetadata(
F);
2814 for (
const GlobalIFunc &GI :
M.ifuncs())
2815 if (GI.hasMetadata())
2816 AddDeclAttachedMetadata(GI);
2819 for (
const GlobalVariable &GV :
M.globals())
2820 if (GV.hasMetadata())
2821 AddDeclAttachedMetadata(GV);
2826void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2833 DILocationLayersAbbrev = 0;
2834 SmallVector<uint64_t, 64>
Record;
2840void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2841 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2845 for (
const auto &
I : MDs) {
2851void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2854 SmallVector<uint64_t, 64>
Record;
2856 if (
F.hasMetadata()) {
2857 pushGlobalMetadataAttachment(Record,
F);
2865 for (
const BasicBlock &BB :
F)
2866 for (
const Instruction &
I : BB) {
2868 I.getAllMetadataOtherThanDebugLoc(MDs);
2871 if (MDs.
empty())
continue;
2875 for (
const auto &[ID, MD] : MDs) {
2886void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2887 SmallVector<uint64_t, 64>
Record;
2892 M.getMDKindNames(Names);
2894 if (Names.
empty())
return;
2898 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2899 Record.push_back(MDKindID);
2900 StringRef KName = Names[MDKindID];
2910void ModuleBitcodeWriter::writeOperandBundleTags() {
2918 M.getOperandBundleTags(Tags);
2925 SmallVector<uint64_t, 64>
Record;
2927 for (
auto Tag : Tags) {
2937void ModuleBitcodeWriter::writeSyncScopeNames() {
2939 M.getContext().getSyncScopeNames(SSNs);
2945 SmallVector<uint64_t, 64>
Record;
2946 for (
auto SSN : SSNs) {
2947 Record.append(SSN.begin(), SSN.end());
2955void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2957 if (FirstVal == LastVal)
return;
2961 unsigned AggregateAbbrev = 0;
2962 unsigned String8Abbrev = 0;
2963 unsigned CString7Abbrev = 0;
2964 unsigned CString6Abbrev = 0;
2968 auto Abbv = std::make_shared<BitCodeAbbrev>();
2972 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2975 Abbv = std::make_shared<BitCodeAbbrev>();
2979 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2981 Abbv = std::make_shared<BitCodeAbbrev>();
2985 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2987 Abbv = std::make_shared<BitCodeAbbrev>();
2991 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2994 SmallVector<uint64_t, 64>
Record;
2997 Type *LastTy =
nullptr;
2998 for (
unsigned i = FirstVal; i != LastVal; ++i) {
2999 const Value *
V = Vals[i].first;
3001 if (
V->getType() != LastTy) {
3002 LastTy =
V->getType();
3005 CONSTANTS_SETTYPE_ABBREV);
3012 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
3013 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
3016 StringRef AsmStr =
IA->getAsmString();
3021 StringRef ConstraintStr =
IA->getConstraintString();
3029 unsigned Code = -1U;
3030 unsigned AbbrevToUse = 0;
3031 if (
C->isNullValue()) {
3038 if (
IV->getBitWidth() <= 64) {
3042 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3048 if (BV->getBitWidth() <= 64) {
3052 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3062 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3066 APInt api = CFP->getValueAPF().bitcastToAPInt();
3068 Record.push_back((p[1] << 48) | (p[0] >> 16));
3069 Record.push_back(p[0] & 0xffffLL);
3071 APInt api = CFP->getValueAPF().bitcastToAPInt();
3076 assert(0 &&
"Unknown FP type!");
3082 uint64_t NumElts = Str->getNumElements();
3084 if (Str->isCString()) {
3089 AbbrevToUse = String8Abbrev;
3093 for (
uint64_t i = 0; i != NumElts; ++i) {
3094 unsigned char V = Str->getElementAsInteger(i);
3096 isCStr7 &= (
V & 128) == 0;
3102 AbbrevToUse = CString6Abbrev;
3104 AbbrevToUse = CString7Abbrev;
3105 }
else if (
const ConstantDataSequential *CDS =
3108 Type *EltTy = CDS->getElementType();
3110 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3111 Record.push_back(CDS->getElementAsInteger(i));
3113 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3115 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3119 for (
const Value *
Op :
C->operands())
3121 AbbrevToUse = AggregateAbbrev;
3123 switch (
CE->getOpcode()) {
3130 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3132 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3142 case Instruction::GetElementPtr: {
3147 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3151 for (
const Value *
Op :
CE->operands()) {
3157 case Instruction::ExtractElement:
3164 case Instruction::InsertElement:
3171 case Instruction::ShuffleVector:
3176 if (
C->getType() ==
C->getOperand(0)->getType()) {
3213 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3220void ModuleBitcodeWriter::writeModuleConstants() {
3225 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3227 writeConstants(i, Vals.size(),
true);
3241bool ModuleBitcodeWriter::pushValueAndType(
const Value *V,
unsigned InstID,
3242 SmallVectorImpl<unsigned> &Vals) {
3246 if (ValID >= InstID) {
3253bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *V,
unsigned InstID,
3254 SmallVectorImpl<unsigned> &Vals) {
3255 bool IsMetadata =
V->getType()->isMetadataTy();
3263 return pushValueAndType(V, InstID, Vals);
3266void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3273 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3275 for (
auto &Input : Bundle.Inputs)
3276 pushValueOrMetadata(Input, InstID, Record);
3285void ModuleBitcodeWriter::pushValue(
const Value *V,
unsigned InstID,
3286 SmallVectorImpl<unsigned> &Vals) {
3291void ModuleBitcodeWriter::pushValueSigned(
const Value *V,
unsigned InstID,
3292 SmallVectorImpl<uint64_t> &Vals) {
3294 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3299void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3301 SmallVectorImpl<unsigned> &Vals) {
3303 unsigned AbbrevToUse = 0;
3305 switch (
I.getOpcode()) {
3309 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3310 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3315 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3316 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3322 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3323 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3324 pushValue(
I.getOperand(1), InstID, Vals);
3328 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3329 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3334 case Instruction::FNeg: {
3336 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3337 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3341 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3342 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3347 case Instruction::GetElementPtr: {
3349 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3353 for (
const Value *
Op :
I.operands())
3354 pushValueAndType(
Op, InstID, Vals);
3357 case Instruction::ExtractValue: {
3359 pushValueAndType(
I.getOperand(0), InstID, Vals);
3364 case Instruction::InsertValue: {
3366 pushValueAndType(
I.getOperand(0), InstID, Vals);
3367 pushValueAndType(
I.getOperand(1), InstID, Vals);
3372 case Instruction::Select: {
3374 pushValueAndType(
I.getOperand(1), InstID, Vals);
3375 pushValue(
I.getOperand(2), InstID, Vals);
3376 pushValueAndType(
I.getOperand(0), InstID, Vals);
3382 case Instruction::ExtractElement:
3384 pushValueAndType(
I.getOperand(0), InstID, Vals);
3385 pushValueAndType(
I.getOperand(1), InstID, Vals);
3387 case Instruction::InsertElement:
3389 pushValueAndType(
I.getOperand(0), InstID, Vals);
3390 pushValue(
I.getOperand(1), InstID, Vals);
3391 pushValueAndType(
I.getOperand(2), InstID, Vals);
3393 case Instruction::BitExtract:
3396 pushValueAndType(
I.getOperand(0), InstID, Vals);
3397 pushValueAndType(
I.getOperand(1), InstID, Vals);
3399 case Instruction::BitInsert:
3401 pushValueAndType(
I.getOperand(0), InstID, Vals);
3402 pushValueAndType(
I.getOperand(1), InstID, Vals);
3403 pushValueAndType(
I.getOperand(2), InstID, Vals);
3405 case Instruction::ShuffleVector:
3407 pushValueAndType(
I.getOperand(0), InstID, Vals);
3408 pushValue(
I.getOperand(1), InstID, Vals);
3412 case Instruction::ICmp:
3413 case Instruction::FCmp: {
3416 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3417 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3419 pushValue(
I.getOperand(1), InstID, Vals);
3425 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3430 case Instruction::Ret:
3433 unsigned NumOperands =
I.getNumOperands();
3434 if (NumOperands == 0)
3435 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3436 else if (NumOperands == 1) {
3437 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3438 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3440 for (
const Value *
Op :
I.operands())
3441 pushValueAndType(
Op, InstID, Vals);
3445 case Instruction::UncondBr: {
3447 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3451 case Instruction::CondBr: {
3453 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3457 pushValue(
II.getCondition(), InstID, Vals);
3459 case Instruction::Switch:
3464 pushValue(
SI.getCondition(), InstID, Vals);
3466 for (
auto Case :
SI.cases()) {
3472 case Instruction::IndirectBr:
3476 pushValue(
I.getOperand(0), InstID, Vals);
3481 case Instruction::Invoke: {
3484 FunctionType *FTy =
II->getFunctionType();
3486 if (
II->hasOperandBundles())
3487 writeOperandBundles(*
II, InstID);
3496 pushValueAndType(Callee, InstID, Vals);
3499 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3500 pushValue(
I.getOperand(i), InstID, Vals);
3503 if (FTy->isVarArg()) {
3504 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3505 pushValueAndType(
I.getOperand(i), InstID, Vals);
3509 case Instruction::Resume:
3511 pushValueAndType(
I.getOperand(0), InstID, Vals);
3513 case Instruction::CleanupRet: {
3516 pushValue(CRI.getCleanupPad(), InstID, Vals);
3517 if (CRI.hasUnwindDest())
3521 case Instruction::CatchRet: {
3524 pushValue(CRI.getCatchPad(), InstID, Vals);
3528 case Instruction::CleanupPad:
3529 case Instruction::CatchPad: {
3533 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3535 unsigned NumArgOperands = FuncletPad.arg_size();
3537 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3538 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3541 case Instruction::CatchSwitch: {
3545 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3547 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3549 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3552 if (CatchSwitch.hasUnwindDest())
3556 case Instruction::CallBr: {
3562 writeOperandBundles(*CBI, InstID);
3577 pushValueAndType(Callee, InstID, Vals);
3580 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3581 pushValue(
I.getOperand(i), InstID, Vals);
3584 if (FTy->isVarArg()) {
3585 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3586 pushValueAndType(
I.getOperand(i), InstID, Vals);
3590 case Instruction::Unreachable:
3592 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3595 case Instruction::PHI: {
3613 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3618 case Instruction::LandingPad: {
3629 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3634 case Instruction::Alloca: {
3640 using APV = AllocaPackedValues;
3642 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3644 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3646 EncodedAlign >> APV::AlignLower::Bits);
3653 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3658 case Instruction::Load: {
3660 if (LI.isAtomic()) {
3662 pushValueAndType(LI.getOperand(0), InstID, Vals);
3665 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3666 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3669 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3671 if (LI.isAtomic()) {
3673 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3674 if (LI.isElementwise())
3680 case Instruction::Store: {
3682 if (
SI.isAtomic()) {
3686 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3688 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3690 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3694 if (
SI.isAtomic()) {
3696 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3697 if (
SI.isElementwise())
3703 case Instruction::AtomicCmpXchg:
3705 pushValueAndType(
I.getOperand(0), InstID, Vals);
3706 pushValueAndType(
I.getOperand(1), InstID, Vals);
3707 pushValue(
I.getOperand(2), InstID, Vals);
3718 case Instruction::AtomicRMW:
3720 pushValueAndType(
I.getOperand(0), InstID, Vals);
3721 pushValueAndType(
I.getOperand(1), InstID, Vals);
3729 case Instruction::Fence:
3734 case Instruction::Call: {
3739 writeOperandBundles(CI, InstID);
3759 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3763 if (FTy->isVarArg()) {
3764 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3769 case Instruction::VAArg:
3772 pushValue(
I.getOperand(0), InstID, Vals);
3775 case Instruction::Freeze:
3777 pushValueAndType(
I.getOperand(0), InstID, Vals);
3787void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3788 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3793 VSTOffset -= bitcodeStartBit();
3794 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3798 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3802 auto Abbv = std::make_shared<BitCodeAbbrev>();
3806 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3811 if (
F.isDeclaration())
3818 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3819 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3823 Record[1] = BitcodeIndex / 32 + 1;
3832void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3833 const ValueSymbolTable &VST) {
3841 SmallVector<uint64_t, 64> NameVals;
3847 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3856 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3860 AbbrevToUse = VST_ENTRY_6_ABBREV;
3862 AbbrevToUse = VST_ENTRY_7_ABBREV;
3865 for (
const auto P :
Name.getKey())
3869 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3876void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3877 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3884 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3889void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3891 "Expected to be preserving use-list order");
3893 auto hasMore = [&]() {
3909void ModuleBitcodeWriter::writeFunction(
3911 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3928 unsigned CstStart, CstEnd;
3930 writeConstants(CstStart, CstEnd,
false);
3933 writeFunctionMetadata(
F);
3936 unsigned InstID = CstEnd;
3938 bool NeedsMetadataAttachment =
F.hasMetadata();
3940 DILocation *LastDL =
nullptr;
3941 SmallSetVector<Function *, 4> BlockAddressUsers;
3944 for (
const BasicBlock &BB :
F) {
3945 for (
const Instruction &
I : BB) {
3946 writeInstruction(
I, InstID, Vals);
3948 if (!
I.getType()->isVoidTy())
3952 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3955 if (DILocation *
DL =
I.getDebugLoc()) {
3968 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3969 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
3970 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3984 if (
I.hasDbgRecords()) {
3988 auto PushValueOrMetadata = [&Vals, InstID,
3991 "RawLocation unexpectedly null in DbgVariableRecord");
3993 SmallVector<unsigned, 2> ValAndType;
3997 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4011 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4037 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4061 SmallPtrSet<Value *, 8> Visited{BA};
4062 while (!Worklist.
empty()) {
4064 for (User *U :
V->users()) {
4070 Visited.
insert(U).second)
4077 if (!BlockAddressUsers.
empty()) {
4086 if (
auto *Symtab =
F.getValueSymbolTable())
4087 writeFunctionLevelValueSymbolTable(*Symtab);
4089 if (NeedsMetadataAttachment)
4090 writeFunctionMetadataAttachment(
F);
4092 writeUseListBlock(&
F);
4098void ModuleBitcodeWriter::writeBlockInfo() {
4111 auto Abbv = std::make_shared<BitCodeAbbrev>();
4122 auto Abbv = std::make_shared<BitCodeAbbrev>();
4132 auto Abbv = std::make_shared<BitCodeAbbrev>();
4142 auto Abbv = std::make_shared<BitCodeAbbrev>();
4148 VST_BBENTRY_6_ABBREV)
4153 auto Abbv = std::make_shared<BitCodeAbbrev>();
4155 Abbv->Add(TypeAbbrevOp);
4157 CONSTANTS_SETTYPE_ABBREV)
4162 auto Abbv = std::make_shared<BitCodeAbbrev>();
4166 CONSTANTS_INTEGER_ABBREV)
4171 auto Abbv = std::make_shared<BitCodeAbbrev>();
4175 CONSTANTS_BYTE_ABBREV)
4180 auto Abbv = std::make_shared<BitCodeAbbrev>();
4188 CONSTANTS_CE_CAST_Abbrev)
4192 auto Abbv = std::make_shared<BitCodeAbbrev>();
4195 CONSTANTS_NULL_Abbrev)
4202 auto Abbv = std::make_shared<BitCodeAbbrev>();
4204 Abbv->Add(ValAbbrevOp);
4205 Abbv->Add(TypeAbbrevOp);
4209 FUNCTION_INST_LOAD_ABBREV)
4213 auto Abbv = std::make_shared<BitCodeAbbrev>();
4215 Abbv->Add(ValAbbrevOp);
4216 Abbv->Add(ValAbbrevOp);
4220 FUNCTION_INST_STORE_ABBREV)
4224 auto Abbv = std::make_shared<BitCodeAbbrev>();
4226 Abbv->Add(ValAbbrevOp);
4229 FUNCTION_INST_UNOP_ABBREV)
4233 auto Abbv = std::make_shared<BitCodeAbbrev>();
4235 Abbv->Add(ValAbbrevOp);
4239 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4243 auto Abbv = std::make_shared<BitCodeAbbrev>();
4245 Abbv->Add(ValAbbrevOp);
4246 Abbv->Add(ValAbbrevOp);
4249 FUNCTION_INST_BINOP_ABBREV)
4253 auto Abbv = std::make_shared<BitCodeAbbrev>();
4255 Abbv->Add(ValAbbrevOp);
4256 Abbv->Add(ValAbbrevOp);
4260 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4264 auto Abbv = std::make_shared<BitCodeAbbrev>();
4266 Abbv->Add(ValAbbrevOp);
4267 Abbv->Add(TypeAbbrevOp);
4270 FUNCTION_INST_CAST_ABBREV)
4274 auto Abbv = std::make_shared<BitCodeAbbrev>();
4276 Abbv->Add(ValAbbrevOp);
4277 Abbv->Add(TypeAbbrevOp);
4281 FUNCTION_INST_CAST_FLAGS_ABBREV)
4286 auto Abbv = std::make_shared<BitCodeAbbrev>();
4289 FUNCTION_INST_RET_VOID_ABBREV)
4293 auto Abbv = std::make_shared<BitCodeAbbrev>();
4295 Abbv->Add(ValAbbrevOp);
4297 FUNCTION_INST_RET_VAL_ABBREV)
4301 auto Abbv = std::make_shared<BitCodeAbbrev>();
4304 Abbv->Add(ValAbbrevOp);
4306 FUNCTION_INST_BR_UNCOND_ABBREV)
4310 auto Abbv = std::make_shared<BitCodeAbbrev>();
4313 Abbv->Add(ValAbbrevOp);
4314 Abbv->Add(ValAbbrevOp);
4315 Abbv->Add(ValAbbrevOp);
4317 FUNCTION_INST_BR_COND_ABBREV)
4321 auto Abbv = std::make_shared<BitCodeAbbrev>();
4324 FUNCTION_INST_UNREACHABLE_ABBREV)
4328 auto Abbv = std::make_shared<BitCodeAbbrev>();
4331 Abbv->Add(TypeAbbrevOp);
4333 Abbv->Add(ValAbbrevOp);
4335 FUNCTION_INST_GEP_ABBREV)
4339 auto Abbv = std::make_shared<BitCodeAbbrev>();
4341 Abbv->Add(ValAbbrevOp);
4342 Abbv->Add(ValAbbrevOp);
4345 FUNCTION_INST_CMP_ABBREV)
4349 auto Abbv = std::make_shared<BitCodeAbbrev>();
4351 Abbv->Add(ValAbbrevOp);
4352 Abbv->Add(ValAbbrevOp);
4356 FUNCTION_INST_CMP_FLAGS_ABBREV)
4360 auto Abbv = std::make_shared<BitCodeAbbrev>();
4365 Abbv->Add(ValAbbrevOp);
4367 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4371 auto Abbv = std::make_shared<BitCodeAbbrev>();
4382 FUNCTION_DEBUG_LOC_ABBREV)
4388 auto Abbv = std::make_shared<BitCodeAbbrev>();
4399 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4407void IndexBitcodeWriter::writeModStrings() {
4413 auto Abbv = std::make_shared<BitCodeAbbrev>();
4418 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4421 Abbv = std::make_shared<BitCodeAbbrev>();
4426 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4429 Abbv = std::make_shared<BitCodeAbbrev>();
4434 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4437 Abbv = std::make_shared<BitCodeAbbrev>();
4444 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4447 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4449 const auto &Hash = MPSE.
getValue();
4451 unsigned AbbrevToUse = Abbrev8Bit;
4453 AbbrevToUse = Abbrev6Bit;
4455 AbbrevToUse = Abbrev7Bit;
4457 auto ModuleId = ModuleIdMap.
size();
4458 ModuleIdMap[
Key] = ModuleId;
4468 Vals.
assign(Hash.begin(), Hash.end());
4480template <
typename Fn>
4484 if (!FS->type_tests().empty())
4489 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4494 for (
auto &VF : VFs) {
4495 Record.push_back(VF.GUID);
4496 Record.push_back(VF.Offset);
4502 FS->type_test_assume_vcalls());
4504 FS->type_checked_load_vcalls());
4506 auto WriteConstVCallVec = [&](
uint64_t Ty,
4508 for (
auto &VC : VCs) {
4510 Record.push_back(VC.VFunc.GUID);
4511 Record.push_back(VC.VFunc.Offset);
4518 FS->type_test_assume_const_vcalls());
4520 FS->type_checked_load_const_vcalls());
4530 if (!FS->paramAccesses().empty()) {
4532 for (
auto &Arg : FS->paramAccesses()) {
4533 size_t UndoSize =
Record.size();
4534 Record.push_back(Arg.ParamNo);
4535 WriteRange(Arg.Use);
4536 Record.push_back(Arg.Calls.size());
4537 for (
auto &
Call : Arg.Calls) {
4539 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4546 Record.push_back(*ValueID);
4547 WriteRange(
Call.Offsets);
4558 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4559 if (!FS->type_tests().empty())
4560 for (
auto &TT : FS->type_tests())
4561 ReferencedTypeIds.insert(TT);
4563 auto GetReferencedTypesFromVFuncIdVec =
4565 for (
auto &VF : VFs)
4566 ReferencedTypeIds.insert(VF.GUID);
4569 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4570 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4572 auto GetReferencedTypesFromConstVCallVec =
4574 for (
auto &VC : VCs)
4575 ReferencedTypeIds.insert(VC.VFunc.GUID);
4578 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4579 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4615 NameVals.
push_back(Summary.TTRes.TheKind);
4616 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4617 NameVals.
push_back(Summary.TTRes.AlignLog2);
4618 NameVals.
push_back(Summary.TTRes.SizeM1);
4619 NameVals.
push_back(Summary.TTRes.BitMask);
4620 NameVals.
push_back(Summary.TTRes.InlineBits);
4622 for (
auto &W : Summary.WPDRes)
4634 for (
auto &
P : Summary) {
4636 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4650 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4651 for (
auto &AI : FS->allocs()) {
4652 for (
auto &MIB : AI.MIBs) {
4654 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4655 for (
auto Id : MIB.StackIdIndices)
4656 StackIdIndices.
push_back(GetStackIndex(Id));
4658 CallStacks.insert({CallStacks.size(), StackIdIndices});
4671 assert(!CallStacks.empty());
4677 Builder.
build(std::move(CallStacks),
nullptr,
4681 return Builder.takeCallStackPos();
4686 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4687 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4688 std::function<
unsigned(
unsigned)> GetStackIndex,
4689 bool WriteContextSizeInfoIndex,
4694 for (
auto &CI : FS->callsites()) {
4698 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4699 Record.push_back(GetValueID(CI.Callee));
4701 Record.push_back(CI.StackIdIndices.size());
4702 Record.push_back(CI.Clones.size());
4704 for (
auto Id : CI.StackIdIndices)
4705 Record.push_back(GetStackIndex(Id));
4713 for (
auto &AI : FS->allocs()) {
4717 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4718 Record.push_back(AI.MIBs.size());
4720 Record.push_back(AI.Versions.size());
4721 for (
auto &MIB : AI.MIBs) {
4728 assert(CallStackCount <= CallStackPos.
size());
4729 Record.push_back(CallStackPos[CallStackCount++]);
4734 assert(AI.ContextSizeInfos.empty() ||
4735 AI.ContextSizeInfos.size() == AI.MIBs.size());
4737 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4745 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4746 for (
auto &Infos : AI.ContextSizeInfos) {
4747 Record.push_back(Infos.size());
4748 for (
auto [FullStackId, TotalSize] : Infos) {
4755 Record.push_back(TotalSize);
4773void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4774 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4775 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4776 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4777 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4784 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4788 auto SpecialRefCnts =
FS->specialRefCounts();
4793 NameVals.
push_back(SpecialRefCnts.first);
4794 NameVals.
push_back(SpecialRefCnts.second);
4796 for (
auto &RI :
FS->refs())
4799 for (
auto &ECI :
FS->calls()) {
4800 NameVals.
push_back(getValueId(ECI.first));
4809 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4811 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4812 [&](
unsigned I) {
return I; },
4813 true, CallStackPos, CallStackCount);
4818void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4819 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4820 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4825 auto VI =
Index->getValueInfo(GUID);
4826 if (!VI ||
VI.getSummaryList().empty()) {
4832 auto *
Summary =
VI.getSummaryList()[0].get();
4838 auto VTableFuncs =
VS->vTableFuncs();
4839 if (!VTableFuncs.empty())
4842 unsigned SizeBeforeRefs = NameVals.
size();
4843 for (
auto &RI :
VS->refs())
4849 if (VTableFuncs.empty())
4854 for (
auto &
P : VTableFuncs) {
4860 FSModVTableRefsAbbrev);
4867void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4870 bool IsThinLTO =
true;
4873 IsThinLTO = MD->getZExtValue();
4885 if (
Index->enableSplitLTOUnit())
4887 if (
Index->hasUnifiedLTO())
4897 auto Abbv = std::make_shared<BitCodeAbbrev>();
4903 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4905 for (
const auto &GVI : valueIds()) {
4907 ArrayRef<uint32_t>{GVI.second,
4908 static_cast<uint32_t
>(GVI.first >> 32),
4909 static_cast<uint32_t
>(GVI.first)},
4913 if (!
Index->stackIds().empty()) {
4914 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4921 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4922 SmallVector<uint32_t> Vals;
4924 for (
auto Id :
Index->stackIds()) {
4925 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4926 Vals.
push_back(
static_cast<uint32_t
>(Id));
4931 unsigned ContextIdAbbvId = 0;
4934 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4946 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4950 Abbv = std::make_shared<BitCodeAbbrev>();
4962 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4965 Abbv = std::make_shared<BitCodeAbbrev>();
4971 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4974 Abbv = std::make_shared<BitCodeAbbrev>();
4982 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4985 Abbv = std::make_shared<BitCodeAbbrev>();
4990 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4993 Abbv = std::make_shared<BitCodeAbbrev>();
5000 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5002 Abbv = std::make_shared<BitCodeAbbrev>();
5008 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5010 Abbv = std::make_shared<BitCodeAbbrev>();
5017 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5019 Abbv = std::make_shared<BitCodeAbbrev>();
5024 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5031 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5042 ValueInfo
VI =
Index->getValueInfo(GUID);
5043 if (!VI ||
VI.getSummaryList().empty()) {
5046 if (!
F.isDeclaration())
5048 " to have an associated value info.");
5051 auto *
Summary =
VI.getSummaryList()[0].get();
5054 FS, [](
unsigned I) {
return I; }, CallStacks);
5058 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5059 if (!CallStacks.
empty()) {
5067 SmallVector<uint64_t, 64> NameVals;
5078 ValueInfo
VI =
Index->getValueInfo(GUID);
5079 if (!VI ||
VI.getSummaryList().empty()) {
5085 auto *
Summary =
VI.getSummaryList()[0].get();
5086 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5087 FSCallsProfileAbbrev, CallsiteAbbrev,
5088 AllocAbbrev, ContextIdAbbvId,
F,
5089 CallStackPos, CallStackCount);
5094 for (
const GlobalVariable &
G :
M.globals())
5095 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5096 FSModVTableRefsAbbrev);
5098 for (
const GlobalAlias &
A :
M.aliases()) {
5099 auto *Aliasee =
A.getAliaseeObject();
5115 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5119 TypeIdCompatibleVtableAbbrev);
5123 if (
Index->getBlockCount())
5125 ArrayRef<uint64_t>{
Index->getBlockCount()});
5130void ModuleBitcodeWriterBase::writeGUIDList() {
5132 for (
const GlobalValue &GV :
M.global_values()) {
5133 auto MaybeGUID = GV.getGUIDIfAssigned();
5134 if (!MaybeGUID || *MaybeGUID == 0)
5137 if (ValueID >= GUIDs.
size())
5138 GUIDs.
resize(ValueID + 1);
5139 GUIDs[ValueID] = *MaybeGUID;
5142 auto Abbv = std::make_shared<BitCodeAbbrev>();
5146 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5148 SmallVector<uint32_t> RecordVals;
5150 for (
auto GUID : GUIDs) {
5151 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5152 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5159void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5168 auto Abbv = std::make_shared<BitCodeAbbrev>();
5174 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5176 for (
const auto &GVI : valueIds()) {
5178 ArrayRef<uint32_t>{GVI.second,
5179 static_cast<uint32_t
>(GVI.first >> 32),
5180 static_cast<uint32_t
>(GVI.first)},
5186 if (!StackIds.empty()) {
5187 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5194 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5195 SmallVector<uint32_t> Vals;
5196 Vals.
reserve(StackIds.size() * 2);
5197 for (
auto Id : StackIds) {
5198 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5199 Vals.
push_back(
static_cast<uint32_t
>(Id));
5205 Abbv = std::make_shared<BitCodeAbbrev>();
5219 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5222 Abbv = std::make_shared<BitCodeAbbrev>();
5229 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5232 Abbv = std::make_shared<BitCodeAbbrev>();
5238 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5240 Abbv = std::make_shared<BitCodeAbbrev>();
5248 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5250 Abbv = std::make_shared<BitCodeAbbrev>();
5261 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5263 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5264 if (DecSummaries ==
nullptr)
5266 return DecSummaries->
count(GVS);
5274 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5276 SmallVector<uint64_t, 64> NameVals;
5280 std::set<GlobalValue::GUID> ReferencedTypeIds;
5284 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5294 NameVals.
push_back(S.getOriginalName());
5299 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5301 Abbv = std::make_shared<BitCodeAbbrev>();
5306 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5313 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5314 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5320 GlobalValueSummary *S =
I.second;
5333 return StackIdIndicesToIndex[
I];
5339 if (!CallStacks.
empty()) {
5349 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5350 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5351 GlobalValueSummary *S =
I.second;
5353 DefOrUseGUIDs.
insert(
I.first);
5354 for (
const ValueInfo &VI : S->
refs())
5355 DefOrUseGUIDs.
insert(
VI.getGUID());
5357 auto ValueId = getValueId(
I.first);
5359 SummaryToValueIdMap[S] = *ValueId;
5377 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5381 for (
auto &RI :
VS->refs()) {
5382 auto RefValueId = getValueId(RI.getGUID());
5392 MaybeEmitOriginalName(*S);
5396 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5398 return std::nullopt;
5399 return getValueId(
VI.getGUID());
5408 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5421 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5422 for (
auto &RI :
FS->refs()) {
5423 auto RefValueId = getValueId(RI.getGUID());
5427 if (RI.isReadOnly())
5429 else if (RI.isWriteOnly())
5433 NameVals[6] =
Count;
5434 NameVals[7] = RORefCnt;
5435 NameVals[8] = WORefCnt;
5437 for (
auto &EI :
FS->calls()) {
5440 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5449 FSCallsProfileAbbrev);
5453 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5456 [&](
const ValueInfo &VI) ->
unsigned {
5457 std::optional<unsigned> ValueID = GetValueId(VI);
5472 return StackIdIndicesToIndex[
I];
5474 false, CallStackPos, CallStackCount);
5476 MaybeEmitOriginalName(*S);
5479 for (
auto *AS : Aliases) {
5480 auto AliasValueId = SummaryToValueIdMap[AS];
5489 auto AliaseeValueId =
5496 MaybeEmitOriginalName(*AS);
5504 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5506 if (CfiIndex.
empty())
5510 for (StringRef Name : Names)
5513 if (Functions.
empty())
5516 for (
const auto &Record : Functions) {
5531 for (
auto &
T : ReferencedTypeIds) {
5532 auto TidIter =
Index.typeIds().equal_range(
T);
5533 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5541 if (
Index.getBlockCount())
5543 ArrayRef<uint64_t>{
Index.getBlockCount()});
5554 auto Abbv = std::make_shared<BitCodeAbbrev>();
5558 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5560 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5563 Abbv = std::make_shared<BitCodeAbbrev>();
5566 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5572void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5577 Hasher.
update(ArrayRef<uint8_t>(
5578 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5579 std::array<uint8_t, 20> Hash = Hasher.
result();
5580 for (
int Pos = 0; Pos < 20; Pos += 4) {
5593void ModuleBitcodeWriter::write() {
5601 writeModuleVersion();
5610 writeAttributeGroupTable();
5613 writeAttributeTable();
5622 writeModuleConstants();
5625 writeModuleMetadataKinds();
5628 writeModuleMetadata();
5632 writeUseListBlock(
nullptr);
5634 writeOperandBundleTags();
5635 writeSyncScopeNames();
5638 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5640 if (!
F.isDeclaration())
5641 writeFunction(
F, FunctionToBitcodeIndex);
5646 writePerModuleGlobalValueSummary();
5648 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5676 unsigned CPUType = ~0U;
5683 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5684 DARWIN_CPU_TYPE_X86 = 7,
5685 DARWIN_CPU_TYPE_ARM = 12,
5686 DARWIN_CPU_TYPE_POWERPC = 18
5691 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5693 CPUType = DARWIN_CPU_TYPE_X86;
5695 CPUType = DARWIN_CPU_TYPE_POWERPC;
5697 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5699 CPUType = DARWIN_CPU_TYPE_ARM;
5703 "Expected header size to be reserved");
5708 unsigned Position = 0;
5716 while (Buffer.
size() & 15)
5723 Stream.
Emit((
unsigned)
'B', 8);
5724 Stream.
Emit((
unsigned)
'C', 8);
5725 Stream.
Emit(0x0, 4);
5726 Stream.
Emit(0xC, 4);
5727 Stream.
Emit(0xE, 4);
5728 Stream.
Emit(0xD, 4);
5746 auto Abbv = std::make_shared<BitCodeAbbrev>();
5749 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5757 assert(!WroteStrtab && !WroteSymtab);
5763 if (M->getModuleInlineAsm().empty())
5767 const Triple TT(M->getTargetTriple());
5769 if (!
T || !
T->hasMCAsmParser())
5791 std::vector<char> Strtab;
5792 StrtabBuilder.finalizeInOrder();
5793 Strtab.resize(StrtabBuilder.getSize());
5794 StrtabBuilder.write((
uint8_t *)Strtab.data());
5797 {Strtab.data(), Strtab.size()});
5808 bool ShouldPreserveUseListOrder,
5817 assert(M.isMaterialized());
5818 Mods.push_back(
const_cast<Module *
>(&M));
5820 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5821 ShouldPreserveUseListOrder, Index,
5822 GenerateHash, ModHash);
5823 ModuleWriter.write();
5830 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5831 ModuleToSummariesForIndex);
5832 IndexWriter.write();
5837 bool ShouldPreserveUseListOrder,
5841 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5843 Writer.writeSymtab();
5844 Writer.writeStrtab();
5846 Triple TT(M.getTargetTriple());
5847 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5858 Out.write(Buffer.
data(), Buffer.
size());
5865void IndexBitcodeWriter::write() {
5868 writeModuleVersion();
5874 writeCombinedGlobalValueSummary();
5891 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5894 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5900class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5910 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5912 ModHash(&ModHash) {}
5917 void writeSimplifiedModuleInfo();
5927void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5939 auto Abbv = std::make_shared<BitCodeAbbrev>();
5942 Abbv->Add(AbbrevOpToUse);
5943 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5945 for (
const auto P :
M.getSourceFileName())
6011void ThinLinkBitcodeWriter::write() {
6014 writeModuleVersion();
6016 writeSimplifiedModuleInfo();
6018 writePerModuleGlobalValueSummary();
6035 assert(M.isMaterialized());
6036 Mods.push_back(
const_cast<Module *
>(&M));
6038 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6040 ThinLinkWriter.write();
6057 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6061 switch (
T.getObjectFormat()) {
6063 return "__LLVM,__bitcode";
6088 switch (
T.getObjectFormat()) {
6090 return "__LLVM,__cmdline";
6116 const std::vector<uint8_t> &CmdArgs) {
6121 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6123 for (
auto *GV : UsedGlobals) {
6124 if (GV->getName() !=
"llvm.embedded.module" &&
6125 GV->getName() !=
"llvm.cmdline")
6130 Used->eraseFromParent();
6135 Triple T(M.getTargetTriple());
6164 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6165 assert(Old->hasZeroLiveUses() &&
6166 "llvm.embedded.module can only be used once in llvm.compiler.used");
6168 Old->eraseFromParent();
6170 GV->
setName(
"llvm.embedded.module");
6188 assert(Old->hasZeroLiveUses() &&
6189 "llvm.cmdline can only be used once in llvm.compiler.used");
6191 Old->eraseFromParent();
6197 if (UsedArray.
empty())
6205 NewUsed->setSection(
"llvm.metadata");
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDIProperty(raw_ostream &Out, const DIProperty *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static cl::opt< bool > PreserveBitcodeUseListOrder("preserve-bc-uselistorder", cl::Hidden, cl::init(true), cl::desc("Preserve use-list order when writing LLVM bitcode."))
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< uint32_t > FlushThreshold("bitcode-flush-threshold", cl::Hidden, cl::init(512), cl::desc("The threshold (unit M) for flushing LLVM bitcode."))
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
Machine Check Debug Module
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Class for arbitrary precision integers.
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
int64_t getSExtValue() const
Get sign extended value.
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
bool hasAttributes() const
Return true if attributes exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI ~BitcodeWriter()
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
bool isDbgDeclareValue() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Lightweight error class with error context and mandatory checking.
Function summary information to aid decisions and implementation of importing.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type size() const
Determine the number of elements in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool isFP128Ty() const
Return true if this is 'fp128'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
NodeAddr< CodeNode * > Code
void write32le(void *P, uint32_t V)
uint32_t read32be(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
void stable_sort(R &&Range)
StringMapEntry< Value * > ValueName
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName