62 "Allow incomplete IR on a best effort basis (references to unknown "
63 "metadata will be dropped)"));
79bool LLParser::finalizeDebugInfoFormat(
Module *M) {
82 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
83 "Mixed debug intrinsics/records seen without a parsing error?");
89 M->setIsNewDbgInfoFormat(
false);
103 "Can't read textual IR with a Context that discards named Values");
106 if (parseTargetDefinitions(DataLayoutCallback))
111 validateEndOfIndex() || finalizeDebugInfoFormat(M);
116 restoreParsingState(Slots);
120 if (parseType(Ty) || parseConstantValue(Ty,
C))
123 return error(Lex.
getLoc(),
"expected end of string");
129 restoreParsingState(Slots);
138 Read =
End.getPointer() - Start.getPointer();
143void LLParser::restoreParsingState(
const SlotMapping *Slots) {
150 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
151 for (
const auto &
I : Slots->
Types)
152 NumberedTypes.insert(
153 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
158 if (!isa<DbgInfoIntrinsic>(II) &&
159 II->
getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
164 if (
auto *MV = dyn_cast<MetadataAsValue>(V))
165 if (
auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
166 if (MD->isTemporary())
180void LLParser::dropUnknownMetadataReferences() {
181 auto Pred = [](
unsigned MDKind,
MDNode *
Node) {
return Node->isTemporary(); };
183 F.eraseMetadataIf(Pred);
185 I.eraseMetadataIf(Pred);
187 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
193 GV.eraseMetadataIf(Pred);
198 if (
Info.first->getNumTemporaryUses() == 1) {
199 NumberedMetadata.erase(
ID);
200 ForwardRefMDNodes.erase(
ID);
211 for (
const auto &RAG : ForwardRefAttrGroups) {
213 const std::vector<unsigned> &
Attrs = RAG.second;
216 for (
const auto &Attr : Attrs) {
217 auto R = NumberedAttrBuilders.find(Attr);
218 if (R != NumberedAttrBuilders.end())
222 if (
Function *Fn = dyn_cast<Function>(V)) {
232 Fn->setAlignment(*
A);
237 Fn->setAttributes(AS);
238 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
244 CI->setAttributes(AS);
245 }
else if (
InvokeInst *II = dyn_cast<InvokeInst>(V)) {
251 II->setAttributes(AS);
252 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
258 CBI->setAttributes(AS);
259 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
270 if (!ForwardRefBlockAddresses.empty())
271 return error(ForwardRefBlockAddresses.begin()->first.Loc,
272 "expected function name in blockaddress");
274 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
278 GV =
M->getNamedValue(GVRef.
StrVal);
280 GV = NumberedVals.get(GVRef.
UIntVal);
285 "' referenced by dso_local_equivalent");
289 "expected a function, alias to function, or ifunc "
290 "in dso_local_equivalent");
293 FwdRef->replaceAllUsesWith(Equiv);
294 FwdRef->eraseFromParent();
301 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
302 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
306 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
309 ForwardRefDSOLocalEquivalentIDs.clear();
310 ForwardRefDSOLocalEquivalentNames.clear();
312 for (
const auto &NT : NumberedTypes)
313 if (
NT.second.second.isValid())
315 "use of undefined type '%" +
Twine(
NT.first) +
"'");
317 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
318 NamedTypes.begin(), E = NamedTypes.end();
I != E; ++
I)
319 if (
I->second.second.isValid())
320 return error(
I->second.second,
321 "use of undefined type named '" +
I->getKey() +
"'");
323 if (!ForwardRefComdats.empty())
324 return error(ForwardRefComdats.begin()->second,
325 "use of undefined comdat '$" +
326 ForwardRefComdats.begin()->first +
"'");
343 auto *CB = dyn_cast<CallBase>(
U.getUser());
344 if (!CB || !CB->isCallee(&U))
345 return error(
Info.second,
"intrinsic can only be used as callee");
350 return error(
Info.second,
"invalid intrinsic signature");
355 Info.first->eraseFromParent();
356 ForwardRefVals.erase(
Name);
367 for (
Use &U :
V->uses()) {
368 auto *CB = dyn_cast<CallBase>(
U.getUser());
369 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
371 FTy = CB->getFunctionType();
379 Type *Ty = GetCommonFunctionType(
Info.first);
384 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
390 Info.first->replaceAllUsesWith(GV);
391 Info.first->eraseFromParent();
392 ForwardRefVals.erase(
Name);
395 if (!ForwardRefVals.empty())
396 return error(ForwardRefVals.begin()->second.second,
397 "use of undefined value '@" + ForwardRefVals.begin()->first +
400 if (!ForwardRefValIDs.empty())
401 return error(ForwardRefValIDs.begin()->second.second,
402 "use of undefined value '@" +
403 Twine(ForwardRefValIDs.begin()->first) +
"'");
406 dropUnknownMetadataReferences();
408 if (!ForwardRefMDNodes.empty())
409 return error(ForwardRefMDNodes.begin()->second.second,
410 "use of undefined metadata '!" +
411 Twine(ForwardRefMDNodes.begin()->first) +
"'");
414 for (
auto &
N : NumberedMetadata) {
415 if (
N.second && !
N.second->isResolved())
416 N.second->resolveCycles();
419 for (
auto *Inst : InstsWithTBAATag) {
420 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
423 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
426 if (MD != UpgradedMD)
427 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
436 if (UpgradeDebugInfo)
449 for (
const auto &
I : NamedTypes)
450 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
451 for (
const auto &
I : NumberedTypes)
452 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
458bool LLParser::validateEndOfIndex() {
462 if (!ForwardRefValueInfos.empty())
463 return error(ForwardRefValueInfos.begin()->second.front().second,
464 "use of undefined summary '^" +
465 Twine(ForwardRefValueInfos.begin()->first) +
"'");
467 if (!ForwardRefAliasees.empty())
468 return error(ForwardRefAliasees.begin()->second.front().second,
469 "use of undefined summary '^" +
470 Twine(ForwardRefAliasees.begin()->first) +
"'");
472 if (!ForwardRefTypeIds.empty())
473 return error(ForwardRefTypeIds.begin()->second.front().second,
474 "use of undefined type id summary '^" +
475 Twine(ForwardRefTypeIds.begin()->first) +
"'");
489 std::string TentativeDLStr =
M->getDataLayoutStr();
496 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
500 if (parseSourceFileName())
509 if (
auto LayoutOverride =
510 DataLayoutCallback(
M->getTargetTriple(), TentativeDLStr)) {
511 TentativeDLStr = *LayoutOverride;
517 M->setDataLayout(MaybeDL.
get());
521bool LLParser::parseTopLevelEntities() {
529 if (parseSummaryEntry())
533 if (parseSourceFileName())
545 return tokError(
"expected top-level entity");
556 if (parseModuleAsm())
560 if (parseUnnamedType())
564 if (parseNamedType())
568 if (parseUnnamedGlobal())
572 if (parseNamedGlobal())
577 if (parseStandaloneMetadata())
581 if (parseSummaryEntry())
585 if (parseNamedMetadata())
589 if (parseUnnamedAttrGrp())
593 if (parseUseListOrder())
597 if (parseUseListOrderBB())
606bool LLParser::parseModuleAsm() {
612 parseStringConstant(AsmStr))
615 M->appendModuleInlineAsm(AsmStr);
622bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
628 return tokError(
"unknown target property");
631 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
632 parseStringConstant(Str))
634 M->setTargetTriple(Str);
638 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
641 if (parseStringConstant(TentativeDLStr))
649bool LLParser::parseSourceFileName() {
652 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
653 parseStringConstant(SourceFileName))
656 M->setSourceFileName(SourceFileName);
662bool LLParser::parseUnnamedType() {
667 if (parseToken(
lltok::equal,
"expected '=' after name") ||
672 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
675 if (!isa<StructType>(Result)) {
676 std::pair<Type*, LocTy> &Entry = NumberedTypes[
TypeID];
678 return error(TypeLoc,
"non-struct types may not be recursive");
680 Entry.second =
SMLoc();
688bool LLParser::parseNamedType() {
693 if (parseToken(
lltok::equal,
"expected '=' after name") ||
698 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
701 if (!isa<StructType>(Result)) {
702 std::pair<Type*, LocTy> &Entry = NamedTypes[
Name];
704 return error(NameLoc,
"non-struct types may not be recursive");
706 Entry.second =
SMLoc();
714bool LLParser::parseDeclare() {
718 std::vector<std::pair<unsigned, MDNode *>> MDs;
722 if (parseMetadataAttachment(MDK,
N))
724 MDs.push_back({MDK,
N});
728 unsigned FunctionNumber = -1;
730 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
733 F->addMetadata(MD.first, *MD.second);
739bool LLParser::parseDefine() {
744 unsigned FunctionNumber = -1;
746 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
747 parseOptionalFunctionMetadata(*
F) ||
748 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
754bool LLParser::parseGlobalType(
bool &IsConstant) {
761 return tokError(
"expected 'global' or 'constant'");
767bool LLParser::parseOptionalUnnamedAddr(
788bool LLParser::parseUnnamedGlobal() {
796 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(), VarID))
800 if (parseToken(
lltok::equal,
"expected '=' after name"))
803 VarID = NumberedVals.getNext();
807 unsigned Linkage, Visibility, DLLStorageClass;
811 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
813 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
818 return parseGlobal(
Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
819 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
822 return parseAliasOrIFunc(
Name, VarID, NameLoc, Linkage, Visibility,
823 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
832bool LLParser::parseNamedGlobal() {
839 unsigned Linkage, Visibility, DLLStorageClass;
843 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
844 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
846 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
851 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
852 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
855 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
856 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
860bool LLParser::parseComdat() {
870 return tokError(
"expected comdat type");
875 return tokError(
"unknown selection kind");
897 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
898 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
901 if (
I != ComdatSymTab.
end())
904 C =
M->getOrInsertComdat(
Name);
905 C->setSelectionKind(SK);
912bool LLParser::parseMDString(
MDString *&Result) {
914 if (parseStringConstant(Str))
922bool LLParser::parseMDNodeID(
MDNode *&Result) {
926 if (parseUInt32(MID))
930 if (NumberedMetadata.count(MID)) {
931 Result = NumberedMetadata[MID];
936 auto &FwdRef = ForwardRefMDNodes[MID];
939 Result = FwdRef.first.get();
940 NumberedMetadata[MID].reset(Result);
946bool LLParser::parseNamedMetadata() {
965 if (parseDIExpression(
N,
false))
971 return tokError(
"found DIArgList outside of function");
979 return parseToken(
lltok::rbrace,
"expected end of metadata node");
984bool LLParser::parseStandaloneMetadata() {
987 unsigned MetadataID = 0;
990 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
995 return tokError(
"unexpected type in metadata definition");
999 if (parseSpecializedMDNode(
Init, IsDistinct))
1002 parseMDTuple(
Init, IsDistinct))
1006 auto FI = ForwardRefMDNodes.find(MetadataID);
1007 if (FI != ForwardRefMDNodes.end()) {
1008 auto *ToReplace = FI->second.first.get();
1011 if (isa<DIAssignID>(
Init)) {
1012 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1013 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1014 "Inst unexpectedly already has DIAssignID attachment");
1015 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
1019 ToReplace->replaceAllUsesWith(
Init);
1020 ForwardRefMDNodes.erase(FI);
1022 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
1024 if (NumberedMetadata.count(MetadataID))
1025 return tokError(
"Metadata id is already used");
1026 NumberedMetadata[MetadataID].reset(
Init);
1033bool LLParser::skipModuleSummaryEntry() {
1043 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1044 "start of summary entry");
1046 return parseSummaryIndexFlags();
1048 return parseBlockCount();
1050 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1051 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1055 unsigned NumOpenParen = 1;
1065 return tokError(
"found end of file while parsing summary entry");
1071 }
while (NumOpenParen > 0);
1077bool LLParser::parseSummaryEntry() {
1091 return skipModuleSummaryEntry();
1093 bool result =
false;
1096 result = parseGVEntry(SummaryID);
1099 result = parseModuleEntry(SummaryID);
1102 result = parseTypeIdEntry(SummaryID);
1105 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1108 result = parseSummaryIndexFlags();
1111 result = parseBlockCount();
1114 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1151bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1152 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1153 unsigned DLLStorageClass,
bool DSOLocal,
1168 return error(NameLoc,
"invalid linkage type for alias");
1171 return error(NameLoc,
1172 "symbol with local linkage must have default visibility");
1175 return error(NameLoc,
1176 "symbol with local linkage cannot have a DLL storage class");
1180 if (parseType(Ty) ||
1181 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1190 if (parseGlobalTypeAndValue(Aliasee))
1195 if (parseValID(
ID,
nullptr))
1198 return error(AliaseeLoc,
"invalid aliasee");
1199 Aliasee =
ID.ConstantVal;
1203 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1205 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1206 unsigned AddrSpace = PTy->getAddressSpace();
1212 if (!
Name.empty()) {
1213 auto I = ForwardRefVals.find(
Name);
1214 if (
I != ForwardRefVals.end()) {
1215 GVal =
I->second.first;
1216 ForwardRefVals.erase(
Name);
1217 }
else if (
M->getNamedValue(
Name)) {
1218 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1221 auto I = ForwardRefValIDs.find(NameID);
1222 if (
I != ForwardRefValIDs.end()) {
1223 GVal =
I->second.first;
1224 ForwardRefValIDs.erase(
I);
1229 std::unique_ptr<GlobalAlias> GA;
1230 std::unique_ptr<GlobalIFunc> GI;
1260 return tokError(
"unknown alias or ifunc property!");
1265 NumberedVals.add(NameID, GV);
1272 "forward reference and definition of alias have different types");
1282 M->insertAlias(GA.release());
1284 M->insertIFunc(GI.release());
1294 case lltok::kw_sanitize_memtag:
1310 Meta.NoAddress =
true;
1313 Meta.NoHWAddress =
true;
1315 case lltok::kw_sanitize_memtag:
1319 Meta.IsDynInit =
true;
1322 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1342bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1343 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1344 unsigned Visibility,
unsigned DLLStorageClass,
1348 return error(NameLoc,
1349 "symbol with local linkage must have default visibility");
1352 return error(NameLoc,
1353 "symbol with local linkage cannot have a DLL storage class");
1357 LocTy IsExternallyInitializedLoc;
1361 if (parseOptionalAddrSpace(AddrSpace) ||
1363 IsExternallyInitialized,
1364 &IsExternallyInitializedLoc) ||
1365 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1374 if (parseGlobalValue(Ty,
Init))
1379 return error(TyLoc,
"invalid type for global variable");
1384 if (!
Name.empty()) {
1385 auto I = ForwardRefVals.find(
Name);
1386 if (
I != ForwardRefVals.end()) {
1387 GVal =
I->second.first;
1388 ForwardRefVals.erase(
I);
1389 }
else if (
M->getNamedValue(
Name)) {
1390 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1395 if (NameID == (
unsigned)-1)
1396 NameID = NumberedVals.getNext();
1398 auto I = ForwardRefValIDs.find(NameID);
1399 if (
I != ForwardRefValIDs.end()) {
1400 GVal =
I->second.first;
1401 ForwardRefValIDs.erase(
I);
1410 NumberedVals.add(NameID, GV);
1428 "forward reference and definition of global have different types");
1448 }
else if (Lex.
getKind() == lltok::kw_align) {
1450 if (parseOptionalAlignment(Alignment))
1456 if (parseOptionalCodeModel(CodeModel))
1460 if (parseGlobalObjectMetadataAttachment(*GV))
1463 if (parseSanitizer(GV))
1467 if (parseOptionalComdat(
Name,
C))
1472 return tokError(
"unknown global variable property!");
1478 std::vector<unsigned> FwdRefAttrGrps;
1479 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1481 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1483 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1491bool LLParser::parseUnnamedAttrGrp() {
1497 return tokError(
"expected attribute group id");
1500 std::vector<unsigned> unused;
1508 auto R = NumberedAttrBuilders.find(VarID);
1509 if (R == NumberedAttrBuilders.end())
1510 R = NumberedAttrBuilders.emplace(VarID,
AttrBuilder(
M->getContext())).first;
1512 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1513 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1516 if (!
R->second.hasAttributes())
1517 return error(AttrGrpLoc,
"attribute group has no attributes");
1524#define GET_ATTR_NAMES
1525#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1526 case lltok::kw_##DISPLAY_NAME: \
1527 return Attribute::ENUM_NAME;
1528#include "llvm/IR/Attributes.inc"
1537 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1540 case Attribute::Alignment: {
1549 if (parseOptionalAlignment(Alignment,
true))
1552 B.addAlignmentAttr(Alignment);
1555 case Attribute::StackAlignment: {
1560 parseUInt32(Alignment))
1563 if (parseOptionalStackAlignment(Alignment))
1566 B.addStackAlignmentAttr(Alignment);
1569 case Attribute::AllocSize: {
1570 unsigned ElemSizeArg;
1571 std::optional<unsigned> NumElemsArg;
1572 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1574 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1577 case Attribute::VScaleRange: {
1578 unsigned MinValue, MaxValue;
1579 if (parseVScaleRangeArguments(MinValue, MaxValue))
1581 B.addVScaleRangeAttr(MinValue,
1582 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1585 case Attribute::Dereferenceable: {
1587 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1589 B.addDereferenceableAttr(Bytes);
1592 case Attribute::DereferenceableOrNull: {
1594 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1596 B.addDereferenceableOrNullAttr(Bytes);
1599 case Attribute::UWTable: {
1601 if (parseOptionalUWTableKind(Kind))
1603 B.addUWTableAttr(Kind);
1606 case Attribute::AllocKind: {
1608 if (parseAllocKind(Kind))
1610 B.addAllocKindAttr(Kind);
1613 case Attribute::Memory: {
1614 std::optional<MemoryEffects> ME = parseMemoryAttr();
1617 B.addMemoryAttr(*ME);
1620 case Attribute::NoFPClass: {
1623 B.addNoFPClassAttr(NoFPClass);
1629 case Attribute::Range:
1630 return parseRangeAttr(
B);
1632 B.addAttribute(Attr);
1640 case lltok::kw_readnone:
1643 case lltok::kw_readonly:
1646 case lltok::kw_writeonly:
1665bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1666 std::vector<unsigned> &FwdRefAttrGrps,
1667 bool InAttrGrp, LocTy &BuiltinLoc) {
1668 bool HaveError =
false;
1679 if (parseStringAttribute(
B))
1691 "cannot have an attribute group reference in an attribute group");
1701 if (Token == lltok::kw_builtin)
1713 return error(Lex.
getLoc(),
"unterminated attribute group");
1716 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1723 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1727 B.addMemoryAttr(ME);
1741 PTy->getAddressSpace());
1750 error(Loc,
"'" +
Name +
"' is not a basic block");
1752 error(Loc,
"'" +
Name +
"' defined with type '" +
1765 error(Loc,
"global variable reference must have pointer type");
1771 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1776 auto I = ForwardRefVals.find(
Name);
1777 if (
I != ForwardRefVals.end())
1778 Val =
I->second.first;
1783 return cast_or_null<GlobalValue>(
1784 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1788 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1795 error(Loc,
"global variable reference must have pointer type");
1804 auto I = ForwardRefValIDs.find(
ID);
1805 if (
I != ForwardRefValIDs.end())
1806 Val =
I->second.first;
1811 return cast_or_null<GlobalValue>(
1812 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1816 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1824Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1828 if (
I != ComdatSymTab.
end())
1833 ForwardRefComdats[
Name] = Loc;
1843bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1845 return tokError(ErrMsg);
1852bool LLParser::parseStringConstant(std::string &Result) {
1854 return tokError(
"expected string constant");
1862bool LLParser::parseUInt32(
uint32_t &Val) {
1864 return tokError(
"expected integer");
1866 if (Val64 !=
unsigned(Val64))
1867 return tokError(
"expected 32-bit integer (too large)");
1875bool LLParser::parseUInt64(
uint64_t &Val) {
1877 return tokError(
"expected integer");
1890 return tokError(
"expected localdynamic, initialexec or localexec");
1918 return parseTLSModel(TLM) ||
1919 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1927bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1928 AddrSpace = DefaultAS;
1932 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1935 if (AddrSpaceStr ==
"A") {
1936 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1937 }
else if (AddrSpaceStr ==
"G") {
1938 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1939 }
else if (AddrSpaceStr ==
"P") {
1940 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1942 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1948 return tokError(
"expected integer or string constant");
1950 if (parseUInt32(AddrSpace))
1952 if (!isUInt<24>(AddrSpace))
1953 return error(Loc,
"invalid address space, must be a 24-bit integer");
1957 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1958 ParseAddrspaceValue(AddrSpace) ||
1969 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1971 B.addAttribute(Attr, Val);
1976bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1977 bool HaveError =
false;
1984 if (parseStringAttribute(
B))
1994 if (parseEnumAttribute(Attr,
B,
false))
1998 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2000 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2048bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2049 unsigned &Visibility,
2050 unsigned &DLLStorageClass,
bool &DSOLocal) {
2054 parseOptionalDSOLocal(DSOLocal);
2055 parseOptionalVisibility(Visibility);
2056 parseOptionalDLLStorageClass(DLLStorageClass);
2059 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2065void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2087void LLParser::parseOptionalVisibility(
unsigned &Res) {
2105bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2109 return tokError(
"unknown import kind. Expect definition or declaration.");
2124void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2193bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2266 return parseUInt32(
CC);
2276bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2283 return parseMDNode(MD);
2288bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2291 return tokError(
"expected metadata after comma");
2295 if (parseMetadataAttachment(MDK,
N))
2298 if (MDK == LLVMContext::MD_DIAssignID)
2299 TempDIAssignIDAttachments[
N].push_back(&Inst);
2303 if (MDK == LLVMContext::MD_tbaa)
2304 InstsWithTBAATag.push_back(&Inst);
2313bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2316 if (parseMetadataAttachment(MDK,
N))
2325bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2327 if (parseGlobalObjectMetadataAttachment(
F))
2335bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2336 Alignment = std::nullopt;
2337 if (!EatIfPresent(lltok::kw_align))
2343 bool HaveParens =
false;
2349 if (parseUInt64(
Value))
2353 return error(ParenLoc,
"expected ')'");
2356 return error(AlignLoc,
"alignment is not a power of two");
2358 return error(AlignLoc,
"huge alignments are not supported yet");
2369 auto ErrMsg =
"expected global code model string";
2370 if (StrVal ==
"tiny")
2372 else if (StrVal ==
"small")
2374 else if (StrVal ==
"kernel")
2376 else if (StrVal ==
"medium")
2378 else if (StrVal ==
"large")
2381 return tokError(ErrMsg);
2392bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2394 assert((AttrKind == lltok::kw_dereferenceable ||
2395 AttrKind == lltok::kw_dereferenceable_or_null) &&
2399 if (!EatIfPresent(AttrKind))
2403 return error(ParenLoc,
"expected '('");
2405 if (parseUInt64(Bytes))
2409 return error(ParenLoc,
"expected ')'");
2411 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2415bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2426 return error(KindLoc,
"expected unwind table kind");
2435 return error(ParenLoc,
"expected '('");
2438 if (parseStringConstant(Arg))
2439 return error(KindLoc,
"expected allockind value");
2443 }
else if (
A ==
"realloc") {
2445 }
else if (
A ==
"free") {
2447 }
else if (
A ==
"uninitialized") {
2449 }
else if (
A ==
"zeroed") {
2451 }
else if (
A ==
"aligned") {
2454 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2459 return error(ParenLoc,
"expected ')'");
2461 return error(KindLoc,
"expected allockind value");
2472 return std::nullopt;
2487 return std::nullopt;
2491std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2501 tokError(
"expected '('");
2502 return std::nullopt;
2505 bool SeenLoc =
false;
2511 tokError(
"expected ':' after location");
2512 return std::nullopt;
2519 tokError(
"expected memory location (argmem, inaccessiblemem) "
2520 "or access kind (none, read, write, readwrite)");
2522 tokError(
"expected access kind (none, read, write, readwrite)");
2523 return std::nullopt;
2532 tokError(
"default access kind must be specified first");
2533 return std::nullopt;
2542 tokError(
"unterminated memory attribute");
2543 return std::nullopt;
2585unsigned LLParser::parseNoFPClassAttr() {
2590 tokError(
"expected '('");
2597 if (TestMask != 0) {
2601 !parseUInt64(
Value)) {
2603 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2614 error(Lex.
getLoc(),
"expected nofpclass test mask");
2632bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2633 bool &AteExtraComma) {
2634 AteExtraComma =
false;
2638 AteExtraComma =
true;
2642 if (Lex.
getKind() != lltok::kw_align)
2643 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2645 if (parseOptionalAlignment(Alignment))
2658bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2659 bool &AteExtraComma) {
2660 AteExtraComma =
false;
2664 AteExtraComma =
true;
2670 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2672 if (parseOptionalAddrSpace(AddrSpace))
2679bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2680 std::optional<unsigned> &HowManyArg) {
2683 auto StartParen = Lex.
getLoc();
2685 return error(StartParen,
"expected '('");
2687 if (parseUInt32(BaseSizeArg))
2691 auto HowManyAt = Lex.
getLoc();
2693 if (parseUInt32(HowMany))
2695 if (HowMany == BaseSizeArg)
2696 return error(HowManyAt,
2697 "'allocsize' indices can't refer to the same parameter");
2698 HowManyArg = HowMany;
2700 HowManyArg = std::nullopt;
2702 auto EndParen = Lex.
getLoc();
2704 return error(EndParen,
"expected ')'");
2708bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2709 unsigned &MaxValue) {
2712 auto StartParen = Lex.
getLoc();
2714 return error(StartParen,
"expected '('");
2716 if (parseUInt32(MinValue))
2720 if (parseUInt32(MaxValue))
2723 MaxValue = MinValue;
2725 auto EndParen = Lex.
getLoc();
2727 return error(EndParen,
"expected ')'");
2736bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2741 return parseScope(SSID) || parseOrdering(Ordering);
2751 auto StartParenAt = Lex.
getLoc();
2753 return error(StartParenAt,
"Expected '(' in syncscope");
2756 auto SSNAt = Lex.
getLoc();
2757 if (parseStringConstant(SSN))
2758 return error(SSNAt,
"Expected synchronization scope name");
2760 auto EndParenAt = Lex.
getLoc();
2762 return error(EndParenAt,
"Expected ')' in syncscope");
2777 return tokError(
"Expected ordering on atomic instruction");
2796bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2798 if (!EatIfPresent(lltok::kw_alignstack))
2802 return error(ParenLoc,
"expected '('");
2804 if (parseUInt32(Alignment))
2808 return error(ParenLoc,
"expected ')'");
2810 return error(AlignLoc,
"stack alignment is not a power of two");
2824 bool &AteExtraComma) {
2825 AteExtraComma =
false;
2828 return tokError(
"expected ',' as start of index list");
2832 if (Indices.
empty())
2833 return tokError(
"expected index");
2834 AteExtraComma =
true;
2838 if (parseUInt32(
Idx))
2851bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2855 return tokError(Msg);
2864 if (
Result->isPointerTy()) {
2866 if (parseOptionalAddrSpace(AddrSpace))
2872 return tokError(
"ptr* is invalid - use ptr instead");
2883 if (parseTargetExtType(Result))
2889 if (parseAnonStructType(Result,
false))
2895 if (parseArrayVectorType(Result,
false))
2902 if (parseAnonStructType(Result,
true) ||
2903 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2905 }
else if (parseArrayVectorType(Result,
true))
2910 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.
getStrVal()];
2916 Entry.second = Lex.
getLoc();
2925 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.
getUIntVal()];
2931 Entry.second = Lex.
getLoc();
2944 if (!AllowVoid &&
Result->isVoidTy())
2945 return error(TypeLoc,
"void type only allowed for function results");
2951 return tokError(
"basic block pointers are invalid");
2953 return tokError(
"pointers to void are invalid - use i8* instead");
2955 return tokError(
"pointer to this type is invalid");
2963 return tokError(
"basic block pointers are invalid");
2965 return tokError(
"pointers to void are invalid; use i8* instead");
2967 return tokError(
"pointer to this type is invalid");
2969 if (parseOptionalAddrSpace(AddrSpace) ||
2970 parseToken(
lltok::star,
"expected '*' in address space"))
2979 if (parseFunctionType(Result))
2992 PerFunctionState &PFS,
bool IsMustTailCall,
2993 bool InVarArgsFunc) {
2999 if (!ArgList.
empty() &&
3000 parseToken(
lltok::comma,
"expected ',' in argument list"))
3005 const char *
Msg =
"unexpected ellipsis in argument list for ";
3006 if (!IsMustTailCall)
3007 return tokError(
Twine(Msg) +
"non-musttail call");
3009 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3011 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3016 Type *ArgTy =
nullptr;
3018 if (parseType(ArgTy, ArgLoc))
3024 if (parseMetadataAsValue(V, PFS))
3028 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3035 if (IsMustTailCall && InVarArgsFunc)
3036 return tokError(
"expected '...' at end of argument list for musttail call "
3037 "in varargs function");
3048 if (!EatIfPresent(AttrToken))
3057 B.addTypeAttr(AttrKind, Ty);
3073 return tokError(
"expected integer");
3076 "integer is too large for the bit width of specified type");
3082 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3085 return error(TyLoc,
"the range must have integer type!");
3093 return tokError(
"the range should not represent the full or empty set!");
3111bool LLParser::parseOptionalOperandBundles(
3119 if (!BundleList.
empty() &&
3120 parseToken(
lltok::comma,
"expected ',' in input list"))
3124 if (parseStringConstant(
Tag))
3127 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3130 std::vector<Value *> Inputs;
3133 if (!Inputs.empty() &&
3134 parseToken(
lltok::comma,
"expected ',' in input list"))
3138 Value *Input =
nullptr;
3139 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3141 Inputs.push_back(Input);
3149 if (BundleList.
empty())
3150 return error(BeginLoc,
"operand bundle set must not be empty");
3157 unsigned NextID,
unsigned ID)
const {
3159 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3160 Twine(NextID) +
"' or greater");
3177 unsigned CurValID = 0;
3192 Type *ArgTy =
nullptr;
3194 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3198 return error(TypeLoc,
"argument can not have void type");
3208 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3215 CurValID = ArgID + 1;
3219 return error(TypeLoc,
"invalid type for function argument");
3227 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3232bool LLParser::parseFunctionType(
Type *&Result) {
3236 return tokError(
"invalid function return type");
3241 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3245 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
3246 if (!ArgList[i].
Name.empty())
3247 return error(ArgList[i].Loc,
"argument name invalid in function type");
3248 if (ArgList[i].
Attrs.hasAttributes())
3249 return error(ArgList[i].Loc,
3250 "argument attributes invalid in function type");
3254 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
3263bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3265 if (parseStructBody(Elts))
3274 std::pair<Type *, LocTy> &Entry,
3277 if (Entry.first && !Entry.second.isValid())
3278 return error(TypeLoc,
"redefinition of type");
3284 Entry.second =
SMLoc();
3289 ResultTy = Entry.first;
3301 return error(TypeLoc,
"forward references to non-struct type");
3305 return parseArrayVectorType(ResultTy,
true);
3306 return parseType(ResultTy);
3310 Entry.second =
SMLoc();
3316 StructType *STy = cast<StructType>(Entry.first);
3319 if (parseStructBody(Body) ||
3320 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3349 return error(EltTyLoc,
"invalid element type for struct");
3357 return error(EltTyLoc,
"invalid element type for struct");
3362 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3371bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3372 bool Scalable =
false;
3376 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3384 return tokError(
"expected number in address space");
3390 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3394 Type *EltTy =
nullptr;
3395 if (parseType(EltTy))
3399 "expected end of sequential type"))
3404 return error(SizeLoc,
"zero element vector is illegal");
3406 return error(SizeLoc,
"size too large for vector");
3408 return error(TypeLoc,
"invalid vector element type");
3412 return error(TypeLoc,
"invalid array element type");
3429bool LLParser::parseTargetExtType(
Type *&Result) {
3434 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3435 parseStringConstant(TypeName))
3443 bool SeenInt =
false;
3450 if (parseUInt32(IntVal))
3453 }
else if (SeenInt) {
3456 return tokError(
"expected uint32 param");
3459 if (parseType(TypeParam,
true))
3465 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3479 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3482 auto It = UnnamedArgNums.
begin();
3485 unsigned ArgNum = *It++;
3486 NumberedVals.add(ArgNum, &
A);
3491LLParser::PerFunctionState::~PerFunctionState() {
3494 for (
const auto &
P : ForwardRefVals) {
3495 if (isa<BasicBlock>(
P.second.first))
3497 P.second.first->replaceAllUsesWith(
3499 P.second.first->deleteValue();
3502 for (
const auto &
P : ForwardRefValIDs) {
3503 if (isa<BasicBlock>(
P.second.first))
3505 P.second.first->replaceAllUsesWith(
3507 P.second.first->deleteValue();
3511bool LLParser::PerFunctionState::finishFunction() {
3512 if (!ForwardRefVals.empty())
3513 return P.error(ForwardRefVals.begin()->second.second,
3514 "use of undefined value '%" + ForwardRefVals.begin()->first +
3516 if (!ForwardRefValIDs.empty())
3517 return P.error(ForwardRefValIDs.begin()->second.second,
3518 "use of undefined value '%" +
3519 Twine(ForwardRefValIDs.begin()->first) +
"'");
3526Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3529 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3534 auto I = ForwardRefVals.find(
Name);
3535 if (
I != ForwardRefVals.end())
3536 Val =
I->second.first;
3541 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3545 P.error(Loc,
"invalid use of a non-first-class type");
3557 P.error(Loc,
"name is too long which can result in name collisions, "
3558 "consider making the name shorter or "
3559 "increasing -non-global-value-max-name-size");
3563 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3567Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3569 Value *Val = NumberedVals.get(
ID);
3574 auto I = ForwardRefValIDs.find(
ID);
3575 if (
I != ForwardRefValIDs.end())
3576 Val =
I->second.first;
3581 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3584 P.error(Loc,
"invalid use of a non-first-class type");
3596 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3602bool LLParser::PerFunctionState::setInstName(
int NameID,
3603 const std::string &NameStr,
3607 if (NameID != -1 || !NameStr.empty())
3608 return P.error(NameLoc,
"instructions returning void cannot have a name");
3614 if (NameStr.empty()) {
3617 NameID = NumberedVals.getNext();
3619 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3623 auto FI = ForwardRefValIDs.find(NameID);
3624 if (FI != ForwardRefValIDs.end()) {
3627 return P.error(NameLoc,
"instruction forward referenced with type '" +
3631 Sentinel->replaceAllUsesWith(Inst);
3633 ForwardRefValIDs.erase(FI);
3636 NumberedVals.add(NameID, Inst);
3641 auto FI = ForwardRefVals.find(NameStr);
3642 if (FI != ForwardRefVals.end()) {
3645 return P.error(NameLoc,
"instruction forward referenced with type '" +
3649 Sentinel->replaceAllUsesWith(Inst);
3651 ForwardRefVals.erase(FI);
3657 if (Inst->
getName() != NameStr)
3658 return P.error(NameLoc,
"multiple definition of local value named '" +
3665BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3667 return dyn_cast_or_null<BasicBlock>(
3671BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3672 return dyn_cast_or_null<BasicBlock>(
3679BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3680 int NameID, LocTy Loc) {
3684 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3687 NameID = NumberedVals.getNext();
3689 BB = getBB(NameID, Loc);
3691 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3695 BB = getBB(
Name, Loc);
3697 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3708 ForwardRefValIDs.erase(NameID);
3709 NumberedVals.add(NameID, BB);
3712 ForwardRefVals.erase(
Name);
3729bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3733 return tokError(
"expected value token");
3776 if (parseGlobalValueVector(Elts) ||
3777 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3780 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3781 ID.UIntVal = Elts.
size();
3782 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3783 Elts.
size() *
sizeof(Elts[0]));
3795 if (parseGlobalValueVector(Elts) ||
3797 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3801 if (isPackedStruct) {
3802 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3803 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3804 Elts.
size() *
sizeof(Elts[0]));
3805 ID.UIntVal = Elts.
size();
3811 return error(
ID.Loc,
"constant vector must not be empty");
3813 if (!Elts[0]->
getType()->isIntegerTy() &&
3814 !Elts[0]->
getType()->isFloatingPointTy() &&
3818 "vector elements must have integer, pointer or floating point type");
3821 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3823 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3824 " is not of type '" +
3835 if (parseGlobalValueVector(Elts) ||
3847 if (!Elts[0]->
getType()->isFirstClassType())
3848 return error(FirstEltLoc,
"invalid array element type: " +
3854 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3856 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3857 " is not of type '" +
3877 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3880 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3883 parseStringConstant(
ID.StrVal) ||
3884 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3889 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3900 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3901 parseValID(Fn, PFS) ||
3903 "expected comma in block address expression") ||
3904 parseValID(Label, PFS) ||
3905 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3909 return error(Fn.
Loc,
"expected function name in blockaddress");
3911 return error(
Label.Loc,
"expected basic block name in blockaddress");
3916 GV = NumberedVals.get(Fn.
UIntVal);
3917 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3918 GV =
M->getNamedValue(Fn.
StrVal);
3923 if (!isa<Function>(GV))
3924 return error(Fn.
Loc,
"expected function name in blockaddress");
3925 F = cast<Function>(GV);
3926 if (
F->isDeclaration())
3927 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3933 ForwardRefBlockAddresses.insert(std::make_pair(
3935 std::map<ValID, GlobalValue *>()))
3936 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
3945 "type of blockaddress must be a pointer and not '" +
3950 FwdDeclAS = PFS->getFunction().getAddressSpace();
3959 ID.ConstantVal = FwdRef;
3967 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
3969 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
3971 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
3973 return error(
Label.Loc,
"referenced value is not a basic block");
3976 return error(
Label.Loc,
"cannot take address of numeric label after "
3977 "the function is defined");
3978 BB = dyn_cast_or_null<BasicBlock>(
3979 F->getValueSymbolTable()->lookup(
Label.StrVal));
3981 return error(
Label.Loc,
"referenced value is not a basic block");
3995 if (parseValID(Fn, PFS))
4000 "expected global value name in dso_local_equivalent");
4005 GV = NumberedVals.get(Fn.
UIntVal);
4006 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4007 GV =
M->getNamedValue(Fn.
StrVal);
4013 ? ForwardRefDSOLocalEquivalentIDs
4014 : ForwardRefDSOLocalEquivalentNames;
4015 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
4022 ID.ConstantVal = FwdRef;
4028 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4029 "in dso_local_equivalent");
4040 if (parseValID(
ID, PFS))
4044 return error(
ID.Loc,
"expected global value name in no_cfi");
4056 Type *DestTy =
nullptr;
4059 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4060 parseGlobalTypeAndValue(SrcVal) ||
4061 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4062 parseType(DestTy) ||
4063 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4066 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4075 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4077 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4079 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4081 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4083 return error(
ID.Loc,
"urem constexprs are no longer supported");
4085 return error(
ID.Loc,
"srem constexprs are no longer supported");
4087 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4089 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4091 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4093 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4095 return error(
ID.Loc,
"frem constexprs are no longer supported");
4097 return error(
ID.Loc,
"and constexprs are no longer supported");
4099 return error(
ID.Loc,
"or constexprs are no longer supported");
4101 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4103 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4105 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4107 return error(
ID.Loc,
"select constexprs are no longer supported");
4109 return error(
ID.Loc,
"zext constexprs are no longer supported");
4111 return error(
ID.Loc,
"sext constexprs are no longer supported");
4113 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4115 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4117 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4119 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4121 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4123 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4129 if (parseCmpPredicate(PredVal, Opc) ||
4130 parseToken(
lltok::lparen,
"expected '(' in compare constantexpr") ||
4131 parseGlobalTypeAndValue(Val0) ||
4132 parseToken(
lltok::comma,
"expected comma in compare constantexpr") ||
4133 parseGlobalTypeAndValue(Val1) ||
4134 parseToken(
lltok::rparen,
"expected ')' in compare constantexpr"))
4138 return error(
ID.Loc,
"compare operands must have the same type");
4142 if (Opc == Instruction::FCmp) {
4144 return error(
ID.Loc,
"fcmp requires floating point operands");
4147 assert(Opc == Instruction::ICmp &&
"Unexpected opcode for CmpInst!");
4150 return error(
ID.Loc,
"icmp requires pointer or integer operands");
4168 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4169 Opc == Instruction::Mul || Opc == Instruction::Shl) {
4178 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4179 parseGlobalTypeAndValue(Val0) ||
4180 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4181 parseGlobalTypeAndValue(Val1) ||
4182 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4185 return error(
ID.Loc,
"operands of constexpr must have same type");
4189 "constexpr requires integer or integer vector operands");
4200 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4203 if (parseGlobalTypeAndValue(
C))
4205 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4219 bool InBounds =
false;
4220 bool HasInRange =
false;
4226 if (Opc == Instruction::GetElementPtr) {
4232 return tokError(
"expected integer");
4238 return tokError(
"expected integer");
4247 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4250 if (Opc == Instruction::GetElementPtr) {
4251 if (parseType(Ty) ||
4252 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4256 if (parseGlobalValueVector(Elts) ||
4260 if (Opc == Instruction::GetElementPtr) {
4261 if (Elts.
size() == 0 ||
4262 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4263 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4266 std::optional<ConstantRange>
InRange;
4268 unsigned IndexWidth =
4269 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4270 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4271 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4272 if (InRangeStart.
sge(InRangeEnd))
4273 return error(
ID.Loc,
"expected end to be larger than start");
4279 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4286 return error(
ID.Loc,
"getelementptr index must be an integer");
4287 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4288 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4289 if (GEPWidth && (ValNumEl != GEPWidth))
4292 "getelementptr vector index has a wrong number of elements");
4295 GEPWidth = ValNumEl;
4300 if (!Indices.empty() && !Ty->
isSized(&Visited))
4301 return error(
ID.Loc,
"base element of getelementptr must be sized");
4304 return error(
ID.Loc,
"invalid getelementptr indices");
4308 }
else if (Opc == Instruction::ShuffleVector) {
4309 if (Elts.
size() != 3)
4310 return error(
ID.Loc,
"expected three operands to shufflevector");
4312 return error(
ID.Loc,
"invalid operands to shufflevector");
4316 }
else if (Opc == Instruction::ExtractElement) {
4317 if (Elts.
size() != 2)
4318 return error(
ID.Loc,
"expected two operands to extractelement");
4320 return error(
ID.Loc,
"invalid extractelement operands");
4323 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4324 if (Elts.
size() != 3)
4325 return error(
ID.Loc,
"expected three operands to insertelement");
4327 return error(
ID.Loc,
"invalid insertelement operands");
4346 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4347 convertValIDToValue(Ty,
ID, V,
nullptr);
4348 if (V && !(
C = dyn_cast<Constant>(V)))
4349 return error(
ID.Loc,
"global values must be constants");
4353bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4355 return parseType(Ty) || parseGlobalValue(Ty, V);
4367 return tokError(
"expected comdat variable");
4370 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4373 if (GlobalName.
empty())
4374 return tokError(
"comdat cannot be unnamed");
4375 C = getComdat(std::string(GlobalName), KwLoc);
4398 if (parseGlobalTypeAndValue(
C))
4406bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4408 if (parseMDNodeVector(Elts))
4419bool LLParser::parseMDNode(
MDNode *&
N) {
4421 return parseSpecializedMDNode(
N);
4423 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4426bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4429 return parseMDTuple(
N);
4432 return parseMDNodeID(
N);
4438template <
class FieldTy>
struct MDFieldImpl {
4439 typedef MDFieldImpl ImplTy;
4443 void assign(FieldTy Val) {
4445 this->Val = std::move(Val);
4448 explicit MDFieldImpl(FieldTy
Default)
4456template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4457 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4468 void assign(FieldTypeA
A) {
4470 this->A = std::move(
A);
4474 void assign(FieldTypeB
B) {
4476 this->B = std::move(
B);
4480 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4482 WhatIs(IsInvalid) {}
4485struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4492struct LineField :
public MDUnsignedField {
4493 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4496struct ColumnField :
public MDUnsignedField {
4497 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4500struct DwarfTagField :
public MDUnsignedField {
4506struct DwarfMacinfoTypeField :
public MDUnsignedField {
4512struct DwarfAttEncodingField :
public MDUnsignedField {
4513 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4516struct DwarfVirtualityField :
public MDUnsignedField {
4520struct DwarfLangField :
public MDUnsignedField {
4524struct DwarfCCField :
public MDUnsignedField {
4525 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4528struct EmissionKindField :
public MDUnsignedField {
4529 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4532struct NameTableKindField :
public MDUnsignedField {
4533 NameTableKindField()
4536 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4539struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4540 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4543struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4544 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4547struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4548 MDAPSIntField() : ImplTy(
APSInt()) {}
4551struct MDSignedField :
public MDFieldImpl<int64_t> {
4555 MDSignedField(int64_t
Default = 0)
4557 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4561struct MDBoolField :
public MDFieldImpl<bool> {
4565struct MDField :
public MDFieldImpl<Metadata *> {
4568 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4571struct MDStringField :
public MDFieldImpl<MDString *> {
4573 MDStringField(
bool AllowEmpty =
true)
4574 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4577struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4581struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4585struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4586 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4587 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4589 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4590 bool AllowNull =
true)
4591 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4593 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4594 bool isMDField()
const {
return WhatIs == IsTypeB; }
4595 int64_t getMDSignedValue()
const {
4596 assert(isMDSignedField() &&
"Wrong field type");
4599 Metadata *getMDFieldValue()
const {
4600 assert(isMDField() &&
"Wrong field type");
4612 return tokError(
"expected integer");
4621 MDUnsignedField &Result) {
4623 return tokError(
"expected unsigned integer");
4626 if (U.ugt(Result.Max))
4627 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4629 Result.assign(U.getZExtValue());
4630 assert(Result.Val <= Result.Max &&
"Expected value in range");
4637 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4641 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4647 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4650 return tokError(
"expected DWARF tag");
4654 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4655 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4664 DwarfMacinfoTypeField &Result) {
4666 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4669 return tokError(
"expected DWARF macinfo type");
4673 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4675 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4677 Result.assign(Macinfo);
4684 DwarfVirtualityField &Result) {
4686 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4689 return tokError(
"expected DWARF virtuality code");
4693 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4695 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4696 Result.assign(Virtuality);
4704 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4707 return tokError(
"expected DWARF language");
4711 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4713 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4714 Result.assign(Lang);
4722 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4725 return tokError(
"expected DWARF calling convention");
4729 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4731 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4739 EmissionKindField &Result) {
4741 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4744 return tokError(
"expected emission kind");
4748 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4750 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4751 Result.assign(*Kind);
4758 NameTableKindField &Result) {
4760 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4763 return tokError(
"expected nameTable kind");
4767 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4769 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4770 Result.assign((
unsigned)*Kind);
4777 DwarfAttEncodingField &Result) {
4779 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4782 return tokError(
"expected DWARF type attribute encoding");
4786 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4788 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4789 Result.assign(Encoding);
4805 bool Res = parseUInt32(TempVal);
4811 return tokError(
"expected debug info flag");
4815 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4830 Result.assign(Combined);
4845 bool Res = parseUInt32(TempVal);
4851 return tokError(
"expected debug info flag");
4855 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4870 Result.assign(Combined);
4877 return tokError(
"expected signed integer");
4881 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4884 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4886 Result.assign(S.getExtValue());
4887 assert(Result.Val >= Result.Min &&
"Expected value in range");
4888 assert(Result.Val <= Result.Max &&
"Expected value in range");
4897 return tokError(
"expected 'true' or 'false'");
4899 Result.assign(
true);
4902 Result.assign(
false);
4912 if (!Result.AllowNull)
4913 return tokError(
"'" +
Name +
"' cannot be null");
4915 Result.assign(
nullptr);
4920 if (parseMetadata(MD,
nullptr))
4929 MDSignedOrMDField &Result) {
4932 MDSignedField Res = Result.A;
4933 if (!parseMDField(Loc,
Name, Res)) {
4941 MDField Res = Result.B;
4942 if (!parseMDField(Loc,
Name, Res)) {
4954 if (parseStringConstant(S))
4957 if (!Result.AllowEmpty && S.empty())
4958 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
4960 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
4967 if (parseMDNodeVector(MDs))
4970 Result.assign(std::move(MDs));
4976 ChecksumKindField &Result) {
4977 std::optional<DIFile::ChecksumKind> CSKind =
4981 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
4984 Result.assign(*CSKind);
4991template <
class ParserTy>
4992bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4995 return tokError(
"expected field label here");
5004template <
class ParserTy>
5005bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5012 if (parseMDFieldsImplBody(ParseField))
5015 ClosingLoc = Lex.
getLoc();
5019template <
class FieldTy>
5020bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5022 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5026 return parseMDField(Loc,
Name, Result);
5029bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5032#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5033 if (Lex.getStrVal() == #CLASS) \
5034 return parse##CLASS(N, IsDistinct);
5035#include "llvm/IR/Metadata.def"
5037 return tokError(
"expected metadata type");
5040#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5041#define NOP_FIELD(NAME, TYPE, INIT)
5042#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5044 return error(ClosingLoc, "missing required field '" #NAME "'");
5045#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5046 if (Lex.getStrVal() == #NAME) \
5047 return parseMDField(#NAME, NAME);
5048#define PARSE_MD_FIELDS() \
5049 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5052 if (parseMDFieldsImpl( \
5054 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5055 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5060 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5062#define GET_OR_DISTINCT(CLASS, ARGS) \
5063 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5068bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5069#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5070 OPTIONAL(line, LineField, ); \
5071 OPTIONAL(column, ColumnField, ); \
5072 REQUIRED(scope, MDField, ( false)); \
5073 OPTIONAL(inlinedAt, MDField, ); \
5074 OPTIONAL(isImplicitCode, MDBoolField, (false));
5076#undef VISIT_MD_FIELDS
5080 inlinedAt.Val, isImplicitCode.Val));
5086bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5088 return Lex.
Error(
"missing 'distinct', required for !DIAssignID()");
5104bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5105#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5106 REQUIRED(tag, DwarfTagField, ); \
5107 OPTIONAL(header, MDStringField, ); \
5108 OPTIONAL(operands, MDFieldList, );
5110#undef VISIT_MD_FIELDS
5113 (Context, tag.Val, header.Val, operands.Val));
5121bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5122#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5123 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5124 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5125 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5126 OPTIONAL(stride, MDSignedOrMDField, );
5128#undef VISIT_MD_FIELDS
5135 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5136 if (Bound.isMDSignedField())
5139 if (Bound.isMDField())
5140 return Bound.getMDFieldValue();
5144 Count = convToMetadata(
count);
5145 LowerBound = convToMetadata(lowerBound);
5147 Stride = convToMetadata(stride);
5150 (Context, Count, LowerBound, UpperBound, Stride));
5158bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5159#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5160 OPTIONAL(count, MDSignedOrMDField, ); \
5161 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5162 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5163 OPTIONAL(stride, MDSignedOrMDField, );
5165#undef VISIT_MD_FIELDS
5167 auto ConvToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5168 if (Bound.isMDSignedField())
5170 Context, {dwarf::DW_OP_consts,
5171 static_cast<uint64_t>(Bound.getMDSignedValue())});
5172 if (Bound.isMDField())
5173 return Bound.getMDFieldValue();
5178 Metadata *LowerBound = ConvToMetadata(lowerBound);
5180 Metadata *Stride = ConvToMetadata(stride);
5183 (Context, Count, LowerBound, UpperBound, Stride));
5190bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5191#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5192 REQUIRED(name, MDStringField, ); \
5193 REQUIRED(value, MDAPSIntField, ); \
5194 OPTIONAL(isUnsigned, MDBoolField, (false));
5196#undef VISIT_MD_FIELDS
5198 if (isUnsigned.Val &&
value.Val.isNegative())
5199 return tokError(
"unsigned enumerator with negative value");
5204 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5216bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5217#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5218 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5219 OPTIONAL(name, MDStringField, ); \
5220 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5221 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5222 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5223 OPTIONAL(flags, DIFlagField, );
5225#undef VISIT_MD_FIELDS
5228 align.Val, encoding.Val, flags.Val));
5234bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5235#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5236 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5237 OPTIONAL(name, MDStringField, ); \
5238 OPTIONAL(stringLength, MDField, ); \
5239 OPTIONAL(stringLengthExpression, MDField, ); \
5240 OPTIONAL(stringLocationExpression, MDField, ); \
5241 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5242 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5243 OPTIONAL(encoding, DwarfAttEncodingField, );
5245#undef VISIT_MD_FIELDS
5249 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5250 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5263bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5264#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5265 REQUIRED(tag, DwarfTagField, ); \
5266 OPTIONAL(name, MDStringField, ); \
5267 OPTIONAL(file, MDField, ); \
5268 OPTIONAL(line, LineField, ); \
5269 OPTIONAL(scope, MDField, ); \
5270 REQUIRED(baseType, MDField, ); \
5271 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5272 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5273 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5274 OPTIONAL(flags, DIFlagField, ); \
5275 OPTIONAL(extraData, MDField, ); \
5276 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5277 OPTIONAL(annotations, MDField, ); \
5278 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5279 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5280 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5281 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5282 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5284#undef VISIT_MD_FIELDS
5286 std::optional<unsigned> DWARFAddressSpace;
5287 if (dwarfAddressSpace.Val != UINT32_MAX)
5288 DWARFAddressSpace = dwarfAddressSpace.Val;
5289 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5291 PtrAuthData.emplace(
5292 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5293 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5294 ptrAuthAuthenticatesNullValues.Val);
5297 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5298 scope.Val, baseType.Val,
size.Val, align.Val,
5299 offset.Val, DWARFAddressSpace, PtrAuthData,
5300 flags.Val, extraData.Val, annotations.Val));
5304bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5305#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5306 REQUIRED(tag, DwarfTagField, ); \
5307 OPTIONAL(name, MDStringField, ); \
5308 OPTIONAL(file, MDField, ); \
5309 OPTIONAL(line, LineField, ); \
5310 OPTIONAL(scope, MDField, ); \
5311 OPTIONAL(baseType, MDField, ); \
5312 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5313 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5314 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5315 OPTIONAL(flags, DIFlagField, ); \
5316 OPTIONAL(elements, MDField, ); \
5317 OPTIONAL(runtimeLang, DwarfLangField, ); \
5318 OPTIONAL(vtableHolder, MDField, ); \
5319 OPTIONAL(templateParams, MDField, ); \
5320 OPTIONAL(identifier, MDStringField, ); \
5321 OPTIONAL(discriminator, MDField, ); \
5322 OPTIONAL(dataLocation, MDField, ); \
5323 OPTIONAL(associated, MDField, ); \
5324 OPTIONAL(allocated, MDField, ); \
5325 OPTIONAL(rank, MDSignedOrMDField, ); \
5326 OPTIONAL(annotations, MDField, );
5328#undef VISIT_MD_FIELDS
5331 if (
rank.isMDSignedField())
5334 else if (
rank.isMDField())
5335 Rank =
rank.getMDFieldValue();
5340 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5341 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val,
5342 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5343 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5344 Rank, annotations.Val)) {
5353 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5354 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5355 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5356 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5361bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5362#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5363 OPTIONAL(flags, DIFlagField, ); \
5364 OPTIONAL(cc, DwarfCCField, ); \
5365 REQUIRED(types, MDField, );
5367#undef VISIT_MD_FIELDS
5370 (Context, flags.Val, cc.Val, types.Val));
5379bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5383#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5384 REQUIRED(filename, MDStringField, ); \
5385 REQUIRED(directory, MDStringField, ); \
5386 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5387 OPTIONAL(checksum, MDStringField, ); \
5388 OPTIONAL(source, MDStringField, );
5390#undef VISIT_MD_FIELDS
5392 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5393 if (checksumkind.Seen && checksum.Seen)
5394 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5395 else if (checksumkind.Seen || checksum.Seen)
5396 return Lex.
Error(
"'checksumkind' and 'checksum' must be provided together");
5402 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5413bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5415 return Lex.
Error(
"missing 'distinct', required for !DICompileUnit");
5417#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5418 REQUIRED(language, DwarfLangField, ); \
5419 REQUIRED(file, MDField, ( false)); \
5420 OPTIONAL(producer, MDStringField, ); \
5421 OPTIONAL(isOptimized, MDBoolField, ); \
5422 OPTIONAL(flags, MDStringField, ); \
5423 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5424 OPTIONAL(splitDebugFilename, MDStringField, ); \
5425 OPTIONAL(emissionKind, EmissionKindField, ); \
5426 OPTIONAL(enums, MDField, ); \
5427 OPTIONAL(retainedTypes, MDField, ); \
5428 OPTIONAL(globals, MDField, ); \
5429 OPTIONAL(imports, MDField, ); \
5430 OPTIONAL(macros, MDField, ); \
5431 OPTIONAL(dwoId, MDUnsignedField, ); \
5432 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5433 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5434 OPTIONAL(nameTableKind, NameTableKindField, ); \
5435 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5436 OPTIONAL(sysroot, MDStringField, ); \
5437 OPTIONAL(sdk, MDStringField, );
5439#undef VISIT_MD_FIELDS
5442 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5443 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5444 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5445 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5446 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5459bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5461#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5462 OPTIONAL(scope, MDField, ); \
5463 OPTIONAL(name, MDStringField, ); \
5464 OPTIONAL(linkageName, MDStringField, ); \
5465 OPTIONAL(file, MDField, ); \
5466 OPTIONAL(line, LineField, ); \
5467 OPTIONAL(type, MDField, ); \
5468 OPTIONAL(isLocal, MDBoolField, ); \
5469 OPTIONAL(isDefinition, MDBoolField, (true)); \
5470 OPTIONAL(scopeLine, LineField, ); \
5471 OPTIONAL(containingType, MDField, ); \
5472 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5473 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5474 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5475 OPTIONAL(flags, DIFlagField, ); \
5476 OPTIONAL(spFlags, DISPFlagField, ); \
5477 OPTIONAL(isOptimized, MDBoolField, ); \
5478 OPTIONAL(unit, MDField, ); \
5479 OPTIONAL(templateParams, MDField, ); \
5480 OPTIONAL(declaration, MDField, ); \
5481 OPTIONAL(retainedNodes, MDField, ); \
5482 OPTIONAL(thrownTypes, MDField, ); \
5483 OPTIONAL(annotations, MDField, ); \
5484 OPTIONAL(targetFuncName, MDStringField, );
5486#undef VISIT_MD_FIELDS
5491 spFlags.Seen ? spFlags.Val
5493 isOptimized.Val, virtuality.Val);
5494 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5497 "missing 'distinct', required for !DISubprogram that is a Definition");
5500 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5501 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5502 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5503 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5504 targetFuncName.Val));
5510bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5511#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5512 REQUIRED(scope, MDField, ( false)); \
5513 OPTIONAL(file, MDField, ); \
5514 OPTIONAL(line, LineField, ); \
5515 OPTIONAL(column, ColumnField, );
5517#undef VISIT_MD_FIELDS
5526bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5527#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5528 REQUIRED(scope, MDField, ( false)); \
5529 OPTIONAL(file, MDField, ); \
5530 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5532#undef VISIT_MD_FIELDS
5535 (Context, scope.Val,
file.Val, discriminator.Val));
5541bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5542#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5543 REQUIRED(scope, MDField, ); \
5544 OPTIONAL(declaration, MDField, ); \
5545 OPTIONAL(name, MDStringField, ); \
5546 OPTIONAL(file, MDField, ); \
5547 OPTIONAL(line, LineField, );
5549#undef VISIT_MD_FIELDS
5552 (Context, scope.Val, declaration.Val,
name.Val,
5553 file.Val, line.Val));
5559bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5560#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5561 REQUIRED(scope, MDField, ); \
5562 OPTIONAL(name, MDStringField, ); \
5563 OPTIONAL(exportSymbols, MDBoolField, );
5565#undef VISIT_MD_FIELDS
5568 (Context, scope.Val,
name.Val, exportSymbols.Val));
5575bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5576#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5577 REQUIRED(type, DwarfMacinfoTypeField, ); \
5578 OPTIONAL(line, LineField, ); \
5579 REQUIRED(name, MDStringField, ); \
5580 OPTIONAL(value, MDStringField, );
5582#undef VISIT_MD_FIELDS
5585 (Context, type.Val, line.Val,
name.Val,
value.Val));
5591bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5592#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5593 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5594 OPTIONAL(line, LineField, ); \
5595 REQUIRED(file, MDField, ); \
5596 OPTIONAL(nodes, MDField, );
5598#undef VISIT_MD_FIELDS
5601 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5609bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5610#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5611 REQUIRED(scope, MDField, ); \
5612 REQUIRED(name, MDStringField, ); \
5613 OPTIONAL(configMacros, MDStringField, ); \
5614 OPTIONAL(includePath, MDStringField, ); \
5615 OPTIONAL(apinotes, MDStringField, ); \
5616 OPTIONAL(file, MDField, ); \
5617 OPTIONAL(line, LineField, ); \
5618 OPTIONAL(isDecl, MDBoolField, );
5620#undef VISIT_MD_FIELDS
5623 configMacros.Val, includePath.Val,
5624 apinotes.Val, line.Val, isDecl.Val));
5630bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5631#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5632 OPTIONAL(name, MDStringField, ); \
5633 REQUIRED(type, MDField, ); \
5634 OPTIONAL(defaulted, MDBoolField, );
5636#undef VISIT_MD_FIELDS
5639 (Context,
name.Val, type.Val, defaulted.Val));
5647bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5648#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5649 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5650 OPTIONAL(name, MDStringField, ); \
5651 OPTIONAL(type, MDField, ); \
5652 OPTIONAL(defaulted, MDBoolField, ); \
5653 REQUIRED(value, MDField, );
5656#undef VISIT_MD_FIELDS
5660 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5669bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5670#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5671 OPTIONAL(name, MDStringField, ( false)); \
5672 OPTIONAL(scope, MDField, ); \
5673 OPTIONAL(linkageName, MDStringField, ); \
5674 OPTIONAL(file, MDField, ); \
5675 OPTIONAL(line, LineField, ); \
5676 OPTIONAL(type, MDField, ); \
5677 OPTIONAL(isLocal, MDBoolField, ); \
5678 OPTIONAL(isDefinition, MDBoolField, (true)); \
5679 OPTIONAL(templateParams, MDField, ); \
5680 OPTIONAL(declaration, MDField, ); \
5681 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5682 OPTIONAL(annotations, MDField, );
5684#undef VISIT_MD_FIELDS
5688 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5689 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5690 declaration.Val, templateParams.Val, align.Val,
5702bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5703#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5704 REQUIRED(scope, MDField, ( false)); \
5705 OPTIONAL(name, MDStringField, ); \
5706 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5707 OPTIONAL(file, MDField, ); \
5708 OPTIONAL(line, LineField, ); \
5709 OPTIONAL(type, MDField, ); \
5710 OPTIONAL(flags, DIFlagField, ); \
5711 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5712 OPTIONAL(annotations, MDField, );
5714#undef VISIT_MD_FIELDS
5717 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5718 type.Val, arg.Val, flags.Val, align.Val,
5725bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5726#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5727 REQUIRED(scope, MDField, ( false)); \
5728 REQUIRED(name, MDStringField, ); \
5729 REQUIRED(file, MDField, ); \
5730 REQUIRED(line, LineField, );
5732#undef VISIT_MD_FIELDS
5735 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5741bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5757 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5766 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5771 return tokError(
"expected unsigned integer");
5789bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5790 assert(PFS &&
"Expected valid function state");
5801 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5803 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5815bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
5817#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5818 REQUIRED(var, MDField, ); \
5819 REQUIRED(expr, MDField, );
5821#undef VISIT_MD_FIELDS
5831bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
5832#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5833 OPTIONAL(name, MDStringField, ); \
5834 OPTIONAL(file, MDField, ); \
5835 OPTIONAL(line, LineField, ); \
5836 OPTIONAL(setter, MDStringField, ); \
5837 OPTIONAL(getter, MDStringField, ); \
5838 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5839 OPTIONAL(type, MDField, );
5841#undef VISIT_MD_FIELDS
5844 (Context,
name.Val,
file.Val, line.Val, setter.Val,
5845 getter.Val, attributes.Val, type.Val));
5852bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
5853#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5854 REQUIRED(tag, DwarfTagField, ); \
5855 REQUIRED(scope, MDField, ); \
5856 OPTIONAL(entity, MDField, ); \
5857 OPTIONAL(file, MDField, ); \
5858 OPTIONAL(line, LineField, ); \
5859 OPTIONAL(name, MDStringField, ); \
5860 OPTIONAL(elements, MDField, );
5862#undef VISIT_MD_FIELDS
5865 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
5866 line.Val,
name.Val, elements.Val));
5870#undef PARSE_MD_FIELD
5882bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
5885 if (parseMetadata(MD, &PFS))
5896bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
5897 PerFunctionState *PFS) {
5900 if (parseType(Ty, TypeMsg, Loc))
5903 return error(Loc,
"invalid metadata-value-metadata roundtrip");
5906 if (parseValue(Ty, V, PFS))
5921bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
5927 if (parseDIArgList(AL, PFS))
5933 if (parseSpecializedMDNode(
N)) {
5943 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
5953 if (parseMDString(S))
5963 if (parseMDNodeTail(
N))
5974 PerFunctionState *PFS) {
5976 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
5981 return error(
ID.Loc,
"invalid use of function-local name");
5982 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
5983 return V ==
nullptr;
5986 return error(
ID.Loc,
"invalid use of function-local name");
5987 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
5988 return V ==
nullptr;
5991 return error(
ID.Loc,
"invalid type for inline asm constraint string");
5995 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6000 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6003 return V ==
nullptr;
6005 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6008 return V ==
nullptr;
6011 return error(
ID.Loc,
"integer constant must have integer type");
6013 V = ConstantInt::get(Context,
ID.APSIntVal);
6018 return error(
ID.Loc,
"floating point constant invalid for type");
6024 bool IsSNAN =
ID.APFloatVal.isSignaling();
6039 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6041 ID.APFloatVal.isNegative(), &Payload);
6044 V = ConstantFP::get(Context,
ID.APFloatVal);
6046 if (
V->getType() != Ty)
6047 return error(
ID.Loc,
"floating point constant does not have type '" +
6053 return error(
ID.Loc,
"null must be a pointer type");
6059 return error(
ID.Loc,
"invalid type for undef constant");
6063 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6064 return error(
ID.Loc,
"invalid empty array initializer");
6070 return error(
ID.Loc,
"invalid type for null constant");
6071 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6073 return error(
ID.Loc,
"invalid type for null constant");
6078 return error(
ID.Loc,
"invalid type for none constant");
6084 return error(
ID.Loc,
"invalid type for poison constant");
6088 if (
ID.ConstantVal->getType() != Ty)
6089 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6096 return error(
ID.Loc,
"vector constant must have vector type");
6098 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6100 "' but expected '" +
6107 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6108 if (
ST->getNumElements() !=
ID.UIntVal)
6110 "initializer with struct type has wrong # elements");
6112 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6115 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6116 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6119 "element " +
Twine(i) +
6120 " of struct initializer doesn't match struct element type");
6123 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6125 return error(
ID.Loc,
"constant expression type mismatch");
6135 if (parseValID(
ID,
nullptr))
6146 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6148 assert(isa<Constant>(V) &&
"Expected a constant value");
6149 C = cast<Constant>(V);
6156 return error(Loc,
"expected a constant value");
6160bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6163 return parseValID(
ID, PFS, Ty) ||
6164 convertValIDToValue(Ty,
ID, V, PFS);
6167bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6169 return parseType(Ty) || parseValue(Ty, V, PFS);
6172bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6173 PerFunctionState &PFS) {
6176 if (parseTypeAndValue(V, PFS))
6178 if (!isa<BasicBlock>(V))
6179 return error(Loc,
"expected a basic block");
6180 BB = cast<BasicBlock>(V);
6188 if (!
Name.starts_with(
"llvm.dbg."))
6191 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6192 FnID == Intrinsic::dbg_assign;
6200bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6201 unsigned &FunctionNumber,
6206 unsigned Visibility;
6207 unsigned DLLStorageClass;
6212 Type *RetType =
nullptr;
6214 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6216 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6217 parseType(RetType, RetTypeLoc,
true ))
6226 return error(LinkageLoc,
"invalid linkage for function definition");
6236 return error(LinkageLoc,
"invalid linkage for function declaration");
6240 return error(LinkageLoc,
"invalid function linkage type");
6244 return error(LinkageLoc,
6245 "symbol with local linkage must have default visibility");
6248 return error(LinkageLoc,
6249 "symbol with local linkage cannot have a DLL storage class");
6252 return error(RetTypeLoc,
"invalid function return type");
6256 std::string FunctionName;
6261 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6265 return tokError(
"expected function name");
6271 return tokError(
"expected '(' in function argument list");
6276 std::vector<unsigned> FwdRefAttrGrps;
6279 std::string Partition;
6283 unsigned AddrSpace = 0;
6289 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6290 parseOptionalUnnamedAddr(UnnamedAddr) ||
6291 parseOptionalProgramAddrSpace(AddrSpace) ||
6292 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6296 parseOptionalComdat(FunctionName,
C) ||
6297 parseOptionalAlignment(Alignment) ||
6298 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6302 parseGlobalTypeAndValue(PersonalityFn)))
6305 if (FuncAttrs.contains(Attribute::Builtin))
6306 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6311 FuncAttrs.removeAttribute(Attribute::Alignment);
6316 std::vector<Type*> ParamTypeList;
6319 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
6320 ParamTypeList.push_back(ArgList[i].Ty);
6321 Attrs.push_back(ArgList[i].Attrs);
6329 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6336 if (!FunctionName.empty()) {
6339 auto FRVI = ForwardRefVals.find(FunctionName);
6340 if (FRVI != ForwardRefVals.end()) {
6341 FwdFn = FRVI->second.first;
6343 return error(FRVI->second.second,
6344 "invalid forward reference to "
6347 "' with wrong type: "
6351 ForwardRefVals.erase(FRVI);
6352 }
else if ((Fn =
M->getFunction(FunctionName))) {
6354 return error(NameLoc,
6355 "invalid redefinition of function '" + FunctionName +
"'");
6356 }
else if (
M->getNamedValue(FunctionName)) {
6357 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6363 if (FunctionNumber == (
unsigned)-1)
6364 FunctionNumber = NumberedVals.getNext();
6368 auto I = ForwardRefValIDs.find(FunctionNumber);
6369 if (
I != ForwardRefValIDs.end()) {
6370 FwdFn =
I->second.first;
6372 return error(NameLoc,
"type of definition and forward reference of '@" +
6373 Twine(FunctionNumber) +
6378 ForwardRefValIDs.erase(
I);
6387 if (FunctionName.empty())
6388 NumberedVals.add(FunctionNumber, Fn);
6403 if (!
GC.empty()) Fn->
setGC(GC);
6406 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6410 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i, ++ArgIt) {
6412 if (ArgList[i].
Name.empty())
continue;
6417 if (ArgIt->
getName() != ArgList[i].Name)
6418 return error(ArgList[i].Loc,
6419 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6432 if (FunctionName.empty()) {
6434 ID.UIntVal = FunctionNumber;
6437 ID.StrVal = FunctionName;
6439 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6440 if (
Blocks != ForwardRefBlockAddresses.end())
6442 "cannot take blockaddress inside a declaration");
6446bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6448 if (FunctionNumber == -1) {
6450 ID.StrVal = std::string(
F.getName());
6453 ID.UIntVal = FunctionNumber;
6456 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6457 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6460 for (
const auto &
I :
Blocks->second) {
6461 const ValID &BBID =
I.first;
6465 "Expected local id or name");
6472 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6483 P.ForwardRefBlockAddresses.erase(
Blocks);
6489bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6492 return tokError(
"expected '{' in function body");
6495 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6499 if (PFS.resolveForwardRefBlockAddresses())
6505 return tokError(
"function body requires at least one basic block");
6509 if (parseBasicBlock(PFS))
6513 if (parseUseListOrder(&PFS))
6520 return PFS.finishFunction();
6525bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6542 std::string NameStr;
6547 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6548 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6555 if (SeenOldDbgInfoFormat)
6556 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6557 "containing debug info intrinsics");
6558 if (!SeenNewDbgInfoFormat)
6559 M->setNewDbgInfoFormatFlag(
true);
6560 SeenNewDbgInfoFormat =
true;
6564 if (parseDebugRecord(DR, PFS))
6566 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6578 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6583 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6587 switch (parseInstruction(Inst, BB, PFS)) {
6590 case InstError:
return true;
6597 if (parseInstructionMetadata(*Inst))
6600 case InstExtraComma:
6605 if (parseInstructionMetadata(*Inst))
6611 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6615 for (DbgRecordPtr &DR : TrailingDbgRecord)
6617 TrailingDbgRecord.clear();
6620 assert(TrailingDbgRecord.empty() &&
6621 "All debug values should have been attached to an instruction.");
6630bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6635 return error(DVRLoc,
"expected debug record type here");
6637 .
Case(
"declare", RecordKind::ValueKind)
6638 .
Case(
"value", RecordKind::ValueKind)
6639 .
Case(
"assign", RecordKind::ValueKind)
6640 .
Case(
"label", RecordKind::LabelKind);
6649 if (parseMDNode(Label))
6654 if (parseMDNode(DbgLoc))
6663 .
Case(
"declare", LocType::Declare)
6664 .
Case(
"value", LocType::Value)
6665 .
Case(
"assign", LocType::Assign);
6673 if (parseMetadata(ValLocMD, &PFS))
6680 if (parseMDNode(Variable))
6693 MDNode *AssignID =
nullptr;
6694 Metadata *AddressLocation =
nullptr;
6695 MDNode *AddressExpression =
nullptr;
6698 if (parseMDNode(AssignID))
6704 if (parseMetadata(AddressLocation, &PFS))
6710 if (parseMDNode(AddressExpression))
6735 PerFunctionState &PFS) {
6738 return tokError(
"found end of file when expecting more instructions");
6745 return error(Loc,
"expected instruction opcode");
6749 return parseRet(Inst, BB, PFS);
6751 return parseBr(Inst, PFS);
6753 return parseSwitch(Inst, PFS);
6755 return parseIndirectBr(Inst, PFS);
6757 return parseInvoke(Inst, PFS);
6759 return parseResume(Inst, PFS);
6761 return parseCleanupRet(Inst, PFS);
6763 return parseCatchRet(Inst, PFS);
6765 return parseCatchSwitch(Inst, PFS);
6767 return parseCatchPad(Inst, PFS);
6769 return parseCleanupPad(Inst, PFS);
6771 return parseCallBr(Inst, PFS);
6775 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6791 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6794 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6795 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6804 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
6818 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6820 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
6826 return parseArithmetic(Inst, PFS, KeywordVal,
6830 if (parseLogical(Inst, PFS, KeywordVal))
6833 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
6838 return parseLogical(Inst, PFS, KeywordVal);
6840 return parseCompare(Inst, PFS, KeywordVal);
6843 int Res = parseCompare(Inst, PFS, KeywordVal);
6855 bool Res = parseCast(Inst, PFS, KeywordVal);
6867 if (parseCast(Inst, PFS, KeywordVal))
6870 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
6872 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
6885 return parseCast(Inst, PFS, KeywordVal);
6889 int Res = parseSelect(Inst, PFS);
6893 if (!isa<FPMathOperator>(Inst))
6894 return error(Loc,
"fast-math-flags specified for select without "
6895 "floating-point scalar or vector return type");
6901 return parseVAArg(Inst, PFS);
6903 return parseExtractElement(Inst, PFS);
6905 return parseInsertElement(Inst, PFS);
6907 return parseShuffleVector(Inst, PFS);
6910 int Res = parsePHI(Inst, PFS);
6914 if (!isa<FPMathOperator>(Inst))
6915 return error(Loc,
"fast-math-flags specified for phi without "
6916 "floating-point scalar or vector return type");
6922 return parseLandingPad(Inst, PFS);
6924 return parseFreeze(Inst, PFS);
6936 return parseAlloc(Inst, PFS);
6938 return parseLoad(Inst, PFS);
6940 return parseStore(Inst, PFS);
6942 return parseCmpXchg(Inst, PFS);
6944 return parseAtomicRMW(Inst, PFS);
6946 return parseFence(Inst, PFS);
6948 return parseGetElementPtr(Inst, PFS);
6950 return parseExtractValue(Inst, PFS);
6952 return parseInsertValue(Inst, PFS);
6957bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
6958 if (Opc == Instruction::FCmp) {
6961 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
6982 return tokError(
"expected icmp predicate (e.g. 'eq')");
7007 PerFunctionState &PFS) {
7010 if (parseType(Ty,
true ))
7013 Type *ResType = PFS.getFunction().getReturnType();
7017 return error(TypeLoc,
"value doesn't match function result type '" +
7025 if (parseValue(Ty, RV, PFS))
7029 return error(TypeLoc,
"value doesn't match function result type '" +
7039bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7043 if (parseTypeAndValue(Op0, Loc, PFS))
7046 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7052 return error(Loc,
"branch condition must have 'i1' type");
7054 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7055 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7056 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7057 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7069bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7070 LocTy CondLoc, BBLoc;
7073 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7074 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7075 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7079 if (!
Cond->getType()->isIntegerTy())
7080 return error(CondLoc,
"switch condition must have integer type");
7089 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7090 parseToken(
lltok::comma,
"expected ',' after case value") ||
7091 parseTypeAndBasicBlock(DestBB, PFS))
7095 return error(CondLoc,
"duplicate case value in switch");
7097 return error(CondLoc,
"case value is not a constant integer");
7105 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7106 SI->addCase(Table[i].first, Table[i].second);
7114bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7117 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7118 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7122 if (!
Address->getType()->isPointerTy())
7123 return error(AddrLoc,
"indirectbr address must have pointer type");
7130 if (parseTypeAndBasicBlock(DestBB, PFS))
7135 if (parseTypeAndBasicBlock(DestBB, PFS))
7141 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7145 for (
unsigned i = 0, e = DestList.
size(); i != e; ++i)
7154bool LLParser::resolveFunctionType(
Type *RetType,
7157 FuncTy = dyn_cast<FunctionType>(RetType);
7160 std::vector<Type*> ParamTypes;
7161 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
7162 ParamTypes.push_back(ArgList[i].
V->getType());
7175bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7177 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7178 std::vector<unsigned> FwdRefAttrGrps;
7181 unsigned InvokeAddrSpace;
7182 Type *RetType =
nullptr;
7189 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7190 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7191 parseType(RetType, RetTypeLoc,
true ) ||
7192 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7193 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7195 parseOptionalOperandBundles(BundleList, PFS) ||
7197 parseTypeAndBasicBlock(NormalBB, PFS) ||
7199 parseTypeAndBasicBlock(UnwindBB, PFS))
7206 if (resolveFunctionType(RetType, ArgList, Ty))
7207 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7225 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7226 Type *ExpectedTy =
nullptr;
7229 }
else if (!Ty->isVarArg()) {
7230 return error(ArgList[i].Loc,
"too many arguments specified");
7233 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7234 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7236 Args.push_back(ArgList[i].V);
7241 return error(CallLoc,
"not enough parameters specified for call");
7252 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7259bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7261 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7270 PerFunctionState &PFS) {
7271 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7276 if (!
Args.empty() &&
7277 parseToken(
lltok::comma,
"expected ',' in argument list"))
7282 Type *ArgTy =
nullptr;
7283 if (parseType(ArgTy, ArgLoc))
7288 if (parseMetadataAsValue(V, PFS))
7291 if (parseValue(ArgTy, V, PFS))
7303bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7304 Value *CleanupPad =
nullptr;
7306 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7321 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7332bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7333 Value *CatchPad =
nullptr;
7335 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7342 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7343 parseTypeAndBasicBlock(BB, PFS))
7352bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7360 return tokError(
"expected scope value for catchswitch");
7365 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7371 if (parseTypeAndBasicBlock(DestBB, PFS))
7376 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7379 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7387 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7394 CatchSwitch->addHandler(DestBB);
7401bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7402 Value *CatchSwitch =
nullptr;
7408 return tokError(
"expected scope value for catchpad");
7414 if (parseExceptionArgs(Args, PFS))
7423bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7424 Value *ParentPad =
nullptr;
7431 return tokError(
"expected scope value for cleanuppad");
7437 if (parseExceptionArgs(Args, PFS))
7453bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7454 unsigned Opc,
bool IsFP) {
7456 if (parseTypeAndValue(LHS, Loc, PFS))
7463 return error(Loc,
"invalid operand type for instruction");
7473bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7475 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7476 std::vector<unsigned> FwdRefAttrGrps;
7479 Type *RetType =
nullptr;
7486 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7487 parseType(RetType, RetTypeLoc,
true ) ||
7488 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7489 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7491 parseOptionalOperandBundles(BundleList, PFS) ||
7493 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7502 if (parseTypeAndBasicBlock(DestBB, PFS))
7507 if (parseTypeAndBasicBlock(DestBB, PFS))
7513 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7520 if (resolveFunctionType(RetType, ArgList, Ty))
7521 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7538 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7539 Type *ExpectedTy =
nullptr;
7542 }
else if (!Ty->isVarArg()) {
7543 return error(ArgList[i].Loc,
"too many arguments specified");
7546 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7547 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7549 Args.push_back(ArgList[i].V);
7554 return error(CallLoc,
"not enough parameters specified for call");
7566 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7580bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7581 unsigned Opc,
bool IsFP) {
7583 if (parseTypeAndValue(LHS, Loc, PFS) ||
7584 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7592 return error(Loc,
"invalid operand type for instruction");
7600bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7603 if (parseTypeAndValue(LHS, Loc, PFS) ||
7604 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7610 "instruction requires integer or integer vector operands");
7619bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7625 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7626 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7630 if (Opc == Instruction::FCmp) {
7632 return error(Loc,
"fcmp requires floating point operands");
7635 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7638 return error(Loc,
"icmp requires integer operands");
7650bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7654 Type *DestTy =
nullptr;
7655 if (parseTypeAndValue(
Op, Loc, PFS) ||
7656 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7662 return error(Loc,
"invalid cast opcode for cast from '" +
7672bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7674 Value *Op0, *Op1, *Op2;
7675 if (parseTypeAndValue(Op0, Loc, PFS) ||
7676 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7677 parseTypeAndValue(Op1, PFS) ||
7678 parseToken(
lltok::comma,
"expected ',' after select value") ||
7679 parseTypeAndValue(Op2, PFS))
7683 return error(Loc, Reason);
7691bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7693 Type *EltTy =
nullptr;
7695 if (parseTypeAndValue(
Op, PFS) ||
7696 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7697 parseType(EltTy, TypeLoc))
7701 return error(TypeLoc,
"va_arg requires operand with first class type");
7709bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7712 if (parseTypeAndValue(Op0, Loc, PFS) ||
7713 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7714 parseTypeAndValue(Op1, PFS))
7718 return error(Loc,
"invalid extractelement operands");
7726bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7728 Value *Op0, *Op1, *Op2;
7729 if (parseTypeAndValue(Op0, Loc, PFS) ||
7730 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7731 parseTypeAndValue(Op1, PFS) ||
7732 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7733 parseTypeAndValue(Op2, PFS))
7737 return error(Loc,
"invalid insertelement operands");
7745bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7747 Value *Op0, *Op1, *Op2;
7748 if (parseTypeAndValue(Op0, Loc, PFS) ||
7749 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7750 parseTypeAndValue(Op1, PFS) ||
7751 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7752 parseTypeAndValue(Op2, PFS))
7756 return error(Loc,
"invalid shufflevector operands");
7764int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7768 if (parseType(Ty, TypeLoc))
7772 return error(TypeLoc,
"phi node must have first class type");
7775 bool AteExtraComma =
false;
7787 AteExtraComma =
true;
7791 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7792 parseValue(Ty, Op0, PFS) ||
7793 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7798 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7802 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
7803 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
7805 return AteExtraComma ? InstExtraComma : InstNormal;
7814bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
7817 if (parseType(Ty, TyLoc))
7830 return tokError(
"expected 'catch' or 'filter' clause type");
7834 if (parseTypeAndValue(V, VLoc, PFS))
7840 if (isa<ArrayType>(
V->getType()))
7841 error(VLoc,
"'catch' clause has an invalid type");
7843 if (!isa<ArrayType>(
V->getType()))
7844 error(VLoc,
"'filter' clause has an invalid type");
7847 Constant *CV = dyn_cast<Constant>(V);
7849 return error(VLoc,
"clause argument must be a constant");
7853 Inst = LP.release();
7859bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
7862 if (parseTypeAndValue(
Op, Loc, PFS))
7878bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
7880 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7881 std::vector<unsigned> FwdRefAttrGrps;
7883 unsigned CallAddrSpace;
7885 Type *RetType =
nullptr;
7894 "expected 'tail call', 'musttail call', or 'notail call'"))
7899 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7900 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7901 parseType(RetType, RetTypeLoc,
true ) ||
7902 parseValID(CalleeID, &PFS) ||
7904 PFS.getFunction().isVarArg()) ||
7905 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
7906 parseOptionalOperandBundles(BundleList, PFS))
7913 if (resolveFunctionType(RetType, ArgList, Ty))
7914 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7920 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7933 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7934 Type *ExpectedTy =
nullptr;
7937 }
else if (!Ty->isVarArg()) {
7938 return error(ArgList[i].Loc,
"too many arguments specified");
7941 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7942 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7944 Args.push_back(ArgList[i].V);
7945 Attrs.push_back(ArgList[i].Attrs);
7949 return error(CallLoc,
"not enough parameters specified for call");
7960 if (!isa<FPMathOperator>(CI)) {
7962 return error(CallLoc,
"fast-math-flags specified for call without "
7963 "floating-point scalar or vector return type");
7970 if (SeenNewDbgInfoFormat) {
7972 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
7973 "using non-intrinsic debug info");
7975 if (!SeenOldDbgInfoFormat)
7976 M->setNewDbgInfoFormatFlag(
false);
7977 SeenOldDbgInfoFormat =
true;
7980 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7992int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
7994 LocTy SizeLoc, TyLoc, ASLoc;
7996 unsigned AddrSpace = 0;
7999 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8000 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8002 if (parseType(Ty, TyLoc))
8006 return error(TyLoc,
"invalid type for alloca");
8008 bool AteExtraComma =
false;
8010 if (Lex.
getKind() == lltok::kw_align) {
8011 if (parseOptionalAlignment(Alignment))
8013 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8017 if (parseOptionalAddrSpace(AddrSpace))
8020 AteExtraComma =
true;
8022 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8025 if (Lex.
getKind() == lltok::kw_align) {
8026 if (parseOptionalAlignment(Alignment))
8028 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8032 if (parseOptionalAddrSpace(AddrSpace))
8035 AteExtraComma =
true;
8041 if (
Size && !
Size->getType()->isIntegerTy())
8042 return error(SizeLoc,
"element count must have integer type");
8045 if (!Alignment && !Ty->
isSized(&Visited))
8046 return error(TyLoc,
"Cannot allocate unsized type");
8048 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8053 return AteExtraComma ? InstExtraComma : InstNormal;
8060int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8063 bool AteExtraComma =
false;
8064 bool isAtomic =
false;
8073 bool isVolatile =
false;
8081 if (parseType(Ty) ||
8082 parseToken(
lltok::comma,
"expected comma after load's type") ||
8083 parseTypeAndValue(Val, Loc, PFS) ||
8084 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8085 parseOptionalCommaAlign(Alignment, AteExtraComma))
8089 return error(Loc,
"load operand must be a pointer to a first class type");
8090 if (isAtomic && !Alignment)
8091 return error(Loc,
"atomic load must have explicit non-zero alignment");
8094 return error(Loc,
"atomic load cannot use Release ordering");
8097 if (!Alignment && !Ty->
isSized(&Visited))
8098 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8100 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8101 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8102 return AteExtraComma ? InstExtraComma : InstNormal;
8110int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8113 bool AteExtraComma =
false;
8114 bool isAtomic =
false;
8123 bool isVolatile =
false;
8129 if (parseTypeAndValue(Val, Loc, PFS) ||
8130 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8131 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8132 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8133 parseOptionalCommaAlign(Alignment, AteExtraComma))
8136 if (!
Ptr->getType()->isPointerTy())
8137 return error(PtrLoc,
"store operand must be a pointer");
8139 return error(Loc,
"store operand must be a first class value");
8140 if (isAtomic && !Alignment)
8141 return error(Loc,
"atomic store must have explicit non-zero alignment");
8144 return error(Loc,
"atomic store cannot use Acquire ordering");
8147 return error(Loc,
"storing unsized types is not allowed");
8149 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8151 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8152 return AteExtraComma ? InstExtraComma : InstNormal;
8159int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8161 bool AteExtraComma =
false;
8165 bool isVolatile =
false;
8166 bool isWeak =
false;
8175 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8176 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8177 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8178 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8179 parseTypeAndValue(New, NewLoc, PFS) ||
8180 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8181 parseOrdering(FailureOrdering) ||
8182 parseOptionalCommaAlign(Alignment, AteExtraComma))
8186 return tokError(
"invalid cmpxchg success ordering");
8188 return tokError(
"invalid cmpxchg failure ordering");
8189 if (!
Ptr->getType()->isPointerTy())
8190 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8191 if (
Cmp->getType() !=
New->getType())
8192 return error(NewLoc,
"compare value and new value type do not match");
8193 if (!
New->getType()->isFirstClassType())
8194 return error(NewLoc,
"cmpxchg operand must be a first class value");
8196 const Align DefaultAlignment(
8197 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8202 SuccessOrdering, FailureOrdering, SSID);
8207 return AteExtraComma ? InstExtraComma : InstNormal;
8213int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8215 bool AteExtraComma =
false;
8218 bool isVolatile =
false;
8228 return tokError(
"expected binary operation in atomicrmw");
8265 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8266 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8267 parseTypeAndValue(Val, ValLoc, PFS) ||
8268 parseScopeAndOrdering(
true , SSID, Ordering) ||
8269 parseOptionalCommaAlign(Alignment, AteExtraComma))
8273 return tokError(
"atomicrmw cannot be unordered");
8274 if (!
Ptr->getType()->isPointerTy())
8275 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8277 return error(ValLoc,
"atomicrmw operand may not be scalable");
8286 " operand must be an integer, floating point, or pointer type");
8290 return error(ValLoc,
"atomicrmw " +
8292 " operand must be a floating point type");
8296 return error(ValLoc,
"atomicrmw " +
8298 " operand must be an integer");
8303 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
8306 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8308 const Align DefaultAlignment(
8309 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8313 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8316 return AteExtraComma ? InstExtraComma : InstNormal;
8321int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8324 if (parseScopeAndOrdering(
true , SSID, Ordering))
8328 return tokError(
"fence cannot be unordered");
8330 return tokError(
"fence cannot be monotonic");
8332 Inst =
new FenceInst(Context, Ordering, SSID);
8338int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8340 Value *Val =
nullptr;
8346 if (parseType(Ty) ||
8347 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8348 parseTypeAndValue(
Ptr, Loc, PFS))
8353 if (!BasePointerType)
8354 return error(Loc,
"base of getelementptr must be a pointer");
8357 bool AteExtraComma =
false;
8361 ? cast<VectorType>(
BaseType)->getElementCount()
8366 AteExtraComma =
true;
8369 if (parseTypeAndValue(Val, EltLoc, PFS))
8372 return error(EltLoc,
"getelementptr index must be an integer");
8374 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8379 "getelementptr vector index has a wrong number of elements");
8380 GEPWidth = ValNumEl;
8387 return error(Loc,
"base element of getelementptr must be sized");
8389 auto *STy = dyn_cast<StructType>(Ty);
8391 return error(Loc,
"getelementptr cannot target structure that contains "
8392 "scalable vector type");
8395 return error(Loc,
"invalid getelementptr indices");
8398 cast<GetElementPtrInst>(Inst)->setIsInBounds(
true);
8399 return AteExtraComma ? InstExtraComma : InstNormal;
8404int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8408 if (parseTypeAndValue(Val, Loc, PFS) ||
8409 parseIndexList(Indices, AteExtraComma))
8413 return error(Loc,
"extractvalue operand must be aggregate type");
8416 return error(Loc,
"invalid indices for extractvalue");
8418 return AteExtraComma ? InstExtraComma : InstNormal;
8423int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8427 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8428 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8429 parseTypeAndValue(Val1, Loc1, PFS) ||
8430 parseIndexList(Indices, AteExtraComma))
8434 return error(Loc0,
"insertvalue operand must be aggregate type");
8438 return error(Loc0,
"invalid indices for insertvalue");
8439 if (IndexedType != Val1->
getType())
8440 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8444 return AteExtraComma ? InstExtraComma : InstNormal;
8470 if (parseMetadata(MD,
nullptr))
8475 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8484 return error(Loc,
"value has no uses");
8486 unsigned NumUses = 0;
8488 for (
const Use &U :
V->uses()) {
8489 if (++NumUses > Indexes.
size())
8491 Order[&
U] = Indexes[NumUses - 1];
8494 return error(Loc,
"value only has one use");
8495 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8497 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8499 V->sortUseList([&](
const Use &L,
const Use &R) {
8512 return Lex.
Error(
"expected non-empty list of uselistorder indexes");
8519 bool IsOrdered =
true;
8520 assert(Indexes.
empty() &&
"Expected empty order vector");
8523 if (parseUInt32(
Index))
8537 if (Indexes.
size() < 2)
8538 return error(Loc,
"expected >= 2 uselistorder indexes");
8541 "expected distinct uselistorder indexes in range [0, size)");
8543 return error(Loc,
"expected uselistorder indexes to change the order");
8550bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8557 if (parseTypeAndValue(V, PFS) ||
8558 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8559 parseUseListOrderIndexes(Indexes))
8562 return sortUseListOrder(V, Indexes, Loc);
8567bool LLParser::parseUseListOrderBB() {
8574 if (parseValID(Fn,
nullptr) ||
8575 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8576 parseValID(Label,
nullptr) ||
8577 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8578 parseUseListOrderIndexes(Indexes))
8584 GV =
M->getNamedValue(Fn.
StrVal);
8586 GV = NumberedVals.get(Fn.
UIntVal);
8588 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8591 "invalid function forward reference in uselistorder_bb");
8592 auto *
F = dyn_cast<Function>(GV);
8594 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8595 if (
F->isDeclaration())
8596 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8600 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8602 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8603 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8605 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8606 if (!isa<BasicBlock>(V))
8607 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8609 return sortUseListOrder(V, Indexes, Loc);
8615bool LLParser::parseModuleEntry(
unsigned ID) {
8624 parseStringConstant(Path) ||
8632 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8633 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8634 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8635 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8636 parseUInt32(Hash[4]))
8643 auto ModuleEntry =
Index->addModule(Path, Hash);
8644 ModuleIdMap[
ID] = ModuleEntry->first();
8651bool LLParser::parseTypeIdEntry(
unsigned ID) {
8660 parseStringConstant(
Name))
8665 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8670 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8671 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8672 for (
auto TIDRef : FwdRefTIDs->second) {
8674 "Forward referenced type id GUID expected to be 0");
8677 ForwardRefTypeIds.erase(FwdRefTIDs);
8689 parseTypeTestResolution(TIS.
TTRes))
8694 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8705 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8711bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8720 parseStringConstant(
Name))
8724 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8731 IdToIndexMapType IdToIndexMap;
8744 if (parseGVReference(VI, GVId))
8751 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8752 TI.push_back({
Offset, VI});
8760 for (
auto I : IdToIndexMap) {
8761 auto &Infos = ForwardRefValueInfos[
I.first];
8762 for (
auto P :
I.second) {
8764 "Forward referenced ValueInfo expected to be empty");
8765 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8775 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8776 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8777 for (
auto TIDRef : FwdRefTIDs->second) {
8779 "Forward referenced type id GUID expected to be 0");
8782 ForwardRefTypeIds.erase(FwdRefTIDs);
8822 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
8849 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
8862 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
8875bool LLParser::parseOptionalWpdResolutions(
8876 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8888 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
8891 WPDResMap[
Offset] = WPDRes;
8927 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
8941 if (parseOptionalResByArg(WPDRes.
ResByArg))
8946 "expected optional WholeProgramDevirtResolution field");
8963bool LLParser::parseOptionalResByArg(
8972 std::vector<uint64_t>
Args;
8973 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
8997 "unexpected WholeProgramDevirtResolution::ByArg kind");
9007 parseUInt64(ByArg.
Info))
9013 parseUInt32(ByArg.
Byte))
9019 parseUInt32(ByArg.
Bit))
9024 "expected optional whole program devirt field");
9031 ResByArg[
Args] = ByArg;
9042bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9050 if (parseUInt64(Val))
9052 Args.push_back(Val);
9061static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9066 assert(!(ReadOnly && WriteOnly));
9076bool LLParser::addGlobalValueToIndex(
9078 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9083 VI =
Index->getOrInsertValueInfo(GUID);
9087 auto *GV =
M->getNamedValue(
Name);
9089 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9091 VI =
Index->getOrInsertValueInfo(GV);
9095 "Need a source_filename to compute GUID for local");
9103 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9104 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9105 for (
auto VIRef : FwdRefVIs->second) {
9107 "Forward referenced ValueInfo expected to be empty");
9110 ForwardRefValueInfos.erase(FwdRefVIs);
9114 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9115 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9116 for (
auto AliaseeRef : FwdRefAliasees->second) {
9117 assert(!AliaseeRef.first->hasAliasee() &&
9118 "Forward referencing alias already has aliasee");
9119 assert(Summary &&
"Aliasee must be a definition");
9120 AliaseeRef.first->setAliasee(VI,
Summary.get());
9122 ForwardRefAliasees.erase(FwdRefAliasees);
9127 Index->addGlobalValueSummary(VI, std::move(Summary));
9130 if (
ID == NumberedValueInfos.size())
9131 NumberedValueInfos.push_back(VI);
9134 if (
ID > NumberedValueInfos.size())
9135 NumberedValueInfos.resize(
ID + 1);
9136 NumberedValueInfos[
ID] =
VI;
9144bool LLParser::parseSummaryIndexFlags() {
9151 if (parseUInt64(Flags))
9154 Index->setFlags(Flags);
9160bool LLParser::parseBlockCount() {
9167 if (parseUInt64(BlockCount))
9170 Index->setBlockCount(BlockCount);
9178bool LLParser::parseGVEntry(
unsigned ID) {
9193 parseStringConstant(
Name))
9199 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9203 return error(Lex.
getLoc(),
"expected name or guid tag");
9228 if (parseFunctionSummary(
Name, GUID,
ID))
9232 if (parseVariableSummary(
Name, GUID,
ID))
9236 if (parseAliasSummary(
Name, GUID,
ID))
9240 return error(Lex.
getLoc(),
"expected summary type");
9266 false,
false,
false,
9269 std::vector<FunctionSummary::EdgeTy> Calls;
9271 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9272 std::vector<ValueInfo> Refs;
9273 std::vector<CallsiteInfo> Callsites;
9274 std::vector<AllocInfo> Allocs;
9279 parseModuleReference(ModulePath) ||
9280 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9283 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9290 if (parseOptionalFFlags(FFlags))
9294 if (parseOptionalCalls(Calls))
9298 if (parseOptionalTypeIdInfo(TypeIdInfo))
9302 if (parseOptionalRefs(Refs))
9306 if (parseOptionalParamAccesses(ParamAccesses))
9310 if (parseOptionalAllocs(Allocs))
9314 if (parseOptionalCallsites(Callsites))
9318 return error(Lex.
getLoc(),
"expected optional function summary field");
9325 auto FS = std::make_unique<FunctionSummary>(
9326 GVFlags, InstCount, FFlags, 0, std::move(Refs),
9327 std::move(Calls), std::move(TypeIdInfo.
TypeTests),
9332 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9334 FS->setModulePath(ModulePath);
9336 return addGlobalValueToIndex(
Name, GUID,
9338 std::move(FS), Loc);
9354 false,
false,
false,
9360 std::vector<ValueInfo> Refs;
9364 parseModuleReference(ModulePath) ||
9365 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9367 parseGVarFlags(GVarFlags))
9374 if (parseOptionalVTableFuncs(VTableFuncs))
9378 if (parseOptionalRefs(Refs))
9382 return error(Lex.
getLoc(),
"expected optional variable summary field");
9390 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9392 GS->setModulePath(ModulePath);
9393 GS->setVTableFuncs(std::move(VTableFuncs));
9395 return addGlobalValueToIndex(
Name, GUID,
9397 std::move(GS), Loc);
9413 false,
false,
false,
9417 parseModuleReference(ModulePath) ||
9418 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9426 if (parseGVReference(AliaseeVI, GVId))
9432 auto AS = std::make_unique<AliasSummary>(GVFlags);
9434 AS->setModulePath(ModulePath);
9438 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9440 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9441 assert(Summary &&
"Aliasee must be a definition");
9442 AS->setAliasee(AliaseeVI, Summary);
9445 return addGlobalValueToIndex(
Name, GUID,
9447 std::move(AS), Loc);
9452bool LLParser::parseFlag(
unsigned &Val) {
9454 return tokError(
"expected integer");
9475 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9484 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9490 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9496 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9502 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9508 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9514 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9520 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9526 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9532 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9538 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9543 return error(Lex.
getLoc(),
"expected function flag type");
9558bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9562 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9566 IdToIndexMapType IdToIndexMap;
9577 if (parseGVReference(VI, GVId))
9582 unsigned HasTailCall =
false;
9589 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9594 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9599 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9603 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9607 return tokError(
"Expected only one of hotness or relbf");
9612 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9622 for (
auto I : IdToIndexMap) {
9623 auto &Infos = ForwardRefValueInfos[
I.first];
9624 for (
auto P :
I.second) {
9626 "Forward referenced ValueInfo expected to be empty");
9627 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9644 case lltok::kw_cold:
9657 return error(Lex.
getLoc(),
"invalid call edge hotness");
9666bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9670 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9674 IdToIndexMapType IdToIndexMap;
9678 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9685 if (parseGVReference(VI, GVId))
9698 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9699 VTableFuncs.push_back({
VI,
Offset});
9701 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9707 for (
auto I : IdToIndexMap) {
9708 auto &Infos = ForwardRefValueInfos[
I.first];
9709 for (
auto P :
I.second) {
9711 "Forward referenced ValueInfo expected to be empty");
9712 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9716 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9723bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9725 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9731bool LLParser::parseParamAccessOffset(
ConstantRange &Range) {
9734 auto ParseAPSInt = [&](
APSInt &Val) {
9736 return tokError(
"expected integer");
9739 Val.setIsSigned(
true);
9762 IdLocListType &IdLocList) {
9771 if (parseGVReference(VI, GVId))
9775 IdLocList.emplace_back(GVId, Loc);
9778 parseParamNo(
Call.ParamNo) ||
9780 parseParamAccessOffset(
Call.Offsets))
9793 IdLocListType &IdLocList) {
9795 parseParamNo(
Param.ParamNo) ||
9797 parseParamAccessOffset(
Param.Use))
9807 if (parseParamAccessCall(Call, IdLocList))
9809 Param.Calls.push_back(Call);
9824bool LLParser::parseOptionalParamAccesses(
9825 std::vector<FunctionSummary::ParamAccess> &Params) {
9833 IdLocListType VContexts;
9834 size_t CallsNum = 0;
9837 if (parseParamAccess(ParamAccess, VContexts))
9839 CallsNum += ParamAccess.
Calls.size();
9840 assert(VContexts.size() == CallsNum);
9842 Params.emplace_back(std::move(ParamAccess));
9850 IdLocListType::const_iterator ItContext = VContexts.begin();
9851 for (
auto &PA : Params) {
9852 for (
auto &
C : PA.Calls) {
9854 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
9859 assert(ItContext == VContexts.end());
9866bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9870 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
9874 struct ValueContext {
9879 std::vector<ValueContext> VContexts;
9884 if (parseGVReference(
VC.VI,
VC.GVId))
9886 VContexts.push_back(VC);
9892 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
9893 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9896 IdToIndexMapType IdToIndexMap;
9897 for (
auto &VC : VContexts) {
9902 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.size(),
VC.Loc));
9903 Refs.push_back(
VC.VI);
9908 for (
auto I : IdToIndexMap) {
9909 auto &Infos = ForwardRefValueInfos[
I.first];
9910 for (
auto P :
I.second) {
9912 "Forward referenced ValueInfo expected to be empty");
9913 Infos.emplace_back(&Refs[
P.first],
P.second);
9927bool LLParser::parseOptionalTypeIdInfo(
9939 if (parseTypeTests(TypeIdInfo.
TypeTests))
9963 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
9967 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
9976bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9984 IdToIndexMapType IdToIndexMap;
9993 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
9995 }
else if (parseUInt64(GUID))
9997 TypeTests.push_back(GUID);
10002 for (
auto I : IdToIndexMap) {
10003 auto &Ids = ForwardRefTypeIds[
I.first];
10004 for (
auto P :
I.second) {
10005 assert(TypeTests[
P.first] == 0 &&
10006 "Forward referenced type id GUID expected to be 0");
10007 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10011 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10019bool LLParser::parseVFuncIdList(
10020 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10028 IdToIndexMapType IdToIndexMap;
10031 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10033 VFuncIdList.push_back(VFuncId);
10041 for (
auto I : IdToIndexMap) {
10042 auto &Ids = ForwardRefTypeIds[
I.first];
10043 for (
auto P :
I.second) {
10044 assert(VFuncIdList[
P.first].GUID == 0 &&
10045 "Forward referenced type id GUID expected to be 0");
10046 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10055bool LLParser::parseConstVCallList(
10057 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10065 IdToIndexMapType IdToIndexMap;
10068 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10070 ConstVCallList.push_back(ConstVCall);
10078 for (
auto I : IdToIndexMap) {
10079 auto &Ids = ForwardRefTypeIds[
I.first];
10080 for (
auto P :
I.second) {
10081 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10082 "Forward referenced type id GUID expected to be 0");
10083 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10093 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10095 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap,
Index))
10099 if (parseArgs(ConstVCall.
Args))
10112 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10127 IdToIndexMap[
ID].push_back(std::make_pair(
Index, Loc));
10129 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10131 parseUInt64(VFuncId.
GUID))
10137 parseUInt64(VFuncId.
Offset) ||
10166 assert(HasLinkage &&
"Linkage not optional in summary entry");
10173 parseOptionalVisibility(Flag);
10178 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10184 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10190 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10196 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10205 if (parseOptionalImportType(Lex.
getKind(), IK))
10207 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10211 return error(Lex.
getLoc(),
"expected gv flag type");
10233 auto ParseRest = [
this](
unsigned int &Val) {
10237 return parseFlag(Val);
10243 case lltok::kw_readonly:
10244 if (ParseRest(Flag))
10248 case lltok::kw_writeonly:
10249 if (ParseRest(Flag))
10254 if (ParseRest(Flag))
10259 if (ParseRest(Flag))
10264 return error(Lex.
getLoc(),
"expected gvar flag type");
10272bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10280 auto I = ModuleIdMap.find(ModuleID);
10282 assert(
I != ModuleIdMap.end());
10283 ModulePath =
I->second;
10289bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10292 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10298 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10300 VI = NumberedValueInfos[GVId];
10317bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10321 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10336 if (parseAllocType(V))
10341 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10345 std::vector<MIBInfo> MIBs;
10346 if (parseMemProfs(MIBs))
10349 Allocs.push_back({Versions, MIBs});
10366bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10370 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10376 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10385 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10394 if (parseUInt64(StackId))
10416bool LLParser::parseAllocType(uint8_t &
AllocType) {
10424 case lltok::kw_cold:
10427 case lltok::kw_hot:
10431 return error(Lex.
getLoc(),
"invalid alloc type");
10444bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10448 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10452 IdToIndexMapType IdToIndexMap;
10455 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10464 if (parseGVReference(VI, GVId))
10468 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10477 if (parseUInt32(V))
10483 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10492 if (parseUInt64(StackId))
10504 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10505 Callsites.push_back({
VI, Clones, StackIdIndices});
10513 for (
auto I : IdToIndexMap) {
10514 auto &Infos = ForwardRefValueInfos[
I.first];
10515 for (
auto P :
I.second) {
10517 "Forward referenced ValueInfo expected to be empty");
10518 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10522 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
static int64_t upperBound(StackOffset Size)
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
DenseMap< Block *, BlockRelaxAux > Blocks
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
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)
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
cl::opt< bool > WriteNewDbgInfoFormat
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
bool WriteNewDbgInfoFormatToBitcode
static unsigned keywordToFPClassTest(lltok::Kind Tok)
llvm::cl::opt< bool > UseNewDbgInfoFormat
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)
Module.h This file contains the declarations for the Module class.
PowerPC Reduce CR logical Operation
llvm::cl::opt< bool > UseNewDbgInfoFormat
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
static SymbolRef::Type getType(const Symbol *Sym)
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Class for arbitrary precision integers.
uint64_t getZExtValue() const
Get zero extended value.
unsigned getBitWidth() const
Return the number of bits in the APInt.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
bool getBoolValue() const
Convert APInt to a boolean value.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
An arbitrary precision integer that knows its signedness.
APSInt extOrTrunc(uint32_t width) const
APSInt extend(uint32_t width) const
an instruction to allocate memory on the stack
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 bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
An instruction that atomically checks whether a specified value is in a memory location,...
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)
an instruction that atomically reads a memory location, combines it with another value,...
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Min
*p = old <signed v ? old : v
@ 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 StringRef getOperationName(BinOp Op)
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
AttributeList removeFnAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the function index from this attribute list.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static 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 bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
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 BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a binary instruction, given the opcode and the two operands.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setTailCallKind(TailCallKind TCK)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static 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, BasicBlock::iterator InsertBefore)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, BasicBlock::iterator InsertBefore)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB, BasicBlock::iterator InsertBefore)
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 Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static 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 bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static ConstantInt * getFalse(LLVMContext &Context)
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
Basic type, like 'int' or 'float'.
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
Build a DICompositeType with the given ODR identifier.
static std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Tagged DWARF-like metadata node.
static DIFlags getFlag(StringRef Flag)
String type, Fortran CHARACTER(n)
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Type array for a subprogram.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
This class represents an Operation in the Expression.
static Expected< DataLayout > parse(StringRef LayoutDescription)
Parse a data layout string and return the layout.
static DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Base class for non-instruction debug metadata records that have positions within IR.
Kind
Subclass discriminator.
static 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)
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Class representing an expression and its matching format.
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
An instruction for ordering other memory operations.
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
Type::subtype_iterator param_iterator
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static 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)
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Generic tagged DWARF-like metadata node.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static 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 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 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...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
void setComdat(Comdat *C)
void setSection(StringRef S)
Change the section for this global.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
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
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
void setDSOLocal(bool Local)
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)
void setVisibility(VisibilityTypes V)
void setSanitizerMetadata(SanitizerMetadata Meta)
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
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
void setPartition(StringRef Part)
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)
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, BasicBlock::iterator InsertBefore)
static 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 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 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 InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
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.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
unsigned getUIntVal() const
lltok::Kind getKind() const
bool Error(LocTy ErrorLoc, const Twine &Msg) const
const std::string & getStrVal() const
const APSInt & getAPSIntVal() const
void setIgnoreColonInIdentifiers(bool val)
const APFloat & getAPFloatVal() const
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*.
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
An instruction for reading from memory.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static 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()
Create MemoryEffectsBase that can read any memory.
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
A Module instance is used to store all the information related to an LLVM module.
void addOperand(MDNode *M)
static 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, BasicBlock::iterator InsertBefore)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static 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 PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Resume the propagation of an exception.
static ResumeInst * Create(Value *Exn, BasicBlock::iterator InsertBefore)
static ReturnInst * Create(LLVMContext &C, Value *retVal, BasicBlock::iterator InsertBefore)
Represents a location in source code.
static 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, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
static 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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
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.
An instruction for storing to memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Class to represent struct types.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
bool containsScalableVectorType(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, BasicBlock::iterator InsertBefore)
static TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types=std::nullopt, ArrayRef< unsigned > Ints=std::nullopt)
Return a target extension type having the specified name and optional type and integer parameters.
@ HasZeroInit
zeroinitializer is valid for this target extension type.
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.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
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.
static IntegerType * getInt1Ty(LLVMContext &C)
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.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
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 IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(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 isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
static IntegerType * getInt64Ty(LLVMContext &C)
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.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a unary instruction, given the opcode and an operand.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
void setName(const Twine &Name)
Change the name of the value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void deleteValue()
Delete a pointer to a generic Value.
StringRef getName() const
Return a constant reference to the value's name.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
unsigned getOperationEncoding(StringRef OperationEncodingString)
unsigned getAttributeEncoding(StringRef EncodingString)
unsigned getTag(StringRef TagString)
unsigned getCallingConvention(StringRef LanguageString)
unsigned getLanguage(StringRef LanguageString)
unsigned getVirtuality(StringRef VirtualityString)
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 TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
const CustomOperand< const MCSubtargetInfo & > Msg[]
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).
@ 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).
@ 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.
@ 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...
@ 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.
bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
initializer< Ty > init(const Ty &Val)
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
@ kw_no_sanitize_hwaddress
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ 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
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
void UpgradeSectionAttributes(Module &M)
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.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
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...
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.)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
@ 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.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
bool isPointerTy(const Type *T)
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.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
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
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.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
static const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static const fltSemantics & IEEEdouble() LLVM_READNONE
static const fltSemantics & IEEEhalf() LLVM_READNONE
static const fltSemantics & BFloat() LLVM_READNONE
This struct is a compact representation of a valid (non-zero power of two) alignment.
Class to accumulate and hold information about a callee.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
A specification for a virtual function call with all constant integer arguments.
std::vector< uint64_t > Args
Flags specific to function summaries.
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
All type identifier related information.
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....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
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.
A utility class that uses RAII to save and restore the value of a variable.
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::@36 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.
Utility type to build an inheritance chain that makes it easy to rank overload candidates.