65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
81 if (Context.shouldDiscardValueNames())
84 "Can't read textual IR with a Context that discards named Values");
87 if (parseTargetDefinitions(DataLayoutCallback))
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
97 restoreParsingState(Slots);
101 if (parseType(Ty) || parseConstantValue(Ty,
C))
104 return error(Lex.getLoc(),
"expected end of string");
110 restoreParsingState(Slots);
114 SMLoc Start = Lex.getLoc();
118 SMLoc End = Lex.getLoc();
126 restoreParsingState(Slots);
130 SMLoc Start = Lex.getLoc();
132 bool Status = parseDIExpressionBody(Result,
false);
133 SMLoc End = Lex.getLoc();
139void LLParser::restoreParsingState(
const SlotMapping *Slots) {
146 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
147 for (
const auto &
I : Slots->
Types)
148 NumberedTypes.insert(
149 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
162 if (MD->isTemporary())
166 assert(
II->use_empty() &&
"Cannot have uses");
167 II->eraseFromParent();
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](
unsigned MDKind, MDNode *
Node) {
return Node->isTemporary(); };
178 for (Function &
F : *M) {
179 F.eraseMetadataIf(Pred);
181 I.eraseMetadataIf(Pred);
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
194 if (
Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(
ID);
196 ForwardRefMDNodes.erase(
ID);
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
213 for (
const auto &RAG : ForwardRefAttrGroups) {
215 const std::vector<unsigned> &
Attrs = RAG.second;
216 AttrBuilder
B(Context);
218 for (
const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(Attr);
220 if (R != NumberedAttrBuilders.end())
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(Context);
233 if (MaybeAlign
A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*
A);
235 FnAttrs.removeAttribute(Attribute::Alignment);
238 AS = AS.addFnAttributes(Context, FnAttrs);
239 Fn->setAttributes(AS);
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(Context);
245 AS = AS.addFnAttributes(Context, FnAttrs);
246 CI->setAttributes(AS);
248 AttributeList AS =
II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(Context);
252 AS = AS.addFnAttributes(Context, FnAttrs);
253 II->setAttributes(AS);
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(Context);
259 AS = AS.addFnAttributes(Context, FnAttrs);
260 CBI->setAttributes(AS);
262 AttrBuilder
Attrs(M->getContext(), GV->getAttributes());
272 if (!ForwardRefBlockAddresses.empty())
273 return error(ForwardRefBlockAddresses.begin()->first.Loc,
274 "expected function name in blockaddress");
276 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV =
nullptr;
280 GV = M->getNamedValue(GVRef.
StrVal);
282 GV = NumberedVals.get(GVRef.
UIntVal);
287 "' referenced by dso_local_equivalent");
291 "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
295 FwdRef->replaceAllUsesWith(Equiv);
296 FwdRef->eraseFromParent();
303 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
307 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
314 for (
const auto &NT : NumberedTypes)
315 if (
NT.second.second.isValid())
317 "use of undefined type '%" + Twine(
NT.first) +
"'");
319 for (
const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(TypeInfo.second,
322 "use of undefined type named '" + Name +
"'");
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first +
"'");
341 if (!CB || !CB->isCallee(&U))
342 return error(
Info.second,
"intrinsic can only be used as callee");
356 return error(
Info.second,
"unknown intrinsic '" + Name +
"'");
357 return error(
Info.second,
"invalid intrinsic signature");
367 Info.first->eraseFromParent();
368 ForwardRefVals.erase(Name);
377 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
378 FunctionType *FTy =
nullptr;
379 for (Use &U :
V->uses()) {
381 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
383 FTy = CB->getFunctionType();
391 Type *Ty = GetCommonFunctionType(
Info.first);
399 GV =
new GlobalVariable(*M, Ty,
false,
402 Info.first->replaceAllUsesWith(GV);
403 Info.first->eraseFromParent();
404 ForwardRefVals.erase(Name);
407 if (!ForwardRefVals.empty())
408 return error(ForwardRefVals.begin()->second.second,
409 "use of undefined value '@" + ForwardRefVals.begin()->first +
412 if (!ForwardRefValIDs.empty())
413 return error(ForwardRefValIDs.begin()->second.second,
414 "use of undefined value '@" +
415 Twine(ForwardRefValIDs.begin()->first) +
"'");
418 dropUnknownMetadataReferences();
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) +
"'");
426 for (
auto &
N : NumberedMetadata) {
427 if (
N.second && !
N.second->isResolved())
428 N.second->resolveCycles();
432 NewDistinctSPs.clear();
434 for (
auto *Inst : InstsWithTBAATag) {
435 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
438 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
441 if (MD != UpgradedMD)
442 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
451 if (UpgradeDebugInfo)
464 Slots->GlobalValues = std::move(NumberedVals);
465 Slots->MetadataNodes = std::move(NumberedMetadata);
466 for (
const auto &
I : NamedTypes)
467 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
468 for (
const auto &
I : NumberedTypes)
469 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
475bool LLParser::validateEndOfIndex() {
479 if (!ForwardRefValueInfos.empty())
480 return error(ForwardRefValueInfos.begin()->second.front().second,
481 "use of undefined summary '^" +
482 Twine(ForwardRefValueInfos.begin()->first) +
"'");
484 if (!ForwardRefAliasees.empty())
485 return error(ForwardRefAliasees.begin()->second.front().second,
486 "use of undefined summary '^" +
487 Twine(ForwardRefAliasees.begin()->first) +
"'");
489 if (!ForwardRefTypeIds.empty())
490 return error(ForwardRefTypeIds.begin()->second.front().second,
491 "use of undefined type id summary '^" +
492 Twine(ForwardRefTypeIds.begin()->first) +
"'");
506 std::string TentativeDLStr = M->getDataLayoutStr();
511 switch (Lex.getKind()) {
513 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
517 if (parseSourceFileName())
526 if (
auto LayoutOverride =
527 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
528 TentativeDLStr = *LayoutOverride;
534 M->setDataLayout(MaybeDL.
get());
538bool LLParser::parseTopLevelEntities() {
542 switch (Lex.getKind()) {
546 if (parseSummaryEntry())
550 if (parseSourceFileName())
560 switch (Lex.getKind()) {
562 return tokError(
"expected top-level entity");
573 if (parseModuleAsm())
577 if (parseUnnamedType())
581 if (parseNamedType())
585 if (parseUnnamedGlobal())
589 if (parseNamedGlobal())
594 if (parseStandaloneMetadata())
598 if (parseSummaryEntry())
602 if (parseNamedMetadata())
606 if (parseUnnamedAttrGrp())
610 if (parseUseListOrder())
614 if (parseUseListOrderBB())
623bool LLParser::parseModuleAsm() {
629 parseStringConstant(AsmStr))
632 M->appendModuleInlineAsm(AsmStr);
639bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
645 return tokError(
"unknown target property");
648 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
649 parseStringConstant(Str))
651 M->setTargetTriple(Triple(std::move(Str)));
655 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
657 DLStrLoc = Lex.getLoc();
658 if (parseStringConstant(TentativeDLStr))
666bool LLParser::parseSourceFileName() {
669 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
670 parseStringConstant(SourceFileName))
673 M->setSourceFileName(SourceFileName);
679bool LLParser::parseUnnamedType() {
680 LocTy TypeLoc = Lex.getLoc();
681 unsigned TypeID = Lex.getUIntVal();
684 if (parseToken(
lltok::equal,
"expected '=' after name") ||
689 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
693 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
695 return error(TypeLoc,
"non-struct types may not be recursive");
697 Entry.second = SMLoc();
705bool LLParser::parseNamedType() {
706 std::string
Name = Lex.getStrVal();
707 LocTy NameLoc = Lex.getLoc();
710 if (parseToken(
lltok::equal,
"expected '=' after name") ||
715 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
719 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
721 return error(NameLoc,
"non-struct types may not be recursive");
723 Entry.second = SMLoc();
731bool LLParser::parseDeclare() {
735 std::vector<std::pair<unsigned, MDNode *>> MDs;
739 if (parseMetadataAttachment(MDK,
N))
741 MDs.push_back({MDK,
N});
745 unsigned FunctionNumber = -1;
746 SmallVector<unsigned> UnnamedArgNums;
747 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
750 F->addMetadata(MD.first, *MD.second);
756bool LLParser::parseDefine() {
759 FileLoc FunctionStart = getTokLineColumnPos();
763 unsigned FunctionNumber = -1;
764 SmallVector<unsigned> UnnamedArgNums;
766 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
767 parseOptionalFunctionMetadata(*
F) ||
768 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
770 ParserContext->addFunctionLocation(
771 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
779bool LLParser::parseGlobalType(
bool &IsConstant) {
786 return tokError(
"expected 'global' or 'constant'");
792bool LLParser::parseOptionalUnnamedAddr(
813bool LLParser::parseUnnamedGlobal() {
816 LocTy NameLoc = Lex.getLoc();
820 VarID = Lex.getUIntVal();
821 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
825 if (parseToken(
lltok::equal,
"expected '=' after name"))
828 VarID = NumberedVals.getNext();
832 unsigned Linkage, Visibility, DLLStorageClass;
836 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
838 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
841 switch (Lex.getKind()) {
843 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
844 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
847 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
848 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
857bool LLParser::parseNamedGlobal() {
859 LocTy NameLoc = Lex.getLoc();
860 std::string
Name = Lex.getStrVal();
864 unsigned Linkage, Visibility, DLLStorageClass;
868 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
869 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
871 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
874 switch (Lex.getKind()) {
876 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
877 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
880 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
881 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
885bool LLParser::parseComdat() {
887 std::string
Name = Lex.getStrVal();
888 LocTy NameLoc = Lex.getLoc();
895 return tokError(
"expected comdat type");
898 switch (Lex.getKind()) {
900 return tokError(
"unknown selection kind");
922 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
923 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
926 if (
I != ComdatSymTab.
end())
929 C = M->getOrInsertComdat(Name);
930 C->setSelectionKind(SK);
937bool LLParser::parseMDString(
MDString *&Result) {
939 if (parseStringConstant(Str))
947bool LLParser::parseMDNodeID(
MDNode *&Result) {
949 LocTy IDLoc = Lex.getLoc();
951 if (parseUInt32(MID))
955 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
962 auto &FwdRef = ForwardRefMDNodes[MID];
965 Result = FwdRef.first.get();
966 It->second.reset(Result);
972bool LLParser::parseNamedMetadata() {
974 std::string
Name = Lex.getStrVal();
982 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
990 Lex.getStrVal() ==
"DIExpression") {
991 if (parseDIExpression(
N,
false))
996 Lex.getStrVal() ==
"DIArgList") {
997 return tokError(
"found DIArgList outside of function");
1005 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1010bool LLParser::parseStandaloneMetadata() {
1013 unsigned MetadataID = 0;
1016 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1021 return tokError(
"unexpected type in metadata definition");
1025 if (parseSpecializedMDNode(Init, IsDistinct))
1028 parseMDTuple(Init, IsDistinct))
1032 auto FI = ForwardRefMDNodes.find(MetadataID);
1033 if (FI != ForwardRefMDNodes.end()) {
1034 auto *ToReplace = FI->second.first.get();
1038 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1039 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1040 "Inst unexpectedly already has DIAssignID attachment");
1041 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1045 ToReplace->replaceAllUsesWith(Init);
1046 ForwardRefMDNodes.erase(FI);
1048 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1050 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1052 return tokError(
"Metadata id is already used");
1053 It->second.reset(Init);
1060bool LLParser::skipModuleSummaryEntry() {
1070 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1071 "start of summary entry");
1073 return parseSummaryIndexFlags();
1075 return parseBlockCount();
1077 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1078 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1082 unsigned NumOpenParen = 1;
1084 switch (Lex.getKind()) {
1092 return tokError(
"found end of file while parsing summary entry");
1098 }
while (NumOpenParen > 0);
1104bool LLParser::parseSummaryEntry() {
1110 Lex.setIgnoreColonInIdentifiers(
true);
1118 return skipModuleSummaryEntry();
1120 bool result =
false;
1121 switch (Lex.getKind()) {
1123 result = parseGVEntry(SummaryID);
1126 result = parseModuleEntry(SummaryID);
1129 result = parseTypeIdEntry(SummaryID);
1132 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1135 result = parseSummaryIndexFlags();
1138 result = parseBlockCount();
1141 result =
error(Lex.getLoc(),
"unexpected summary kind");
1144 Lex.setIgnoreColonInIdentifiers(
false);
1178bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1179 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1180 unsigned DLLStorageClass,
bool DSOLocal,
1195 return error(NameLoc,
"invalid linkage type for alias");
1198 return error(NameLoc,
1199 "symbol with local linkage must have default visibility");
1202 return error(NameLoc,
1203 "symbol with local linkage cannot have a DLL storage class");
1206 LocTy ExplicitTypeLoc = Lex.getLoc();
1207 if (parseType(Ty) ||
1208 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1212 LocTy AliaseeLoc = Lex.getLoc();
1217 if (parseGlobalTypeAndValue(Aliasee))
1222 if (parseValID(
ID,
nullptr))
1225 return error(AliaseeLoc,
"invalid aliasee");
1226 Aliasee =
ID.ConstantVal;
1232 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1233 unsigned AddrSpace = PTy->getAddressSpace();
1235 GlobalValue *GVal =
nullptr;
1239 if (!
Name.empty()) {
1240 auto I = ForwardRefVals.find(Name);
1241 if (
I != ForwardRefVals.end()) {
1242 GVal =
I->second.first;
1243 ForwardRefVals.erase(Name);
1244 }
else if (M->getNamedValue(Name)) {
1245 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1248 auto I = ForwardRefValIDs.find(NameID);
1249 if (
I != ForwardRefValIDs.end()) {
1250 GVal =
I->second.first;
1251 ForwardRefValIDs.erase(
I);
1256 std::unique_ptr<GlobalAlias> GA;
1257 std::unique_ptr<GlobalIFunc> GI;
1285 if (parseGlobalObjectMetadataAttachment(*GI))
1288 return tokError(
"unknown alias or ifunc property!");
1293 NumberedVals.add(NameID, GV);
1300 "forward reference and definition of alias have different types");
1310 M->insertAlias(GA.release());
1312 M->insertIFunc(GI.release());
1313 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1322 case lltok::kw_sanitize_memtag:
1336 switch (Lex.getKind()) {
1338 Meta.NoAddress =
true;
1341 Meta.NoHWAddress =
true;
1343 case lltok::kw_sanitize_memtag:
1347 Meta.IsDynInit =
true;
1350 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1370bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1371 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1372 unsigned Visibility,
unsigned DLLStorageClass,
1376 return error(NameLoc,
1377 "symbol with local linkage must have default visibility");
1380 return error(NameLoc,
1381 "symbol with local linkage cannot have a DLL storage class");
1385 LocTy IsExternallyInitializedLoc;
1389 if (parseOptionalAddrSpace(AddrSpace) ||
1391 IsExternallyInitialized,
1392 &IsExternallyInitializedLoc) ||
1393 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1402 if (parseGlobalValue(Ty, Init))
1407 return error(TyLoc,
"invalid type for global variable");
1409 GlobalValue *GVal =
nullptr;
1412 if (!
Name.empty()) {
1413 auto I = ForwardRefVals.find(Name);
1414 if (
I != ForwardRefVals.end()) {
1415 GVal =
I->second.first;
1416 ForwardRefVals.erase(
I);
1417 }
else if (M->getNamedValue(Name)) {
1418 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1423 if (NameID == (
unsigned)-1)
1424 NameID = NumberedVals.getNext();
1426 auto I = ForwardRefValIDs.find(NameID);
1427 if (
I != ForwardRefValIDs.end()) {
1428 GVal =
I->second.first;
1429 ForwardRefValIDs.erase(
I);
1433 GlobalVariable *GV =
new GlobalVariable(
1438 NumberedVals.add(NameID, GV);
1456 "forward reference and definition of global have different types");
1476 }
else if (Lex.getKind() == lltok::kw_align) {
1477 MaybeAlign Alignment;
1478 if (parseOptionalAlignment(Alignment))
1484 if (parseOptionalCodeModel(CodeModel))
1488 if (parseGlobalObjectMetadataAttachment(*GV))
1491 if (parseSanitizer(GV))
1495 if (parseOptionalComdat(Name,
C))
1500 return tokError(
"unknown global variable property!");
1504 AttrBuilder
Attrs(M->getContext());
1506 std::vector<unsigned> FwdRefAttrGrps;
1507 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1509 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1511 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1519bool LLParser::parseUnnamedAttrGrp() {
1521 LocTy AttrGrpLoc = Lex.getLoc();
1525 return tokError(
"expected attribute group id");
1527 unsigned VarID = Lex.getUIntVal();
1528 std::vector<unsigned> unused;
1536 auto R = NumberedAttrBuilders.find(
VarID);
1537 if (R == NumberedAttrBuilders.end())
1538 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1540 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1541 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1544 if (!
R->second.hasAttributes())
1545 return error(AttrGrpLoc,
"attribute group has no attributes");
1552#define GET_ATTR_NAMES
1553#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1554 case lltok::kw_##DISPLAY_NAME: \
1555 return Attribute::ENUM_NAME;
1556#include "llvm/IR/Attributes.inc"
1565 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1568 case Attribute::Alignment: {
1569 MaybeAlign Alignment;
1577 if (parseOptionalAlignment(Alignment,
true))
1580 B.addAlignmentAttr(Alignment);
1583 case Attribute::StackAlignment: {
1588 parseUInt32(Alignment))
1591 if (parseOptionalStackAlignment(Alignment))
1594 B.addStackAlignmentAttr(Alignment);
1597 case Attribute::AllocSize: {
1598 unsigned ElemSizeArg;
1599 std::optional<unsigned> NumElemsArg;
1600 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1602 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1605 case Attribute::VScaleRange: {
1606 unsigned MinValue, MaxValue;
1607 if (parseVScaleRangeArguments(MinValue, MaxValue))
1609 B.addVScaleRangeAttr(MinValue,
1610 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1613 case Attribute::Dereferenceable: {
1614 std::optional<uint64_t> Bytes;
1615 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1617 assert(Bytes.has_value());
1618 B.addDereferenceableAttr(Bytes.value());
1621 case Attribute::DeadOnReturn: {
1622 std::optional<uint64_t> Bytes;
1623 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1626 if (Bytes.has_value()) {
1627 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1629 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1633 case Attribute::DereferenceableOrNull: {
1634 std::optional<uint64_t> Bytes;
1635 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1637 assert(Bytes.has_value());
1638 B.addDereferenceableOrNullAttr(Bytes.value());
1641 case Attribute::UWTable: {
1643 if (parseOptionalUWTableKind(Kind))
1645 B.addUWTableAttr(Kind);
1648 case Attribute::AllocKind: {
1650 if (parseAllocKind(Kind))
1652 B.addAllocKindAttr(Kind);
1655 case Attribute::Memory: {
1656 std::optional<MemoryEffects> ME = parseMemoryAttr();
1659 B.addMemoryAttr(*ME);
1662 case Attribute::DenormalFPEnv: {
1663 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1667 B.addDenormalFPEnvAttr(*
Mode);
1670 case Attribute::NoFPClass: {
1673 B.addNoFPClassAttr(NoFPClass);
1679 case Attribute::Range:
1680 return parseRangeAttr(
B);
1681 case Attribute::Initializes:
1682 return parseInitializesAttr(
B);
1683 case Attribute::Captures:
1684 return parseCapturesAttr(
B);
1686 B.addAttribute(Attr);
1694 case lltok::kw_readnone:
1697 case lltok::kw_readonly:
1700 case lltok::kw_writeonly:
1719bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1720 std::vector<unsigned> &FwdRefAttrGrps,
1721 bool InAttrGrp, LocTy &BuiltinLoc) {
1722 bool HaveError =
false;
1733 if (parseStringAttribute(
B))
1745 "cannot have an attribute group reference in an attribute group");
1748 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1754 SMLoc Loc = Lex.getLoc();
1755 if (Token == lltok::kw_builtin)
1767 return error(Lex.getLoc(),
"unterminated attribute group");
1770 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1777 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1781 B.addMemoryAttr(ME);
1795 PTy->getAddressSpace());
1804 error(Loc,
"'" + Name +
"' is not a basic block");
1806 error(Loc,
"'" + Name +
"' defined with type '" +
1819 error(Loc,
"global variable reference must have pointer type");
1830 auto I = ForwardRefVals.find(Name);
1831 if (
I != ForwardRefVals.end())
1832 Val =
I->second.first;
1838 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1842 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1849 error(Loc,
"global variable reference must have pointer type");
1853 GlobalValue *Val = NumberedVals.get(
ID);
1858 auto I = ForwardRefValIDs.find(
ID);
1859 if (
I != ForwardRefValIDs.end())
1860 Val =
I->second.first;
1866 checkValidVariableType(Loc,
"@" + Twine(
ID), Ty, Val));
1870 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1878Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
1882 if (
I != ComdatSymTab.
end())
1886 Comdat *
C = M->getOrInsertComdat(Name);
1887 ForwardRefComdats[
Name] = Loc;
1897bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1898 if (Lex.getKind() !=
T)
1899 return tokError(ErrMsg);
1906bool LLParser::parseStringConstant(std::string &Result) {
1908 return tokError(
"expected string constant");
1909 Result = Lex.getStrVal();
1916bool LLParser::parseUInt32(uint32_t &Val) {
1917 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1918 return tokError(
"expected integer");
1919 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1920 if (Val64 !=
unsigned(Val64))
1921 return tokError(
"expected 32-bit integer (too large)");
1929bool LLParser::parseUInt64(uint64_t &Val) {
1930 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1931 return tokError(
"expected integer");
1932 Val = Lex.getAPSIntVal().getLimitedValue();
1942 switch (Lex.getKind()) {
1944 return tokError(
"expected localdynamic, initialexec or localexec");
1972 return parseTLSModel(TLM) ||
1973 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1981bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1982 AddrSpace = DefaultAS;
1986 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1988 const std::string &AddrSpaceStr = Lex.getStrVal();
1989 if (AddrSpaceStr ==
"A") {
1990 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1991 }
else if (AddrSpaceStr ==
"G") {
1992 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1993 }
else if (AddrSpaceStr ==
"P") {
1994 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1995 }
else if (std::optional<unsigned> AS =
1996 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
1999 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2005 return tokError(
"expected integer or string constant");
2006 SMLoc Loc = Lex.getLoc();
2007 if (parseUInt32(AddrSpace))
2010 return error(Loc,
"invalid address space, must be a 24-bit integer");
2014 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2015 ParseAddrspaceValue(AddrSpace) ||
2022bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2023 std::string Attr = Lex.getStrVal();
2026 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2028 B.addAttribute(Attr, Val);
2033bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2034 bool HaveError =
false;
2041 if (parseStringAttribute(
B))
2052 SMLoc Loc = Lex.getLoc();
2057 if (parseEnumAttribute(Attr,
B,
false))
2061 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2063 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2111bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2112 unsigned &Visibility,
2113 unsigned &DLLStorageClass,
bool &DSOLocal) {
2117 parseOptionalDSOLocal(DSOLocal);
2118 parseOptionalVisibility(Visibility);
2119 parseOptionalDLLStorageClass(DLLStorageClass);
2122 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2128void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2129 switch (Lex.getKind()) {
2150void LLParser::parseOptionalVisibility(
unsigned &Res) {
2151 switch (Lex.getKind()) {
2168bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2172 return tokError(
"unknown import kind. Expect definition or declaration.");
2187void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2188 switch (Lex.getKind()) {
2258bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2259 switch (Lex.getKind()) {
2346 return tokError(
"unknown RISC-V ABI VLEN");
2347#define CC_VLS_CASE(ABIVlen) \
2349 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2377 return parseUInt32(CC);
2387bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2390 std::string
Name = Lex.getStrVal();
2391 Kind = M->getMDKindID(Name);
2394 return parseMDNode(MD);
2399bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2402 return tokError(
"expected metadata after comma");
2406 if (parseMetadataAttachment(MDK,
N))
2409 if (MDK == LLVMContext::MD_DIAssignID)
2410 TempDIAssignIDAttachments[
N].push_back(&Inst);
2414 if (MDK == LLVMContext::MD_tbaa)
2415 InstsWithTBAATag.push_back(&Inst);
2424bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2427 if (parseMetadataAttachment(MDK,
N))
2436bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2438 if (parseGlobalObjectMetadataAttachment(
F))
2446bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2447 Alignment = std::nullopt;
2448 if (!EatIfPresent(lltok::kw_align))
2450 LocTy AlignLoc = Lex.getLoc();
2453 LocTy ParenLoc = Lex.getLoc();
2454 bool HaveParens =
false;
2460 if (parseUInt64(
Value))
2464 return error(ParenLoc,
"expected ')'");
2467 return error(AlignLoc,
"alignment is not a power of two");
2469 return error(AlignLoc,
"huge alignments are not supported yet");
2477bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2478 Alignment = std::nullopt;
2481 LocTy AlignLoc = Lex.getLoc();
2484 LocTy ParenLoc = Lex.getLoc();
2486 return error(ParenLoc,
"expected '('");
2488 if (parseUInt64(
Value))
2491 ParenLoc = Lex.getLoc();
2493 return error(ParenLoc,
"expected ')'");
2496 return error(AlignLoc,
"alignment is not a power of two");
2498 return error(AlignLoc,
"huge alignments are not supported yet");
2508 auto StrVal = Lex.getStrVal();
2509 auto ErrMsg =
"expected global code model string";
2510 if (StrVal ==
"tiny")
2512 else if (StrVal ==
"small")
2514 else if (StrVal ==
"kernel")
2516 else if (StrVal ==
"medium")
2518 else if (StrVal ==
"large")
2521 return tokError(ErrMsg);
2533bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2534 std::optional<uint64_t> &Bytes,
2535 bool ErrorNoBytes) {
2536 assert((AttrKind == lltok::kw_dereferenceable ||
2537 AttrKind == lltok::kw_dereferenceable_or_null ||
2538 AttrKind == lltok::kw_dead_on_return) &&
2542 if (!EatIfPresent(AttrKind))
2544 LocTy ParenLoc = Lex.getLoc();
2547 return error(ParenLoc,
"expected '('");
2548 Bytes = std::nullopt;
2551 LocTy DerefLoc = Lex.getLoc();
2552 if (parseUInt64(Bytes.value()))
2554 ParenLoc = Lex.getLoc();
2556 return error(ParenLoc,
"expected ')'");
2558 return error(DerefLoc,
"byte count specified must be non-zero");
2562bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2567 LocTy KindLoc = Lex.getLoc();
2573 return error(KindLoc,
"expected unwind table kind");
2580 LocTy ParenLoc = Lex.getLoc();
2582 return error(ParenLoc,
"expected '('");
2583 LocTy KindLoc = Lex.getLoc();
2585 if (parseStringConstant(Arg))
2586 return error(KindLoc,
"expected allockind value");
2590 }
else if (
A ==
"realloc") {
2592 }
else if (
A ==
"free") {
2594 }
else if (
A ==
"uninitialized") {
2596 }
else if (
A ==
"zeroed") {
2598 }
else if (
A ==
"aligned") {
2601 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2604 ParenLoc = Lex.getLoc();
2606 return error(ParenLoc,
"expected ')'");
2608 return error(KindLoc,
"expected allockind value");
2625 return std::nullopt;
2640 return std::nullopt;
2644static std::optional<DenormalMode::DenormalModeKind>
2656 return std::nullopt;
2660std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2665 Lex.setIgnoreColonInIdentifiers(
true);
2670 tokError(
"expected '('");
2671 return std::nullopt;
2674 bool SeenLoc =
false;
2676 std::optional<IRMemLocation> Loc =
keywordToLoc(Lex.getKind());
2680 tokError(
"expected ':' after location");
2681 return std::nullopt;
2688 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2689 "or access kind (none, read, write, readwrite)");
2691 tokError(
"expected access kind (none, read, write, readwrite)");
2692 return std::nullopt;
2701 tokError(
"default access kind must be specified first");
2702 return std::nullopt;
2711 tokError(
"unterminated memory attribute");
2712 return std::nullopt;
2715std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2716 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2719 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2720 "positivezero, dynamic)");
2726 std::optional<DenormalMode::DenormalModeKind> InputMode;
2730 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2731 "positivezero, dynamic)");
2738 InputMode = OutputMode;
2741 return DenormalMode(*OutputMode, *InputMode);
2744std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2747 Lex.setIgnoreColonInIdentifiers(
true);
2758 bool HasDefaultSection =
false;
2760 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2761 if (!ParsedDefaultMode)
2763 DefaultMode = *ParsedDefaultMode;
2764 HasDefaultSection =
true;
2769 if (HasDefaultSection && !HasComma) {
2770 tokError(
"expected ',' before float:");
2775 if (parseType(Ty) || !Ty->
isFloatTy()) {
2776 tokError(
"expected float:");
2780 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2783 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2787 F32Mode = *ParsedF32Mode;
2790 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2793 return DenormalFPEnv(DefaultMode, F32Mode);
2835unsigned LLParser::parseNoFPClassAttr() {
2840 tokError(
"expected '('");
2847 if (TestMask != 0) {
2851 !parseUInt64(
Value)) {
2853 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
2858 error(Lex.getLoc(),
"expected ')'");
2864 error(Lex.getLoc(),
"expected nofpclass test mask");
2882bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2883 bool &AteExtraComma) {
2884 AteExtraComma =
false;
2888 AteExtraComma =
true;
2892 if (Lex.getKind() != lltok::kw_align)
2893 return error(Lex.getLoc(),
"expected metadata or 'align'");
2895 if (parseOptionalAlignment(Alignment))
2908bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
2909 bool &AteExtraComma) {
2910 AteExtraComma =
false;
2914 AteExtraComma =
true;
2920 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
2922 if (parseOptionalAddrSpace(AddrSpace))
2929bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2930 std::optional<unsigned> &HowManyArg) {
2933 auto StartParen = Lex.getLoc();
2935 return error(StartParen,
"expected '('");
2937 if (parseUInt32(BaseSizeArg))
2941 auto HowManyAt = Lex.getLoc();
2943 if (parseUInt32(HowMany))
2945 if (HowMany == BaseSizeArg)
2946 return error(HowManyAt,
2947 "'allocsize' indices can't refer to the same parameter");
2948 HowManyArg = HowMany;
2950 HowManyArg = std::nullopt;
2952 auto EndParen = Lex.getLoc();
2954 return error(EndParen,
"expected ')'");
2958bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2959 unsigned &MaxValue) {
2962 auto StartParen = Lex.getLoc();
2964 return error(StartParen,
"expected '('");
2966 if (parseUInt32(MinValue))
2970 if (parseUInt32(MaxValue))
2973 MaxValue = MinValue;
2975 auto EndParen = Lex.getLoc();
2977 return error(EndParen,
"expected ')'");
2986bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2991 return parseScope(SSID) || parseOrdering(Ordering);
3001 auto StartParenAt = Lex.getLoc();
3003 return error(StartParenAt,
"Expected '(' in syncscope");
3006 auto SSNAt = Lex.getLoc();
3007 if (parseStringConstant(SSN))
3008 return error(SSNAt,
"Expected synchronization scope name");
3010 auto EndParenAt = Lex.getLoc();
3012 return error(EndParenAt,
"Expected ')' in syncscope");
3014 SSID = Context.getOrInsertSyncScopeID(SSN);
3025 switch (Lex.getKind()) {
3027 return tokError(
"Expected ordering on atomic instruction");
3046bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3048 if (!EatIfPresent(lltok::kw_alignstack))
3050 LocTy ParenLoc = Lex.getLoc();
3052 return error(ParenLoc,
"expected '('");
3053 LocTy AlignLoc = Lex.getLoc();
3054 if (parseUInt32(Alignment))
3056 ParenLoc = Lex.getLoc();
3058 return error(ParenLoc,
"expected ')'");
3060 return error(AlignLoc,
"stack alignment is not a power of two");
3074 bool &AteExtraComma) {
3075 AteExtraComma =
false;
3078 return tokError(
"expected ',' as start of index list");
3082 if (Indices.
empty())
3083 return tokError(
"expected index");
3084 AteExtraComma =
true;
3088 if (parseUInt32(Idx))
3101bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
3102 SMLoc TypeLoc = Lex.getLoc();
3103 switch (Lex.getKind()) {
3105 return tokError(Msg);
3114 if (
Result->isPointerTy()) {
3116 if (parseOptionalAddrSpace(AddrSpace))
3122 return tokError(
"ptr* is invalid - use ptr instead");
3133 if (parseTargetExtType(Result))
3139 if (parseAnonStructType(Result,
false))
3145 if (parseArrayVectorType(Result,
false))
3152 if (parseAnonStructType(Result,
true) ||
3153 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3155 }
else if (parseArrayVectorType(Result,
true))
3160 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3166 Entry.second = Lex.getLoc();
3175 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3181 Entry.second = Lex.getLoc();
3191 switch (Lex.getKind()) {
3194 if (!AllowVoid &&
Result->isVoidTy())
3195 return error(TypeLoc,
"void type only allowed for function results");
3201 return tokError(
"basic block pointers are invalid");
3203 return tokError(
"pointers to void are invalid - use i8* instead");
3205 return tokError(
"pointer to this type is invalid");
3213 return tokError(
"basic block pointers are invalid");
3215 return tokError(
"pointers to void are invalid; use i8* instead");
3217 return tokError(
"pointer to this type is invalid");
3219 if (parseOptionalAddrSpace(AddrSpace) ||
3220 parseToken(
lltok::star,
"expected '*' in address space"))
3229 if (parseFunctionType(Result))
3242 PerFunctionState &PFS,
bool IsMustTailCall,
3243 bool InVarArgsFunc) {
3249 if (!ArgList.
empty() &&
3250 parseToken(
lltok::comma,
"expected ',' in argument list"))
3255 const char *Msg =
"unexpected ellipsis in argument list for ";
3256 if (!IsMustTailCall)
3257 return tokError(Twine(Msg) +
"non-musttail call");
3259 return tokError(Twine(Msg) +
"musttail call in non-varargs function");
3261 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3266 Type *ArgTy =
nullptr;
3268 if (parseType(ArgTy, ArgLoc))
3271 return error(ArgLoc,
"invalid type for function argument");
3273 AttrBuilder ArgAttrs(M->getContext());
3276 if (parseMetadataAsValue(V, PFS))
3280 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3287 if (IsMustTailCall && InVarArgsFunc)
3288 return tokError(
"expected '...' at end of argument list for musttail call "
3289 "in varargs function");
3297bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3300 if (!EatIfPresent(AttrToken))
3303 return error(Lex.getLoc(),
"expected '('");
3307 return error(Lex.getLoc(),
"expected ')'");
3309 B.addTypeAttr(AttrKind, Ty);
3315bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3323 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3325 return tokError(
"expected integer");
3326 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3328 "integer is too large for the bit width of specified type");
3329 Val = Lex.getAPSIntVal().extend(
BitWidth);
3334 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3337 return error(TyLoc,
"the range must have integer type!");
3345 return tokError(
"the range represent the empty set but limits aren't 0!");
3356bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3359 auto ParseAPSInt = [&](APInt &Val) {
3361 return tokError(
"expected integer");
3362 Val = Lex.getAPSIntVal().extend(64);
3382 return tokError(
"the range should not represent the full or empty set!");
3394 if (!CRLOrNull.has_value())
3395 return tokError(
"Invalid (unordered or overlapping) range list");
3396 B.addInitializesAttr(*CRLOrNull);
3400bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3402 std::optional<CaptureComponents> Ret;
3406 Lex.setIgnoreColonInIdentifiers(
true);
3414 bool SeenComponent =
false;
3420 return tokError(
"duplicate 'ret' location");
3423 SeenComponent =
false;
3428 return tokError(
"cannot use 'none' with other component");
3432 return tokError(
"cannot use 'none' with other component");
3443 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3444 "'provenance' or 'read_provenance'");
3447 SeenComponent =
true;
3455 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3468bool LLParser::parseOptionalOperandBundles(
3470 LocTy BeginLoc = Lex.getLoc();
3476 if (!BundleList.
empty() &&
3477 parseToken(
lltok::comma,
"expected ',' in input list"))
3481 if (parseStringConstant(
Tag))
3484 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3487 std::vector<Value *> Inputs;
3490 if (!Inputs.empty() &&
3491 parseToken(
lltok::comma,
"expected ',' in input list"))
3495 Value *Input =
nullptr;
3499 if (parseMetadataAsValue(Input, PFS))
3501 }
else if (parseValue(Ty, Input, PFS)) {
3504 Inputs.push_back(Input);
3512 if (BundleList.
empty())
3513 return error(BeginLoc,
"operand bundle set must not be empty");
3520 unsigned NextID,
unsigned ID) {
3522 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3523 Twine(NextID) +
"' or greater");
3540 unsigned CurValID = 0;
3554 LocTy TypeLoc = Lex.getLoc();
3555 Type *ArgTy =
nullptr;
3556 AttrBuilder
Attrs(M->getContext());
3557 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3561 return error(TypeLoc,
"argument can not have void type");
3566 bool Unnamed =
false;
3568 Name = Lex.getStrVal();
3569 IdentStart = getTokLineColumnPos();
3571 IdentEnd = getPrevTokEndLineColumnPos();
3575 ArgID = Lex.getUIntVal();
3576 IdentStart = getTokLineColumnPos();
3577 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3580 IdentEnd = getPrevTokEndLineColumnPos();
3586 CurValID = ArgID + 1;
3590 return error(TypeLoc,
"invalid type for function argument");
3594 Unnamed ? std::nullopt
3595 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3600 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3605bool LLParser::parseFunctionType(
Type *&Result) {
3609 return tokError(
"invalid function return type");
3613 SmallVector<unsigned> UnnamedArgNums;
3614 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3618 for (
const ArgInfo &Arg : ArgList) {
3619 if (!Arg.Name.empty())
3620 return error(Arg.Loc,
"argument name invalid in function type");
3621 if (Arg.Attrs.hasAttributes())
3622 return error(Arg.Loc,
"argument attributes invalid in function type");
3626 for (
const ArgInfo &Arg : ArgList)
3635bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3637 if (parseStructBody(Elts))
3645bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3646 std::pair<Type *, LocTy> &Entry,
3650 return error(TypeLoc,
"redefinition of type");
3656 Entry.second = SMLoc();
3661 ResultTy =
Entry.first;
3673 return error(TypeLoc,
"forward references to non-struct type");
3677 return parseArrayVectorType(ResultTy,
true);
3678 return parseType(ResultTy);
3682 Entry.second = SMLoc();
3691 if (parseStructBody(Body) ||
3692 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3696 return tokError(
toString(std::move(
E)));
3716 LocTy EltTyLoc = Lex.getLoc();
3723 return error(EltTyLoc,
"invalid element type for struct");
3726 EltTyLoc = Lex.getLoc();
3731 return error(EltTyLoc,
"invalid element type for struct");
3736 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3745bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3746 bool Scalable =
false;
3750 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3756 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3757 Lex.getAPSIntVal().getBitWidth() > 64)
3758 return tokError(
"expected number in address space");
3760 LocTy SizeLoc = Lex.getLoc();
3761 uint64_t
Size = Lex.getAPSIntVal().getZExtValue();
3764 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3767 LocTy TypeLoc = Lex.getLoc();
3768 Type *EltTy =
nullptr;
3769 if (parseType(EltTy))
3773 "expected end of sequential type"))
3778 return error(SizeLoc,
"zero element vector is illegal");
3780 return error(SizeLoc,
"size too large for vector");
3782 return error(TypeLoc,
"invalid vector element type");
3786 return error(TypeLoc,
"invalid array element type");
3803bool LLParser::parseTargetExtType(
Type *&Result) {
3808 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3809 parseStringConstant(TypeName))
3816 SmallVector<unsigned> IntParams;
3817 bool SeenInt =
false;
3824 if (parseUInt32(IntVal))
3827 }
else if (SeenInt) {
3830 return tokError(
"expected uint32 param");
3833 if (parseType(TypeParam,
true))
3839 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3844 if (
auto E = TTy.takeError())
3845 return tokError(
toString(std::move(
E)));
3858 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3861 auto It = UnnamedArgNums.
begin();
3864 unsigned ArgNum = *It++;
3865 NumberedVals.add(ArgNum, &A);
3870LLParser::PerFunctionState::~PerFunctionState() {
3873 for (
const auto &P : ForwardRefVals) {
3876 P.second.first->replaceAllUsesWith(
3878 P.second.first->deleteValue();
3881 for (
const auto &P : ForwardRefValIDs) {
3884 P.second.first->replaceAllUsesWith(
3886 P.second.first->deleteValue();
3890bool LLParser::PerFunctionState::finishFunction() {
3891 if (!ForwardRefVals.empty())
3892 return P.error(ForwardRefVals.begin()->second.second,
3893 "use of undefined value '%" + ForwardRefVals.begin()->first +
3895 if (!ForwardRefValIDs.empty())
3896 return P.error(ForwardRefValIDs.begin()->second.second,
3897 "use of undefined value '%" +
3898 Twine(ForwardRefValIDs.begin()->first) +
"'");
3905Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
3908 Value *Val =
F.getValueSymbolTable()->lookup(Name);
3913 auto I = ForwardRefVals.find(Name);
3914 if (
I != ForwardRefVals.end())
3915 Val =
I->second.first;
3920 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
3924 P.error(Loc,
"invalid use of a non-first-class type");
3935 if (FwdVal->
getName() != Name) {
3936 P.error(Loc,
"name is too long which can result in name collisions, "
3937 "consider making the name shorter or "
3938 "increasing -non-global-value-max-name-size");
3942 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3946Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
3948 Value *Val = NumberedVals.get(
ID);
3953 auto I = ForwardRefValIDs.find(
ID);
3954 if (
I != ForwardRefValIDs.end())
3955 Val =
I->second.first;
3960 return P.checkValidVariableType(Loc,
"%" + Twine(
ID), Ty, Val);
3963 P.error(Loc,
"invalid use of a non-first-class type");
3975 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3981bool LLParser::PerFunctionState::setInstName(
int NameID,
3982 const std::string &NameStr,
3983 LocTy NameLoc, Instruction *Inst) {
3986 if (NameID != -1 || !NameStr.empty())
3987 return P.error(NameLoc,
"instructions returning void cannot have a name");
3993 if (NameStr.empty()) {
3996 NameID = NumberedVals.getNext();
3998 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4002 auto FI = ForwardRefValIDs.find(NameID);
4003 if (FI != ForwardRefValIDs.end()) {
4006 return P.error(NameLoc,
"instruction forward referenced with type '" +
4010 Sentinel->replaceAllUsesWith(Inst);
4012 ForwardRefValIDs.erase(FI);
4015 NumberedVals.add(NameID, Inst);
4020 auto FI = ForwardRefVals.find(NameStr);
4021 if (FI != ForwardRefVals.end()) {
4024 return P.error(NameLoc,
"instruction forward referenced with type '" +
4028 Sentinel->replaceAllUsesWith(Inst);
4030 ForwardRefVals.erase(FI);
4036 if (Inst->
getName() != NameStr)
4037 return P.error(NameLoc,
"multiple definition of local value named '" +
4044BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4058BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4059 int NameID,
LocTy Loc) {
4063 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4066 NameID = NumberedVals.getNext();
4068 BB = getBB(NameID, Loc);
4070 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4074 BB = getBB(Name, Loc);
4076 P.error(Loc,
"unable to create block named '" + Name +
"'");
4087 ForwardRefValIDs.erase(NameID);
4088 NumberedVals.add(NameID, BB);
4091 ForwardRefVals.erase(Name);
4108bool LLParser::parseValID(ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4109 ID.Loc = Lex.getLoc();
4110 switch (Lex.getKind()) {
4112 return tokError(
"expected value token");
4114 ID.UIntVal = Lex.getUIntVal();
4118 ID.StrVal = Lex.getStrVal();
4122 ID.UIntVal = Lex.getUIntVal();
4126 ID.StrVal = Lex.getStrVal();
4130 ID.APSIntVal = Lex.getAPSIntVal();
4134 ID.APFloatVal = Lex.getAPFloatVal();
4155 if (parseGlobalValueVector(Elts) ||
4156 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4159 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4160 ID.UIntVal = Elts.
size();
4161 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4162 Elts.
size() *
sizeof(Elts[0]));
4173 LocTy FirstEltLoc = Lex.getLoc();
4174 if (parseGlobalValueVector(Elts) ||
4176 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4180 if (isPackedStruct) {
4181 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4182 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4183 Elts.
size() *
sizeof(Elts[0]));
4184 ID.UIntVal = Elts.
size();
4190 return error(
ID.Loc,
"constant vector must not be empty");
4192 if (!Elts[0]->
getType()->isIntegerTy() &&
4193 !Elts[0]->
getType()->isFloatingPointTy() &&
4197 "vector elements must have integer, pointer or floating point type");
4200 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4202 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4203 " is not of type '" +
4213 LocTy FirstEltLoc = Lex.getLoc();
4214 if (parseGlobalValueVector(Elts) ||
4226 if (!Elts[0]->
getType()->isFirstClassType())
4227 return error(FirstEltLoc,
"invalid array element type: " +
4233 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4235 return error(FirstEltLoc,
"array element #" + Twine(i) +
4236 " is not of type '" +
4256 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4259 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4262 parseStringConstant(
ID.StrVal) ||
4263 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4266 ID.StrVal2 = Lex.getStrVal();
4267 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4268 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4279 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4280 parseValID(Fn, PFS) ||
4282 "expected comma in block address expression") ||
4283 parseValID(Label, PFS) ||
4284 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4288 return error(Fn.
Loc,
"expected function name in blockaddress");
4290 return error(
Label.Loc,
"expected basic block name in blockaddress");
4293 GlobalValue *GV =
nullptr;
4295 GV = NumberedVals.get(Fn.
UIntVal);
4296 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4297 GV = M->getNamedValue(Fn.
StrVal);
4303 return error(Fn.
Loc,
"expected function name in blockaddress");
4305 if (
F->isDeclaration())
4306 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4311 GlobalValue *&FwdRef =
4312 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4320 "type of blockaddress must be a pointer and not '" +
4325 FwdDeclAS = PFS->getFunction().getAddressSpace();
4329 FwdRef =
new GlobalVariable(
4334 ID.ConstantVal = FwdRef;
4342 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4344 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4346 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4348 return error(
Label.Loc,
"referenced value is not a basic block");
4351 return error(
Label.Loc,
"cannot take address of numeric label after "
4352 "the function is defined");
4354 F->getValueSymbolTable()->lookup(
Label.StrVal));
4356 return error(
Label.Loc,
"referenced value is not a basic block");
4370 if (parseValID(Fn, PFS))
4375 "expected global value name in dso_local_equivalent");
4378 GlobalValue *GV =
nullptr;
4380 GV = NumberedVals.get(Fn.
UIntVal);
4381 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4382 GV = M->getNamedValue(Fn.
StrVal);
4388 ? ForwardRefDSOLocalEquivalentIDs
4389 : ForwardRefDSOLocalEquivalentNames;
4390 GlobalValue *&FwdRef = FwdRefMap[Fn];
4397 ID.ConstantVal = FwdRef;
4403 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4404 "in dso_local_equivalent");
4415 if (parseValID(
ID, PFS))
4419 return error(
ID.Loc,
"expected global value name in no_cfi");
4431 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4432 *DeactivationSymbol =
nullptr;
4435 "expected '(' in constant ptrauth expression") ||
4436 parseGlobalTypeAndValue(Ptr) ||
4438 "expected comma in constant ptrauth expression") ||
4439 parseGlobalTypeAndValue(
Key))
4442 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4444 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4447 parseGlobalTypeAndValue(DeactivationSymbol))
4450 "expected ')' in constant ptrauth expression"))
4454 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4457 if (!KeyC || KeyC->getBitWidth() != 32)
4458 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4460 ConstantInt *DiscC =
nullptr;
4466 "constant ptrauth integer discriminator must be i64 constant");
4472 if (!AddrDisc->getType()->isPointerTy())
4474 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4479 if (!DeactivationSymbol)
4480 DeactivationSymbol =
4482 if (!DeactivationSymbol->getType()->isPointerTy())
4484 "constant ptrauth deactivation symbol must be a pointer");
4498 unsigned Opc = Lex.getUIntVal();
4499 Type *DestTy =
nullptr;
4502 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4503 parseGlobalTypeAndValue(SrcVal) ||
4504 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4505 parseType(DestTy) ||
4506 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4509 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4518 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4520 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4522 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4524 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4526 return error(
ID.Loc,
"urem constexprs are no longer supported");
4528 return error(
ID.Loc,
"srem constexprs are no longer supported");
4530 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4532 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4534 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4536 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4538 return error(
ID.Loc,
"frem constexprs are no longer supported");
4540 return error(
ID.Loc,
"and constexprs are no longer supported");
4542 return error(
ID.Loc,
"or constexprs are no longer supported");
4544 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4546 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4548 return error(
ID.Loc,
"shl constexprs are no longer supported");
4550 return error(
ID.Loc,
"mul constexprs are no longer supported");
4552 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4554 return error(
ID.Loc,
"select constexprs are no longer supported");
4556 return error(
ID.Loc,
"zext constexprs are no longer supported");
4558 return error(
ID.Loc,
"sext constexprs are no longer supported");
4560 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4562 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4564 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4566 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4568 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4570 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4572 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4574 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4582 unsigned Opc = Lex.getUIntVal();
4585 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4586 Opc == Instruction::Mul) {
4595 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4596 parseGlobalTypeAndValue(Val0) ||
4597 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4598 parseGlobalTypeAndValue(Val1) ||
4599 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4602 return error(
ID.Loc,
"operands of constexpr must have same type");
4606 "constexpr requires integer or integer vector operands");
4617 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4620 if (parseGlobalTypeAndValue(
C))
4622 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4634 unsigned Opc = Lex.getUIntVal();
4637 bool HasInRange =
false;
4643 if (
Opc == Instruction::GetElementPtr) {
4659 return tokError(
"expected integer");
4660 InRangeStart = Lex.getAPSIntVal();
4665 return tokError(
"expected integer");
4666 InRangeEnd = Lex.getAPSIntVal();
4674 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4677 if (
Opc == Instruction::GetElementPtr) {
4678 if (parseType(Ty) ||
4679 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4683 if (parseGlobalValueVector(Elts) ||
4687 if (
Opc == Instruction::GetElementPtr) {
4688 if (Elts.
size() == 0 ||
4689 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4690 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4693 std::optional<ConstantRange>
InRange;
4695 unsigned IndexWidth =
4696 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4697 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4698 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4699 if (InRangeStart.
sge(InRangeEnd))
4700 return error(
ID.Loc,
"expected end to be larger than start");
4710 for (Constant *Val : Indices) {
4713 return error(
ID.Loc,
"getelementptr index must be an integer");
4716 if (GEPWidth && (ValNumEl != GEPWidth))
4719 "getelementptr vector index has a wrong number of elements");
4722 GEPWidth = ValNumEl;
4726 SmallPtrSet<Type*, 4> Visited;
4727 if (!Indices.empty() && !Ty->
isSized(&Visited))
4728 return error(
ID.Loc,
"base element of getelementptr must be sized");
4731 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4734 return error(
ID.Loc,
"invalid getelementptr indices");
4738 }
else if (
Opc == Instruction::ShuffleVector) {
4739 if (Elts.
size() != 3)
4740 return error(
ID.Loc,
"expected three operands to shufflevector");
4742 return error(
ID.Loc,
"invalid operands to shufflevector");
4743 SmallVector<int, 16>
Mask;
4746 }
else if (
Opc == Instruction::ExtractElement) {
4747 if (Elts.
size() != 2)
4748 return error(
ID.Loc,
"expected two operands to extractelement");
4750 return error(
ID.Loc,
"invalid extractelement operands");
4753 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4754 if (Elts.
size() != 3)
4755 return error(
ID.Loc,
"expected three operands to insertelement");
4757 return error(
ID.Loc,
"invalid insertelement operands");
4772bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4776 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4777 convertValIDToValue(Ty,
ID, V,
nullptr);
4779 return error(
ID.Loc,
"global values must be constants");
4783bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4785 return parseType(Ty) || parseGlobalValue(Ty, V);
4788bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4791 LocTy KwLoc = Lex.getLoc();
4797 return tokError(
"expected comdat variable");
4798 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4800 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4803 if (GlobalName.
empty())
4804 return tokError(
"comdat cannot be unnamed");
4805 C = getComdat(std::string(GlobalName), KwLoc);
4814bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4828 if (parseGlobalTypeAndValue(
C))
4836bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
4838 if (parseMDNodeVector(Elts))
4849bool LLParser::parseMDNode(MDNode *&
N) {
4851 return parseSpecializedMDNode(
N);
4853 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4856bool LLParser::parseMDNodeTail(MDNode *&
N) {
4859 return parseMDTuple(
N);
4862 return parseMDNodeID(
N);
4868template <
class FieldTy>
struct MDFieldImpl {
4869 typedef MDFieldImpl ImplTy;
4873 void assign(FieldTy Val) {
4875 this->Val = std::move(Val);
4878 explicit MDFieldImpl(FieldTy
Default)
4886template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4887 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4898 void assign(FieldTypeA
A) {
4900 this->
A = std::move(
A);
4904 void assign(FieldTypeB
B) {
4906 this->
B = std::move(
B);
4910 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4912 WhatIs(IsInvalid) {}
4915struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4922struct LineField :
public MDUnsignedField {
4923 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4926struct ColumnField :
public MDUnsignedField {
4927 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4930struct DwarfTagField :
public MDUnsignedField {
4936struct DwarfMacinfoTypeField :
public MDUnsignedField {
4942struct DwarfAttEncodingField :
public MDUnsignedField {
4943 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4946struct DwarfVirtualityField :
public MDUnsignedField {
4950struct DwarfLangField :
public MDUnsignedField {
4954struct DwarfSourceLangNameField :
public MDUnsignedField {
4955 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4958struct DwarfCCField :
public MDUnsignedField {
4959 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4962struct DwarfEnumKindField :
public MDUnsignedField {
4963 DwarfEnumKindField()
4968struct EmissionKindField :
public MDUnsignedField {
4969 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4972struct FixedPointKindField :
public MDUnsignedField {
4973 FixedPointKindField()
4974 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4977struct NameTableKindField :
public MDUnsignedField {
4978 NameTableKindField()
4981 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4984struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4985 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4988struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4989 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4992struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4993 MDAPSIntField() : ImplTy(
APSInt()) {}
4996struct MDSignedField :
public MDFieldImpl<int64_t> {
5000 MDSignedField(int64_t
Default = 0)
5002 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5006struct MDBoolField :
public MDFieldImpl<bool> {
5010struct MDField :
public MDFieldImpl<Metadata *> {
5013 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5016struct MDStringField :
public MDFieldImpl<MDString *> {
5017 enum class EmptyIs {
5022 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5023 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5026struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5030struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5034struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5035 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5036 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5038 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5039 bool AllowNull =
true)
5040 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5042 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5043 bool isMDField()
const {
return WhatIs == IsTypeB; }
5044 int64_t getMDSignedValue()
const {
5045 assert(isMDSignedField() &&
"Wrong field type");
5048 Metadata *getMDFieldValue()
const {
5049 assert(isMDField() &&
"Wrong field type");
5054struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5055 MDUnsignedOrMDField(uint64_t
Default = 0,
bool AllowNull =
true)
5056 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5058 MDUnsignedOrMDField(uint64_t
Default, uint64_t Max,
bool AllowNull =
true)
5059 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5061 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5062 bool isMDField()
const {
return WhatIs == IsTypeB; }
5063 uint64_t getMDUnsignedValue()
const {
5064 assert(isMDUnsignedField() &&
"Wrong field type");
5067 Metadata *getMDFieldValue()
const {
5068 assert(isMDField() &&
"Wrong field type");
5073 if (isMDUnsignedField())
5075 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5077 return getMDFieldValue();
5089 return tokError(
"expected integer");
5091 Result.assign(Lex.getAPSIntVal());
5098 MDUnsignedField &Result) {
5099 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5100 return tokError(
"expected unsigned integer");
5102 auto &U = Lex.getAPSIntVal();
5103 if (U.ugt(Result.Max))
5104 return tokError(
"value for '" + Name +
"' too large, limit is " +
5106 Result.assign(U.getZExtValue());
5107 assert(Result.Val <= Result.Max &&
"Expected value in range");
5114 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5118 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5124 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5127 return tokError(
"expected DWARF tag");
5131 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5132 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5141 DwarfMacinfoTypeField &Result) {
5143 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5146 return tokError(
"expected DWARF macinfo type");
5150 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5151 Lex.getStrVal() +
"'");
5152 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5154 Result.assign(Macinfo);
5161 DwarfVirtualityField &Result) {
5163 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5166 return tokError(
"expected DWARF virtuality code");
5170 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5171 Lex.getStrVal() +
"'");
5172 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5173 Result.assign(Virtuality);
5180 DwarfEnumKindField &Result) {
5182 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5185 return tokError(
"expected DWARF enum kind code");
5189 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5190 Lex.getStrVal() +
"'");
5191 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5192 Result.assign(EnumKind);
5200 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5203 return tokError(
"expected DWARF language");
5207 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5209 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5210 Result.assign(Lang);
5217 DwarfSourceLangNameField &Result) {
5219 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5222 return tokError(
"expected DWARF source language name");
5226 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5227 Lex.getStrVal() +
"'");
5228 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5229 Result.assign(Lang);
5237 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5240 return tokError(
"expected DWARF calling convention");
5244 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5245 Lex.getStrVal() +
"'");
5246 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5254 EmissionKindField &Result) {
5256 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5259 return tokError(
"expected emission kind");
5263 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5265 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5266 Result.assign(*Kind);
5273 FixedPointKindField &Result) {
5275 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5278 return tokError(
"expected fixed-point kind");
5282 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5284 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5285 Result.assign(*Kind);
5292 NameTableKindField &Result) {
5294 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5297 return tokError(
"expected nameTable kind");
5301 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5303 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5304 Result.assign((
unsigned)*Kind);
5311 DwarfAttEncodingField &Result) {
5313 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5316 return tokError(
"expected DWARF type attribute encoding");
5320 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5321 Lex.getStrVal() +
"'");
5322 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5323 Result.assign(Encoding);
5337 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5339 bool Res = parseUInt32(TempVal);
5345 return tokError(
"expected debug info flag");
5349 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5364 Result.assign(Combined);
5377 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5379 bool Res = parseUInt32(TempVal);
5385 return tokError(
"expected debug info flag");
5389 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5390 Lex.getStrVal() +
"'");
5404 Result.assign(Combined);
5411 return tokError(
"expected signed integer");
5413 auto &S = Lex.getAPSIntVal();
5415 return tokError(
"value for '" + Name +
"' too small, limit is " +
5418 return tokError(
"value for '" + Name +
"' too large, limit is " +
5420 Result.assign(S.getExtValue());
5421 assert(Result.Val >= Result.Min &&
"Expected value in range");
5422 assert(Result.Val <= Result.Max &&
"Expected value in range");
5429 switch (Lex.getKind()) {
5431 return tokError(
"expected 'true' or 'false'");
5433 Result.assign(
true);
5436 Result.assign(
false);
5446 if (!Result.AllowNull)
5447 return tokError(
"'" + Name +
"' cannot be null");
5449 Result.assign(
nullptr);
5454 if (parseMetadata(MD,
nullptr))
5463 MDSignedOrMDField &Result) {
5466 MDSignedField Res = Result.A;
5467 if (!parseMDField(
Loc, Name, Res)) {
5475 MDField Res = Result.B;
5476 if (!parseMDField(
Loc, Name, Res)) {
5486 MDUnsignedOrMDField &Result) {
5489 MDUnsignedField Res = Result.A;
5490 if (!parseMDField(
Loc, Name, Res)) {
5498 MDField Res = Result.B;
5499 if (!parseMDField(
Loc, Name, Res)) {
5509 LocTy ValueLoc = Lex.getLoc();
5511 if (parseStringConstant(S))
5515 switch (Result.EmptyIs) {
5516 case MDStringField::EmptyIs::Null:
5517 Result.assign(
nullptr);
5519 case MDStringField::EmptyIs::Empty:
5521 case MDStringField::EmptyIs::Error:
5522 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5533 if (parseMDNodeVector(MDs))
5536 Result.assign(std::move(MDs));
5542 ChecksumKindField &Result) {
5543 std::optional<DIFile::ChecksumKind> CSKind =
5547 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5550 Result.assign(*CSKind);
5557template <
class ParserTy>
5558bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5561 return tokError(
"expected field label here");
5570template <
class ParserTy>
5571bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5578 if (parseMDFieldsImplBody(ParseField))
5581 ClosingLoc = Lex.getLoc();
5585template <
class FieldTy>
5586bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5588 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5590 LocTy Loc = Lex.getLoc();
5592 return parseMDField(Loc, Name, Result);
5595bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5598#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5599 if (Lex.getStrVal() == #CLASS) \
5600 return parse##CLASS(N, IsDistinct);
5601#include "llvm/IR/Metadata.def"
5603 return tokError(
"expected metadata type");
5606#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5607#define NOP_FIELD(NAME, TYPE, INIT)
5608#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5610 return error(ClosingLoc, "missing required field '" #NAME "'");
5611#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5612 if (Lex.getStrVal() == #NAME) \
5613 return parseMDField(#NAME, NAME);
5614#define PARSE_MD_FIELDS() \
5615 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5618 if (parseMDFieldsImpl( \
5620 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5621 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5626 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5628#define GET_OR_DISTINCT(CLASS, ARGS) \
5629 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5634bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5635#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5636 OPTIONAL(line, LineField, ); \
5637 OPTIONAL(column, ColumnField, ); \
5638 REQUIRED(scope, MDField, ( false)); \
5639 OPTIONAL(inlinedAt, MDField, ); \
5640 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5641 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5642 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5644#undef VISIT_MD_FIELDS
5647 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5648 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5654bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5656 return tokError(
"missing 'distinct', required for !DIAssignID()");
5672bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5673#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5674 REQUIRED(tag, DwarfTagField, ); \
5675 OPTIONAL(header, MDStringField, ); \
5676 OPTIONAL(operands, MDFieldList, );
5678#undef VISIT_MD_FIELDS
5681 (Context, tag.Val, header.Val, operands.Val));
5690bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5691#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5692 OPTIONAL(name, MDStringField, ); \
5693 OPTIONAL(file, MDField, ); \
5694 OPTIONAL(line, LineField, ); \
5695 OPTIONAL(scope, MDField, ); \
5696 OPTIONAL(baseType, MDField, ); \
5697 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5698 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5699 OPTIONAL(flags, DIFlagField, ); \
5700 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5701 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5702 OPTIONAL(stride, MDSignedOrMDField, ); \
5703 OPTIONAL(bias, MDSignedOrMDField, );
5705#undef VISIT_MD_FIELDS
5707 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5708 if (Bound.isMDSignedField())
5711 if (Bound.isMDField())
5712 return Bound.getMDFieldValue();
5716 Metadata *LowerBound = convToMetadata(lowerBound);
5718 Metadata *Stride = convToMetadata(stride);
5719 Metadata *Bias = convToMetadata(bias);
5722 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5723 size.getValueAsMetadata(Context), align.Val, flags.Val,
5724 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5733bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5734#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5735 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5736 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5737 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5738 OPTIONAL(stride, MDSignedOrMDField, );
5740#undef VISIT_MD_FIELDS
5747 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5748 if (Bound.isMDSignedField())
5751 if (Bound.isMDField())
5752 return Bound.getMDFieldValue();
5757 LowerBound = convToMetadata(lowerBound);
5759 Stride = convToMetadata(stride);
5762 (Context,
Count, LowerBound, UpperBound, Stride));
5770bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5771#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5772 OPTIONAL(count, MDSignedOrMDField, ); \
5773 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5774 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5775 OPTIONAL(stride, MDSignedOrMDField, );
5777#undef VISIT_MD_FIELDS
5779 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5780 if (Bound.isMDSignedField())
5782 Context, {dwarf::DW_OP_consts,
5783 static_cast<uint64_t
>(Bound.getMDSignedValue())});
5784 if (Bound.isMDField())
5785 return Bound.getMDFieldValue();
5790 Metadata *LowerBound = ConvToMetadata(lowerBound);
5792 Metadata *Stride = ConvToMetadata(stride);
5795 (Context,
Count, LowerBound, UpperBound, Stride));
5802bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5803#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5804 REQUIRED(name, MDStringField, ); \
5805 REQUIRED(value, MDAPSIntField, ); \
5806 OPTIONAL(isUnsigned, MDBoolField, (false));
5808#undef VISIT_MD_FIELDS
5810 if (isUnsigned.Val && value.Val.isNegative())
5811 return tokError(
"unsigned enumerator with negative value");
5816 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5828bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5829#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5830 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5831 OPTIONAL(name, MDStringField, ); \
5832 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5833 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5834 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5835 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5836 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5837 OPTIONAL(flags, DIFlagField, );
5839#undef VISIT_MD_FIELDS
5843 (Context, tag.Val,
name.Val,
size.getValueAsMetadata(Context), align.Val,
5844 encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5853bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
5854#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5855 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5856 OPTIONAL(name, MDStringField, ); \
5857 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5858 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5859 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5860 OPTIONAL(flags, DIFlagField, ); \
5861 OPTIONAL(kind, FixedPointKindField, ); \
5862 OPTIONAL(factor, MDSignedField, ); \
5863 OPTIONAL(numerator, MDAPSIntField, ); \
5864 OPTIONAL(denominator, MDAPSIntField, );
5866#undef VISIT_MD_FIELDS
5869 (Context, tag.Val,
name.Val,
5870 size.getValueAsMetadata(Context), align.Val,
5871 encoding.Val, flags.Val, kind.Val, factor.Val,
5872 numerator.Val, denominator.Val));
5878bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5879#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5880 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5881 OPTIONAL(name, MDStringField, ); \
5882 OPTIONAL(stringLength, MDField, ); \
5883 OPTIONAL(stringLengthExpression, MDField, ); \
5884 OPTIONAL(stringLocationExpression, MDField, ); \
5885 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5886 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5887 OPTIONAL(encoding, DwarfAttEncodingField, );
5889#undef VISIT_MD_FIELDS
5893 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5894 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
5895 align.Val, encoding.Val));
5908bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5909#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5910 REQUIRED(tag, DwarfTagField, ); \
5911 OPTIONAL(name, MDStringField, ); \
5912 OPTIONAL(file, MDField, ); \
5913 OPTIONAL(line, LineField, ); \
5914 OPTIONAL(scope, MDField, ); \
5915 REQUIRED(baseType, MDField, ); \
5916 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5917 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5918 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5919 OPTIONAL(flags, DIFlagField, ); \
5920 OPTIONAL(extraData, MDField, ); \
5921 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5922 OPTIONAL(annotations, MDField, ); \
5923 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5924 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5925 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5926 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5927 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5929#undef VISIT_MD_FIELDS
5931 std::optional<unsigned> DWARFAddressSpace;
5932 if (dwarfAddressSpace.Val != UINT32_MAX)
5933 DWARFAddressSpace = dwarfAddressSpace.Val;
5934 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5936 PtrAuthData.emplace(
5937 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5938 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5939 ptrAuthAuthenticatesNullValues.Val);
5942 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
5943 baseType.Val,
size.getValueAsMetadata(Context), align.Val,
5944 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5945 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5949bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5950#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5951 REQUIRED(tag, DwarfTagField, ); \
5952 OPTIONAL(name, MDStringField, ); \
5953 OPTIONAL(file, MDField, ); \
5954 OPTIONAL(line, LineField, ); \
5955 OPTIONAL(scope, MDField, ); \
5956 OPTIONAL(baseType, MDField, ); \
5957 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5958 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5959 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5960 OPTIONAL(flags, DIFlagField, ); \
5961 OPTIONAL(elements, MDField, ); \
5962 OPTIONAL(runtimeLang, DwarfLangField, ); \
5963 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5964 OPTIONAL(vtableHolder, MDField, ); \
5965 OPTIONAL(templateParams, MDField, ); \
5966 OPTIONAL(identifier, MDStringField, ); \
5967 OPTIONAL(discriminator, MDField, ); \
5968 OPTIONAL(dataLocation, MDField, ); \
5969 OPTIONAL(associated, MDField, ); \
5970 OPTIONAL(allocated, MDField, ); \
5971 OPTIONAL(rank, MDSignedOrMDField, ); \
5972 OPTIONAL(annotations, MDField, ); \
5973 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5974 OPTIONAL(specification, MDField, ); \
5975 OPTIONAL(bitStride, MDField, );
5977#undef VISIT_MD_FIELDS
5980 if (rank.isMDSignedField())
5983 else if (rank.isMDField())
5984 Rank = rank.getMDFieldValue();
5986 std::optional<unsigned> EnumKind;
5988 EnumKind = enumKind.Val;
5993 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5994 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
5995 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5996 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5997 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5998 dataLocation.Val, associated.Val, allocated.Val, Rank,
5999 annotations.Val, bitStride.Val)) {
6008 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6009 size.getValueAsMetadata(Context), align.Val,
6010 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6011 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6012 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6013 allocated.Val, Rank, annotations.Val, specification.Val,
6014 num_extra_inhabitants.Val, bitStride.Val));
6018bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6019#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6020 OPTIONAL(flags, DIFlagField, ); \
6021 OPTIONAL(cc, DwarfCCField, ); \
6022 REQUIRED(types, MDField, );
6024#undef VISIT_MD_FIELDS
6027 (Context, flags.Val, cc.Val, types.Val));
6036bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6040#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6041 REQUIRED(filename, MDStringField, ); \
6042 REQUIRED(directory, MDStringField, ); \
6043 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6044 OPTIONAL(checksum, MDStringField, ); \
6045 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6047#undef VISIT_MD_FIELDS
6049 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6050 if (checksumkind.Seen && checksum.Seen)
6051 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6052 else if (checksumkind.Seen || checksum.Seen)
6053 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6055 MDString *
Source =
nullptr;
6059 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6070bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6072 return tokError(
"missing 'distinct', required for !DICompileUnit");
6074 LocTy Loc = Lex.getLoc();
6076#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6077 REQUIRED(file, MDField, ( false)); \
6078 OPTIONAL(language, DwarfLangField, ); \
6079 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6080 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6081 OPTIONAL(producer, MDStringField, ); \
6082 OPTIONAL(isOptimized, MDBoolField, ); \
6083 OPTIONAL(flags, MDStringField, ); \
6084 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6085 OPTIONAL(splitDebugFilename, MDStringField, ); \
6086 OPTIONAL(emissionKind, EmissionKindField, ); \
6087 OPTIONAL(enums, MDField, ); \
6088 OPTIONAL(retainedTypes, MDField, ); \
6089 OPTIONAL(globals, MDField, ); \
6090 OPTIONAL(imports, MDField, ); \
6091 OPTIONAL(macros, MDField, ); \
6092 OPTIONAL(dwoId, MDUnsignedField, ); \
6093 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6094 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6095 OPTIONAL(nameTableKind, NameTableKindField, ); \
6096 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6097 OPTIONAL(sysroot, MDStringField, ); \
6098 OPTIONAL(sdk, MDStringField, );
6100#undef VISIT_MD_FIELDS
6102 if (!language.Seen && !sourceLanguageName.Seen)
6103 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6104 "required for !DICompileUnit");
6106 if (language.Seen && sourceLanguageName.Seen)
6107 return error(Loc,
"can only specify one of 'language' and "
6108 "'sourceLanguageName' on !DICompileUnit");
6110 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6111 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6112 "'sourceLanguageName' on !DICompileUnit");
6116 language.Seen ? DISourceLanguageName(language.Val)
6117 : DISourceLanguageName(sourceLanguageName.Val,
6118 sourceLanguageVersion.Val),
6119 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
6120 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
6121 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
6122 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
6123 sysroot.Val, sdk.Val);
6136bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6137 auto Loc = Lex.getLoc();
6138#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6139 OPTIONAL(scope, MDField, ); \
6140 OPTIONAL(name, MDStringField, ); \
6141 OPTIONAL(linkageName, MDStringField, ); \
6142 OPTIONAL(file, MDField, ); \
6143 OPTIONAL(line, LineField, ); \
6144 OPTIONAL(type, MDField, ); \
6145 OPTIONAL(isLocal, MDBoolField, ); \
6146 OPTIONAL(isDefinition, MDBoolField, (true)); \
6147 OPTIONAL(scopeLine, LineField, ); \
6148 OPTIONAL(containingType, MDField, ); \
6149 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6150 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6151 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6152 OPTIONAL(flags, DIFlagField, ); \
6153 OPTIONAL(spFlags, DISPFlagField, ); \
6154 OPTIONAL(isOptimized, MDBoolField, ); \
6155 OPTIONAL(unit, MDField, ); \
6156 OPTIONAL(templateParams, MDField, ); \
6157 OPTIONAL(declaration, MDField, ); \
6158 OPTIONAL(retainedNodes, MDField, ); \
6159 OPTIONAL(thrownTypes, MDField, ); \
6160 OPTIONAL(annotations, MDField, ); \
6161 OPTIONAL(targetFuncName, MDStringField, ); \
6162 OPTIONAL(keyInstructions, MDBoolField, );
6164#undef VISIT_MD_FIELDS
6169 spFlags.Seen ? spFlags.Val
6171 isOptimized.Val, virtuality.Val);
6172 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6175 "missing 'distinct', required for !DISubprogram that is a Definition");
6178 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6179 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6180 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6181 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6182 targetFuncName.Val, keyInstructions.Val));
6192bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6193#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6194 REQUIRED(scope, MDField, ( false)); \
6195 OPTIONAL(file, MDField, ); \
6196 OPTIONAL(line, LineField, ); \
6197 OPTIONAL(column, ColumnField, );
6199#undef VISIT_MD_FIELDS
6202 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6208bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6209#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6210 REQUIRED(scope, MDField, ( false)); \
6211 OPTIONAL(file, MDField, ); \
6212 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6214#undef VISIT_MD_FIELDS
6217 (Context, scope.Val,
file.Val, discriminator.Val));
6223bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6224#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6225 REQUIRED(scope, MDField, ); \
6226 OPTIONAL(declaration, MDField, ); \
6227 OPTIONAL(name, MDStringField, ); \
6228 OPTIONAL(file, MDField, ); \
6229 OPTIONAL(line, LineField, );
6231#undef VISIT_MD_FIELDS
6234 (Context, scope.Val, declaration.Val,
name.Val,
6235 file.Val, line.Val));
6241bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6242#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6243 REQUIRED(scope, MDField, ); \
6244 OPTIONAL(name, MDStringField, ); \
6245 OPTIONAL(exportSymbols, MDBoolField, );
6247#undef VISIT_MD_FIELDS
6250 (Context, scope.Val,
name.Val, exportSymbols.Val));
6257bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6258#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6259 REQUIRED(type, DwarfMacinfoTypeField, ); \
6260 OPTIONAL(line, LineField, ); \
6261 REQUIRED(name, MDStringField, ); \
6262 OPTIONAL(value, MDStringField, );
6264#undef VISIT_MD_FIELDS
6267 (Context, type.Val, line.Val,
name.Val, value.Val));
6273bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6274#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6275 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6276 OPTIONAL(line, LineField, ); \
6277 REQUIRED(file, MDField, ); \
6278 OPTIONAL(nodes, MDField, );
6280#undef VISIT_MD_FIELDS
6283 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6291bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6292#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6293 REQUIRED(scope, MDField, ); \
6294 REQUIRED(name, MDStringField, ); \
6295 OPTIONAL(configMacros, MDStringField, ); \
6296 OPTIONAL(includePath, MDStringField, ); \
6297 OPTIONAL(apinotes, MDStringField, ); \
6298 OPTIONAL(file, MDField, ); \
6299 OPTIONAL(line, LineField, ); \
6300 OPTIONAL(isDecl, MDBoolField, );
6302#undef VISIT_MD_FIELDS
6305 configMacros.Val, includePath.Val,
6306 apinotes.Val, line.Val, isDecl.Val));
6312bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6313#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6314 OPTIONAL(name, MDStringField, ); \
6315 REQUIRED(type, MDField, ); \
6316 OPTIONAL(defaulted, MDBoolField, );
6318#undef VISIT_MD_FIELDS
6321 (Context,
name.Val, type.Val, defaulted.Val));
6329bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6330#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6331 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6332 OPTIONAL(name, MDStringField, ); \
6333 OPTIONAL(type, MDField, ); \
6334 OPTIONAL(defaulted, MDBoolField, ); \
6335 REQUIRED(value, MDField, );
6338#undef VISIT_MD_FIELDS
6341 DITemplateValueParameter,
6342 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6351bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6352#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6353 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6354 OPTIONAL(scope, MDField, ); \
6355 OPTIONAL(linkageName, MDStringField, ); \
6356 OPTIONAL(file, MDField, ); \
6357 OPTIONAL(line, LineField, ); \
6358 OPTIONAL(type, MDField, ); \
6359 OPTIONAL(isLocal, MDBoolField, ); \
6360 OPTIONAL(isDefinition, MDBoolField, (true)); \
6361 OPTIONAL(templateParams, MDField, ); \
6362 OPTIONAL(declaration, MDField, ); \
6363 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6364 OPTIONAL(annotations, MDField, );
6366#undef VISIT_MD_FIELDS
6370 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6371 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6372 declaration.Val, templateParams.Val, align.Val,
6384bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6385#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6386 REQUIRED(scope, MDField, ( false)); \
6387 OPTIONAL(name, MDStringField, ); \
6388 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6389 OPTIONAL(file, MDField, ); \
6390 OPTIONAL(line, LineField, ); \
6391 OPTIONAL(type, MDField, ); \
6392 OPTIONAL(flags, DIFlagField, ); \
6393 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6394 OPTIONAL(annotations, MDField, );
6396#undef VISIT_MD_FIELDS
6399 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6400 type.Val, arg.Val, flags.Val, align.Val,
6407bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6408#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6409 REQUIRED(scope, MDField, ( false)); \
6410 REQUIRED(name, MDStringField, ); \
6411 REQUIRED(file, MDField, ); \
6412 REQUIRED(line, LineField, ); \
6413 OPTIONAL(column, ColumnField, ); \
6414 OPTIONAL(isArtificial, MDBoolField, ); \
6415 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6417#undef VISIT_MD_FIELDS
6419 std::optional<unsigned> CoroSuspendIdx =
6420 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6424 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6425 column.Val, isArtificial.Val, CoroSuspendIdx));
6431bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6444 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6453 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6454 Lex.getStrVal() +
"'");
6457 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6458 return tokError(
"expected unsigned integer");
6460 auto &
U = Lex.getAPSIntVal();
6462 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6476bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6478 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6481 return parseDIExpressionBody(Result, IsDistinct);
6486bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6487 assert(PFS &&
"Expected valid function state");
6498 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6512bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6514#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6515 REQUIRED(var, MDField, ); \
6516 REQUIRED(expr, MDField, );
6518#undef VISIT_MD_FIELDS
6521 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6528bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6529#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6530 OPTIONAL(name, MDStringField, ); \
6531 OPTIONAL(file, MDField, ); \
6532 OPTIONAL(line, LineField, ); \
6533 OPTIONAL(setter, MDStringField, ); \
6534 OPTIONAL(getter, MDStringField, ); \
6535 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6536 OPTIONAL(type, MDField, );
6538#undef VISIT_MD_FIELDS
6541 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6542 setter.Val, attributes.Val, type.Val));
6549bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6550#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6551 REQUIRED(tag, DwarfTagField, ); \
6552 REQUIRED(scope, MDField, ); \
6553 OPTIONAL(entity, MDField, ); \
6554 OPTIONAL(file, MDField, ); \
6555 OPTIONAL(line, LineField, ); \
6556 OPTIONAL(name, MDStringField, ); \
6557 OPTIONAL(elements, MDField, );
6559#undef VISIT_MD_FIELDS
6562 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6563 line.Val,
name.Val, elements.Val));
6567#undef PARSE_MD_FIELD
6579bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6582 if (parseMetadata(MD, &PFS))
6593bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6594 PerFunctionState *PFS) {
6597 if (parseType(Ty, TypeMsg, Loc))
6600 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6603 if (parseValue(Ty, V, PFS))
6618bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6622 if (Lex.getStrVal() ==
"DIArgList") {
6624 if (parseDIArgList(AL, PFS))
6630 if (parseSpecializedMDNode(
N)) {
6640 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6650 if (parseMDString(S))
6660 if (parseMDNodeTail(
N))
6671 PerFunctionState *PFS) {
6673 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6678 return error(
ID.Loc,
"invalid use of function-local name");
6679 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6680 return V ==
nullptr;
6683 return error(
ID.Loc,
"invalid use of function-local name");
6684 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6685 return V ==
nullptr;
6688 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6692 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6697 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6700 return V ==
nullptr;
6702 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6705 return V ==
nullptr;
6708 return error(
ID.Loc,
"integer constant must have integer type");
6710 V = ConstantInt::get(Context,
ID.APSIntVal);
6715 return error(
ID.Loc,
"floating point constant invalid for type");
6721 bool IsSNAN =
ID.APFloatVal.isSignaling();
6736 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6738 ID.APFloatVal.isNegative(), &Payload);
6741 V = ConstantFP::get(Context,
ID.APFloatVal);
6743 if (
V->getType() != Ty)
6744 return error(
ID.Loc,
"floating point constant does not have type '" +
6750 return error(
ID.Loc,
"null must be a pointer type");
6756 return error(
ID.Loc,
"invalid type for undef constant");
6761 return error(
ID.Loc,
"invalid empty array initializer");
6767 return error(
ID.Loc,
"invalid type for null constant");
6770 return error(
ID.Loc,
"invalid type for null constant");
6775 return error(
ID.Loc,
"invalid type for none constant");
6781 return error(
ID.Loc,
"invalid type for poison constant");
6785 if (
ID.ConstantVal->getType() != Ty)
6786 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6793 return error(
ID.Loc,
"vector constant must have vector type");
6795 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6797 "' but expected '" +
6805 if (
ST->getNumElements() !=
ID.UIntVal)
6807 "initializer with struct type has wrong # elements");
6809 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6812 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6813 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6816 "element " + Twine(i) +
6817 " of struct initializer doesn't match struct element type");
6820 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6822 return error(
ID.Loc,
"constant expression type mismatch");
6831 auto Loc = Lex.getLoc();
6832 if (parseValID(
ID,
nullptr))
6845 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6855 return error(Loc,
"expected a constant value");
6859bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6863 FileLoc
Start = getTokLineColumnPos();
6864 bool Ret = parseValID(
ID, PFS, Ty) || convertValIDToValue(Ty,
ID, V, PFS);
6865 if (!Ret && ParserContext) {
6866 FileLoc End = getPrevTokEndLineColumnPos();
6867 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6872bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6874 return parseType(Ty) || parseValue(Ty, V, PFS);
6877bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
6878 PerFunctionState &PFS) {
6881 if (parseTypeAndValue(V, PFS))
6884 return error(Loc,
"expected a basic block");
6893 if (!Name.starts_with(
"llvm.dbg."))
6896 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6897 FnID == Intrinsic::dbg_assign;
6905bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6906 unsigned &FunctionNumber,
6909 LocTy LinkageLoc = Lex.getLoc();
6911 unsigned Visibility;
6912 unsigned DLLStorageClass;
6914 AttrBuilder RetAttrs(M->getContext());
6917 Type *RetType =
nullptr;
6918 LocTy RetTypeLoc = Lex.getLoc();
6919 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
6921 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6922 parseType(RetType, RetTypeLoc,
true ))
6931 return error(LinkageLoc,
"invalid linkage for function definition");
6941 return error(LinkageLoc,
"invalid linkage for function declaration");
6945 return error(LinkageLoc,
"invalid function linkage type");
6949 return error(LinkageLoc,
6950 "symbol with local linkage must have default visibility");
6953 return error(LinkageLoc,
6954 "symbol with local linkage cannot have a DLL storage class");
6957 return error(RetTypeLoc,
"invalid function return type");
6959 LocTy NameLoc = Lex.getLoc();
6961 std::string FunctionName;
6963 FunctionName = Lex.getStrVal();
6965 FunctionNumber = Lex.getUIntVal();
6966 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6970 return tokError(
"expected function name");
6976 return tokError(
"expected '(' in function argument list");
6980 AttrBuilder FuncAttrs(M->getContext());
6981 std::vector<unsigned> FwdRefAttrGrps;
6984 std::string Partition;
6985 MaybeAlign Alignment, PrefAlignment;
6988 unsigned AddrSpace = 0;
6994 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6995 parseOptionalUnnamedAddr(UnnamedAddr) ||
6996 parseOptionalProgramAddrSpace(AddrSpace) ||
6997 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7001 parseOptionalComdat(FunctionName,
C) ||
7002 parseOptionalAlignment(Alignment) ||
7003 parseOptionalPrefAlignment(PrefAlignment) ||
7004 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7008 parseGlobalTypeAndValue(PersonalityFn)))
7011 if (FuncAttrs.contains(Attribute::Builtin))
7012 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7015 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7017 FuncAttrs.removeAttribute(Attribute::Alignment);
7022 std::vector<Type*> ParamTypeList;
7025 for (
const ArgInfo &Arg : ArgList) {
7026 ParamTypeList.push_back(Arg.Ty);
7027 Attrs.push_back(Arg.Attrs);
7034 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7035 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7041 GlobalValue *FwdFn =
nullptr;
7042 if (!FunctionName.empty()) {
7045 auto FRVI = ForwardRefVals.find(FunctionName);
7046 if (FRVI != ForwardRefVals.end()) {
7047 FwdFn = FRVI->second.first;
7049 return error(FRVI->second.second,
7050 "invalid forward reference to "
7053 "' with wrong type: "
7057 ForwardRefVals.erase(FRVI);
7058 }
else if ((Fn = M->getFunction(FunctionName))) {
7060 return error(NameLoc,
7061 "invalid redefinition of function '" + FunctionName +
"'");
7062 }
else if (M->getNamedValue(FunctionName)) {
7063 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7069 if (FunctionNumber == (
unsigned)-1)
7070 FunctionNumber = NumberedVals.getNext();
7074 auto I = ForwardRefValIDs.find(FunctionNumber);
7075 if (
I != ForwardRefValIDs.end()) {
7076 FwdFn =
I->second.first;
7078 return error(NameLoc,
"type of definition and forward reference of '@" +
7079 Twine(FunctionNumber) +
7084 ForwardRefValIDs.erase(
I);
7093 if (FunctionName.empty())
7094 NumberedVals.add(FunctionNumber, Fn);
7110 if (!
GC.empty()) Fn->
setGC(GC);
7113 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7117 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7118 if (ParserContext && ArgList[i].IdentLoc)
7119 ParserContext->addInstructionOrArgumentLocation(
7120 &*ArgIt, ArgList[i].IdentLoc.value());
7122 if (ArgList[i].
Name.empty())
continue;
7125 ArgIt->
setName(ArgList[i].Name);
7127 if (ArgIt->
getName() != ArgList[i].Name)
7128 return error(ArgList[i].Loc,
7129 "redefinition of argument '%" + ArgList[i].Name +
"'");
7142 if (FunctionName.empty()) {
7144 ID.UIntVal = FunctionNumber;
7147 ID.StrVal = FunctionName;
7149 auto Blocks = ForwardRefBlockAddresses.find(
ID);
7150 if (Blocks != ForwardRefBlockAddresses.end())
7151 return error(Blocks->first.Loc,
7152 "cannot take blockaddress inside a declaration");
7156bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7158 if (FunctionNumber == -1) {
7160 ID.StrVal = std::string(F.getName());
7163 ID.UIntVal = FunctionNumber;
7166 auto Blocks = P.ForwardRefBlockAddresses.find(
ID);
7167 if (Blocks == P.ForwardRefBlockAddresses.end())
7170 for (
const auto &
I : Blocks->second) {
7171 const ValID &BBID =
I.first;
7172 GlobalValue *GV =
I.second;
7175 "Expected local id or name");
7182 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7185 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7193 P.ForwardRefBlockAddresses.erase(Blocks);
7199bool LLParser::parseFunctionBody(Function &Fn,
unsigned FunctionNumber,
7200 ArrayRef<unsigned> UnnamedArgNums) {
7202 return tokError(
"expected '{' in function body");
7205 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7209 if (PFS.resolveForwardRefBlockAddresses())
7215 return tokError(
"function body requires at least one basic block");
7219 if (parseBasicBlock(PFS))
7223 if (parseUseListOrder(&PFS))
7230 return PFS.finishFunction();
7235bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7236 FileLoc BBStart = getTokLineColumnPos();
7241 LocTy NameLoc = Lex.getLoc();
7243 Name = Lex.getStrVal();
7246 NameID = Lex.getUIntVal();
7250 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7254 std::string NameStr;
7259 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7260 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7267 if (SeenOldDbgInfoFormat)
7268 return error(Lex.getLoc(),
"debug record should not appear in a module "
7269 "containing debug info intrinsics");
7270 SeenNewDbgInfoFormat =
true;
7274 if (parseDebugRecord(DR, PFS))
7276 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7279 FileLoc InstStart = getTokLineColumnPos();
7282 LocTy NameLoc = Lex.getLoc();
7287 NameID = Lex.getUIntVal();
7289 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7292 NameStr = Lex.getStrVal();
7294 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7298 switch (parseInstruction(Inst, BB, PFS)) {
7301 case InstError:
return true;
7308 if (parseInstructionMetadata(*Inst))
7311 case InstExtraComma:
7316 if (parseInstructionMetadata(*Inst))
7322 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7326 for (DbgRecordPtr &DR : TrailingDbgRecord)
7328 TrailingDbgRecord.clear();
7329 if (ParserContext) {
7330 ParserContext->addInstructionOrArgumentLocation(
7331 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7336 ParserContext->addBlockLocation(
7337 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7339 assert(TrailingDbgRecord.empty() &&
7340 "All debug values should have been attached to an instruction.");
7349bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7352 LocTy DVRLoc = Lex.getLoc();
7354 return error(DVRLoc,
"expected debug record type here");
7355 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7356 .Case(
"declare", RecordKind::ValueKind)
7357 .Case(
"value", RecordKind::ValueKind)
7358 .Case(
"assign", RecordKind::ValueKind)
7359 .Case(
"label", RecordKind::LabelKind)
7360 .Case(
"declare_value", RecordKind::ValueKind);
7369 if (parseMDNode(Label))
7374 if (parseMDNode(DbgLoc))
7382 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7383 .Case(
"declare", LocType::Declare)
7384 .Case(
"value", LocType::Value)
7385 .Case(
"assign", LocType::Assign)
7386 .Case(
"declare_value", LocType::DeclareValue);
7394 if (parseMetadata(ValLocMD, &PFS))
7401 if (parseMDNode(Variable))
7408 if (parseMDNode(Expression))
7414 MDNode *AssignID =
nullptr;
7415 Metadata *AddressLocation =
nullptr;
7416 MDNode *AddressExpression =
nullptr;
7419 if (parseMDNode(AssignID))
7425 if (parseMetadata(AddressLocation, &PFS))
7431 if (parseMDNode(AddressExpression))
7445 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7455int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7456 PerFunctionState &PFS) {
7459 return tokError(
"found end of file when expecting more instructions");
7460 LocTy Loc = Lex.getLoc();
7461 unsigned KeywordVal = Lex.getUIntVal();
7466 return error(Loc,
"expected instruction opcode");
7470 return parseRet(Inst, BB, PFS);
7472 return parseBr(Inst, PFS);
7474 return parseSwitch(Inst, PFS);
7476 return parseIndirectBr(Inst, PFS);
7478 return parseInvoke(Inst, PFS);
7480 return parseResume(Inst, PFS);
7482 return parseCleanupRet(Inst, PFS);
7484 return parseCatchRet(Inst, PFS);
7486 return parseCatchSwitch(Inst, PFS);
7488 return parseCatchPad(Inst, PFS);
7490 return parseCleanupPad(Inst, PFS);
7492 return parseCallBr(Inst, PFS);
7495 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7496 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7512 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7524 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7525 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7539 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7547 return parseArithmetic(Inst, PFS, KeywordVal,
7551 if (parseLogical(Inst, PFS, KeywordVal))
7559 return parseLogical(Inst, PFS, KeywordVal);
7562 if (parseCompare(Inst, PFS, KeywordVal))
7569 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7570 int Res = parseCompare(Inst, PFS, KeywordVal);
7582 bool Res = parseCast(Inst, PFS, KeywordVal);
7594 if (parseCast(Inst, PFS, KeywordVal))
7611 return parseCast(Inst, PFS, KeywordVal);
7614 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7615 if (parseCast(Inst, PFS, KeywordVal))
7624 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7625 int Res = parseSelect(Inst, PFS);
7630 return error(Loc,
"fast-math-flags specified for select without "
7631 "floating-point scalar or vector return type");
7637 return parseVAArg(Inst, PFS);
7639 return parseExtractElement(Inst, PFS);
7641 return parseInsertElement(Inst, PFS);
7643 return parseShuffleVector(Inst, PFS);
7645 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7646 int Res = parsePHI(Inst, PFS);
7651 return error(Loc,
"fast-math-flags specified for phi without "
7652 "floating-point scalar or vector return type");
7658 return parseLandingPad(Inst, PFS);
7660 return parseFreeze(Inst, PFS);
7672 return parseAlloc(Inst, PFS);
7674 return parseLoad(Inst, PFS);
7676 return parseStore(Inst, PFS);
7678 return parseCmpXchg(Inst, PFS);
7680 return parseAtomicRMW(Inst, PFS);
7682 return parseFence(Inst, PFS);
7684 return parseGetElementPtr(Inst, PFS);
7686 return parseExtractValue(Inst, PFS);
7688 return parseInsertValue(Inst, PFS);
7693bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7694 if (
Opc == Instruction::FCmp) {
7695 switch (Lex.getKind()) {
7697 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7716 switch (Lex.getKind()) {
7718 return tokError(
"expected icmp predicate (e.g. 'eq')");
7742bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7743 PerFunctionState &PFS) {
7744 SMLoc TypeLoc = Lex.getLoc();
7746 if (parseType(Ty,
true ))
7749 Type *ResType = PFS.getFunction().getReturnType();
7753 return error(TypeLoc,
"value doesn't match function result type '" +
7761 if (parseValue(Ty, RV, PFS))
7765 return error(TypeLoc,
"value doesn't match function result type '" +
7775bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7779 if (parseTypeAndValue(Op0, Loc, PFS))
7788 return error(Loc,
"branch condition must have 'i1' type");
7790 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7791 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7792 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7793 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7805bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7806 LocTy CondLoc, BBLoc;
7809 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7810 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7811 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7815 if (!
Cond->getType()->isIntegerTy())
7816 return error(CondLoc,
"switch condition must have integer type");
7819 SmallPtrSet<Value*, 32> SeenCases;
7825 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7826 parseToken(
lltok::comma,
"expected ',' after case value") ||
7827 parseTypeAndBasicBlock(DestBB, PFS))
7830 if (!SeenCases.
insert(Constant).second)
7831 return error(CondLoc,
"duplicate case value in switch");
7833 return error(CondLoc,
"case value is not a constant integer");
7841 for (
const auto &[OnVal, Dest] : Table)
7842 SI->addCase(OnVal, Dest);
7850bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7853 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7854 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7858 if (!
Address->getType()->isPointerTy())
7859 return error(AddrLoc,
"indirectbr address must have pointer type");
7862 SmallVector<BasicBlock*, 16> DestList;
7866 if (parseTypeAndBasicBlock(DestBB, PFS))
7871 if (parseTypeAndBasicBlock(DestBB, PFS))
7877 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7881 for (BasicBlock *Dest : DestList)
7891 FunctionType *&FuncTy) {
7897 for (
const ParamInfo &Arg : ArgList)
7911bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7912 LocTy CallLoc = Lex.getLoc();
7913 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7914 std::vector<unsigned> FwdRefAttrGrps;
7917 unsigned InvokeAddrSpace;
7918 Type *RetType =
nullptr;
7925 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7926 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7927 parseType(RetType, RetTypeLoc,
true ) ||
7928 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7929 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7931 parseOptionalOperandBundles(BundleList, PFS) ||
7933 parseTypeAndBasicBlock(NormalBB, PFS) ||
7935 parseTypeAndBasicBlock(UnwindBB, PFS))
7942 if (resolveFunctionType(RetType, ArgList, Ty))
7943 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7949 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
7954 SmallVector<Value *, 8>
Args;
7961 for (
const ParamInfo &Arg : ArgList) {
7962 Type *ExpectedTy =
nullptr;
7965 }
else if (!Ty->isVarArg()) {
7966 return error(Arg.Loc,
"too many arguments specified");
7969 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7970 return error(Arg.Loc,
"argument is not of expected type '" +
7972 Args.push_back(Arg.V);
7977 return error(CallLoc,
"not enough parameters specified for call");
7986 II->setCallingConv(CC);
7987 II->setAttributes(PAL);
7988 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
7995bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7997 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8005bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8006 PerFunctionState &PFS) {
8007 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8012 if (!
Args.empty() &&
8013 parseToken(
lltok::comma,
"expected ',' in argument list"))
8018 Type *ArgTy =
nullptr;
8019 if (parseType(ArgTy, ArgLoc))
8024 if (parseMetadataAsValue(V, PFS))
8027 if (parseValue(ArgTy, V, PFS))
8039bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8040 Value *CleanupPad =
nullptr;
8042 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8057 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8068bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8069 Value *CatchPad =
nullptr;
8071 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8078 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8079 parseTypeAndBasicBlock(BB, PFS))
8088bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8096 return tokError(
"expected scope value for catchswitch");
8101 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8107 if (parseTypeAndBasicBlock(DestBB, PFS))
8112 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8115 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8123 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8129 for (BasicBlock *DestBB : Table)
8130 CatchSwitch->addHandler(DestBB);
8137bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8138 Value *CatchSwitch =
nullptr;
8144 return tokError(
"expected scope value for catchpad");
8149 SmallVector<Value *, 8>
Args;
8150 if (parseExceptionArgs(Args, PFS))
8159bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8160 Value *ParentPad =
nullptr;
8167 return tokError(
"expected scope value for cleanuppad");
8172 SmallVector<Value *, 8>
Args;
8173 if (parseExceptionArgs(Args, PFS))
8189bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8190 unsigned Opc,
bool IsFP) {
8192 if (parseTypeAndValue(
LHS, Loc, PFS))
8199 return error(Loc,
"invalid operand type for instruction");
8209bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8210 LocTy CallLoc = Lex.getLoc();
8211 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8212 std::vector<unsigned> FwdRefAttrGrps;
8215 Type *RetType =
nullptr;
8222 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8223 parseType(RetType, RetTypeLoc,
true ) ||
8224 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8225 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8227 parseOptionalOperandBundles(BundleList, PFS) ||
8229 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8234 SmallVector<BasicBlock *, 16> IndirectDests;
8238 if (parseTypeAndBasicBlock(DestBB, PFS))
8243 if (parseTypeAndBasicBlock(DestBB, PFS))
8249 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8256 if (resolveFunctionType(RetType, ArgList, Ty))
8257 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8268 SmallVector<Value *, 8>
Args;
8275 for (
const ParamInfo &Arg : ArgList) {
8276 Type *ExpectedTy =
nullptr;
8279 }
else if (!Ty->isVarArg()) {
8280 return error(Arg.Loc,
"too many arguments specified");
8283 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8284 return error(Arg.Loc,
"argument is not of expected type '" +
8286 Args.push_back(Arg.V);
8291 return error(CallLoc,
"not enough parameters specified for call");
8303 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8317bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8318 unsigned Opc,
bool IsFP) {
8320 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8321 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8329 return error(Loc,
"invalid operand type for instruction");
8337bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8340 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8341 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8347 "instruction requires integer or integer vector operands");
8356bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8362 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8363 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8367 if (
Opc == Instruction::FCmp) {
8369 return error(Loc,
"fcmp requires floating point operands");
8372 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8375 return error(Loc,
"icmp requires integer operands");
8387bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8391 Type *DestTy =
nullptr;
8392 if (parseTypeAndValue(
Op, Loc, PFS) ||
8393 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8398 return error(Loc,
"invalid cast opcode for cast from '" +
8407bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8409 Value *Op0, *Op1, *Op2;
8410 if (parseTypeAndValue(Op0, Loc, PFS) ||
8411 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8412 parseTypeAndValue(Op1, PFS) ||
8413 parseToken(
lltok::comma,
"expected ',' after select value") ||
8414 parseTypeAndValue(Op2, PFS))
8418 return error(Loc, Reason);
8426bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8428 Type *EltTy =
nullptr;
8430 if (parseTypeAndValue(
Op, PFS) ||
8431 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8432 parseType(EltTy, TypeLoc))
8436 return error(TypeLoc,
"va_arg requires operand with first class type");
8438 Inst =
new VAArgInst(
Op, EltTy);
8444bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8447 if (parseTypeAndValue(Op0, Loc, PFS) ||
8448 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8449 parseTypeAndValue(Op1, PFS))
8453 return error(Loc,
"invalid extractelement operands");
8461bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8463 Value *Op0, *Op1, *Op2;
8464 if (parseTypeAndValue(Op0, Loc, PFS) ||
8465 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8466 parseTypeAndValue(Op1, PFS) ||
8467 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8468 parseTypeAndValue(Op2, PFS))
8472 return error(Loc,
"invalid insertelement operands");
8480bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8482 Value *Op0, *Op1, *Op2;
8483 if (parseTypeAndValue(Op0, Loc, PFS) ||
8484 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8485 parseTypeAndValue(Op1, PFS) ||
8486 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8487 parseTypeAndValue(Op2, PFS))
8491 return error(Loc,
"invalid shufflevector operands");
8493 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8499int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8503 if (parseType(Ty, TypeLoc))
8507 return error(TypeLoc,
"phi node must have first class type");
8510 bool AteExtraComma =
false;
8522 AteExtraComma =
true;
8526 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8527 parseValue(Ty, Op0, PFS) ||
8528 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8537 for (
const auto &[Val, BB] : PHIVals)
8540 return AteExtraComma ? InstExtraComma : InstNormal;
8549bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8552 if (parseType(Ty, TyLoc))
8565 return tokError(
"expected 'catch' or 'filter' clause type");
8569 if (parseTypeAndValue(V, VLoc, PFS))
8576 return error(VLoc,
"'catch' clause has an invalid type");
8579 return error(VLoc,
"'filter' clause has an invalid type");
8584 return error(VLoc,
"clause argument must be a constant");
8588 Inst = LP.release();
8594bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8597 if (parseTypeAndValue(
Op, Loc, PFS))
8600 Inst =
new FreezeInst(
Op);
8613bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8615 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8616 std::vector<unsigned> FwdRefAttrGrps;
8618 unsigned CallAddrSpace;
8620 Type *RetType =
nullptr;
8625 LocTy CallLoc = Lex.getLoc();
8629 "expected 'tail call', 'musttail call', or 'notail call'"))
8632 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8634 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8635 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8636 parseType(RetType, RetTypeLoc,
true ) ||
8637 parseValID(CalleeID, &PFS) ||
8639 PFS.getFunction().isVarArg()) ||
8640 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8641 parseOptionalOperandBundles(BundleList, PFS))
8648 if (resolveFunctionType(RetType, ArgList, Ty))
8649 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8655 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8662 SmallVector<Value*, 8>
Args;
8668 for (
const ParamInfo &Arg : ArgList) {
8669 Type *ExpectedTy =
nullptr;
8672 }
else if (!Ty->isVarArg()) {
8673 return error(Arg.Loc,
"too many arguments specified");
8676 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8677 return error(Arg.Loc,
"argument is not of expected type '" +
8679 Args.push_back(Arg.V);
8680 Attrs.push_back(Arg.Attrs);
8684 return error(CallLoc,
"not enough parameters specified for call");
8697 return error(CallLoc,
"fast-math-flags specified for call without "
8698 "floating-point scalar or vector return type");
8705 if (SeenNewDbgInfoFormat) {
8707 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8708 "using non-intrinsic debug info");
8710 SeenOldDbgInfoFormat =
true;
8713 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8725int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8727 LocTy SizeLoc, TyLoc, ASLoc;
8728 MaybeAlign Alignment;
8729 unsigned AddrSpace = 0;
8732 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8733 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8735 if (parseType(Ty, TyLoc))
8739 return error(TyLoc,
"invalid type for alloca");
8741 bool AteExtraComma =
false;
8743 if (Lex.getKind() == lltok::kw_align) {
8744 if (parseOptionalAlignment(Alignment))
8746 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8749 ASLoc = Lex.getLoc();
8750 if (parseOptionalAddrSpace(AddrSpace))
8753 AteExtraComma =
true;
8755 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8758 if (Lex.getKind() == lltok::kw_align) {
8759 if (parseOptionalAlignment(Alignment))
8761 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8764 ASLoc = Lex.getLoc();
8765 if (parseOptionalAddrSpace(AddrSpace))
8768 AteExtraComma =
true;
8774 if (
Size && !
Size->getType()->isIntegerTy())
8775 return error(SizeLoc,
"element count must have integer type");
8777 SmallPtrSet<Type *, 4> Visited;
8778 if (!Alignment && !Ty->
isSized(&Visited))
8779 return error(TyLoc,
"Cannot allocate unsized type");
8781 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8782 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
8786 return AteExtraComma ? InstExtraComma : InstNormal;
8793int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8795 MaybeAlign Alignment;
8796 bool AteExtraComma =
false;
8797 bool isAtomic =
false;
8806 bool isVolatile =
false;
8813 LocTy ExplicitTypeLoc = Lex.getLoc();
8814 if (parseType(Ty) ||
8815 parseToken(
lltok::comma,
"expected comma after load's type") ||
8816 parseTypeAndValue(Val, Loc, PFS) ||
8817 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8818 parseOptionalCommaAlign(Alignment, AteExtraComma))
8822 return error(Loc,
"load operand must be a pointer to a first class type");
8823 if (isAtomic && !Alignment)
8824 return error(Loc,
"atomic load must have explicit non-zero alignment");
8827 return error(Loc,
"atomic load cannot use Release ordering");
8829 SmallPtrSet<Type *, 4> Visited;
8830 if (!Alignment && !Ty->
isSized(&Visited))
8831 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8833 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8834 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8835 return AteExtraComma ? InstExtraComma : InstNormal;
8843int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8845 MaybeAlign Alignment;
8846 bool AteExtraComma =
false;
8847 bool isAtomic =
false;
8856 bool isVolatile =
false;
8862 if (parseTypeAndValue(Val, Loc, PFS) ||
8863 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8864 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8865 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8866 parseOptionalCommaAlign(Alignment, AteExtraComma))
8870 return error(PtrLoc,
"store operand must be a pointer");
8872 return error(Loc,
"store operand must be a first class value");
8873 if (isAtomic && !Alignment)
8874 return error(Loc,
"atomic store must have explicit non-zero alignment");
8877 return error(Loc,
"atomic store cannot use Acquire ordering");
8878 SmallPtrSet<Type *, 4> Visited;
8880 return error(Loc,
"storing unsized types is not allowed");
8882 Alignment = M->getDataLayout().getABITypeAlign(Val->
getType());
8884 Inst =
new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8885 return AteExtraComma ? InstExtraComma : InstNormal;
8892int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8894 bool AteExtraComma =
false;
8898 bool isVolatile =
false;
8899 bool isWeak =
false;
8900 MaybeAlign Alignment;
8908 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8909 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8910 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8911 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8912 parseTypeAndValue(New, NewLoc, PFS) ||
8913 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8914 parseOrdering(FailureOrdering) ||
8915 parseOptionalCommaAlign(Alignment, AteExtraComma))
8919 return tokError(
"invalid cmpxchg success ordering");
8921 return tokError(
"invalid cmpxchg failure ordering");
8923 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8924 if (
Cmp->getType() !=
New->getType())
8925 return error(NewLoc,
"compare value and new value type do not match");
8926 if (!
New->getType()->isFirstClassType())
8927 return error(NewLoc,
"cmpxchg operand must be a first class value");
8929 const Align DefaultAlignment(
8930 PFS.getFunction().getDataLayout().getTypeStoreSize(
8933 AtomicCmpXchgInst *CXI =
8934 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8935 SuccessOrdering, FailureOrdering, SSID);
8940 return AteExtraComma ? InstExtraComma : InstNormal;
8946int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8948 bool AteExtraComma =
false;
8951 bool isVolatile =
false;
8954 MaybeAlign Alignment;
8959 switch (Lex.getKind()) {
8961 return tokError(
"expected binary operation in atomicrmw");
9012 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9013 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9014 parseTypeAndValue(Val, ValLoc, PFS) ||
9015 parseScopeAndOrdering(
true , SSID, Ordering) ||
9016 parseOptionalCommaAlign(Alignment, AteExtraComma))
9020 return tokError(
"atomicrmw cannot be unordered");
9022 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9024 return error(ValLoc,
"atomicrmw operand may not be scalable");
9033 " operand must be an integer, floating point, or pointer type");
9037 return error(ValLoc,
"atomicrmw " +
9039 " operand must be a floating point type");
9043 return error(ValLoc,
"atomicrmw " +
9045 " operand must be an integer");
9050 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
9053 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
9055 const Align DefaultAlignment(
9056 PFS.getFunction().getDataLayout().getTypeStoreSize(
9058 AtomicRMWInst *RMWI =
9060 Alignment.value_or(DefaultAlignment), Ordering, SSID);
9063 return AteExtraComma ? InstExtraComma : InstNormal;
9068int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9071 if (parseScopeAndOrdering(
true , SSID, Ordering))
9075 return tokError(
"fence cannot be unordered");
9077 return tokError(
"fence cannot be monotonic");
9079 Inst =
new FenceInst(Context, Ordering, SSID);
9085int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9086 Value *Ptr =
nullptr;
9087 Value *Val =
nullptr;
9103 if (parseType(Ty) ||
9104 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9105 parseTypeAndValue(Ptr, Loc, PFS))
9110 if (!BasePointerType)
9111 return error(Loc,
"base of getelementptr must be a pointer");
9113 SmallVector<Value*, 16> Indices;
9114 bool AteExtraComma =
false;
9117 ElementCount GEPWidth =
BaseType->isVectorTy()
9123 AteExtraComma =
true;
9126 if (parseTypeAndValue(Val, EltLoc, PFS))
9129 return error(EltLoc,
"getelementptr index must be an integer");
9132 ElementCount ValNumEl = ValVTy->getElementCount();
9136 "getelementptr vector index has a wrong number of elements");
9137 GEPWidth = ValNumEl;
9142 SmallPtrSet<Type*, 4> Visited;
9144 return error(Loc,
"base element of getelementptr must be sized");
9148 return error(Loc,
"getelementptr cannot target structure that contains "
9149 "scalable vector type");
9152 return error(Loc,
"invalid getelementptr indices");
9155 GEP->setNoWrapFlags(NW);
9156 return AteExtraComma ? InstExtraComma : InstNormal;
9161int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9163 SmallVector<unsigned, 4> Indices;
9165 if (parseTypeAndValue(Val, Loc, PFS) ||
9166 parseIndexList(Indices, AteExtraComma))
9170 return error(Loc,
"extractvalue operand must be aggregate type");
9173 return error(Loc,
"invalid indices for extractvalue");
9175 return AteExtraComma ? InstExtraComma : InstNormal;
9180int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9182 SmallVector<unsigned, 4> Indices;
9184 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9185 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9186 parseTypeAndValue(Val1, Loc1, PFS) ||
9187 parseIndexList(Indices, AteExtraComma))
9191 return error(Loc0,
"insertvalue operand must be aggregate type");
9195 return error(Loc0,
"invalid indices for insertvalue");
9196 if (IndexedType != Val1->
getType())
9197 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9201 return AteExtraComma ? InstExtraComma : InstNormal;
9212bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9227 if (parseMetadata(MD,
nullptr))
9232 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9238bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9240 if (!
V->hasUseList())
9243 return error(Loc,
"value has no uses");
9245 unsigned NumUses = 0;
9246 SmallDenseMap<const Use *, unsigned, 16> Order;
9247 for (
const Use &U :
V->uses()) {
9248 if (++NumUses > Indexes.
size())
9250 Order[&
U] = Indexes[NumUses - 1];
9253 return error(Loc,
"value only has one use");
9254 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9256 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9258 V->sortUseList([&](
const Use &L,
const Use &R) {
9266bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9267 SMLoc Loc = Lex.getLoc();
9271 return tokError(
"expected non-empty list of uselistorder indexes");
9278 bool IsOrdered =
true;
9279 assert(Indexes.
empty() &&
"Expected empty order vector");
9282 if (parseUInt32(Index))
9287 Max = std::max(Max, Index);
9288 IsOrdered &= Index == Indexes.
size();
9296 if (Indexes.
size() < 2)
9297 return error(Loc,
"expected >= 2 uselistorder indexes");
9300 "expected distinct uselistorder indexes in range [0, size)");
9302 return error(Loc,
"expected uselistorder indexes to change the order");
9309bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9310 SMLoc Loc = Lex.getLoc();
9315 SmallVector<unsigned, 16> Indexes;
9316 if (parseTypeAndValue(V, PFS) ||
9317 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9318 parseUseListOrderIndexes(Indexes))
9321 return sortUseListOrder(V, Indexes, Loc);
9326bool LLParser::parseUseListOrderBB() {
9328 SMLoc Loc = Lex.getLoc();
9332 SmallVector<unsigned, 16> Indexes;
9333 if (parseValID(Fn,
nullptr) ||
9334 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9335 parseValID(Label,
nullptr) ||
9336 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9337 parseUseListOrderIndexes(Indexes))
9343 GV = M->getNamedValue(Fn.
StrVal);
9345 GV = NumberedVals.get(Fn.
UIntVal);
9347 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9350 "invalid function forward reference in uselistorder_bb");
9353 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9354 if (
F->isDeclaration())
9355 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
9359 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
9361 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
9362 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
9364 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
9366 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
9368 return sortUseListOrder(V, Indexes, Loc);
9374bool LLParser::parseModuleEntry(
unsigned ID) {
9383 parseStringConstant(Path) ||
9391 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9392 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9393 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9394 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9395 parseUInt32(Hash[4]))
9402 auto ModuleEntry = Index->addModule(Path, Hash);
9403 ModuleIdMap[
ID] = ModuleEntry->first();
9410bool LLParser::parseTypeIdEntry(
unsigned ID) {
9419 parseStringConstant(Name))
9422 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9424 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9429 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9430 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9431 for (
auto TIDRef : FwdRefTIDs->second) {
9433 "Forward referenced type id GUID expected to be 0");
9436 ForwardRefTypeIds.erase(FwdRefTIDs);
9444bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9448 parseTypeTestResolution(TIS.
TTRes))
9453 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9464 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
9470bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9479 parseStringConstant(Name))
9483 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9490 IdToIndexMapType IdToIndexMap;
9503 if (parseGVReference(VI, GVId))
9510 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9511 TI.push_back({
Offset, VI});
9519 for (
auto I : IdToIndexMap) {
9520 auto &Infos = ForwardRefValueInfos[
I.first];
9521 for (
auto P :
I.second) {
9523 "Forward referenced ValueInfo expected to be empty");
9524 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9534 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9535 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9536 for (
auto TIDRef : FwdRefTIDs->second) {
9538 "Forward referenced type id GUID expected to be 0");
9541 ForwardRefTypeIds.erase(FwdRefTIDs);
9553bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9561 switch (Lex.getKind()) {
9581 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9593 switch (Lex.getKind()) {
9608 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9621 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9634bool LLParser::parseOptionalWpdResolutions(
9635 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9643 WholeProgramDevirtResolution WPDRes;
9647 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9650 WPDResMap[
Offset] = WPDRes;
9667bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9675 switch (Lex.getKind()) {
9686 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9692 switch (Lex.getKind()) {
9700 if (parseOptionalResByArg(WPDRes.
ResByArg))
9704 return error(Lex.getLoc(),
9705 "expected optional WholeProgramDevirtResolution field");
9722bool LLParser::parseOptionalResByArg(
9723 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9731 std::vector<uint64_t>
Args;
9732 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9740 WholeProgramDevirtResolution::ByArg ByArg;
9741 switch (Lex.getKind()) {
9755 return error(Lex.getLoc(),
9756 "unexpected WholeProgramDevirtResolution::ByArg kind");
9762 switch (Lex.getKind()) {
9766 parseUInt64(ByArg.
Info))
9772 parseUInt32(ByArg.
Byte))
9778 parseUInt32(ByArg.
Bit))
9782 return error(Lex.getLoc(),
9783 "expected optional whole program devirt field");
9790 ResByArg[
Args] = ByArg;
9801bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9809 if (parseUInt64(Val))
9811 Args.push_back(Val);
9820static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9825 assert(!(ReadOnly && WriteOnly));
9835bool LLParser::addGlobalValueToIndex(
9837 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
9842 VI = Index->getOrInsertValueInfo(GUID);
9846 auto *GV = M->getNamedValue(Name);
9848 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
9850 VI = Index->getOrInsertValueInfo(GV);
9854 "Need a source_filename to compute GUID for local");
9857 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9862 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9863 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9864 for (
auto VIRef : FwdRefVIs->second) {
9866 "Forward referenced ValueInfo expected to be empty");
9869 ForwardRefValueInfos.erase(FwdRefVIs);
9873 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9874 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9875 for (
auto AliaseeRef : FwdRefAliasees->second) {
9876 assert(!AliaseeRef.first->hasAliasee() &&
9877 "Forward referencing alias already has aliasee");
9878 assert(Summary &&
"Aliasee must be a definition");
9879 AliaseeRef.first->setAliasee(VI,
Summary.get());
9881 ForwardRefAliasees.erase(FwdRefAliasees);
9886 Index->addGlobalValueSummary(VI, std::move(Summary));
9889 if (
ID == NumberedValueInfos.size())
9890 NumberedValueInfos.push_back(VI);
9893 if (
ID > NumberedValueInfos.size())
9894 NumberedValueInfos.resize(
ID + 1);
9895 NumberedValueInfos[
ID] =
VI;
9903bool LLParser::parseSummaryIndexFlags() {
9910 if (parseUInt64(Flags))
9913 Index->setFlags(Flags);
9919bool LLParser::parseBlockCount() {
9925 uint64_t BlockCount;
9926 if (parseUInt64(BlockCount))
9929 Index->setBlockCount(BlockCount);
9937bool LLParser::parseGVEntry(
unsigned ID) {
9945 LocTy Loc = Lex.getLoc();
9948 switch (Lex.getKind()) {
9952 parseStringConstant(Name))
9958 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9962 return error(Lex.getLoc(),
"expected name or guid tag");
9985 switch (Lex.getKind()) {
9987 if (parseFunctionSummary(Name, GUID,
ID))
9991 if (parseVariableSummary(Name, GUID,
ID))
9995 if (parseAliasSummary(Name, GUID,
ID))
9999 return error(Lex.getLoc(),
"expected summary type");
10017 LocTy Loc = Lex.getLoc();
10021 StringRef ModulePath;
10022 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10025 false,
false,
false,
10027 unsigned InstCount;
10029 FunctionSummary::TypeIdInfo TypeIdInfo;
10030 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10032 std::vector<CallsiteInfo> Callsites;
10033 std::vector<AllocInfo> Allocs;
10035 FunctionSummary::FFlags FFlags = {};
10038 parseModuleReference(ModulePath) ||
10039 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10042 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10047 switch (Lex.getKind()) {
10049 if (parseOptionalFFlags(FFlags))
10053 if (parseOptionalCalls(Calls))
10057 if (parseOptionalTypeIdInfo(TypeIdInfo))
10061 if (parseOptionalRefs(Refs))
10065 if (parseOptionalParamAccesses(ParamAccesses))
10069 if (parseOptionalAllocs(Allocs))
10073 if (parseOptionalCallsites(Callsites))
10077 return error(Lex.getLoc(),
"expected optional function summary field");
10084 auto FS = std::make_unique<FunctionSummary>(
10085 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10091 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10093 FS->setModulePath(ModulePath);
10095 return addGlobalValueToIndex(Name, GUID,
10097 std::move(FS), Loc);
10105 LocTy Loc = Lex.getLoc();
10109 StringRef ModulePath;
10110 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10113 false,
false,
false,
10115 GlobalVarSummary::GVarFlags GVarFlags(
false,
10123 parseModuleReference(ModulePath) ||
10124 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10126 parseGVarFlags(GVarFlags))
10131 switch (Lex.getKind()) {
10133 if (parseOptionalVTableFuncs(VTableFuncs))
10137 if (parseOptionalRefs(Refs))
10141 return error(Lex.getLoc(),
"expected optional variable summary field");
10149 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10151 GS->setModulePath(ModulePath);
10152 GS->setVTableFuncs(std::move(VTableFuncs));
10154 return addGlobalValueToIndex(Name, GUID,
10156 std::move(GS), Loc);
10165 LocTy Loc = Lex.getLoc();
10168 StringRef ModulePath;
10169 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10172 false,
false,
false,
10176 parseModuleReference(ModulePath) ||
10177 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10183 ValueInfo AliaseeVI;
10185 auto AS = std::make_unique<AliasSummary>(GVFlags);
10186 AS->setModulePath(ModulePath);
10189 if (parseGVReference(AliaseeVI, GVId))
10194 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10196 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10197 assert(Summary &&
"Aliasee must be a definition");
10198 AS->setAliasee(AliaseeVI, Summary);
10205 return addGlobalValueToIndex(Name, GUID,
10207 std::move(AS), Loc);
10212bool LLParser::parseFlag(
unsigned &Val) {
10213 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10214 return tokError(
"expected integer");
10215 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10231bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10235 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10241 switch (Lex.getKind()) {
10244 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10250 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10256 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10262 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10268 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10274 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10280 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10286 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10292 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10298 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10303 return error(Lex.getLoc(),
"expected function flag type");
10307 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10318bool LLParser::parseOptionalCalls(
10319 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10323 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10327 IdToIndexMapType IdToIndexMap;
10336 LocTy Loc = Lex.getLoc();
10338 if (parseGVReference(VI, GVId))
10342 unsigned RelBF = 0;
10343 unsigned HasTailCall =
false;
10347 switch (Lex.getKind()) {
10350 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10356 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10361 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10365 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10372 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10382 for (
auto I : IdToIndexMap) {
10383 auto &Infos = ForwardRefValueInfos[
I.first];
10384 for (
auto P :
I.second) {
10386 "Forward referenced ValueInfo expected to be empty");
10387 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10400 switch (Lex.getKind()) {
10404 case lltok::kw_cold:
10410 case lltok::kw_hot:
10417 return error(Lex.getLoc(),
"invalid call edge hotness");
10426bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10430 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10434 IdToIndexMapType IdToIndexMap;
10438 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10443 LocTy Loc = Lex.getLoc();
10445 if (parseGVReference(VI, GVId))
10458 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10459 VTableFuncs.push_back({
VI,
Offset});
10461 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10467 for (
auto I : IdToIndexMap) {
10468 auto &Infos = ForwardRefValueInfos[
I.first];
10469 for (
auto P :
I.second) {
10471 "Forward referenced ValueInfo expected to be empty");
10472 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10476 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10483bool LLParser::parseParamNo(uint64_t &ParamNo) {
10485 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10491bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10494 auto ParseAPSInt = [&](
APSInt &Val) {
10496 return tokError(
"expected integer");
10497 Val = Lex.getAPSIntVal();
10499 Val.setIsSigned(
true);
10521bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10522 IdLocListType &IdLocList) {
10530 LocTy Loc = Lex.getLoc();
10531 if (parseGVReference(VI, GVId))
10535 IdLocList.emplace_back(GVId, Loc);
10538 parseParamNo(
Call.ParamNo) ||
10540 parseParamAccessOffset(
Call.Offsets))
10552bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10553 IdLocListType &IdLocList) {
10555 parseParamNo(
Param.ParamNo) ||
10557 parseParamAccessOffset(
Param.Use))
10566 FunctionSummary::ParamAccess::Call
Call;
10567 if (parseParamAccessCall(
Call, IdLocList))
10584bool LLParser::parseOptionalParamAccesses(
10585 std::vector<FunctionSummary::ParamAccess> &Params) {
10593 IdLocListType VContexts;
10594 size_t CallsNum = 0;
10596 FunctionSummary::ParamAccess ParamAccess;
10597 if (parseParamAccess(ParamAccess, VContexts))
10599 CallsNum += ParamAccess.
Calls.size();
10600 assert(VContexts.size() == CallsNum);
10602 Params.emplace_back(std::move(ParamAccess));
10610 IdLocListType::const_iterator ItContext = VContexts.begin();
10611 for (
auto &PA : Params) {
10612 for (
auto &
C : PA.Calls) {
10614 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10615 ItContext->second);
10619 assert(ItContext == VContexts.end());
10626bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10630 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10634 struct ValueContext {
10639 std::vector<ValueContext> VContexts;
10643 VC.Loc = Lex.getLoc();
10644 if (parseGVReference(
VC.VI,
VC.GVId))
10646 VContexts.push_back(VC);
10652 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10653 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10656 IdToIndexMapType IdToIndexMap;
10657 for (
auto &VC : VContexts) {
10662 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10668 for (
auto I : IdToIndexMap) {
10669 auto &Infos = ForwardRefValueInfos[
I.first];
10670 for (
auto P :
I.second) {
10672 "Forward referenced ValueInfo expected to be empty");
10673 Infos.emplace_back(&Refs[
P.first],
P.second);
10687bool LLParser::parseOptionalTypeIdInfo(
10688 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10697 switch (Lex.getKind()) {
10699 if (parseTypeTests(TypeIdInfo.
TypeTests))
10723 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
10727 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10736bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10744 IdToIndexMapType IdToIndexMap;
10748 unsigned ID = Lex.getUIntVal();
10749 LocTy Loc = Lex.getLoc();
10753 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10755 }
else if (parseUInt64(GUID))
10757 TypeTests.push_back(GUID);
10762 for (
auto I : IdToIndexMap) {
10763 auto &Ids = ForwardRefTypeIds[
I.first];
10764 for (
auto P :
I.second) {
10765 assert(TypeTests[
P.first] == 0 &&
10766 "Forward referenced type id GUID expected to be 0");
10767 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10771 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10779bool LLParser::parseVFuncIdList(
10780 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10781 assert(Lex.getKind() == Kind);
10788 IdToIndexMapType IdToIndexMap;
10790 FunctionSummary::VFuncId VFuncId;
10791 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10793 VFuncIdList.push_back(VFuncId);
10801 for (
auto I : IdToIndexMap) {
10802 auto &Ids = ForwardRefTypeIds[
I.first];
10803 for (
auto P :
I.second) {
10804 assert(VFuncIdList[
P.first].GUID == 0 &&
10805 "Forward referenced type id GUID expected to be 0");
10806 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10815bool LLParser::parseConstVCallList(
10817 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10818 assert(Lex.getKind() == Kind);
10825 IdToIndexMapType IdToIndexMap;
10827 FunctionSummary::ConstVCall ConstVCall;
10828 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10830 ConstVCallList.push_back(ConstVCall);
10838 for (
auto I : IdToIndexMap) {
10839 auto &Ids = ForwardRefTypeIds[
I.first];
10840 for (
auto P :
I.second) {
10841 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10842 "Forward referenced type id GUID expected to be 0");
10843 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10852bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10853 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10855 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10859 if (parseArgs(ConstVCall.
Args))
10871bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10872 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10882 unsigned ID = Lex.getUIntVal();
10883 LocTy Loc = Lex.getLoc();
10887 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
10889 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10891 parseUInt64(VFuncId.
GUID))
10897 parseUInt64(VFuncId.
Offset) ||
10909bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10919 switch (Lex.getKind()) {
10926 assert(HasLinkage &&
"Linkage not optional in summary entry");
10933 parseOptionalVisibility(Flag);
10938 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10944 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10950 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10956 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10965 if (parseOptionalImportType(Lex.getKind(), IK))
10967 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10972 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10977 return error(Lex.getLoc(),
"expected gv flag type");
10991bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10999 auto ParseRest = [
this](
unsigned int &Val) {
11003 return parseFlag(Val);
11008 switch (Lex.getKind()) {
11009 case lltok::kw_readonly:
11010 if (ParseRest(Flag))
11014 case lltok::kw_writeonly:
11015 if (ParseRest(Flag))
11020 if (ParseRest(Flag))
11025 if (ParseRest(Flag))
11030 return error(Lex.getLoc(),
"expected gvar flag type");
11038bool LLParser::parseModuleReference(StringRef &ModulePath) {
11045 unsigned ModuleID = Lex.getUIntVal();
11046 auto I = ModuleIdMap.find(ModuleID);
11048 assert(
I != ModuleIdMap.end());
11049 ModulePath =
I->second;
11055bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11058 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11062 GVId = Lex.getUIntVal();
11064 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11066 VI = NumberedValueInfos[GVId];
11083bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11087 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11099 SmallVector<uint8_t> Versions;
11102 if (parseAllocType(V))
11107 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11111 std::vector<MIBInfo> MIBs;
11112 if (parseMemProfs(MIBs))
11115 Allocs.push_back({Versions, MIBs});
11132bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11136 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11142 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11151 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11157 SmallVector<unsigned> StackIdIndices;
11161 uint64_t StackId = 0;
11162 if (parseUInt64(StackId))
11164 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11185bool LLParser::parseAllocType(uint8_t &
AllocType) {
11186 switch (Lex.getKind()) {
11193 case lltok::kw_cold:
11196 case lltok::kw_hot:
11200 return error(Lex.getLoc(),
"invalid alloc type");
11213bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11217 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11221 IdToIndexMapType IdToIndexMap;
11224 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11231 LocTy Loc = Lex.getLoc();
11233 if (parseGVReference(VI, GVId))
11237 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11243 SmallVector<unsigned> Clones;
11246 if (parseUInt32(V))
11252 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11258 SmallVector<unsigned> StackIdIndices;
11262 uint64_t StackId = 0;
11263 if (parseUInt64(StackId))
11265 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11276 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11277 Callsites.push_back({
VI, Clones, StackIdIndices});
11285 for (
auto I : IdToIndexMap) {
11286 auto &Infos = ForwardRefValueInfos[
I.first];
11287 for (
auto P :
I.second) {
11289 "Forward referenced ValueInfo expected to be empty");
11290 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11294 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-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...
GlobalValue::SanitizerMetadata SanitizerMetadata
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
dot regions Print regions of function to dot file(with no function bodies)"
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
static SymbolRef::Type getType(const Symbol *Sym)
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static const fltSemantics & IEEEsingle()
static const fltSemantics & BFloat()
static const fltSemantics & IEEEdouble()
static constexpr roundingMode rmNearestTiesToEven
static const fltSemantics & IEEEhalf()
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
APSInt extOrTrunc(uint32_t width) const
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ 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
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ 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 LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static constexpr ElementCount getFixed(ScalarTy MinVal)
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
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.
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind getKind() const
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
A Module instance is used to store all the information related to an LLVM module.
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
constexpr const char * getPointer() const
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
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.
iterator find(StringRef Key)
StringMapIterBase< Comdat, false > iterator
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
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.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
LLVM_ABI unsigned getTag(StringRef TagString)
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
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 Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ kw_amdgpu_gfx_whole_wave
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
FunctionAddr VTableAddr Count
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
CaptureComponents
Components of the pointer that may be captured.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
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.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ TargetMem0
Represents target specific state.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
std::vector< uint64_t > Args
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
std::map< unsigned, Type * > Types
StringMap< Type * > NamedTypes
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
NumberedValues< GlobalValue * > GlobalValues
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
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
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.