33#include "llvm/Config/llvm-config.h"
95 cl::desc(
"Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
99 cl::desc(
"The threshold (unit M) for flushing LLVM bitcode."));
119 cl::desc(
"Preserve use-list order when writing LLVM bitcode."));
134 VST_BBENTRY_6_ABBREV,
138 CONSTANTS_INTEGER_ABBREV,
139 CONSTANTS_BYTE_ABBREV,
140 CONSTANTS_CE_CAST_Abbrev,
141 CONSTANTS_NULL_Abbrev,
145 FUNCTION_INST_STORE_ABBREV,
146 FUNCTION_INST_UNOP_ABBREV,
147 FUNCTION_INST_UNOP_FLAGS_ABBREV,
148 FUNCTION_INST_BINOP_ABBREV,
149 FUNCTION_INST_BINOP_FLAGS_ABBREV,
150 FUNCTION_INST_CAST_ABBREV,
151 FUNCTION_INST_CAST_FLAGS_ABBREV,
152 FUNCTION_INST_RET_VOID_ABBREV,
153 FUNCTION_INST_RET_VAL_ABBREV,
154 FUNCTION_INST_BR_UNCOND_ABBREV,
155 FUNCTION_INST_BR_COND_ABBREV,
156 FUNCTION_INST_UNREACHABLE_ABBREV,
157 FUNCTION_INST_GEP_ABBREV,
158 FUNCTION_INST_CMP_ABBREV,
159 FUNCTION_INST_CMP_FLAGS_ABBREV,
160 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
161 FUNCTION_DEBUG_LOC_ABBREV,
166class BitcodeWriterBase {
169 BitstreamWriter &Stream;
171 StringTableBuilder &StrtabBuilder;
176 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
177 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
180 void writeModuleVersion();
183void BitcodeWriterBase::writeModuleVersion() {
190class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
199 const ModuleSummaryIndex *Index;
204 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
207 unsigned GlobalValueId;
216 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
217 BitstreamWriter &Stream,
218 bool ShouldPreserveUseListOrder,
219 const ModuleSummaryIndex *Index)
220 : BitcodeWriterBase(Stream, StrtabBuilder),
M(
M),
223 : ShouldPreserveUseListOrder),
234 for (
const auto &GUIDSummaryLists :
235 Index->sortedGlobalValueSummariesRange())
237 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
243 for (auto &CallEdge : FS->calls())
244 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
245 assignValueId(CallEdge.first.getGUID());
251 for (auto &RefEdge : FS->refs())
252 if (!RefEdge.haveGVs() || !RefEdge.getValue())
253 assignValueId(RefEdge.getGUID());
258 void writePerModuleGlobalValueSummary();
259 void writeGUIDList();
262 void writePerModuleFunctionSummaryRecord(
263 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
264 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
265 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
266 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
268 void writeModuleLevelReferences(
const GlobalVariable &V,
269 SmallVector<uint64_t, 64> &NameVals,
270 unsigned FSModRefsAbbrev,
271 unsigned FSModVTableRefsAbbrev);
274 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
278 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
281 assert(VMI != GUIDToValueIdMap.end() &&
282 "GUID does not have assigned value Id");
287 unsigned getValueId(ValueInfo VI) {
288 if (!
VI.haveGVs() || !
VI.getValue())
289 return getValueId(
VI.getGUID());
293 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
297class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
313 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
314 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
315 const ModuleSummaryIndex *Index,
bool GenerateHash,
317 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
318 ShouldPreserveUseListOrder,
Index),
319 GenerateHash(GenerateHash), ModHash(ModHash),
320 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
326 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
328 size_t addToStrtab(StringRef Str);
330 void writeAttributeGroupTable();
331 void writeAttributeTable();
332 void writeTypeTable();
334 void writeValueSymbolTableForwardDecl();
335 void writeModuleInfo();
336 void writeValueAsMetadata(
const ValueAsMetadata *MD,
337 SmallVectorImpl<uint64_t> &Record);
338 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
340 unsigned createDILocationAbbrev();
341 void writeDILocation(
const DILocation *
N, 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);
414 SmallVectorImpl<uint64_t> &Record,
416 unsigned createNamedMetadataAbbrev();
417 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
418 unsigned createMetadataStringsAbbrev();
420 SmallVectorImpl<uint64_t> &Record);
422 SmallVectorImpl<uint64_t> &Record,
423 std::vector<unsigned> *MDAbbrevs =
nullptr,
424 std::vector<uint64_t> *IndexPos =
nullptr);
425 void writeModuleMetadata();
426 void writeFunctionMetadata(
const Function &
F);
427 void writeFunctionMetadataAttachment(
const Function &
F);
428 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
429 const GlobalObject &GO);
430 void writeModuleMetadataKinds();
431 void writeOperandBundleTags();
432 void writeSyncScopeNames();
433 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
434 void writeModuleConstants();
435 bool pushValueAndType(
const Value *V,
unsigned InstID,
436 SmallVectorImpl<unsigned> &Vals);
437 bool pushValueOrMetadata(
const Value *V,
unsigned InstID,
438 SmallVectorImpl<unsigned> &Vals);
439 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
440 void pushValue(
const Value *V,
unsigned InstID,
441 SmallVectorImpl<unsigned> &Vals);
442 void pushValueSigned(
const Value *V,
unsigned InstID,
443 SmallVectorImpl<uint64_t> &Vals);
444 void writeInstruction(
const Instruction &
I,
unsigned InstID,
445 SmallVectorImpl<unsigned> &Vals);
446 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
447 void writeGlobalValueSymbolTable(
448 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
449 void writeUseList(UseListOrder &&Order);
450 void writeUseListBlock(
const Function *
F);
453 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
454 void writeBlockInfo();
455 void writeModuleHash(StringRef View);
458 return unsigned(SSID);
461 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
465class IndexBitcodeWriter :
public BitcodeWriterBase {
467 const ModuleSummaryIndex &
Index;
480 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
484 std::vector<uint64_t> StackIds;
489 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
492 unsigned GlobalValueId = 0;
496 DenseMap<StringRef, uint64_t> ModuleIdMap;
506 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
507 const ModuleSummaryIndex &Index,
510 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
511 DecSummaries(DecSummaries),
512 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
516 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
521 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
523 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
530 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
531 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
543 for (
auto &CI :
FS->callsites()) {
554 if (CI.StackIdIndices.empty()) {
555 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
558 for (
auto Idx : CI.StackIdIndices)
559 RecordStackIdReference(Idx);
562 for (
auto &AI :
FS->allocs())
563 for (
auto &MIB : AI.MIBs)
564 for (
auto Idx : MIB.StackIdIndices)
565 RecordStackIdReference(Idx);
571 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
576 template<
typename Functor>
577 void forEachSummary(Functor Callback) {
578 if (ModuleToSummariesForIndex) {
579 for (
auto &M : *ModuleToSummariesForIndex)
580 for (
auto &Summary :
M.second) {
586 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
590 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
591 for (
auto &Summary : Summaries.second.getSummaryList())
600 template <
typename Functor>
void forEachModule(Functor Callback) {
601 if (ModuleToSummariesForIndex) {
602 for (
const auto &M : *ModuleToSummariesForIndex) {
603 const auto &MPI =
Index.modulePaths().find(
M.first);
604 if (MPI ==
Index.modulePaths().end()) {
608 assert(ModuleToSummariesForIndex->size() == 1);
618 std::vector<StringRef> ModulePaths;
619 for (
auto &[ModPath,
_] :
Index.modulePaths())
620 ModulePaths.push_back(ModPath);
622 for (
auto &ModPath : ModulePaths)
631 void writeModStrings();
632 void writeCombinedGlobalValueSummary();
635 auto VMI = GUIDToValueIdMap.find(ValGUID);
636 if (VMI == GUIDToValueIdMap.end())
641 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
676 case Instruction::Add:
678 case Instruction::Sub:
680 case Instruction::Mul:
683 case Instruction::FDiv:
686 case Instruction::FRem:
698 unsigned Encoding = 0;
699 switch (
I.getOperation()) {
772 if (
I.isElementwise())
807 case Attribute::Alignment:
809 case Attribute::AllocAlign:
811 case Attribute::AllocSize:
813 case Attribute::AlwaysInline:
815 case Attribute::Builtin:
817 case Attribute::ByVal:
819 case Attribute::Convergent:
821 case Attribute::InAlloca:
823 case Attribute::Cold:
825 case Attribute::DisableSanitizerInstrumentation:
827 case Attribute::FnRetThunkExtern:
829 case Attribute::Flatten:
833 case Attribute::ElementType:
835 case Attribute::HybridPatchable:
837 case Attribute::InlineHint:
839 case Attribute::InReg:
841 case Attribute::JumpTable:
843 case Attribute::MinSize:
845 case Attribute::AllocatedPointer:
847 case Attribute::AllocKind:
849 case Attribute::Memory:
851 case Attribute::NoFPClass:
853 case Attribute::Naked:
855 case Attribute::Nest:
857 case Attribute::NoAlias:
859 case Attribute::NoBuiltin:
861 case Attribute::NoCallback:
863 case Attribute::NoDivergenceSource:
865 case Attribute::NoDuplicate:
867 case Attribute::NoFree:
869 case Attribute::NoFreeObj:
871 case Attribute::NoImplicitFloat:
873 case Attribute::NoInline:
875 case Attribute::NoRecurse:
877 case Attribute::NoMerge:
879 case Attribute::NonLazyBind:
881 case Attribute::NonNull:
883 case Attribute::Dereferenceable:
885 case Attribute::DereferenceableOrNull:
887 case Attribute::NoRedZone:
889 case Attribute::NoReturn:
891 case Attribute::NoSync:
893 case Attribute::NoCfCheck:
895 case Attribute::NoProfile:
897 case Attribute::SkipProfile:
899 case Attribute::NoUnwind:
901 case Attribute::NoSanitizeBounds:
903 case Attribute::NoSanitizeCoverage:
905 case Attribute::NullPointerIsValid:
907 case Attribute::OptimizeForDebugging:
909 case Attribute::OptForFuzzing:
911 case Attribute::OptimizeForSize:
913 case Attribute::OptimizeNone:
915 case Attribute::ReadNone:
917 case Attribute::ReadOnly:
919 case Attribute::Returned:
921 case Attribute::ReturnsTwice:
923 case Attribute::SExt:
925 case Attribute::Speculatable:
927 case Attribute::StackAlignment:
929 case Attribute::StackProtect:
931 case Attribute::StackProtectReq:
933 case Attribute::StackProtectStrong:
935 case Attribute::SafeStack:
937 case Attribute::ShadowCallStack:
939 case Attribute::StrictFP:
941 case Attribute::StructRet:
943 case Attribute::SanitizeAddress:
945 case Attribute::SanitizeAllocToken:
947 case Attribute::SanitizeHWAddress:
949 case Attribute::SanitizeThread:
951 case Attribute::SanitizeType:
953 case Attribute::SanitizeMemory:
955 case Attribute::SanitizeNumericalStability:
957 case Attribute::SanitizeRealtime:
959 case Attribute::SanitizeRealtimeBlocking:
961 case Attribute::SpeculativeLoadHardening:
963 case Attribute::SwiftError:
965 case Attribute::SwiftSelf:
967 case Attribute::SwiftAsync:
969 case Attribute::UWTable:
971 case Attribute::VScaleRange:
973 case Attribute::WillReturn:
975 case Attribute::WriteOnly:
977 case Attribute::ZExt:
979 case Attribute::ImmArg:
981 case Attribute::SanitizeMemTag:
983 case Attribute::Preallocated:
985 case Attribute::NoUndef:
987 case Attribute::ByRef:
989 case Attribute::MustProgress:
991 case Attribute::PresplitCoroutine:
993 case Attribute::Writable:
995 case Attribute::CoroDestroyOnlyWhenComplete:
997 case Attribute::CoroElideSafe:
999 case Attribute::DeadOnUnwind:
1001 case Attribute::Range:
1003 case Attribute::Initializes:
1005 case Attribute::NoExt:
1007 case Attribute::Captures:
1009 case Attribute::DeadOnReturn:
1011 case Attribute::NoCreateUndefOrPoison:
1013 case Attribute::DenormalFPEnv:
1015 case Attribute::NoOutline:
1017 case Attribute::NoIPA:
1032 if ((int64_t)V >= 0)
1043 unsigned NumWords =
A.getActiveWords();
1044 const uint64_t *RawData =
A.getRawData();
1045 for (
unsigned i = 0; i < NumWords; i++)
1065void ModuleBitcodeWriter::writeAttributeGroupTable() {
1066 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1068 if (AttrGrps.empty())
return;
1072 SmallVector<uint64_t, 64>
Record;
1074 unsigned AttrListIndex = Pair.first;
1075 AttributeSet AS = Pair.second;
1077 Record.push_back(AttrListIndex);
1080 if (Attr.isEnumAttribute()) {
1083 }
else if (Attr.isIntAttribute()) {
1085 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1087 if (Kind == Attribute::Memory) {
1092 Record.push_back(Attr.getValueAsInt());
1094 }
else if (Attr.isStringAttribute()) {
1095 StringRef
Kind = Attr.getKindAsString();
1096 StringRef Val = Attr.getValueAsString();
1105 }
else if (Attr.isTypeAttribute()) {
1106 Type *Ty = Attr.getValueAsType();
1107 Record.push_back(Ty ? 6 : 5);
1111 }
else if (Attr.isConstantRangeAttribute()) {
1117 assert(Attr.isConstantRangeListAttribute());
1123 for (
auto &CR : Val)
1135void ModuleBitcodeWriter::writeAttributeTable() {
1137 if (
Attrs.empty())
return;
1141 SmallVector<uint64_t, 64>
Record;
1142 for (
const AttributeList &AL : Attrs) {
1143 for (
unsigned i :
AL.indexes()) {
1144 AttributeSet AS =
AL.getAttributes(i);
1157void ModuleBitcodeWriter::writeTypeTable() {
1161 SmallVector<uint64_t, 64> TypeVals;
1166 auto Abbv = std::make_shared<BitCodeAbbrev>();
1168 Abbv->Add(BitCodeAbbrevOp(0));
1169 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1172 Abbv = std::make_shared<BitCodeAbbrev>();
1177 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1180 Abbv = std::make_shared<BitCodeAbbrev>();
1185 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1188 Abbv = std::make_shared<BitCodeAbbrev>();
1192 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1195 Abbv = std::make_shared<BitCodeAbbrev>();
1200 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1203 Abbv = std::make_shared<BitCodeAbbrev>();
1207 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1215 for (
Type *
T : TypeList) {
1216 int AbbrevToUse = 0;
1219 switch (
T->getTypeID()) {
1229 case Type::MetadataTyID:
1234 case Type::ByteTyID:
1239 case Type::IntegerTyID:
1244 case Type::PointerTyID: {
1251 AbbrevToUse = OpaquePtrAbbrev;
1254 case Type::FunctionTyID: {
1260 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1262 AbbrevToUse = FunctionAbbrev;
1265 case Type::StructTyID: {
1270 for (
Type *ET :
ST->elements())
1273 if (
ST->isLiteral()) {
1275 AbbrevToUse = StructAnonAbbrev;
1277 if (
ST->isOpaque()) {
1281 AbbrevToUse = StructNamedAbbrev;
1285 if (!
ST->getName().empty())
1291 case Type::ArrayTyID: {
1295 TypeVals.
push_back(AT->getNumElements());
1297 AbbrevToUse = ArrayAbbrev;
1300 case Type::FixedVectorTyID:
1301 case Type::ScalableVectorTyID: {
1306 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1312 case Type::TargetExtTyID: {
1318 for (
Type *InnerTy :
TET->type_params())
1323 case Type::TypedPointerTyID:
1328 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1369 RawFlags |= Flags.ReadNone;
1370 RawFlags |= (Flags.ReadOnly << 1);
1371 RawFlags |= (Flags.NoRecurse << 2);
1372 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1373 RawFlags |= (Flags.NoInline << 4);
1374 RawFlags |= (Flags.AlwaysInline << 5);
1375 RawFlags |= (Flags.NoUnwind << 6);
1376 RawFlags |= (Flags.MayThrow << 7);
1377 RawFlags |= (Flags.HasUnknownCall << 8);
1378 RawFlags |= (Flags.MustBeUnreachable << 9);
1385 bool ImportAsDecl =
false) {
1388 RawFlags |= Flags.NotEligibleToImport;
1389 RawFlags |= (Flags.Live << 1);
1390 RawFlags |= (Flags.DSOLocal << 2);
1391 RawFlags |= (Flags.CanAutoHide << 3);
1396 RawFlags = (RawFlags << 4) | Flags.Linkage;
1398 RawFlags |= (Flags.Visibility << 8);
1400 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1401 RawFlags |= (ImportType << 10);
1403 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1409 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1410 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1453 switch (
C.getSelectionKind()) {
1477size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1480 return StrtabBuilder.
add(Str);
1483void ModuleBitcodeWriter::writeComdats() {
1498void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1503 auto Abbv = std::make_shared<BitCodeAbbrev>();
1509 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1525 bool isChar6 =
true;
1526 for (
char C : Str) {
1529 if ((
unsigned char)
C & 128)
1538static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1539 "Sanitizer Metadata is too large for naive serialization.");
1542 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1543 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1549void ModuleBitcodeWriter::writeModuleInfo() {
1551 if (!
M.getTargetTriple().empty())
1553 M.getTargetTriple().str(), 0 );
1554 const std::string &
DL =
M.getDataLayoutStr();
1558 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1560 Frag.Props.getAsStrings();
1573 std::map<std::string, unsigned> SectionMap;
1574 std::map<std::string, unsigned> GCMap;
1575 MaybeAlign MaxGVarAlignment;
1576 unsigned MaxGlobalType = 0;
1577 for (
const GlobalVariable &GV :
M.globals()) {
1578 if (MaybeAlign
A = GV.getAlign())
1579 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1580 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1581 if (GV.hasSection()) {
1583 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1587 Entry = SectionMap.size();
1592 if (
F.hasSection()) {
1594 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1598 Entry = SectionMap.size();
1603 unsigned &
Entry = GCMap[
F.getGC()];
1607 Entry = GCMap.size();
1613 unsigned SimpleGVarAbbrev = 0;
1614 if (!
M.global_empty()) {
1616 auto Abbv = std::make_shared<BitCodeAbbrev>();
1627 if (!MaxGVarAlignment)
1628 Abbv->Add(BitCodeAbbrevOp(0));
1630 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1634 if (SectionMap.empty())
1635 Abbv->Add(BitCodeAbbrevOp(0));
1640 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1654 auto Abbv = std::make_shared<BitCodeAbbrev>();
1657 Abbv->Add(AbbrevOpToUse);
1658 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1660 for (
const auto P :
M.getSourceFileName())
1671 for (
const GlobalVariable &GV :
M.globals()) {
1672 unsigned AbbrevToUse = 0;
1678 Vals.
push_back(addToStrtab(GV.getName()));
1681 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1685 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1686 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1688 if (GV.isThreadLocal() ||
1690 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1691 GV.isExternallyInitialized() ||
1693 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1694 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1698 Vals.
push_back(GV.isExternallyInitialized());
1702 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1706 Vals.
push_back(addToStrtab(GV.getPartition()));
1707 Vals.
push_back(GV.getPartition().size());
1710 GV.getSanitizerMetadata())
1714 AbbrevToUse = SimpleGVarAbbrev;
1735 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1736 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1748 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1752 Vals.
push_back(addToStrtab(
F.getPartition()));
1754 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1756 unsigned AbbrevToUse = 0;
1762 for (
const GlobalAlias &
A :
M.aliases()) {
1769 Vals.
push_back(
A.getType()->getAddressSpace());
1777 Vals.
push_back(addToStrtab(
A.getPartition()));
1780 unsigned AbbrevToUse = 0;
1786 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1792 Vals.
push_back(
I.getType()->getAddressSpace());
1797 Vals.
push_back(addToStrtab(
I.getPartition()));
1803 writeValueSymbolTableForwardDecl();
1810 if (OBO->hasNoSignedWrap())
1812 if (OBO->hasNoUnsignedWrap())
1818 if (PDI->isDisjoint())
1821 if (FPMO->hasAllowReassoc())
1823 if (FPMO->hasNoNaNs())
1825 if (FPMO->hasNoInfs())
1827 if (FPMO->hasNoSignedZeros())
1829 if (FPMO->hasAllowReciprocal())
1831 if (FPMO->hasAllowContract())
1833 if (FPMO->hasApproxFunc())
1839 if (NNI->hasNonNeg())
1843 if (NNI->hasNonNeg())
1846 if (TI->hasNoSignedWrap())
1848 if (TI->hasNoUnsignedWrap())
1851 if (
GEP->isInBounds())
1853 if (
GEP->hasNoUnsignedSignedWrap())
1855 if (
GEP->hasNoUnsignedWrap())
1858 if (ICmp->hasSameSign())
1865void ModuleBitcodeWriter::writeValueAsMetadata(
1866 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1875void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1876 SmallVectorImpl<uint64_t> &Record,
1878 for (
const MDOperand &MDO :
N->operands()) {
1881 "Unexpected function-local metadata");
1890unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1893 auto Abbv = std::make_shared<BitCodeAbbrev>();
1906void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1907 SmallVectorImpl<uint64_t> &Record,
1910 Abbrev = createDILocationAbbrev();
1912 Record.push_back(
N->isDistinct());
1913 Record.push_back(
N->getLine());
1914 Record.push_back(
N->getColumn());
1917 Record.push_back(
N->isImplicitCode());
1918 Record.push_back(
N->getAtomGroup());
1919 Record.push_back(
N->getAtomRank());
1924unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1927 auto Abbv = std::make_shared<BitCodeAbbrev>();
1938void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
1939 SmallVectorImpl<uint64_t> &Record,
1942 Abbrev = createGenericDINodeAbbrev();
1944 Record.push_back(
N->isDistinct());
1945 Record.push_back(
N->getTag());
1948 for (
auto &
I :
N->operands())
1955void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
1956 SmallVectorImpl<uint64_t> &Record,
1969void ModuleBitcodeWriter::writeDIGenericSubrange(
1970 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
1982void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
1983 SmallVectorImpl<uint64_t> &Record,
1986 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
1987 Record.push_back(
N->getValue().getBitWidth());
1995void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
1996 SmallVectorImpl<uint64_t> &Record,
1998 const unsigned SizeIsMetadata = 0x2;
1999 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2000 Record.push_back(
N->getTag());
2003 Record.push_back(
N->getAlignInBits());
2004 Record.push_back(
N->getEncoding());
2005 Record.push_back(
N->getFlags());
2006 Record.push_back(
N->getNumExtraInhabitants());
2007 Record.push_back(
N->getDataSizeInBits());
2009 Record.push_back(
N->getLine());
2016void ModuleBitcodeWriter::writeDIFixedPointType(
2017 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2019 const unsigned SizeIsMetadata = 0x2;
2020 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2021 Record.push_back(
N->getTag());
2024 Record.push_back(
N->getAlignInBits());
2025 Record.push_back(
N->getEncoding());
2026 Record.push_back(
N->getFlags());
2027 Record.push_back(
N->getKind());
2028 Record.push_back(
N->getFactorRaw());
2030 auto WriteWideInt = [&](
const APInt &
Value) {
2035 Record.push_back(Encoded);
2039 WriteWideInt(
N->getNumeratorRaw());
2040 WriteWideInt(
N->getDenominatorRaw());
2043 Record.push_back(
N->getLine());
2050void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2051 SmallVectorImpl<uint64_t> &Record,
2053 const unsigned SizeIsMetadata = 0x2;
2054 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2055 Record.push_back(
N->getTag());
2061 Record.push_back(
N->getAlignInBits());
2062 Record.push_back(
N->getEncoding());
2068void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2069 SmallVectorImpl<uint64_t> &Record,
2071 const unsigned SizeIsMetadata = 0x2;
2072 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2073 Record.push_back(
N->getTag());
2076 Record.push_back(
N->getLine());
2080 Record.push_back(
N->getAlignInBits());
2082 Record.push_back(
N->getFlags());
2087 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2088 Record.push_back(*DWARFAddressSpace + 1);
2094 if (
auto PtrAuthData =
N->getPtrAuthData())
2095 Record.push_back(PtrAuthData->RawData);
2103void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2104 SmallVectorImpl<uint64_t> &Record,
2106 const unsigned SizeIsMetadata = 0x2;
2107 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2110 Record.push_back(
N->getLine());
2113 Record.push_back(
N->getAlignInBits());
2114 Record.push_back(
N->getFlags());
2125void ModuleBitcodeWriter::writeDICompositeType(
2126 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2128 const unsigned IsNotUsedInOldTypeRef = 0x2;
2129 const unsigned SizeIsMetadata = 0x4;
2130 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2131 (
unsigned)
N->isDistinct());
2132 Record.push_back(
N->getTag());
2135 Record.push_back(
N->getLine());
2139 Record.push_back(
N->getAlignInBits());
2141 Record.push_back(
N->getFlags());
2143 Record.push_back(
N->getRuntimeLang());
2153 Record.push_back(
N->getNumExtraInhabitants());
2163void ModuleBitcodeWriter::writeDISubroutineType(
2164 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2166 const unsigned HasNoOldTypeRefs = 0x2;
2167 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2168 Record.push_back(
N->getFlags());
2176void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2177 SmallVectorImpl<uint64_t> &Record,
2179 Record.push_back(
N->isDistinct());
2182 if (
N->getRawChecksum()) {
2183 Record.push_back(
N->getRawChecksum()->Kind);
2191 auto Source =
N->getRawSource();
2199void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2200 SmallVectorImpl<uint64_t> &Record,
2202 assert(
N->isDistinct() &&
"Expected distinct compile units");
2205 auto Lang =
N->getSourceLanguage();
2206 Record.push_back(Lang.getName());
2209 if (Lang.hasVersionedName())
2214 Record.push_back(
N->isOptimized());
2216 Record.push_back(
N->getRuntimeVersion());
2218 Record.push_back(
N->getEmissionKind());
2224 Record.push_back(
N->getDWOId());
2226 Record.push_back(
N->getSplitDebugInlining());
2227 Record.push_back(
N->getDebugInfoForProfiling());
2228 Record.push_back((
unsigned)
N->getNameTableKind());
2229 Record.push_back(
N->getRangesBaseAddress());
2232 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2233 Record.push_back(Lang.getDialect());
2239void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2240 SmallVectorImpl<uint64_t> &Record,
2242 const uint64_t HasUnitFlag = 1 << 1;
2243 const uint64_t HasSPFlagsFlag = 1 << 2;
2244 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2249 Record.push_back(
N->getLine());
2251 Record.push_back(
N->getScopeLine());
2253 Record.push_back(
N->getSPFlags());
2254 Record.push_back(
N->getVirtualIndex());
2255 Record.push_back(
N->getFlags());
2260 Record.push_back(
N->getThisAdjustment());
2264 Record.push_back(
N->getKeyInstructionsEnabled());
2270void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2271 SmallVectorImpl<uint64_t> &Record,
2273 Record.push_back(
N->isDistinct());
2276 Record.push_back(
N->getLine());
2277 Record.push_back(
N->getColumn());
2283void ModuleBitcodeWriter::writeDILexicalBlockFile(
2284 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2286 Record.push_back(
N->isDistinct());
2289 Record.push_back(
N->getDiscriminator());
2295void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2296 SmallVectorImpl<uint64_t> &Record,
2298 Record.push_back(
N->isDistinct());
2303 Record.push_back(
N->getLineNo());
2309void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2310 SmallVectorImpl<uint64_t> &Record,
2312 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2320void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2321 SmallVectorImpl<uint64_t> &Record,
2323 Record.push_back(
N->isDistinct());
2324 Record.push_back(
N->getMacinfoType());
2325 Record.push_back(
N->getLine());
2333void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2334 SmallVectorImpl<uint64_t> &Record,
2336 Record.push_back(
N->isDistinct());
2337 Record.push_back(
N->getMacinfoType());
2338 Record.push_back(
N->getLine());
2346void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2347 SmallVectorImpl<uint64_t> &Record) {
2348 Record.reserve(
N->getArgs().size());
2349 for (ValueAsMetadata *MD :
N->getArgs())
2356void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2357 SmallVectorImpl<uint64_t> &Record,
2359 Record.push_back(
N->isDistinct());
2360 for (
auto &
I :
N->operands())
2362 Record.push_back(
N->getLineNo());
2363 Record.push_back(
N->getIsDecl());
2369void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2370 SmallVectorImpl<uint64_t> &Record,
2373 Record.push_back(
N->isDistinct());
2378void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2379 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2381 Record.push_back(
N->isDistinct());
2384 Record.push_back(
N->isDefault());
2390void ModuleBitcodeWriter::writeDITemplateValueParameter(
2391 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2393 Record.push_back(
N->isDistinct());
2394 Record.push_back(
N->getTag());
2397 Record.push_back(
N->isDefault());
2404void ModuleBitcodeWriter::writeDIGlobalVariable(
2405 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2413 Record.push_back(
N->getLine());
2415 Record.push_back(
N->isLocalToUnit());
2416 Record.push_back(
N->isDefinition());
2419 Record.push_back(
N->getAlignInBits());
2426void ModuleBitcodeWriter::writeDILocalVariable(
2427 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2442 const uint64_t HasAlignmentFlag = 1 << 1;
2447 Record.push_back(
N->getLine());
2449 Record.push_back(
N->getArg());
2450 Record.push_back(
N->getFlags());
2451 Record.push_back(
N->getAlignInBits());
2458void ModuleBitcodeWriter::writeDILabel(
2459 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2466 Record.push_back(
N->getLine());
2467 Record.push_back(
N->getColumn());
2468 Record.push_back(
N->getCoroSuspendIdx().has_value()
2469 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2470 : std::numeric_limits<uint64_t>::max());
2476void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2477 SmallVectorImpl<uint64_t> &Record,
2479 Record.reserve(
N->getElements().size() + 1);
2482 Record.append(
N->elements_begin(),
N->elements_end());
2488void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2489 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2491 Record.push_back(
N->isDistinct());
2499void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2500 SmallVectorImpl<uint64_t> &Record,
2502 Record.push_back(
N->isDistinct());
2505 Record.push_back(
N->getLine());
2508 Record.push_back(
N->getAttributes());
2515void ModuleBitcodeWriter::writeDIImportedEntity(
2516 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2518 Record.push_back(
N->isDistinct());
2519 Record.push_back(
N->getTag());
2522 Record.push_back(
N->getLine());
2531unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2532 auto Abbv = std::make_shared<BitCodeAbbrev>();
2539void ModuleBitcodeWriter::writeNamedMetadata(
2540 SmallVectorImpl<uint64_t> &Record) {
2541 if (
M.named_metadata_empty())
2544 unsigned Abbrev = createNamedMetadataAbbrev();
2545 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2547 StringRef Str = NMD.getName();
2548 Record.append(Str.bytes_begin(), Str.bytes_end());
2553 for (
const MDNode *
N : NMD.operands())
2560unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2561 auto Abbv = std::make_shared<BitCodeAbbrev>();
2573void ModuleBitcodeWriter::writeMetadataStrings(
2575 if (Strings.
empty())
2583 SmallString<256> Blob;
2585 BitstreamWriter
W(Blob);
2605#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2606#include "llvm/IR/Metadata.def"
2610void ModuleBitcodeWriter::writeMetadataRecords(
2612 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2617#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2618#include "llvm/IR/Metadata.def"
2624 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2626 switch (
N->getMetadataID()) {
2629#define HANDLE_MDNODE_LEAF(CLASS) \
2630 case Metadata::CLASS##Kind: \
2632 write##CLASS(cast<CLASS>(N), Record, \
2633 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2635 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2637#include "llvm/IR/Metadata.def"
2648void ModuleBitcodeWriter::writeModuleMetadata() {
2649 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2653 SmallVector<uint64_t, 64>
Record;
2657 std::vector<unsigned> MDAbbrevs;
2660 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2661 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2662 createGenericDINodeAbbrev();
2664 auto Abbv = std::make_shared<BitCodeAbbrev>();
2668 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2670 Abbv = std::make_shared<BitCodeAbbrev>();
2674 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2696 std::vector<uint64_t> IndexPos;
2700 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2711 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2712 for (
auto &Elt : IndexPos) {
2713 auto EltDelta = Elt - PreviousValue;
2714 PreviousValue = Elt;
2723 writeNamedMetadata(Record);
2725 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2726 SmallVector<uint64_t, 4>
Record;
2728 pushGlobalMetadataAttachment(Record, GO);
2732 if (
F.isDeclaration() &&
F.hasMetadata())
2733 AddDeclAttachedMetadata(
F);
2734 for (
const GlobalIFunc &GI :
M.ifuncs())
2735 if (GI.hasMetadata())
2736 AddDeclAttachedMetadata(GI);
2739 for (
const GlobalVariable &GV :
M.globals())
2740 if (GV.hasMetadata())
2741 AddDeclAttachedMetadata(GV);
2746void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2751 SmallVector<uint64_t, 64>
Record;
2757void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2758 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2762 for (
const auto &
I : MDs) {
2768void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2771 SmallVector<uint64_t, 64>
Record;
2773 if (
F.hasMetadata()) {
2774 pushGlobalMetadataAttachment(Record,
F);
2782 for (
const BasicBlock &BB :
F)
2783 for (
const Instruction &
I : BB) {
2785 I.getAllMetadataOtherThanDebugLoc(MDs);
2788 if (MDs.
empty())
continue;
2792 for (
const auto &[ID, MD] : MDs) {
2803void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2804 SmallVector<uint64_t, 64>
Record;
2809 M.getMDKindNames(Names);
2811 if (Names.
empty())
return;
2815 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2816 Record.push_back(MDKindID);
2817 StringRef KName = Names[MDKindID];
2827void ModuleBitcodeWriter::writeOperandBundleTags() {
2835 M.getOperandBundleTags(Tags);
2842 SmallVector<uint64_t, 64>
Record;
2844 for (
auto Tag : Tags) {
2854void ModuleBitcodeWriter::writeSyncScopeNames() {
2856 M.getContext().getSyncScopeNames(SSNs);
2862 SmallVector<uint64_t, 64>
Record;
2863 for (
auto SSN : SSNs) {
2864 Record.append(SSN.begin(), SSN.end());
2872void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2874 if (FirstVal == LastVal)
return;
2878 unsigned AggregateAbbrev = 0;
2879 unsigned String8Abbrev = 0;
2880 unsigned CString7Abbrev = 0;
2881 unsigned CString6Abbrev = 0;
2885 auto Abbv = std::make_shared<BitCodeAbbrev>();
2889 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2892 Abbv = std::make_shared<BitCodeAbbrev>();
2896 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2898 Abbv = std::make_shared<BitCodeAbbrev>();
2902 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2904 Abbv = std::make_shared<BitCodeAbbrev>();
2908 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2911 SmallVector<uint64_t, 64>
Record;
2914 Type *LastTy =
nullptr;
2915 for (
unsigned i = FirstVal; i != LastVal; ++i) {
2916 const Value *
V = Vals[i].first;
2918 if (
V->getType() != LastTy) {
2919 LastTy =
V->getType();
2922 CONSTANTS_SETTYPE_ABBREV);
2929 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
2930 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
2933 StringRef AsmStr =
IA->getAsmString();
2938 StringRef ConstraintStr =
IA->getConstraintString();
2946 unsigned Code = -1U;
2947 unsigned AbbrevToUse = 0;
2948 if (
C->isNullValue()) {
2955 if (
IV->getBitWidth() <= 64) {
2959 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2965 if (BV->getBitWidth() <= 64) {
2969 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
2979 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2983 APInt api = CFP->getValueAPF().bitcastToAPInt();
2985 Record.push_back((p[1] << 48) | (p[0] >> 16));
2986 Record.push_back(p[0] & 0xffffLL);
2988 APInt api = CFP->getValueAPF().bitcastToAPInt();
2993 assert(0 &&
"Unknown FP type!");
2999 uint64_t NumElts = Str->getNumElements();
3001 if (Str->isCString()) {
3006 AbbrevToUse = String8Abbrev;
3010 for (
uint64_t i = 0; i != NumElts; ++i) {
3011 unsigned char V = Str->getElementAsInteger(i);
3013 isCStr7 &= (
V & 128) == 0;
3019 AbbrevToUse = CString6Abbrev;
3021 AbbrevToUse = CString7Abbrev;
3022 }
else if (
const ConstantDataSequential *CDS =
3025 Type *EltTy = CDS->getElementType();
3027 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3028 Record.push_back(CDS->getElementAsInteger(i));
3030 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3032 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3036 for (
const Value *
Op :
C->operands())
3038 AbbrevToUse = AggregateAbbrev;
3040 switch (
CE->getOpcode()) {
3047 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3049 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3059 case Instruction::FNeg: {
3060 assert(
CE->getNumOperands() == 1 &&
"Unknown constant expr!");
3069 case Instruction::GetElementPtr: {
3074 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3078 for (
const Value *
Op :
CE->operands()) {
3084 case Instruction::ExtractElement:
3091 case Instruction::InsertElement:
3098 case Instruction::ShuffleVector:
3103 if (
C->getType() ==
C->getOperand(0)->getType()) {
3140 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3147void ModuleBitcodeWriter::writeModuleConstants() {
3152 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3154 writeConstants(i, Vals.size(),
true);
3168bool ModuleBitcodeWriter::pushValueAndType(
const Value *V,
unsigned InstID,
3169 SmallVectorImpl<unsigned> &Vals) {
3173 if (ValID >= InstID) {
3180bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *V,
unsigned InstID,
3181 SmallVectorImpl<unsigned> &Vals) {
3182 bool IsMetadata =
V->getType()->isMetadataTy();
3190 return pushValueAndType(V, InstID, Vals);
3193void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3200 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3202 for (
auto &Input : Bundle.Inputs)
3203 pushValueOrMetadata(Input, InstID, Record);
3212void ModuleBitcodeWriter::pushValue(
const Value *V,
unsigned InstID,
3213 SmallVectorImpl<unsigned> &Vals) {
3218void ModuleBitcodeWriter::pushValueSigned(
const Value *V,
unsigned InstID,
3219 SmallVectorImpl<uint64_t> &Vals) {
3221 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3226void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3228 SmallVectorImpl<unsigned> &Vals) {
3230 unsigned AbbrevToUse = 0;
3232 switch (
I.getOpcode()) {
3236 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3237 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3242 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3243 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3249 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3250 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3251 pushValue(
I.getOperand(1), InstID, Vals);
3255 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3256 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3261 case Instruction::FNeg: {
3263 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3264 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3268 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3269 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3274 case Instruction::GetElementPtr: {
3276 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3280 for (
const Value *
Op :
I.operands())
3281 pushValueAndType(
Op, InstID, Vals);
3284 case Instruction::ExtractValue: {
3286 pushValueAndType(
I.getOperand(0), InstID, Vals);
3291 case Instruction::InsertValue: {
3293 pushValueAndType(
I.getOperand(0), InstID, Vals);
3294 pushValueAndType(
I.getOperand(1), InstID, Vals);
3299 case Instruction::Select: {
3301 pushValueAndType(
I.getOperand(1), InstID, Vals);
3302 pushValue(
I.getOperand(2), InstID, Vals);
3303 pushValueAndType(
I.getOperand(0), InstID, Vals);
3309 case Instruction::ExtractElement:
3311 pushValueAndType(
I.getOperand(0), InstID, Vals);
3312 pushValueAndType(
I.getOperand(1), InstID, Vals);
3314 case Instruction::InsertElement:
3316 pushValueAndType(
I.getOperand(0), InstID, Vals);
3317 pushValue(
I.getOperand(1), InstID, Vals);
3318 pushValueAndType(
I.getOperand(2), InstID, Vals);
3320 case Instruction::ShuffleVector:
3322 pushValueAndType(
I.getOperand(0), InstID, Vals);
3323 pushValue(
I.getOperand(1), InstID, Vals);
3327 case Instruction::ICmp:
3328 case Instruction::FCmp: {
3331 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3332 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3334 pushValue(
I.getOperand(1), InstID, Vals);
3340 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3345 case Instruction::Ret:
3348 unsigned NumOperands =
I.getNumOperands();
3349 if (NumOperands == 0)
3350 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3351 else if (NumOperands == 1) {
3352 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3353 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3355 for (
const Value *
Op :
I.operands())
3356 pushValueAndType(
Op, InstID, Vals);
3360 case Instruction::UncondBr: {
3362 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3366 case Instruction::CondBr: {
3368 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3372 pushValue(
II.getCondition(), InstID, Vals);
3374 case Instruction::Switch:
3379 pushValue(
SI.getCondition(), InstID, Vals);
3381 for (
auto Case :
SI.cases()) {
3387 case Instruction::IndirectBr:
3391 pushValue(
I.getOperand(0), InstID, Vals);
3396 case Instruction::Invoke: {
3399 FunctionType *FTy =
II->getFunctionType();
3401 if (
II->hasOperandBundles())
3402 writeOperandBundles(*
II, InstID);
3411 pushValueAndType(Callee, InstID, Vals);
3414 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3415 pushValue(
I.getOperand(i), InstID, Vals);
3418 if (FTy->isVarArg()) {
3419 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3420 pushValueAndType(
I.getOperand(i), InstID, Vals);
3424 case Instruction::Resume:
3426 pushValueAndType(
I.getOperand(0), InstID, Vals);
3428 case Instruction::CleanupRet: {
3431 pushValue(CRI.getCleanupPad(), InstID, Vals);
3432 if (CRI.hasUnwindDest())
3436 case Instruction::CatchRet: {
3439 pushValue(CRI.getCatchPad(), InstID, Vals);
3443 case Instruction::CleanupPad:
3444 case Instruction::CatchPad: {
3448 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3450 unsigned NumArgOperands = FuncletPad.arg_size();
3452 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3453 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3456 case Instruction::CatchSwitch: {
3460 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3462 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3464 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3467 if (CatchSwitch.hasUnwindDest())
3471 case Instruction::CallBr: {
3477 writeOperandBundles(*CBI, InstID);
3492 pushValueAndType(Callee, InstID, Vals);
3495 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3496 pushValue(
I.getOperand(i), InstID, Vals);
3499 if (FTy->isVarArg()) {
3500 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3501 pushValueAndType(
I.getOperand(i), InstID, Vals);
3505 case Instruction::Unreachable:
3507 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3510 case Instruction::PHI: {
3528 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3533 case Instruction::LandingPad: {
3544 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3549 case Instruction::Alloca: {
3555 using APV = AllocaPackedValues;
3557 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3559 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3561 EncodedAlign >> APV::AlignLower::Bits);
3568 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3573 case Instruction::Load: {
3575 if (LI.isAtomic()) {
3577 pushValueAndType(LI.getOperand(0), InstID, Vals);
3580 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3581 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3584 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3586 if (LI.isAtomic()) {
3588 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3589 if (LI.isElementwise())
3595 case Instruction::Store: {
3597 if (
SI.isAtomic()) {
3601 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3603 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3605 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3609 if (
SI.isAtomic()) {
3611 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3612 if (
SI.isElementwise())
3618 case Instruction::AtomicCmpXchg:
3620 pushValueAndType(
I.getOperand(0), InstID, Vals);
3621 pushValueAndType(
I.getOperand(1), InstID, Vals);
3622 pushValue(
I.getOperand(2), InstID, Vals);
3633 case Instruction::AtomicRMW:
3635 pushValueAndType(
I.getOperand(0), InstID, Vals);
3636 pushValueAndType(
I.getOperand(1), InstID, Vals);
3644 case Instruction::Fence:
3649 case Instruction::Call: {
3654 writeOperandBundles(CI, InstID);
3674 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3678 if (FTy->isVarArg()) {
3679 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3684 case Instruction::VAArg:
3687 pushValue(
I.getOperand(0), InstID, Vals);
3690 case Instruction::Freeze:
3692 pushValueAndType(
I.getOperand(0), InstID, Vals);
3702void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3703 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3708 VSTOffset -= bitcodeStartBit();
3709 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3713 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3717 auto Abbv = std::make_shared<BitCodeAbbrev>();
3721 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3726 if (
F.isDeclaration())
3733 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3734 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3738 Record[1] = BitcodeIndex / 32 + 1;
3747void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3748 const ValueSymbolTable &VST) {
3756 SmallVector<uint64_t, 64> NameVals;
3762 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3771 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3775 AbbrevToUse = VST_ENTRY_6_ABBREV;
3777 AbbrevToUse = VST_ENTRY_7_ABBREV;
3780 for (
const auto P :
Name.getKey())
3784 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3791void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3792 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3799 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3804void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3806 "Expected to be preserving use-list order");
3808 auto hasMore = [&]() {
3824void ModuleBitcodeWriter::writeFunction(
3826 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3843 unsigned CstStart, CstEnd;
3845 writeConstants(CstStart, CstEnd,
false);
3848 writeFunctionMetadata(
F);
3851 unsigned InstID = CstEnd;
3853 bool NeedsMetadataAttachment =
F.hasMetadata();
3855 DILocation *LastDL =
nullptr;
3856 SmallSetVector<Function *, 4> BlockAddressUsers;
3859 for (
const BasicBlock &BB :
F) {
3860 for (
const Instruction &
I : BB) {
3861 writeInstruction(
I, InstID, Vals);
3863 if (!
I.getType()->isVoidTy())
3867 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3870 if (DILocation *
DL =
I.getDebugLoc()) {
3883 FUNCTION_DEBUG_LOC_ABBREV);
3893 if (
I.hasDbgRecords()) {
3897 auto PushValueOrMetadata = [&Vals, InstID,
3900 "RawLocation unexpectedly null in DbgVariableRecord");
3902 SmallVector<unsigned, 2> ValAndType;
3906 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3920 for (DbgRecord &DR :
I.DebugMarker->getDbgRecordRange()) {
3946 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3970 SmallPtrSet<Value *, 8> Visited{BA};
3971 while (!Worklist.
empty()) {
3973 for (User *U :
V->users()) {
3979 Visited.
insert(U).second)
3986 if (!BlockAddressUsers.
empty()) {
3995 if (
auto *Symtab =
F.getValueSymbolTable())
3996 writeFunctionLevelValueSymbolTable(*Symtab);
3998 if (NeedsMetadataAttachment)
3999 writeFunctionMetadataAttachment(
F);
4001 writeUseListBlock(&
F);
4007void ModuleBitcodeWriter::writeBlockInfo() {
4020 auto Abbv = std::make_shared<BitCodeAbbrev>();
4031 auto Abbv = std::make_shared<BitCodeAbbrev>();
4041 auto Abbv = std::make_shared<BitCodeAbbrev>();
4051 auto Abbv = std::make_shared<BitCodeAbbrev>();
4057 VST_BBENTRY_6_ABBREV)
4062 auto Abbv = std::make_shared<BitCodeAbbrev>();
4064 Abbv->Add(TypeAbbrevOp);
4066 CONSTANTS_SETTYPE_ABBREV)
4071 auto Abbv = std::make_shared<BitCodeAbbrev>();
4075 CONSTANTS_INTEGER_ABBREV)
4080 auto Abbv = std::make_shared<BitCodeAbbrev>();
4084 CONSTANTS_BYTE_ABBREV)
4089 auto Abbv = std::make_shared<BitCodeAbbrev>();
4097 CONSTANTS_CE_CAST_Abbrev)
4101 auto Abbv = std::make_shared<BitCodeAbbrev>();
4104 CONSTANTS_NULL_Abbrev)
4111 auto Abbv = std::make_shared<BitCodeAbbrev>();
4113 Abbv->Add(ValAbbrevOp);
4114 Abbv->Add(TypeAbbrevOp);
4118 FUNCTION_INST_LOAD_ABBREV)
4122 auto Abbv = std::make_shared<BitCodeAbbrev>();
4124 Abbv->Add(ValAbbrevOp);
4125 Abbv->Add(ValAbbrevOp);
4129 FUNCTION_INST_STORE_ABBREV)
4133 auto Abbv = std::make_shared<BitCodeAbbrev>();
4135 Abbv->Add(ValAbbrevOp);
4138 FUNCTION_INST_UNOP_ABBREV)
4142 auto Abbv = std::make_shared<BitCodeAbbrev>();
4144 Abbv->Add(ValAbbrevOp);
4148 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4152 auto Abbv = std::make_shared<BitCodeAbbrev>();
4154 Abbv->Add(ValAbbrevOp);
4155 Abbv->Add(ValAbbrevOp);
4158 FUNCTION_INST_BINOP_ABBREV)
4162 auto Abbv = std::make_shared<BitCodeAbbrev>();
4164 Abbv->Add(ValAbbrevOp);
4165 Abbv->Add(ValAbbrevOp);
4169 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4173 auto Abbv = std::make_shared<BitCodeAbbrev>();
4175 Abbv->Add(ValAbbrevOp);
4176 Abbv->Add(TypeAbbrevOp);
4179 FUNCTION_INST_CAST_ABBREV)
4183 auto Abbv = std::make_shared<BitCodeAbbrev>();
4185 Abbv->Add(ValAbbrevOp);
4186 Abbv->Add(TypeAbbrevOp);
4190 FUNCTION_INST_CAST_FLAGS_ABBREV)
4195 auto Abbv = std::make_shared<BitCodeAbbrev>();
4198 FUNCTION_INST_RET_VOID_ABBREV)
4202 auto Abbv = std::make_shared<BitCodeAbbrev>();
4204 Abbv->Add(ValAbbrevOp);
4206 FUNCTION_INST_RET_VAL_ABBREV)
4210 auto Abbv = std::make_shared<BitCodeAbbrev>();
4213 Abbv->Add(ValAbbrevOp);
4215 FUNCTION_INST_BR_UNCOND_ABBREV)
4219 auto Abbv = std::make_shared<BitCodeAbbrev>();
4222 Abbv->Add(ValAbbrevOp);
4223 Abbv->Add(ValAbbrevOp);
4224 Abbv->Add(ValAbbrevOp);
4226 FUNCTION_INST_BR_COND_ABBREV)
4230 auto Abbv = std::make_shared<BitCodeAbbrev>();
4233 FUNCTION_INST_UNREACHABLE_ABBREV)
4237 auto Abbv = std::make_shared<BitCodeAbbrev>();
4240 Abbv->Add(TypeAbbrevOp);
4242 Abbv->Add(ValAbbrevOp);
4244 FUNCTION_INST_GEP_ABBREV)
4248 auto Abbv = std::make_shared<BitCodeAbbrev>();
4250 Abbv->Add(ValAbbrevOp);
4251 Abbv->Add(ValAbbrevOp);
4254 FUNCTION_INST_CMP_ABBREV)
4258 auto Abbv = std::make_shared<BitCodeAbbrev>();
4260 Abbv->Add(ValAbbrevOp);
4261 Abbv->Add(ValAbbrevOp);
4265 FUNCTION_INST_CMP_FLAGS_ABBREV)
4269 auto Abbv = std::make_shared<BitCodeAbbrev>();
4274 Abbv->Add(ValAbbrevOp);
4276 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4280 auto Abbv = std::make_shared<BitCodeAbbrev>();
4291 FUNCTION_DEBUG_LOC_ABBREV)
4299void IndexBitcodeWriter::writeModStrings() {
4305 auto Abbv = std::make_shared<BitCodeAbbrev>();
4310 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4313 Abbv = std::make_shared<BitCodeAbbrev>();
4318 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4321 Abbv = std::make_shared<BitCodeAbbrev>();
4326 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4329 Abbv = std::make_shared<BitCodeAbbrev>();
4336 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4339 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4341 const auto &Hash = MPSE.
getValue();
4343 unsigned AbbrevToUse = Abbrev8Bit;
4345 AbbrevToUse = Abbrev6Bit;
4347 AbbrevToUse = Abbrev7Bit;
4349 auto ModuleId = ModuleIdMap.
size();
4350 ModuleIdMap[
Key] = ModuleId;
4360 Vals.
assign(Hash.begin(), Hash.end());
4372template <
typename Fn>
4376 if (!FS->type_tests().empty())
4381 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4386 for (
auto &VF : VFs) {
4387 Record.push_back(VF.GUID);
4388 Record.push_back(VF.Offset);
4394 FS->type_test_assume_vcalls());
4396 FS->type_checked_load_vcalls());
4398 auto WriteConstVCallVec = [&](
uint64_t Ty,
4400 for (
auto &VC : VCs) {
4402 Record.push_back(VC.VFunc.GUID);
4403 Record.push_back(VC.VFunc.Offset);
4410 FS->type_test_assume_const_vcalls());
4412 FS->type_checked_load_const_vcalls());
4422 if (!FS->paramAccesses().empty()) {
4424 for (
auto &Arg : FS->paramAccesses()) {
4425 size_t UndoSize =
Record.size();
4426 Record.push_back(Arg.ParamNo);
4427 WriteRange(Arg.Use);
4428 Record.push_back(Arg.Calls.size());
4429 for (
auto &
Call : Arg.Calls) {
4431 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4438 Record.push_back(*ValueID);
4439 WriteRange(
Call.Offsets);
4450 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4451 if (!FS->type_tests().empty())
4452 for (
auto &TT : FS->type_tests())
4453 ReferencedTypeIds.insert(TT);
4455 auto GetReferencedTypesFromVFuncIdVec =
4457 for (
auto &VF : VFs)
4458 ReferencedTypeIds.insert(VF.GUID);
4461 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4462 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4464 auto GetReferencedTypesFromConstVCallVec =
4466 for (
auto &VC : VCs)
4467 ReferencedTypeIds.insert(VC.VFunc.GUID);
4470 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4471 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4507 NameVals.
push_back(Summary.TTRes.TheKind);
4508 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4509 NameVals.
push_back(Summary.TTRes.AlignLog2);
4510 NameVals.
push_back(Summary.TTRes.SizeM1);
4511 NameVals.
push_back(Summary.TTRes.BitMask);
4512 NameVals.
push_back(Summary.TTRes.InlineBits);
4514 for (
auto &W : Summary.WPDRes)
4526 for (
auto &
P : Summary) {
4528 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4542 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4543 for (
auto &AI : FS->allocs()) {
4544 for (
auto &MIB : AI.MIBs) {
4546 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4547 for (
auto Id : MIB.StackIdIndices)
4548 StackIdIndices.
push_back(GetStackIndex(Id));
4550 CallStacks.insert({CallStacks.size(), StackIdIndices});
4563 assert(!CallStacks.empty());
4569 Builder.
build(std::move(CallStacks),
nullptr,
4573 return Builder.takeCallStackPos();
4578 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4579 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4580 std::function<
unsigned(
unsigned)> GetStackIndex,
4581 bool WriteContextSizeInfoIndex,
4586 for (
auto &CI : FS->callsites()) {
4590 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4591 Record.push_back(GetValueID(CI.Callee));
4593 Record.push_back(CI.StackIdIndices.size());
4594 Record.push_back(CI.Clones.size());
4596 for (
auto Id : CI.StackIdIndices)
4597 Record.push_back(GetStackIndex(Id));
4605 for (
auto &AI : FS->allocs()) {
4609 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4610 Record.push_back(AI.MIBs.size());
4612 Record.push_back(AI.Versions.size());
4613 for (
auto &MIB : AI.MIBs) {
4620 assert(CallStackCount <= CallStackPos.
size());
4621 Record.push_back(CallStackPos[CallStackCount++]);
4626 assert(AI.ContextSizeInfos.empty() ||
4627 AI.ContextSizeInfos.size() == AI.MIBs.size());
4629 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4637 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4638 for (
auto &Infos : AI.ContextSizeInfos) {
4639 Record.push_back(Infos.size());
4640 for (
auto [FullStackId, TotalSize] : Infos) {
4647 Record.push_back(TotalSize);
4665void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4666 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4667 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4668 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4669 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4676 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4680 auto SpecialRefCnts =
FS->specialRefCounts();
4685 NameVals.
push_back(SpecialRefCnts.first);
4686 NameVals.
push_back(SpecialRefCnts.second);
4688 for (
auto &RI :
FS->refs())
4691 for (
auto &ECI :
FS->calls()) {
4692 NameVals.
push_back(getValueId(ECI.first));
4701 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4703 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4704 [&](
unsigned I) {
return I; },
4705 true, CallStackPos, CallStackCount);
4710void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4711 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4712 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4717 auto VI =
Index->getValueInfo(GUID);
4718 if (!VI ||
VI.getSummaryList().empty()) {
4724 auto *
Summary =
VI.getSummaryList()[0].get();
4730 auto VTableFuncs =
VS->vTableFuncs();
4731 if (!VTableFuncs.empty())
4734 unsigned SizeBeforeRefs = NameVals.
size();
4735 for (
auto &RI :
VS->refs())
4741 if (VTableFuncs.empty())
4746 for (
auto &
P : VTableFuncs) {
4752 FSModVTableRefsAbbrev);
4759void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4762 bool IsThinLTO =
true;
4765 IsThinLTO = MD->getZExtValue();
4777 if (
Index->enableSplitLTOUnit())
4779 if (
Index->hasUnifiedLTO())
4789 auto Abbv = std::make_shared<BitCodeAbbrev>();
4795 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4797 for (
const auto &GVI : valueIds()) {
4799 ArrayRef<uint32_t>{GVI.second,
4800 static_cast<uint32_t
>(GVI.first >> 32),
4801 static_cast<uint32_t
>(GVI.first)},
4805 if (!
Index->stackIds().empty()) {
4806 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4813 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4814 SmallVector<uint32_t> Vals;
4816 for (
auto Id :
Index->stackIds()) {
4817 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4818 Vals.
push_back(
static_cast<uint32_t
>(Id));
4823 unsigned ContextIdAbbvId = 0;
4826 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4838 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4842 Abbv = std::make_shared<BitCodeAbbrev>();
4854 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4857 Abbv = std::make_shared<BitCodeAbbrev>();
4863 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4866 Abbv = std::make_shared<BitCodeAbbrev>();
4874 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4877 Abbv = std::make_shared<BitCodeAbbrev>();
4882 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4885 Abbv = std::make_shared<BitCodeAbbrev>();
4892 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4894 Abbv = std::make_shared<BitCodeAbbrev>();
4900 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4902 Abbv = std::make_shared<BitCodeAbbrev>();
4909 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4911 Abbv = std::make_shared<BitCodeAbbrev>();
4916 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4923 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
4934 ValueInfo
VI =
Index->getValueInfo(GUID);
4935 if (!VI ||
VI.getSummaryList().empty()) {
4938 if (!
F.isDeclaration())
4940 " to have an associated value info.");
4943 auto *
Summary =
VI.getSummaryList()[0].get();
4946 FS, [](
unsigned I) {
return I; }, CallStacks);
4950 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
4951 if (!CallStacks.
empty()) {
4959 SmallVector<uint64_t, 64> NameVals;
4970 ValueInfo
VI =
Index->getValueInfo(GUID);
4971 if (!VI ||
VI.getSummaryList().empty()) {
4977 auto *
Summary =
VI.getSummaryList()[0].get();
4978 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
4979 FSCallsProfileAbbrev, CallsiteAbbrev,
4980 AllocAbbrev, ContextIdAbbvId,
F,
4981 CallStackPos, CallStackCount);
4986 for (
const GlobalVariable &
G :
M.globals())
4987 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
4988 FSModVTableRefsAbbrev);
4990 for (
const GlobalAlias &
A :
M.aliases()) {
4991 auto *Aliasee =
A.getAliaseeObject();
5007 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5011 TypeIdCompatibleVtableAbbrev);
5015 if (
Index->getBlockCount())
5017 ArrayRef<uint64_t>{
Index->getBlockCount()});
5022void ModuleBitcodeWriterBase::writeGUIDList() {
5024 const size_t Max = Vals.size();
5026 std::vector<GlobalValue::GUID> GUIDs(Max, 0);
5027 for (
const GlobalValue &GV :
M.global_values()) {
5028 auto MaybeGUID = GV.getGUIDIfAssigned();
5031 auto GUID = *MaybeGUID;
5034 GUIDs[ValueID] =
GUID;
5037 auto Abbv = std::make_shared<BitCodeAbbrev>();
5041 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5043 SmallVector<uint32_t> RecordVals;
5045 for (
auto GUID : GUIDs) {
5046 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5047 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5054void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5063 auto Abbv = std::make_shared<BitCodeAbbrev>();
5069 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5071 for (
const auto &GVI : valueIds()) {
5073 ArrayRef<uint32_t>{GVI.second,
5074 static_cast<uint32_t
>(GVI.first >> 32),
5075 static_cast<uint32_t
>(GVI.first)},
5081 if (!StackIds.empty()) {
5082 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5089 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5090 SmallVector<uint32_t> Vals;
5091 Vals.
reserve(StackIds.size() * 2);
5092 for (
auto Id : StackIds) {
5093 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5094 Vals.
push_back(
static_cast<uint32_t
>(Id));
5100 Abbv = std::make_shared<BitCodeAbbrev>();
5114 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5117 Abbv = std::make_shared<BitCodeAbbrev>();
5124 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5127 Abbv = std::make_shared<BitCodeAbbrev>();
5133 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5135 Abbv = std::make_shared<BitCodeAbbrev>();
5143 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5145 Abbv = std::make_shared<BitCodeAbbrev>();
5156 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5158 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5159 if (DecSummaries ==
nullptr)
5161 return DecSummaries->
count(GVS);
5169 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5171 SmallVector<uint64_t, 64> NameVals;
5175 std::set<GlobalValue::GUID> ReferencedTypeIds;
5179 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5189 NameVals.
push_back(S.getOriginalName());
5194 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5196 Abbv = std::make_shared<BitCodeAbbrev>();
5201 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5208 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5209 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5215 GlobalValueSummary *S =
I.second;
5228 return StackIdIndicesToIndex[
I];
5234 if (!CallStacks.
empty()) {
5244 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5245 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5246 GlobalValueSummary *S =
I.second;
5248 DefOrUseGUIDs.
insert(
I.first);
5249 for (
const ValueInfo &VI : S->
refs())
5250 DefOrUseGUIDs.
insert(
VI.getGUID());
5252 auto ValueId = getValueId(
I.first);
5254 SummaryToValueIdMap[S] = *ValueId;
5272 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5276 for (
auto &RI :
VS->refs()) {
5277 auto RefValueId = getValueId(RI.getGUID());
5287 MaybeEmitOriginalName(*S);
5291 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5293 return std::nullopt;
5294 return getValueId(
VI.getGUID());
5303 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5316 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5317 for (
auto &RI :
FS->refs()) {
5318 auto RefValueId = getValueId(RI.getGUID());
5322 if (RI.isReadOnly())
5324 else if (RI.isWriteOnly())
5328 NameVals[6] =
Count;
5329 NameVals[7] = RORefCnt;
5330 NameVals[8] = WORefCnt;
5332 for (
auto &EI :
FS->calls()) {
5335 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5344 FSCallsProfileAbbrev);
5348 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5351 [&](
const ValueInfo &VI) ->
unsigned {
5352 std::optional<unsigned> ValueID = GetValueId(VI);
5367 return StackIdIndicesToIndex[
I];
5369 false, CallStackPos, CallStackCount);
5371 MaybeEmitOriginalName(*S);
5374 for (
auto *AS : Aliases) {
5375 auto AliasValueId = SummaryToValueIdMap[AS];
5384 auto AliaseeValueId =
5391 MaybeEmitOriginalName(*AS);
5399 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5401 if (CfiIndex.
empty())
5405 for (StringRef Name : Names)
5408 if (Functions.
empty())
5411 for (
const auto &Record : Functions) {
5426 for (
auto &
T : ReferencedTypeIds) {
5427 auto TidIter =
Index.typeIds().equal_range(
T);
5428 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5436 if (
Index.getBlockCount())
5438 ArrayRef<uint64_t>{
Index.getBlockCount()});
5449 auto Abbv = std::make_shared<BitCodeAbbrev>();
5453 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5455 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5458 Abbv = std::make_shared<BitCodeAbbrev>();
5461 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5467void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5472 Hasher.
update(ArrayRef<uint8_t>(
5473 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5474 std::array<uint8_t, 20> Hash = Hasher.
result();
5475 for (
int Pos = 0; Pos < 20; Pos += 4) {
5488void ModuleBitcodeWriter::write() {
5496 writeModuleVersion();
5505 writeAttributeGroupTable();
5508 writeAttributeTable();
5517 writeModuleConstants();
5520 writeModuleMetadataKinds();
5523 writeModuleMetadata();
5527 writeUseListBlock(
nullptr);
5529 writeOperandBundleTags();
5530 writeSyncScopeNames();
5533 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5535 if (!
F.isDeclaration())
5536 writeFunction(
F, FunctionToBitcodeIndex);
5541 writePerModuleGlobalValueSummary();
5543 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5571 unsigned CPUType = ~0U;
5578 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5579 DARWIN_CPU_TYPE_X86 = 7,
5580 DARWIN_CPU_TYPE_ARM = 12,
5581 DARWIN_CPU_TYPE_POWERPC = 18
5586 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5588 CPUType = DARWIN_CPU_TYPE_X86;
5590 CPUType = DARWIN_CPU_TYPE_POWERPC;
5592 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5594 CPUType = DARWIN_CPU_TYPE_ARM;
5598 "Expected header size to be reserved");
5603 unsigned Position = 0;
5611 while (Buffer.
size() & 15)
5618 Stream.
Emit((
unsigned)
'B', 8);
5619 Stream.
Emit((
unsigned)
'C', 8);
5620 Stream.
Emit(0x0, 4);
5621 Stream.
Emit(0xC, 4);
5622 Stream.
Emit(0xE, 4);
5623 Stream.
Emit(0xD, 4);
5641 auto Abbv = std::make_shared<BitCodeAbbrev>();
5644 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5652 assert(!WroteStrtab && !WroteSymtab);
5658 if (M->getModuleInlineAsm().empty())
5662 const Triple TT(M->getTargetTriple());
5664 if (!
T || !
T->hasMCAsmParser())
5686 std::vector<char> Strtab;
5687 StrtabBuilder.finalizeInOrder();
5688 Strtab.resize(StrtabBuilder.getSize());
5689 StrtabBuilder.write((
uint8_t *)Strtab.data());
5692 {Strtab.data(), Strtab.size()});
5703 bool ShouldPreserveUseListOrder,
5712 assert(M.isMaterialized());
5713 Mods.push_back(
const_cast<Module *
>(&M));
5715 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5716 ShouldPreserveUseListOrder, Index,
5717 GenerateHash, ModHash);
5718 ModuleWriter.write();
5725 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5726 ModuleToSummariesForIndex);
5727 IndexWriter.write();
5732 bool ShouldPreserveUseListOrder,
5736 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5738 Writer.writeSymtab();
5739 Writer.writeStrtab();
5741 Triple TT(M.getTargetTriple());
5742 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5760void IndexBitcodeWriter::write() {
5763 writeModuleVersion();
5769 writeCombinedGlobalValueSummary();
5786 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5795class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5805 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5807 ModHash(&ModHash) {}
5812 void writeSimplifiedModuleInfo();
5822void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5834 auto Abbv = std::make_shared<BitCodeAbbrev>();
5837 Abbv->Add(AbbrevOpToUse);
5838 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5840 for (
const auto P :
M.getSourceFileName())
5906void ThinLinkBitcodeWriter::write() {
5909 writeModuleVersion();
5911 writeSimplifiedModuleInfo();
5913 writePerModuleGlobalValueSummary();
5930 assert(M.isMaterialized());
5931 Mods.push_back(
const_cast<Module *
>(&M));
5933 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5935 ThinLinkWriter.write();
5956 switch (
T.getObjectFormat()) {
5958 return "__LLVM,__bitcode";
5983 switch (
T.getObjectFormat()) {
5985 return "__LLVM,__cmdline";
6011 const std::vector<uint8_t> &CmdArgs) {
6016 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6018 for (
auto *GV : UsedGlobals) {
6019 if (GV->getName() !=
"llvm.embedded.module" &&
6020 GV->getName() !=
"llvm.cmdline")
6025 Used->eraseFromParent();
6030 Triple T(M.getTargetTriple());
6059 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6060 assert(Old->hasZeroLiveUses() &&
6061 "llvm.embedded.module can only be used once in llvm.compiler.used");
6063 Old->eraseFromParent();
6065 GV->
setName(
"llvm.embedded.module");
6083 assert(Old->hasZeroLiveUses() &&
6084 "llvm.cmdline can only be used once in llvm.compiler.used");
6086 Old->eraseFromParent();
6092 if (UsedArray.
empty())
6100 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 writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static cl::opt< bool > PreserveBitcodeUseListOrder("preserve-bc-uselistorder", cl::Hidden, cl::init(true), cl::desc("Preserve use-list order when writing LLVM bitcode."))
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< uint32_t > FlushThreshold("bitcode-flush-threshold", cl::Hidden, cl::init(512), cl::desc("The threshold (unit M) for flushing LLVM bitcode."))
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
Machine Check Debug Module
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Class for arbitrary precision integers.
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
int64_t getSExtValue() const
Get sign extended value.
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
bool hasAttributes() const
Return true if attributes exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI ~BitcodeWriter()
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
bool isDbgDeclareValue() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false 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.
ForceSummaryHotnessType
Types for -force-summary-edges-cold debugging option.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type size() const
Determine the number of elements in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool isFP128Ty() const
Return true if this is 'fp128'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_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_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.
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.
FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName