34#include "llvm/Config/llvm-config.h"
119 VST_BBENTRY_6_ABBREV,
123 CONSTANTS_INTEGER_ABBREV,
124 CONSTANTS_BYTE_ABBREV,
125 CONSTANTS_CE_CAST_Abbrev,
126 CONSTANTS_NULL_Abbrev,
130 FUNCTION_INST_STORE_ABBREV,
131 FUNCTION_INST_UNOP_ABBREV,
132 FUNCTION_INST_UNOP_FLAGS_ABBREV,
133 FUNCTION_INST_BINOP_ABBREV,
134 FUNCTION_INST_BINOP_FLAGS_ABBREV,
135 FUNCTION_INST_CAST_ABBREV,
136 FUNCTION_INST_CAST_FLAGS_ABBREV,
137 FUNCTION_INST_RET_VOID_ABBREV,
138 FUNCTION_INST_RET_VAL_ABBREV,
139 FUNCTION_INST_BR_UNCOND_ABBREV,
140 FUNCTION_INST_BR_COND_ABBREV,
141 FUNCTION_INST_UNREACHABLE_ABBREV,
142 FUNCTION_INST_GEP_ABBREV,
143 FUNCTION_INST_CMP_ABBREV,
144 FUNCTION_INST_CMP_FLAGS_ABBREV,
145 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
146 FUNCTION_DEBUG_LOC_ABBREV,
147 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
152class BitcodeWriterBase {
155 BitstreamWriter &Stream;
157 StringTableBuilder &StrtabBuilder;
162 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
163 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
166 void writeModuleVersion();
169void BitcodeWriterBase::writeModuleVersion() {
176class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
178 const BitWriterOptions &Opts;
187 const ModuleSummaryIndex *Index;
192 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
195 unsigned GlobalValueId;
204 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
205 BitstreamWriter &Stream,
206 bool ShouldPreserveUseListOrder,
207 const ModuleSummaryIndex *Index)
208 : BitcodeWriterBase(Stream, StrtabBuilder),
211 valueOr(Opts.preserve_bc_uselistorder, ShouldPreserveUseListOrder)),
222 for (
const auto &GUIDSummaryLists :
223 Index->sortedGlobalValueSummariesRange())
225 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
231 for (auto &CallEdge : FS->calls())
232 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
233 assignValueId(CallEdge.first.getGUID());
239 for (auto &RefEdge : FS->refs())
240 if (!RefEdge.haveGVs() || !RefEdge.getValue())
241 assignValueId(RefEdge.getGUID());
246 void writePerModuleGlobalValueSummary();
247 void writeGUIDList();
250 void writePerModuleFunctionSummaryRecord(
251 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
252 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
253 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
254 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
256 void writeModuleLevelReferences(
const GlobalVariable &
V,
257 SmallVector<uint64_t, 64> &NameVals,
258 unsigned FSModRefsAbbrev,
259 unsigned FSModVTableRefsAbbrev);
262 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
266 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
269 assert(VMI != GUIDToValueIdMap.end() &&
270 "GUID does not have assigned value Id");
275 unsigned getValueId(ValueInfo VI) {
276 if (!
VI.haveGVs() || !
VI.getValue())
277 return getValueId(
VI.getGUID());
281 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
285class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
301 unsigned DILocationLayersAbbrev = 0;
306 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
307 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
308 const ModuleSummaryIndex *Index,
bool GenerateHash,
310 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
311 ShouldPreserveUseListOrder,
Index),
312 GenerateHash(GenerateHash), ModHash(ModHash),
313 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
319 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
321 size_t addToStrtab(StringRef Str);
323 void writeAttributeGroupTable();
324 void writeAttributeTable();
325 void writeTypeTable();
327 void writeValueSymbolTableForwardDecl();
328 void writeModuleInfo();
329 void writeValueAsMetadata(
const ValueAsMetadata *MD,
330 SmallVectorImpl<uint64_t> &Record);
331 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
333 unsigned createDILocationAbbrev(
bool WithIRLayers);
334 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
336 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
339 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
341 SmallVectorImpl<uint64_t> &Record,
343 unsigned createGenericDINodeAbbrev();
345 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
346 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
349 SmallVectorImpl<uint64_t> &Record,
352 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
356 SmallVectorImpl<uint64_t> &Record,
359 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
361 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
363 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
365 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
367 SmallVectorImpl<uint64_t> &Record,
369 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
372 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
374 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
376 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
378 SmallVectorImpl<uint64_t> &Record,
381 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
388 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
389 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
391 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
394 SmallVectorImpl<uint64_t> &Record,
397 SmallVectorImpl<uint64_t> &Record,
400 SmallVectorImpl<uint64_t> &Record,
403 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
405 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
407 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
409 SmallVectorImpl<uint64_t> &Record,
412 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
413 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
416 SmallVectorImpl<uint64_t> &Record,
418 unsigned createNamedMetadataAbbrev();
419 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
420 unsigned createMetadataStringsAbbrev();
422 SmallVectorImpl<uint64_t> &Record);
424 SmallVectorImpl<uint64_t> &Record,
425 std::vector<unsigned> *MDAbbrevs =
nullptr,
426 std::vector<uint64_t> *IndexPos =
nullptr);
427 void writeModuleMetadata();
428 void writeFunctionMetadata(
const Function &
F);
429 void writeFunctionMetadataAttachment(
const Function &
F);
430 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
431 const GlobalObject &GO);
432 void writeModuleMetadataKinds();
433 void writeOperandBundleTags();
434 void writeSyncScopeNames();
435 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
436 void writeModuleConstants();
437 bool pushValueAndType(
const Value *
V,
unsigned InstID,
438 SmallVectorImpl<unsigned> &Vals);
439 bool pushValueOrMetadata(
const Value *
V,
unsigned InstID,
440 SmallVectorImpl<unsigned> &Vals);
441 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
442 void pushValue(
const Value *
V,
unsigned InstID,
443 SmallVectorImpl<unsigned> &Vals);
444 void pushValueSigned(
const Value *
V,
unsigned InstID,
445 SmallVectorImpl<uint64_t> &Vals);
446 void writeInstruction(
const Instruction &
I,
unsigned InstID,
447 SmallVectorImpl<unsigned> &Vals);
448 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
449 void writeGlobalValueSymbolTable(
450 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
451 void writeUseList(UseListOrder &&Order);
452 void writeUseListBlock(
const Function *
F);
455 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
456 void writeBlockInfo();
457 void writeModuleHash(StringRef View);
460 return unsigned(SSID);
463 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
467class IndexBitcodeWriter :
public BitcodeWriterBase {
469 const ModuleSummaryIndex &
Index;
485 SortedSummariesForIndex;
489 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
493 std::vector<uint64_t> StackIds;
498 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
501 unsigned GlobalValueId = 0;
505 DenseMap<StringRef, uint64_t> ModuleIdMap;
515 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
516 const ModuleSummaryIndex &Index,
519 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
520 DecSummaries(DecSummaries),
521 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
522 if (ModuleToSummariesForIndex) {
523 for (
const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
534 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
539 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
541 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
548 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
549 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
561 for (
auto &CI :
FS->callsites()) {
572 if (CI.StackIdIndices.empty()) {
573 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
576 for (
auto Idx : CI.StackIdIndices)
577 RecordStackIdReference(Idx);
580 for (
auto &AI :
FS->allocs())
581 for (
auto &MIB : AI.MIBs)
582 for (
auto Idx : MIB.StackIdIndices)
583 RecordStackIdReference(Idx);
589 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
594 template<
typename Functor>
595 void forEachSummary(Functor Callback) {
596 if (ModuleToSummariesForIndex) {
597 for (
auto &[GUID, GVS] : SortedSummariesForIndex) {
603 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
607 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
608 for (
auto &Summary : Summaries.second.getSummaryList())
617 template <
typename Functor>
void forEachModule(Functor Callback) {
618 if (ModuleToSummariesForIndex) {
619 for (
const auto &M : *ModuleToSummariesForIndex) {
620 const auto &MPI =
Index.modulePaths().find(
M.first);
621 if (MPI ==
Index.modulePaths().end()) {
625 assert(ModuleToSummariesForIndex->size() == 1);
635 std::vector<StringRef> ModulePaths;
636 for (
auto &[ModPath,
_] :
Index.modulePaths())
637 ModulePaths.push_back(ModPath);
639 for (
auto &ModPath : ModulePaths)
648 void writeModStrings();
649 void writeCombinedGlobalValueSummary();
652 auto VMI = GUIDToValueIdMap.find(ValGUID);
653 if (VMI == GUIDToValueIdMap.end())
658 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
693 case Instruction::Add:
695 case Instruction::Sub:
697 case Instruction::Mul:
700 case Instruction::FDiv:
703 case Instruction::FRem:
715 unsigned Encoding = 0;
716 switch (
I.getOperation()) {
789 if (
I.isElementwise())
824 case Attribute::Alignment:
826 case Attribute::AllocAlign:
828 case Attribute::AllocSize:
830 case Attribute::AlwaysInline:
832 case Attribute::Builtin:
834 case Attribute::ByVal:
836 case Attribute::Convergent:
838 case Attribute::InAlloca:
840 case Attribute::Cold:
842 case Attribute::DisableSanitizerInstrumentation:
844 case Attribute::FnRetThunkExtern:
846 case Attribute::Flatten:
850 case Attribute::ElementType:
852 case Attribute::HybridPatchable:
854 case Attribute::InlineHint:
856 case Attribute::InReg:
858 case Attribute::JumpTable:
860 case Attribute::MinSize:
862 case Attribute::AllocatedPointer:
864 case Attribute::AllocKind:
866 case Attribute::Memory:
868 case Attribute::NoFPClass:
870 case Attribute::Naked:
872 case Attribute::Nest:
874 case Attribute::NoAlias:
876 case Attribute::NoBuiltin:
878 case Attribute::NoCallback:
880 case Attribute::NoDivergenceSource:
882 case Attribute::NoDuplicate:
884 case Attribute::NoFree:
886 case Attribute::NoFreeObj:
888 case Attribute::NoImplicitFloat:
890 case Attribute::NoInline:
892 case Attribute::NoRecurse:
894 case Attribute::NoMerge:
896 case Attribute::NonLazyBind:
898 case Attribute::NonNull:
900 case Attribute::Dereferenceable:
902 case Attribute::DereferenceableOrNull:
904 case Attribute::NoRedZone:
906 case Attribute::NoReturn:
908 case Attribute::NoSync:
910 case Attribute::NoCfCheck:
912 case Attribute::NoProfile:
914 case Attribute::SkipProfile:
916 case Attribute::NoUnwind:
918 case Attribute::NoSanitizeBounds:
920 case Attribute::NoSanitizeCoverage:
922 case Attribute::NullPointerIsValid:
924 case Attribute::OptimizeForDebugging:
926 case Attribute::OptForFuzzing:
928 case Attribute::OptimizeForSize:
930 case Attribute::OptimizeNone:
932 case Attribute::ReadNone:
934 case Attribute::ReadOnly:
936 case Attribute::Returned:
938 case Attribute::ReturnsTwice:
940 case Attribute::SExt:
942 case Attribute::Speculatable:
944 case Attribute::StackAlignment:
946 case Attribute::StackProtect:
948 case Attribute::StackProtectReq:
950 case Attribute::StackProtectStrong:
952 case Attribute::SafeStack:
954 case Attribute::ShadowCallStack:
956 case Attribute::StrictFP:
958 case Attribute::StructRet:
960 case Attribute::SanitizeAddress:
962 case Attribute::SanitizeAllocToken:
964 case Attribute::SanitizeHWAddress:
966 case Attribute::SanitizeThread:
968 case Attribute::SanitizeConcurrency:
970 case Attribute::SanitizeType:
972 case Attribute::SanitizeMemory:
974 case Attribute::SanitizeNumericalStability:
976 case Attribute::SanitizeRealtime:
978 case Attribute::SanitizeRealtimeBlocking:
980 case Attribute::SpeculativeLoadHardening:
982 case Attribute::SwiftError:
984 case Attribute::SwiftSelf:
986 case Attribute::SwiftAsync:
988 case Attribute::UWTable:
990 case Attribute::VScaleRange:
992 case Attribute::WillReturn:
994 case Attribute::WriteOnly:
996 case Attribute::ZExt:
998 case Attribute::ImmArg:
1000 case Attribute::SanitizeMemTag:
1002 case Attribute::Preallocated:
1004 case Attribute::NoUndef:
1006 case Attribute::ByRef:
1008 case Attribute::MustProgress:
1010 case Attribute::PresplitCoroutine:
1012 case Attribute::Writable:
1014 case Attribute::CoroDestroyOnlyWhenComplete:
1016 case Attribute::CoroElideSafe:
1018 case Attribute::DeadOnUnwind:
1020 case Attribute::Range:
1022 case Attribute::Initializes:
1024 case Attribute::NoExt:
1026 case Attribute::Captures:
1028 case Attribute::DeadOnReturn:
1030 case Attribute::NoCreateUndefOrPoison:
1032 case Attribute::DenormalFPEnv:
1034 case Attribute::NoOutline:
1036 case Attribute::NoIPA:
1038 case Attribute::LikelyModuleLocal:
1053 if ((int64_t)
V >= 0)
1064 unsigned NumWords =
A.getActiveWords();
1065 const uint64_t *RawData =
A.getRawData();
1066 for (
unsigned i = 0; i < NumWords; i++)
1086void ModuleBitcodeWriter::writeAttributeGroupTable() {
1087 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1089 if (AttrGrps.empty())
return;
1093 SmallVector<uint64_t, 64>
Record;
1095 unsigned AttrListIndex = Pair.first;
1096 AttributeSet AS = Pair.second;
1098 Record.push_back(AttrListIndex);
1101 if (Attr.isEnumAttribute()) {
1104 }
else if (Attr.isIntAttribute()) {
1106 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1108 if (Kind == Attribute::Memory) {
1113 Record.push_back(Attr.getValueAsInt());
1115 }
else if (Attr.isStringAttribute()) {
1116 StringRef
Kind = Attr.getKindAsString();
1117 StringRef Val = Attr.getValueAsString();
1126 }
else if (Attr.isTypeAttribute()) {
1127 Type *Ty = Attr.getValueAsType();
1128 Record.push_back(Ty ? 6 : 5);
1132 }
else if (Attr.isConstantRangeAttribute()) {
1138 assert(Attr.isConstantRangeListAttribute());
1144 for (
auto &CR : Val)
1156void ModuleBitcodeWriter::writeAttributeTable() {
1158 if (
Attrs.empty())
return;
1162 SmallVector<uint64_t, 64>
Record;
1163 for (
const AttributeList &AL : Attrs) {
1164 for (
unsigned i :
AL.indexes()) {
1165 AttributeSet AS =
AL.getAttributes(i);
1178void ModuleBitcodeWriter::writeTypeTable() {
1182 SmallVector<uint64_t, 64> TypeVals;
1187 auto Abbv = std::make_shared<BitCodeAbbrev>();
1189 Abbv->Add(BitCodeAbbrevOp(0));
1190 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1193 Abbv = std::make_shared<BitCodeAbbrev>();
1198 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1201 Abbv = std::make_shared<BitCodeAbbrev>();
1206 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1209 Abbv = std::make_shared<BitCodeAbbrev>();
1213 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1216 Abbv = std::make_shared<BitCodeAbbrev>();
1221 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1224 Abbv = std::make_shared<BitCodeAbbrev>();
1228 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1236 for (
Type *
T : TypeList) {
1237 int AbbrevToUse = 0;
1240 switch (
T->getTypeID()) {
1250 case Type::MetadataTyID:
1255 case Type::ByteTyID:
1260 case Type::IntegerTyID:
1265 case Type::PointerTyID: {
1272 AbbrevToUse = OpaquePtrAbbrev;
1275 case Type::FunctionTyID: {
1281 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1283 AbbrevToUse = FunctionAbbrev;
1286 case Type::StructTyID: {
1291 for (
Type *ET :
ST->elements())
1294 if (
ST->isLiteral()) {
1296 AbbrevToUse = StructAnonAbbrev;
1298 if (
ST->isOpaque()) {
1302 AbbrevToUse = StructNamedAbbrev;
1306 if (!
ST->getName().empty())
1312 case Type::ArrayTyID: {
1316 TypeVals.
push_back(AT->getNumElements());
1318 AbbrevToUse = ArrayAbbrev;
1321 case Type::FixedVectorTyID:
1322 case Type::ScalableVectorTyID: {
1327 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1333 case Type::TargetExtTyID: {
1339 for (
Type *InnerTy :
TET->type_params())
1344 case Type::TypedPointerTyID:
1349 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1390 RawFlags |= Flags.ReadNone;
1391 RawFlags |= (Flags.ReadOnly << 1);
1392 RawFlags |= (Flags.NoRecurse << 2);
1393 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1394 RawFlags |= (Flags.NoInline << 4);
1395 RawFlags |= (Flags.AlwaysInline << 5);
1396 RawFlags |= (Flags.NoUnwind << 6);
1397 RawFlags |= (Flags.MayThrow << 7);
1398 RawFlags |= (Flags.HasUnknownCall << 8);
1399 RawFlags |= (Flags.MustBeUnreachable << 9);
1406 bool ImportAsDecl =
false) {
1409 RawFlags |= Flags.NotEligibleToImport;
1410 RawFlags |= (Flags.Live << 1);
1411 RawFlags |= (Flags.DSOLocal << 2);
1412 RawFlags |= (Flags.CanAutoHide << 3);
1417 RawFlags = (RawFlags << 4) | Flags.Linkage;
1419 RawFlags |= (Flags.Visibility << 8);
1421 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1422 RawFlags |= (ImportType << 10);
1424 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1430 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1431 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1475 switch (
C.getSelectionKind()) {
1499size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1502 return StrtabBuilder.
add(Str);
1505void ModuleBitcodeWriter::writeComdats() {
1520void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1525 auto Abbv = std::make_shared<BitCodeAbbrev>();
1531 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1547 bool isChar6 =
true;
1548 for (
char C : Str) {
1551 if ((
unsigned char)
C & 128)
1560static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1561 "Sanitizer Metadata is too large for naive serialization.");
1564 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1565 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1571void ModuleBitcodeWriter::writeModuleInfo() {
1573 if (!
M.getTargetTriple().empty())
1575 M.getTargetTriple().str(), 0 );
1576 const std::string &
DL =
M.getDataLayoutStr();
1580 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1582 Frag.Props.getAsStrings();
1595 std::map<std::string, unsigned> SectionMap;
1596 std::map<std::string, unsigned> GCMap;
1597 MaybeAlign MaxGVarAlignment;
1598 unsigned MaxGlobalType = 0;
1599 for (
const GlobalVariable &GV :
M.globals()) {
1600 if (MaybeAlign
A = GV.getAlign())
1601 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1602 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1603 if (GV.hasSection()) {
1605 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1609 Entry = SectionMap.size();
1614 if (
F.hasSection()) {
1616 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1620 Entry = SectionMap.size();
1625 unsigned &
Entry = GCMap[
F.getGC()];
1629 Entry = GCMap.size();
1635 unsigned SimpleGVarAbbrev = 0;
1636 if (!
M.global_empty()) {
1638 auto Abbv = std::make_shared<BitCodeAbbrev>();
1649 if (!MaxGVarAlignment)
1650 Abbv->Add(BitCodeAbbrevOp(0));
1652 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1656 if (SectionMap.empty())
1657 Abbv->Add(BitCodeAbbrevOp(0));
1662 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1676 auto Abbv = std::make_shared<BitCodeAbbrev>();
1679 Abbv->Add(AbbrevOpToUse);
1680 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1682 for (
const auto P :
M.getSourceFileName())
1693 for (
const GlobalVariable &GV :
M.globals()) {
1694 unsigned AbbrevToUse = 0;
1700 Vals.
push_back(addToStrtab(GV.getName()));
1703 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1707 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1708 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1710 if (GV.isThreadLocal() ||
1712 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1713 GV.isExternallyInitialized() ||
1715 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1716 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1720 Vals.
push_back(GV.isExternallyInitialized());
1724 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1728 Vals.
push_back(addToStrtab(GV.getPartition()));
1729 Vals.
push_back(GV.getPartition().size());
1732 GV.getSanitizerMetadata())
1736 AbbrevToUse = SimpleGVarAbbrev;
1757 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1758 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1770 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1774 Vals.
push_back(addToStrtab(
F.getPartition()));
1776 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1778 unsigned AbbrevToUse = 0;
1784 for (
const GlobalAlias &
A :
M.aliases()) {
1791 Vals.
push_back(
A.getType()->getAddressSpace());
1799 Vals.
push_back(addToStrtab(
A.getPartition()));
1802 unsigned AbbrevToUse = 0;
1808 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1814 Vals.
push_back(
I.getType()->getAddressSpace());
1819 Vals.
push_back(addToStrtab(
I.getPartition()));
1825 writeValueSymbolTableForwardDecl();
1832 if (OBO->hasNoSignedWrap())
1834 if (OBO->hasNoUnsignedWrap())
1840 if (PDI->isDisjoint())
1843 if (FPMO->hasAllowReassoc())
1845 if (FPMO->hasNoNaNs())
1847 if (FPMO->hasNoInfs())
1849 if (FPMO->hasNoSignedZeros())
1851 if (FPMO->hasAllowReciprocal())
1853 if (FPMO->hasAllowContract())
1855 if (FPMO->hasApproxFunc())
1861 if (NNI->hasNonNeg())
1865 if (NNI->hasNonNeg())
1868 if (TI->hasNoSignedWrap())
1870 if (TI->hasNoUnsignedWrap())
1873 if (
GEP->isInBounds())
1875 if (
GEP->hasNoUnsignedSignedWrap())
1877 if (
GEP->hasNoUnsignedWrap())
1880 if (ICmp->hasSameSign())
1883 if (ASC->hasNonNull())
1890void ModuleBitcodeWriter::writeValueAsMetadata(
1891 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1900void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1901 SmallVectorImpl<uint64_t> &Record,
1903 for (
const MDOperand &MDO :
N->operands()) {
1906 "Unexpected function-local metadata");
1915void ModuleBitcodeWriter::writeMDFunctionLocalContext(
1916 const MDFunctionLocalContext *
N, SmallVectorImpl<uint64_t> &Record,
1921unsigned ModuleBitcodeWriter::createDILocationAbbrev(
bool WithIRLayers) {
1927 auto Abbv = std::make_shared<BitCodeAbbrev>();
1942void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1943 SmallVectorImpl<uint64_t> &Record,
1946 Abbrev = createDILocationAbbrev(
false);
1948 Record.push_back(
N->isDistinct());
1949 Record.push_back(
N->getLine());
1950 Record.push_back(
N->getColumn());
1953 Record.push_back(
N->isImplicitCode());
1954 Record.push_back(
N->getAtomGroup());
1955 Record.push_back(
N->getAtomRank());
1957 unsigned AbbrevToUse = Abbrev;
1958 if (DILayerLocList *IRLayers =
N->getIRLayers()) {
1959 if (!DILocationLayersAbbrev)
1960 DILocationLayersAbbrev = createDILocationAbbrev(
true);
1961 AbbrevToUse = DILocationLayersAbbrev;
1969void ModuleBitcodeWriter::writeDILayerLoc(
const DILayerLoc *
N,
1970 SmallVectorImpl<uint64_t> &Record,
1972 Record.push_back(
N->isDistinct());
1973 Record.push_back(
N->getLine());
1974 Record.push_back(
N->getColumn());
1981void ModuleBitcodeWriter::writeDILayerLocList(
const DILayerLocList *
N,
1982 SmallVectorImpl<uint64_t> &Record,
1984 Record.push_back(
N->isDistinct());
1985 for (
const MDOperand &
Op :
N->layers())
1991unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1994 auto Abbv = std::make_shared<BitCodeAbbrev>();
2005void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
2006 SmallVectorImpl<uint64_t> &Record,
2009 Abbrev = createGenericDINodeAbbrev();
2011 Record.push_back(
N->isDistinct());
2012 Record.push_back(
N->getTag());
2015 for (
auto &
I :
N->operands())
2022void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
2023 SmallVectorImpl<uint64_t> &Record,
2036void ModuleBitcodeWriter::writeDIGenericSubrange(
2037 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
2049void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
2050 SmallVectorImpl<uint64_t> &Record,
2053 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
2054 Record.push_back(
N->getValue().getBitWidth());
2062void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
2063 SmallVectorImpl<uint64_t> &Record,
2065 const unsigned SizeIsMetadata = 0x2;
2066 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2067 Record.push_back(
N->getTag());
2070 Record.push_back(
N->getAlignInBits());
2071 Record.push_back(
N->getEncoding());
2072 Record.push_back(
N->getFlags());
2073 Record.push_back(
N->getNumExtraInhabitants());
2074 Record.push_back(
N->getDataSizeInBits());
2076 Record.push_back(
N->getLine());
2083void ModuleBitcodeWriter::writeDIFixedPointType(
2084 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2086 const unsigned SizeIsMetadata = 0x2;
2087 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2088 Record.push_back(
N->getTag());
2091 Record.push_back(
N->getAlignInBits());
2092 Record.push_back(
N->getEncoding());
2093 Record.push_back(
N->getFlags());
2094 Record.push_back(
N->getKind());
2095 Record.push_back(
N->getFactorRaw());
2097 auto WriteWideInt = [&](
const APInt &
Value) {
2102 Record.push_back(Encoded);
2106 WriteWideInt(
N->getNumeratorRaw());
2107 WriteWideInt(
N->getDenominatorRaw());
2110 Record.push_back(
N->getLine());
2117void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2118 SmallVectorImpl<uint64_t> &Record,
2120 const unsigned SizeIsMetadata = 0x2;
2121 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2122 Record.push_back(
N->getTag());
2128 Record.push_back(
N->getAlignInBits());
2129 Record.push_back(
N->getEncoding());
2136void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2137 SmallVectorImpl<uint64_t> &Record,
2139 const unsigned SizeIsMetadata = 0x2;
2140 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2141 Record.push_back(
N->getTag());
2144 Record.push_back(
N->getLine());
2148 Record.push_back(
N->getAlignInBits());
2150 Record.push_back(
N->getFlags());
2155 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2156 Record.push_back(*DWARFAddressSpace + 1);
2162 if (
auto PtrAuthData =
N->getPtrAuthData())
2163 Record.push_back(PtrAuthData->RawData);
2171void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2172 SmallVectorImpl<uint64_t> &Record,
2174 const unsigned SizeIsMetadata = 0x2;
2175 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2178 Record.push_back(
N->getLine());
2181 Record.push_back(
N->getAlignInBits());
2182 Record.push_back(
N->getFlags());
2193void ModuleBitcodeWriter::writeDICompositeType(
2194 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2196 const unsigned IsNotUsedInOldTypeRef = 0x2;
2197 const unsigned SizeIsMetadata = 0x4;
2198 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2199 (
unsigned)
N->isDistinct());
2200 Record.push_back(
N->getTag());
2203 Record.push_back(
N->getLine());
2207 Record.push_back(
N->getAlignInBits());
2209 Record.push_back(
N->getFlags());
2211 Record.push_back(
N->getRuntimeLang());
2221 Record.push_back(
N->getNumExtraInhabitants());
2231void ModuleBitcodeWriter::writeDISubroutineType(
2232 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2234 const unsigned HasNoOldTypeRefs = 0x2;
2235 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2236 Record.push_back(
N->getFlags());
2244void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2245 SmallVectorImpl<uint64_t> &Record,
2247 Record.push_back(
N->isDistinct());
2250 if (
N->getRawChecksum()) {
2251 Record.push_back(
N->getRawChecksum()->Kind);
2259 auto Source =
N->getRawSource();
2267void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2268 SmallVectorImpl<uint64_t> &Record,
2270 assert(
N->isDistinct() &&
"Expected distinct compile units");
2273 auto Lang =
N->getSourceLanguage();
2274 Record.push_back(Lang.getName());
2277 if (Lang.hasVersionedName())
2282 Record.push_back(
N->isOptimized());
2284 Record.push_back(
N->getRuntimeVersion());
2286 Record.push_back(
N->getEmissionKind());
2292 Record.push_back(
N->getDWOId());
2294 Record.push_back(
N->getSplitDebugInlining());
2295 Record.push_back(
N->getDebugInfoForProfiling());
2296 Record.push_back((
unsigned)
N->getNameTableKind());
2297 Record.push_back(
N->getRangesBaseAddress());
2300 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2301 Record.push_back(Lang.getDialect());
2307void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2308 SmallVectorImpl<uint64_t> &Record,
2310 const uint64_t HasUnitFlag = 1 << 1;
2311 const uint64_t HasSPFlagsFlag = 1 << 2;
2312 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2317 Record.push_back(
N->getLine());
2319 Record.push_back(
N->getScopeLine());
2321 Record.push_back(
N->getSPFlags());
2322 Record.push_back(
N->getVirtualIndex());
2323 Record.push_back(
N->getFlags());
2328 Record.push_back(
N->getThisAdjustment());
2332 Record.push_back(
N->getKeyInstructionsEnabled());
2338void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2339 SmallVectorImpl<uint64_t> &Record,
2341 Record.push_back(
N->isDistinct());
2344 Record.push_back(
N->getLine());
2345 Record.push_back(
N->getColumn());
2351void ModuleBitcodeWriter::writeDILexicalBlockFile(
2352 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2354 Record.push_back(
N->isDistinct());
2357 Record.push_back(
N->getDiscriminator());
2363void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2364 SmallVectorImpl<uint64_t> &Record,
2366 Record.push_back(
N->isDistinct());
2371 Record.push_back(
N->getLineNo());
2377void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2378 SmallVectorImpl<uint64_t> &Record,
2380 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2388void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2389 SmallVectorImpl<uint64_t> &Record,
2391 Record.push_back(
N->isDistinct());
2392 Record.push_back(
N->getMacinfoType());
2393 Record.push_back(
N->getLine());
2401void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2402 SmallVectorImpl<uint64_t> &Record,
2404 Record.push_back(
N->isDistinct());
2405 Record.push_back(
N->getMacinfoType());
2406 Record.push_back(
N->getLine());
2414void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2415 SmallVectorImpl<uint64_t> &Record) {
2416 Record.reserve(
N->getArgs().size());
2417 for (ValueAsMetadata *MD :
N->getArgs())
2424void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2425 SmallVectorImpl<uint64_t> &Record,
2427 Record.push_back(
N->isDistinct());
2428 for (
auto &
I :
N->operands())
2430 Record.push_back(
N->getLineNo());
2431 Record.push_back(
N->getIsDecl());
2437void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2438 SmallVectorImpl<uint64_t> &Record,
2441 Record.push_back(
N->isDistinct());
2446void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2447 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2449 Record.push_back(
N->isDistinct());
2452 Record.push_back(
N->isDefault());
2458void ModuleBitcodeWriter::writeDITemplateValueParameter(
2459 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2461 Record.push_back(
N->isDistinct());
2462 Record.push_back(
N->getTag());
2465 Record.push_back(
N->isDefault());
2472void ModuleBitcodeWriter::writeDIGlobalVariable(
2473 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2481 Record.push_back(
N->getLine());
2483 Record.push_back(
N->isLocalToUnit());
2484 Record.push_back(
N->isDefinition());
2487 Record.push_back(
N->getAlignInBits());
2494void ModuleBitcodeWriter::writeDILocalVariable(
2495 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2510 const uint64_t HasAlignmentFlag = 1 << 1;
2515 Record.push_back(
N->getLine());
2517 Record.push_back(
N->getArg());
2518 Record.push_back(
N->getFlags());
2519 Record.push_back(
N->getAlignInBits());
2526void ModuleBitcodeWriter::writeDILabel(
2527 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2534 Record.push_back(
N->getLine());
2535 Record.push_back(
N->getColumn());
2536 Record.push_back(
N->getCoroSuspendIdx().has_value()
2537 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2538 : std::numeric_limits<uint64_t>::max());
2544void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2545 SmallVectorImpl<uint64_t> &Record,
2547 Record.reserve(
N->getElements().size() + 1);
2550 Record.append(
N->elements_begin(),
N->elements_end());
2556void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2557 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2559 Record.push_back(
N->isDistinct());
2567void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2568 SmallVectorImpl<uint64_t> &Record,
2570 Record.push_back(
N->isDistinct());
2573 Record.push_back(
N->getLine());
2576 Record.push_back(
N->getAttributes());
2583void ModuleBitcodeWriter::writeDIProperty(
const DIProperty *
N,
2584 SmallVectorImpl<uint64_t> &Record,
2586 Record.push_back(
N->isDistinct());
2589 Record.push_back(
N->getLine());
2597void ModuleBitcodeWriter::writeDIImportedEntity(
2598 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2600 Record.push_back(
N->isDistinct());
2601 Record.push_back(
N->getTag());
2604 Record.push_back(
N->getLine());
2613unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2614 auto Abbv = std::make_shared<BitCodeAbbrev>();
2621void ModuleBitcodeWriter::writeNamedMetadata(
2622 SmallVectorImpl<uint64_t> &Record) {
2623 if (
M.named_metadata_empty())
2626 unsigned Abbrev = createNamedMetadataAbbrev();
2627 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2629 StringRef Str = NMD.getName();
2630 Record.append(Str.bytes_begin(), Str.bytes_end());
2635 for (
const MDNode *
N : NMD.operands())
2642unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2643 auto Abbv = std::make_shared<BitCodeAbbrev>();
2655void ModuleBitcodeWriter::writeMetadataStrings(
2657 if (Strings.
empty())
2665 SmallString<256> Blob;
2667 BitstreamWriter
W(Blob);
2687#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2688#include "llvm/IR/Metadata.def"
2692void ModuleBitcodeWriter::writeMetadataRecords(
2694 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2699#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2700#include "llvm/IR/Metadata.def"
2706 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2708 switch (
N->getMetadataID()) {
2711#define HANDLE_MDNODE_LEAF(CLASS) \
2712 case Metadata::CLASS##Kind: \
2714 write##CLASS(cast<CLASS>(N), Record, \
2715 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2717 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2719#include "llvm/IR/Metadata.def"
2730void ModuleBitcodeWriter::writeModuleMetadata() {
2731 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2735 SmallVector<uint64_t, 64>
Record;
2739 std::vector<unsigned> MDAbbrevs;
2742 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2743 createDILocationAbbrev(
false);
2744 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2745 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2746 createGenericDINodeAbbrev();
2748 auto Abbv = std::make_shared<BitCodeAbbrev>();
2752 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2754 Abbv = std::make_shared<BitCodeAbbrev>();
2758 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2780 std::vector<uint64_t> IndexPos;
2784 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2795 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2796 for (
auto &Elt : IndexPos) {
2797 auto EltDelta = Elt - PreviousValue;
2798 PreviousValue = Elt;
2807 writeNamedMetadata(Record);
2809 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2810 SmallVector<uint64_t, 4>
Record;
2812 pushGlobalMetadataAttachment(Record, GO);
2816 if (
F.isDeclaration() &&
F.hasMetadata())
2817 AddDeclAttachedMetadata(
F);
2818 for (
const GlobalIFunc &GI :
M.ifuncs())
2819 if (GI.hasMetadata())
2820 AddDeclAttachedMetadata(GI);
2823 for (
const GlobalVariable &GV :
M.globals())
2824 if (GV.hasMetadata())
2825 AddDeclAttachedMetadata(GV);
2830void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2837 DILocationLayersAbbrev = 0;
2838 SmallVector<uint64_t, 64>
Record;
2844void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2845 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2849 for (
const auto &
I : MDs) {
2855void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2858 SmallVector<uint64_t, 64>
Record;
2860 if (
F.hasMetadata()) {
2861 pushGlobalMetadataAttachment(Record,
F);
2869 for (
const BasicBlock &BB :
F)
2870 for (
const Instruction &
I : BB) {
2872 I.getAllMetadataOtherThanDebugLoc(MDs);
2875 if (MDs.
empty())
continue;
2879 for (
const auto &[ID, MD] : MDs) {
2890void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2891 SmallVector<uint64_t, 64>
Record;
2896 M.getMDKindNames(Names);
2898 if (Names.
empty())
return;
2902 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2903 Record.push_back(MDKindID);
2904 StringRef KName = Names[MDKindID];
2914void ModuleBitcodeWriter::writeOperandBundleTags() {
2922 M.getOperandBundleTags(Tags);
2929 SmallVector<uint64_t, 64>
Record;
2931 for (
auto Tag : Tags) {
2941void ModuleBitcodeWriter::writeSyncScopeNames() {
2943 M.getContext().getSyncScopeNames(SSNs);
2949 SmallVector<uint64_t, 64>
Record;
2950 for (
auto SSN : SSNs) {
2951 Record.append(SSN.begin(), SSN.end());
2959void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2961 if (FirstVal == LastVal)
return;
2965 unsigned AggregateAbbrev = 0;
2966 unsigned String8Abbrev = 0;
2967 unsigned CString7Abbrev = 0;
2968 unsigned CString6Abbrev = 0;
2972 auto Abbv = std::make_shared<BitCodeAbbrev>();
2976 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2979 Abbv = std::make_shared<BitCodeAbbrev>();
2983 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2985 Abbv = std::make_shared<BitCodeAbbrev>();
2989 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2991 Abbv = std::make_shared<BitCodeAbbrev>();
2995 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2998 SmallVector<uint64_t, 64>
Record;
3001 Type *LastTy =
nullptr;
3002 for (
unsigned i = FirstVal; i != LastVal; ++i) {
3003 const Value *
V = Vals[i].first;
3005 if (
V->getType() != LastTy) {
3006 LastTy =
V->getType();
3009 CONSTANTS_SETTYPE_ABBREV);
3016 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
3017 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
3020 StringRef AsmStr =
IA->getAsmString();
3025 StringRef ConstraintStr =
IA->getConstraintString();
3033 unsigned Code = -1U;
3034 unsigned AbbrevToUse = 0;
3035 if (
C->isNullValue()) {
3042 if (
IV->getBitWidth() <= 64) {
3046 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3052 if (BV->getBitWidth() <= 64) {
3056 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3066 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3070 APInt api = CFP->getValueAPF().bitcastToAPInt();
3072 Record.push_back((p[1] << 48) | (p[0] >> 16));
3073 Record.push_back(p[0] & 0xffffLL);
3075 APInt api = CFP->getValueAPF().bitcastToAPInt();
3080 assert(0 &&
"Unknown FP type!");
3086 uint64_t NumElts = Str->getNumElements();
3088 if (Str->isCString()) {
3093 AbbrevToUse = String8Abbrev;
3097 for (
uint64_t i = 0; i != NumElts; ++i) {
3098 unsigned char V = Str->getElementAsInteger(i);
3100 isCStr7 &= (
V & 128) == 0;
3106 AbbrevToUse = CString6Abbrev;
3108 AbbrevToUse = CString7Abbrev;
3109 }
else if (
const ConstantDataSequential *CDS =
3112 Type *EltTy = CDS->getElementType();
3114 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3115 Record.push_back(CDS->getElementAsInteger(i));
3117 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3119 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3123 for (
const Value *
Op :
C->operands())
3125 AbbrevToUse = AggregateAbbrev;
3127 switch (
CE->getOpcode()) {
3134 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3136 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3146 case Instruction::GetElementPtr: {
3151 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3155 for (
const Value *
Op :
CE->operands()) {
3161 case Instruction::ExtractElement:
3168 case Instruction::InsertElement:
3175 case Instruction::ShuffleVector:
3180 if (
C->getType() ==
C->getOperand(0)->getType()) {
3217 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3224void ModuleBitcodeWriter::writeModuleConstants() {
3229 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3231 writeConstants(i, Vals.size(),
true);
3245bool ModuleBitcodeWriter::pushValueAndType(
const Value *
V,
unsigned InstID,
3246 SmallVectorImpl<unsigned> &Vals) {
3250 if (ValID >= InstID) {
3257bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *
V,
unsigned InstID,
3258 SmallVectorImpl<unsigned> &Vals) {
3259 bool IsMetadata =
V->getType()->isMetadataTy();
3267 return pushValueAndType(
V, InstID, Vals);
3270void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3277 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3279 for (
auto &Input : Bundle.Inputs)
3280 pushValueOrMetadata(Input, InstID, Record);
3289void ModuleBitcodeWriter::pushValue(
const Value *
V,
unsigned InstID,
3290 SmallVectorImpl<unsigned> &Vals) {
3295void ModuleBitcodeWriter::pushValueSigned(
const Value *
V,
unsigned InstID,
3296 SmallVectorImpl<uint64_t> &Vals) {
3298 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3303void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3305 SmallVectorImpl<unsigned> &Vals) {
3307 unsigned AbbrevToUse = 0;
3309 switch (
I.getOpcode()) {
3313 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3314 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3319 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3320 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3326 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3327 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3328 pushValue(
I.getOperand(1), InstID, Vals);
3332 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3333 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3338 case Instruction::FNeg: {
3340 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3341 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3345 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3346 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3351 case Instruction::GetElementPtr: {
3353 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3357 for (
const Value *
Op :
I.operands())
3358 pushValueAndType(
Op, InstID, Vals);
3361 case Instruction::ExtractValue: {
3363 pushValueAndType(
I.getOperand(0), InstID, Vals);
3368 case Instruction::InsertValue: {
3370 pushValueAndType(
I.getOperand(0), InstID, Vals);
3371 pushValueAndType(
I.getOperand(1), InstID, Vals);
3376 case Instruction::Select: {
3378 pushValueAndType(
I.getOperand(1), InstID, Vals);
3379 pushValue(
I.getOperand(2), InstID, Vals);
3380 pushValueAndType(
I.getOperand(0), InstID, Vals);
3386 case Instruction::ExtractElement:
3388 pushValueAndType(
I.getOperand(0), InstID, Vals);
3389 pushValueAndType(
I.getOperand(1), InstID, Vals);
3391 case Instruction::InsertElement:
3393 pushValueAndType(
I.getOperand(0), InstID, Vals);
3394 pushValue(
I.getOperand(1), InstID, Vals);
3395 pushValueAndType(
I.getOperand(2), InstID, Vals);
3397 case Instruction::BitExtract:
3400 pushValueAndType(
I.getOperand(0), InstID, Vals);
3401 pushValueAndType(
I.getOperand(1), InstID, Vals);
3403 case Instruction::BitInsert:
3405 pushValueAndType(
I.getOperand(0), InstID, Vals);
3406 pushValueAndType(
I.getOperand(1), InstID, Vals);
3407 pushValueAndType(
I.getOperand(2), InstID, Vals);
3409 case Instruction::ShuffleVector:
3411 pushValueAndType(
I.getOperand(0), InstID, Vals);
3412 pushValue(
I.getOperand(1), InstID, Vals);
3416 case Instruction::ICmp:
3417 case Instruction::FCmp: {
3420 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3421 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3423 pushValue(
I.getOperand(1), InstID, Vals);
3429 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3434 case Instruction::Ret:
3437 unsigned NumOperands =
I.getNumOperands();
3438 if (NumOperands == 0)
3439 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3440 else if (NumOperands == 1) {
3441 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3442 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3444 for (
const Value *
Op :
I.operands())
3445 pushValueAndType(
Op, InstID, Vals);
3449 case Instruction::UncondBr: {
3451 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3455 case Instruction::CondBr: {
3457 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3461 pushValue(
II.getCondition(), InstID, Vals);
3463 case Instruction::Switch:
3468 pushValue(
SI.getCondition(), InstID, Vals);
3470 for (
auto Case :
SI.cases()) {
3476 case Instruction::IndirectBr:
3480 pushValue(
I.getOperand(0), InstID, Vals);
3485 case Instruction::Invoke: {
3488 FunctionType *FTy =
II->getFunctionType();
3490 if (
II->hasOperandBundles())
3491 writeOperandBundles(*
II, InstID);
3500 pushValueAndType(Callee, InstID, Vals);
3503 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3504 pushValue(
I.getOperand(i), InstID, Vals);
3507 if (FTy->isVarArg()) {
3508 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3509 pushValueAndType(
I.getOperand(i), InstID, Vals);
3513 case Instruction::Resume:
3515 pushValueAndType(
I.getOperand(0), InstID, Vals);
3517 case Instruction::CleanupRet: {
3520 pushValue(CRI.getCleanupPad(), InstID, Vals);
3521 if (CRI.hasUnwindDest())
3525 case Instruction::CatchRet: {
3528 pushValue(CRI.getCatchPad(), InstID, Vals);
3532 case Instruction::CleanupPad:
3533 case Instruction::CatchPad: {
3537 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3539 unsigned NumArgOperands = FuncletPad.arg_size();
3541 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3542 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3545 case Instruction::CatchSwitch: {
3549 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3551 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3553 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3556 if (CatchSwitch.hasUnwindDest())
3560 case Instruction::CallBr: {
3566 writeOperandBundles(*CBI, InstID);
3581 pushValueAndType(Callee, InstID, Vals);
3584 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3585 pushValue(
I.getOperand(i), InstID, Vals);
3588 if (FTy->isVarArg()) {
3589 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3590 pushValueAndType(
I.getOperand(i), InstID, Vals);
3594 case Instruction::Unreachable:
3596 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3599 case Instruction::PHI: {
3617 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3622 case Instruction::LandingPad: {
3633 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3638 case Instruction::Alloca: {
3644 using APV = AllocaPackedValues;
3646 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3648 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3650 EncodedAlign >> APV::AlignLower::Bits);
3657 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3662 case Instruction::Load: {
3664 if (LI.isAtomic()) {
3666 pushValueAndType(LI.getOperand(0), InstID, Vals);
3669 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3670 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3673 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3675 if (LI.isAtomic()) {
3677 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3678 if (LI.isElementwise())
3684 case Instruction::Store: {
3686 if (
SI.isAtomic()) {
3690 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3692 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3694 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3698 if (
SI.isAtomic()) {
3700 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3701 if (
SI.isElementwise())
3707 case Instruction::AtomicCmpXchg:
3709 pushValueAndType(
I.getOperand(0), InstID, Vals);
3710 pushValueAndType(
I.getOperand(1), InstID, Vals);
3711 pushValue(
I.getOperand(2), InstID, Vals);
3722 case Instruction::AtomicRMW:
3724 pushValueAndType(
I.getOperand(0), InstID, Vals);
3725 pushValueAndType(
I.getOperand(1), InstID, Vals);
3733 case Instruction::Fence:
3738 case Instruction::Call: {
3743 writeOperandBundles(CI, InstID);
3763 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3767 if (FTy->isVarArg()) {
3768 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3773 case Instruction::VAArg:
3776 pushValue(
I.getOperand(0), InstID, Vals);
3779 case Instruction::Freeze:
3781 pushValueAndType(
I.getOperand(0), InstID, Vals);
3791void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3792 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3797 VSTOffset -= bitcodeStartBit();
3798 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3802 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3806 auto Abbv = std::make_shared<BitCodeAbbrev>();
3810 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3815 if (
F.isDeclaration())
3822 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3823 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3827 Record[1] = BitcodeIndex / 32 + 1;
3836void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3837 const ValueSymbolTable &VST) {
3845 SmallVector<uint64_t, 64> NameVals;
3851 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3860 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3864 AbbrevToUse = VST_ENTRY_6_ABBREV;
3866 AbbrevToUse = VST_ENTRY_7_ABBREV;
3869 for (
const auto P :
Name.getKey())
3873 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3880void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3881 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3888 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3893void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3895 "Expected to be preserving use-list order");
3897 auto hasMore = [&]() {
3913void ModuleBitcodeWriter::writeFunction(
3915 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3932 unsigned CstStart, CstEnd;
3934 writeConstants(CstStart, CstEnd,
false);
3937 writeFunctionMetadata(
F);
3940 unsigned InstID = CstEnd;
3942 bool NeedsMetadataAttachment =
F.hasMetadata();
3944 DILocation *LastDL =
nullptr;
3945 SmallSetVector<Function *, 4> BlockAddressUsers;
3948 for (
const BasicBlock &BB :
F) {
3949 for (
const Instruction &
I : BB) {
3950 writeInstruction(
I, InstID, Vals);
3952 if (!
I.getType()->isVoidTy())
3956 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3959 if (DILocation *
DL =
I.getDebugLoc()) {
3972 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3973 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
3974 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3988 if (
I.hasDbgRecords()) {
3992 auto PushValueOrMetadata = [&Vals, InstID,
3995 "RawLocation unexpectedly null in DbgVariableRecord");
3997 SmallVector<unsigned, 2> ValAndType;
4001 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4015 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4041 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4065 SmallPtrSet<Value *, 8> Visited{BA};
4066 while (!Worklist.
empty()) {
4068 for (User *U :
V->users()) {
4074 Visited.
insert(U).second)
4081 if (!BlockAddressUsers.
empty()) {
4090 if (
auto *Symtab =
F.getValueSymbolTable())
4091 writeFunctionLevelValueSymbolTable(*Symtab);
4093 if (NeedsMetadataAttachment)
4094 writeFunctionMetadataAttachment(
F);
4096 writeUseListBlock(&
F);
4102void ModuleBitcodeWriter::writeBlockInfo() {
4115 auto Abbv = std::make_shared<BitCodeAbbrev>();
4126 auto Abbv = std::make_shared<BitCodeAbbrev>();
4136 auto Abbv = std::make_shared<BitCodeAbbrev>();
4146 auto Abbv = std::make_shared<BitCodeAbbrev>();
4152 VST_BBENTRY_6_ABBREV)
4157 auto Abbv = std::make_shared<BitCodeAbbrev>();
4159 Abbv->Add(TypeAbbrevOp);
4161 CONSTANTS_SETTYPE_ABBREV)
4166 auto Abbv = std::make_shared<BitCodeAbbrev>();
4170 CONSTANTS_INTEGER_ABBREV)
4175 auto Abbv = std::make_shared<BitCodeAbbrev>();
4179 CONSTANTS_BYTE_ABBREV)
4184 auto Abbv = std::make_shared<BitCodeAbbrev>();
4192 CONSTANTS_CE_CAST_Abbrev)
4196 auto Abbv = std::make_shared<BitCodeAbbrev>();
4199 CONSTANTS_NULL_Abbrev)
4206 auto Abbv = std::make_shared<BitCodeAbbrev>();
4208 Abbv->Add(ValAbbrevOp);
4209 Abbv->Add(TypeAbbrevOp);
4213 FUNCTION_INST_LOAD_ABBREV)
4217 auto Abbv = std::make_shared<BitCodeAbbrev>();
4219 Abbv->Add(ValAbbrevOp);
4220 Abbv->Add(ValAbbrevOp);
4224 FUNCTION_INST_STORE_ABBREV)
4228 auto Abbv = std::make_shared<BitCodeAbbrev>();
4230 Abbv->Add(ValAbbrevOp);
4233 FUNCTION_INST_UNOP_ABBREV)
4237 auto Abbv = std::make_shared<BitCodeAbbrev>();
4239 Abbv->Add(ValAbbrevOp);
4243 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4247 auto Abbv = std::make_shared<BitCodeAbbrev>();
4249 Abbv->Add(ValAbbrevOp);
4250 Abbv->Add(ValAbbrevOp);
4253 FUNCTION_INST_BINOP_ABBREV)
4257 auto Abbv = std::make_shared<BitCodeAbbrev>();
4259 Abbv->Add(ValAbbrevOp);
4260 Abbv->Add(ValAbbrevOp);
4264 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4268 auto Abbv = std::make_shared<BitCodeAbbrev>();
4270 Abbv->Add(ValAbbrevOp);
4271 Abbv->Add(TypeAbbrevOp);
4274 FUNCTION_INST_CAST_ABBREV)
4278 auto Abbv = std::make_shared<BitCodeAbbrev>();
4280 Abbv->Add(ValAbbrevOp);
4281 Abbv->Add(TypeAbbrevOp);
4285 FUNCTION_INST_CAST_FLAGS_ABBREV)
4290 auto Abbv = std::make_shared<BitCodeAbbrev>();
4293 FUNCTION_INST_RET_VOID_ABBREV)
4297 auto Abbv = std::make_shared<BitCodeAbbrev>();
4299 Abbv->Add(ValAbbrevOp);
4301 FUNCTION_INST_RET_VAL_ABBREV)
4305 auto Abbv = std::make_shared<BitCodeAbbrev>();
4308 Abbv->Add(ValAbbrevOp);
4310 FUNCTION_INST_BR_UNCOND_ABBREV)
4314 auto Abbv = std::make_shared<BitCodeAbbrev>();
4317 Abbv->Add(ValAbbrevOp);
4318 Abbv->Add(ValAbbrevOp);
4319 Abbv->Add(ValAbbrevOp);
4321 FUNCTION_INST_BR_COND_ABBREV)
4325 auto Abbv = std::make_shared<BitCodeAbbrev>();
4328 FUNCTION_INST_UNREACHABLE_ABBREV)
4332 auto Abbv = std::make_shared<BitCodeAbbrev>();
4335 Abbv->Add(TypeAbbrevOp);
4337 Abbv->Add(ValAbbrevOp);
4339 FUNCTION_INST_GEP_ABBREV)
4343 auto Abbv = std::make_shared<BitCodeAbbrev>();
4345 Abbv->Add(ValAbbrevOp);
4346 Abbv->Add(ValAbbrevOp);
4349 FUNCTION_INST_CMP_ABBREV)
4353 auto Abbv = std::make_shared<BitCodeAbbrev>();
4355 Abbv->Add(ValAbbrevOp);
4356 Abbv->Add(ValAbbrevOp);
4360 FUNCTION_INST_CMP_FLAGS_ABBREV)
4364 auto Abbv = std::make_shared<BitCodeAbbrev>();
4369 Abbv->Add(ValAbbrevOp);
4371 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4375 auto Abbv = std::make_shared<BitCodeAbbrev>();
4386 FUNCTION_DEBUG_LOC_ABBREV)
4392 auto Abbv = std::make_shared<BitCodeAbbrev>();
4403 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4411void IndexBitcodeWriter::writeModStrings() {
4417 auto Abbv = std::make_shared<BitCodeAbbrev>();
4422 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4425 Abbv = std::make_shared<BitCodeAbbrev>();
4430 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4433 Abbv = std::make_shared<BitCodeAbbrev>();
4438 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4441 Abbv = std::make_shared<BitCodeAbbrev>();
4448 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4451 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4453 const auto &Hash = MPSE.
getValue();
4455 unsigned AbbrevToUse = Abbrev8Bit;
4457 AbbrevToUse = Abbrev6Bit;
4459 AbbrevToUse = Abbrev7Bit;
4461 auto ModuleId = ModuleIdMap.
size();
4462 ModuleIdMap[
Key] = ModuleId;
4472 Vals.
assign(Hash.begin(), Hash.end());
4484template <
typename Fn>
4488 if (!FS->type_tests().empty())
4493 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4498 for (
auto &VF : VFs) {
4499 Record.push_back(VF.GUID);
4500 Record.push_back(VF.Offset);
4506 FS->type_test_assume_vcalls());
4508 FS->type_checked_load_vcalls());
4510 auto WriteConstVCallVec = [&](
uint64_t Ty,
4512 for (
auto &VC : VCs) {
4514 Record.push_back(VC.VFunc.GUID);
4515 Record.push_back(VC.VFunc.Offset);
4522 FS->type_test_assume_const_vcalls());
4524 FS->type_checked_load_const_vcalls());
4534 if (!FS->paramAccesses().empty()) {
4536 for (
auto &Arg : FS->paramAccesses()) {
4537 size_t UndoSize =
Record.size();
4538 Record.push_back(Arg.ParamNo);
4539 WriteRange(Arg.Use);
4540 Record.push_back(Arg.Calls.size());
4541 for (
auto &
Call : Arg.Calls) {
4543 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4550 Record.push_back(*ValueID);
4551 WriteRange(
Call.Offsets);
4562 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4563 if (!FS->type_tests().empty())
4564 for (
auto &TT : FS->type_tests())
4565 ReferencedTypeIds.insert(TT);
4567 auto GetReferencedTypesFromVFuncIdVec =
4569 for (
auto &VF : VFs)
4570 ReferencedTypeIds.insert(VF.GUID);
4573 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4574 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4576 auto GetReferencedTypesFromConstVCallVec =
4578 for (
auto &VC : VCs)
4579 ReferencedTypeIds.insert(VC.VFunc.GUID);
4582 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4583 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4619 NameVals.
push_back(Summary.TTRes.TheKind);
4620 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4621 NameVals.
push_back(Summary.TTRes.AlignLog2);
4622 NameVals.
push_back(Summary.TTRes.SizeM1);
4623 NameVals.
push_back(Summary.TTRes.BitMask);
4624 NameVals.
push_back(Summary.TTRes.InlineBits);
4626 for (
auto &W : Summary.WPDRes)
4638 for (
auto &
P : Summary) {
4640 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4654 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4655 for (
auto &AI : FS->allocs()) {
4656 for (
auto &MIB : AI.MIBs) {
4658 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4659 for (
auto Id : MIB.StackIdIndices)
4660 StackIdIndices.
push_back(GetStackIndex(Id));
4662 CallStacks.insert({CallStacks.size(), StackIdIndices});
4675 assert(!CallStacks.empty());
4681 Builder.
build(std::move(CallStacks),
nullptr,
4685 return Builder.takeCallStackPos();
4690 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4691 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4692 std::function<
unsigned(
unsigned)> GetStackIndex,
4693 bool WriteContextSizeInfoIndex,
4698 for (
auto &CI : FS->callsites()) {
4702 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4703 Record.push_back(GetValueID(CI.Callee));
4705 Record.push_back(CI.StackIdIndices.size());
4706 Record.push_back(CI.Clones.size());
4708 for (
auto Id : CI.StackIdIndices)
4709 Record.push_back(GetStackIndex(Id));
4717 for (
auto &AI : FS->allocs()) {
4721 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4722 Record.push_back(AI.MIBs.size());
4724 Record.push_back(AI.Versions.size());
4725 for (
auto &MIB : AI.MIBs) {
4732 assert(CallStackCount <= CallStackPos.
size());
4733 Record.push_back(CallStackPos[CallStackCount++]);
4738 assert(AI.ContextSizeInfos.empty() ||
4739 AI.ContextSizeInfos.size() == AI.MIBs.size());
4741 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4749 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4750 for (
auto &Infos : AI.ContextSizeInfos) {
4751 Record.push_back(Infos.size());
4752 for (
auto [FullStackId, TotalSize] : Infos) {
4759 Record.push_back(TotalSize);
4777void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4778 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4779 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4780 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4781 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4788 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4792 auto SpecialRefCnts =
FS->specialRefCounts();
4797 NameVals.
push_back(SpecialRefCnts.first);
4798 NameVals.
push_back(SpecialRefCnts.second);
4800 for (
auto &RI :
FS->refs())
4803 for (
auto &ECI :
FS->calls()) {
4804 NameVals.
push_back(getValueId(ECI.first));
4813 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4815 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4816 [&](
unsigned I) {
return I; },
4817 true, CallStackPos, CallStackCount);
4822void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4823 const GlobalVariable &
V, SmallVector<uint64_t, 64> &NameVals,
4824 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4829 auto VI =
Index->getValueInfo(GUID);
4830 if (!VI ||
VI.getSummaryList().empty()) {
4836 auto *
Summary =
VI.getSummaryList()[0].get();
4842 auto VTableFuncs =
VS->vTableFuncs();
4843 if (!VTableFuncs.empty())
4846 unsigned SizeBeforeRefs = NameVals.
size();
4847 for (
auto &RI :
VS->refs())
4853 if (VTableFuncs.empty())
4858 for (
auto &
P : VTableFuncs) {
4864 FSModVTableRefsAbbrev);
4871void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4874 bool IsThinLTO =
true;
4877 IsThinLTO = MD->getZExtValue();
4889 if (
Index->enableSplitLTOUnit())
4891 if (
Index->hasUnifiedLTO())
4901 auto Abbv = std::make_shared<BitCodeAbbrev>();
4907 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4909 for (
const auto &GVI : valueIds()) {
4911 ArrayRef<uint32_t>{GVI.second,
4912 static_cast<uint32_t
>(GVI.first >> 32),
4913 static_cast<uint32_t
>(GVI.first)},
4917 if (!
Index->stackIds().empty()) {
4918 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4925 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4926 SmallVector<uint32_t> Vals;
4928 for (
auto Id :
Index->stackIds()) {
4929 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4930 Vals.
push_back(
static_cast<uint32_t
>(Id));
4935 unsigned ContextIdAbbvId = 0;
4938 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4950 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4954 Abbv = std::make_shared<BitCodeAbbrev>();
4966 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4969 Abbv = std::make_shared<BitCodeAbbrev>();
4975 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4978 Abbv = std::make_shared<BitCodeAbbrev>();
4986 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4989 Abbv = std::make_shared<BitCodeAbbrev>();
4994 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4997 Abbv = std::make_shared<BitCodeAbbrev>();
5004 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5006 Abbv = std::make_shared<BitCodeAbbrev>();
5012 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5014 Abbv = std::make_shared<BitCodeAbbrev>();
5021 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5023 Abbv = std::make_shared<BitCodeAbbrev>();
5028 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5035 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5046 ValueInfo
VI =
Index->getValueInfo(GUID);
5047 if (!VI ||
VI.getSummaryList().empty()) {
5050 if (!
F.isDeclaration())
5052 " to have an associated value info.");
5055 auto *
Summary =
VI.getSummaryList()[0].get();
5058 FS, [](
unsigned I) {
return I; }, CallStacks);
5062 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5063 if (!CallStacks.
empty()) {
5071 SmallVector<uint64_t, 64> NameVals;
5082 ValueInfo
VI =
Index->getValueInfo(GUID);
5083 if (!VI ||
VI.getSummaryList().empty()) {
5089 auto *
Summary =
VI.getSummaryList()[0].get();
5090 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5091 FSCallsProfileAbbrev, CallsiteAbbrev,
5092 AllocAbbrev, ContextIdAbbvId,
F,
5093 CallStackPos, CallStackCount);
5098 for (
const GlobalVariable &
G :
M.globals())
5099 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5100 FSModVTableRefsAbbrev);
5102 for (
const GlobalAlias &
A :
M.aliases()) {
5103 auto *Aliasee =
A.getAliaseeObject();
5119 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5123 TypeIdCompatibleVtableAbbrev);
5127 if (
Index->getBlockCount())
5129 ArrayRef<uint64_t>{
Index->getBlockCount()});
5134void ModuleBitcodeWriterBase::writeGUIDList() {
5136 for (
const GlobalValue &GV :
M.global_values()) {
5137 auto MaybeGUID = GV.getGUIDIfAssigned();
5138 if (!MaybeGUID || *MaybeGUID == 0)
5141 if (ValueID >= GUIDs.
size())
5142 GUIDs.
resize(ValueID + 1);
5143 GUIDs[ValueID] = *MaybeGUID;
5146 auto Abbv = std::make_shared<BitCodeAbbrev>();
5150 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5152 SmallVector<uint32_t> RecordVals;
5154 for (
auto GUID : GUIDs) {
5155 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5156 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5163void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5172 auto Abbv = std::make_shared<BitCodeAbbrev>();
5178 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5180 for (
const auto &GVI : valueIds()) {
5182 ArrayRef<uint32_t>{GVI.second,
5183 static_cast<uint32_t
>(GVI.first >> 32),
5184 static_cast<uint32_t
>(GVI.first)},
5190 if (!StackIds.empty()) {
5191 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5198 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5199 SmallVector<uint32_t> Vals;
5200 Vals.
reserve(StackIds.size() * 2);
5201 for (
auto Id : StackIds) {
5202 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5203 Vals.
push_back(
static_cast<uint32_t
>(Id));
5209 Abbv = std::make_shared<BitCodeAbbrev>();
5223 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5226 Abbv = std::make_shared<BitCodeAbbrev>();
5233 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5236 Abbv = std::make_shared<BitCodeAbbrev>();
5242 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5244 Abbv = std::make_shared<BitCodeAbbrev>();
5252 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5254 Abbv = std::make_shared<BitCodeAbbrev>();
5265 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5267 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5268 if (DecSummaries ==
nullptr)
5270 return DecSummaries->
count(GVS);
5278 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5280 SmallVector<uint64_t, 64> NameVals;
5284 std::set<GlobalValue::GUID> ReferencedTypeIds;
5288 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5298 NameVals.
push_back(S.getOriginalName());
5303 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5305 Abbv = std::make_shared<BitCodeAbbrev>();
5310 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5317 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5318 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5324 GlobalValueSummary *S =
I.second;
5337 return StackIdIndicesToIndex[
I];
5343 if (!CallStacks.
empty()) {
5353 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5354 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5355 GlobalValueSummary *S =
I.second;
5357 DefOrUseGUIDs.
insert(
I.first);
5358 for (
const ValueInfo &VI : S->
refs())
5359 DefOrUseGUIDs.
insert(
VI.getGUID());
5361 auto ValueId = getValueId(
I.first);
5363 SummaryToValueIdMap[S] = *ValueId;
5381 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5385 for (
auto &RI :
VS->refs()) {
5386 auto RefValueId = getValueId(RI.getGUID());
5396 MaybeEmitOriginalName(*S);
5400 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5402 return std::nullopt;
5403 return getValueId(
VI.getGUID());
5412 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5425 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5426 for (
auto &RI :
FS->refs()) {
5427 auto RefValueId = getValueId(RI.getGUID());
5431 if (RI.isReadOnly())
5433 else if (RI.isWriteOnly())
5437 NameVals[6] =
Count;
5438 NameVals[7] = RORefCnt;
5439 NameVals[8] = WORefCnt;
5441 for (
auto &EI :
FS->calls()) {
5444 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5453 FSCallsProfileAbbrev);
5457 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5460 [&](
const ValueInfo &VI) ->
unsigned {
5461 std::optional<unsigned> ValueID = GetValueId(VI);
5476 return StackIdIndicesToIndex[
I];
5478 false, CallStackPos, CallStackCount);
5480 MaybeEmitOriginalName(*S);
5483 for (
auto *AS : Aliases) {
5484 auto AliasValueId = SummaryToValueIdMap[AS];
5493 auto AliaseeValueId =
5500 MaybeEmitOriginalName(*AS);
5508 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5510 if (CfiIndex.
empty())
5514 for (StringRef Name : Names)
5517 if (Functions.
empty())
5520 for (
const auto &Record : Functions) {
5535 for (
auto &
T : ReferencedTypeIds) {
5536 auto TidIter =
Index.typeIds().equal_range(
T);
5537 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5545 if (
Index.getBlockCount())
5547 ArrayRef<uint64_t>{
Index.getBlockCount()});
5558 auto Abbv = std::make_shared<BitCodeAbbrev>();
5562 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5564 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5567 Abbv = std::make_shared<BitCodeAbbrev>();
5570 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5576void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5581 Hasher.
update(ArrayRef<uint8_t>(
5582 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5583 std::array<uint8_t, 20> Hash = Hasher.
result();
5584 for (
int Pos = 0; Pos < 20; Pos += 4) {
5597void ModuleBitcodeWriter::write() {
5605 writeModuleVersion();
5614 writeAttributeGroupTable();
5617 writeAttributeTable();
5626 writeModuleConstants();
5629 writeModuleMetadataKinds();
5632 writeModuleMetadata();
5636 writeUseListBlock(
nullptr);
5638 writeOperandBundleTags();
5639 writeSyncScopeNames();
5642 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5644 if (!
F.isDeclaration())
5645 writeFunction(
F, FunctionToBitcodeIndex);
5650 writePerModuleGlobalValueSummary();
5652 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5680 unsigned CPUType = ~0U;
5687 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5688 DARWIN_CPU_TYPE_X86 = 7,
5689 DARWIN_CPU_TYPE_ARM = 12,
5690 DARWIN_CPU_TYPE_POWERPC = 18
5695 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5697 CPUType = DARWIN_CPU_TYPE_X86;
5699 CPUType = DARWIN_CPU_TYPE_POWERPC;
5701 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5703 CPUType = DARWIN_CPU_TYPE_ARM;
5707 "Expected header size to be reserved");
5712 unsigned Position = 0;
5720 while (Buffer.
size() & 15)
5727 Stream.
Emit((
unsigned)
'B', 8);
5728 Stream.
Emit((
unsigned)
'C', 8);
5729 Stream.
Emit(0x0, 4);
5730 Stream.
Emit(0xC, 4);
5731 Stream.
Emit(0xE, 4);
5732 Stream.
Emit(0xD, 4);
5750 auto Abbv = std::make_shared<BitCodeAbbrev>();
5753 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5761 assert(!WroteStrtab && !WroteSymtab);
5767 if (M->getModuleInlineAsm().empty())
5771 const Triple TT(M->getTargetTriple());
5773 if (!
T || !
T->hasMCAsmParser())
5795 std::vector<char> Strtab;
5796 StrtabBuilder.finalizeInOrder();
5797 Strtab.resize(StrtabBuilder.getSize());
5798 StrtabBuilder.write((
uint8_t *)Strtab.data());
5801 {Strtab.data(), Strtab.size()});
5812 bool ShouldPreserveUseListOrder,
5821 assert(M.isMaterialized());
5822 Mods.push_back(
const_cast<Module *
>(&M));
5824 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5825 ShouldPreserveUseListOrder, Index,
5826 GenerateHash, ModHash);
5827 ModuleWriter.write();
5834 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5835 ModuleToSummariesForIndex);
5836 IndexWriter.write();
5841 bool ShouldPreserveUseListOrder,
5845 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5847 Writer.writeSymtab();
5848 Writer.writeStrtab();
5850 Triple TT(M.getTargetTriple());
5851 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5862 Out.write(Buffer.
data(), Buffer.
size());
5870void IndexBitcodeWriter::write() {
5873 writeModuleVersion();
5879 writeCombinedGlobalValueSummary();
5896 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5899 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5905class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5915 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5917 ModHash(&ModHash) {}
5922 void writeSimplifiedModuleInfo();
5932void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5944 auto Abbv = std::make_shared<BitCodeAbbrev>();
5947 Abbv->Add(AbbrevOpToUse);
5948 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5950 for (
const auto P :
M.getSourceFileName())
6016void ThinLinkBitcodeWriter::write() {
6019 writeModuleVersion();
6021 writeSimplifiedModuleInfo();
6023 writePerModuleGlobalValueSummary();
6040 assert(M.isMaterialized());
6041 Mods.push_back(
const_cast<Module *
>(&M));
6043 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6045 ThinLinkWriter.write();
6062 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6066 switch (
T.getObjectFormat()) {
6068 return "__LLVM,__bitcode";
6093 switch (
T.getObjectFormat()) {
6095 return "__LLVM,__cmdline";
6121 const std::vector<uint8_t> &CmdArgs) {
6126 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6128 for (
auto *GV : UsedGlobals) {
6129 if (GV->getName() !=
"llvm.embedded.module" &&
6130 GV->getName() !=
"llvm.cmdline")
6135 Used->eraseFromParent();
6140 Triple T(M.getTargetTriple());
6169 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6170 assert(Old->hasZeroLiveUses() &&
6171 "llvm.embedded.module can only be used once in llvm.compiler.used");
6173 Old->eraseFromParent();
6175 GV->
setName(
"llvm.embedded.module");
6193 assert(Old->hasZeroLiveUses() &&
6194 "llvm.cmdline can only be used once in llvm.compiler.used");
6196 Old->eraseFromParent();
6202 if (UsedArray.
empty())
6210 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 writeMDFunctionLocalContext(raw_ostream &Out, const MDFunctionLocalContext *FLMD, 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 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 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 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
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
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().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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.
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_SANITIZE_CONCURRENCY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_LIKELY_MODULE_LOCAL
@ 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.
const BitWriterOptions & getBitWriterOptions(const LLVMContext &C)
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.
constexpr bool valueOr(BoolOrDefault X, bool Default)
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