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 +
"'");
331 for (
Use &U :
V->uses()) {
332 auto *CB = dyn_cast<CallBase>(
U.getUser());
333 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
335 FTy = CB->getFunctionType();
344 if (
Name.starts_with(
"llvm."))
347 return GetCommonFunctionType(V);
353 if (
auto *Ty = GetCommonFunctionType(V))
364 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
370 Info.first->replaceAllUsesWith(GV);
371 Info.first->eraseFromParent();
372 ForwardRefVals.erase(
Name);
376 if (!ForwardRefVals.empty())
377 return error(ForwardRefVals.begin()->second.second,
378 "use of undefined value '@" + ForwardRefVals.begin()->first +
381 if (!ForwardRefValIDs.empty())
382 return error(ForwardRefValIDs.begin()->second.second,
383 "use of undefined value '@" +
384 Twine(ForwardRefValIDs.begin()->first) +
"'");
387 dropUnknownMetadataReferences();
389 if (!ForwardRefMDNodes.empty())
390 return error(ForwardRefMDNodes.begin()->second.second,
391 "use of undefined metadata '!" +
392 Twine(ForwardRefMDNodes.begin()->first) +
"'");
395 for (
auto &
N : NumberedMetadata) {
396 if (
N.second && !
N.second->isResolved())
397 N.second->resolveCycles();
400 for (
auto *Inst : InstsWithTBAATag) {
401 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
404 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
407 if (MD != UpgradedMD)
408 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
417 if (UpgradeDebugInfo)
430 for (
const auto &
I : NamedTypes)
431 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
432 for (
const auto &
I : NumberedTypes)
433 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
439bool LLParser::validateEndOfIndex() {
443 if (!ForwardRefValueInfos.empty())
444 return error(ForwardRefValueInfos.begin()->second.front().second,
445 "use of undefined summary '^" +
446 Twine(ForwardRefValueInfos.begin()->first) +
"'");
448 if (!ForwardRefAliasees.empty())
449 return error(ForwardRefAliasees.begin()->second.front().second,
450 "use of undefined summary '^" +
451 Twine(ForwardRefAliasees.begin()->first) +
"'");
453 if (!ForwardRefTypeIds.empty())
454 return error(ForwardRefTypeIds.begin()->second.front().second,
455 "use of undefined type id summary '^" +
456 Twine(ForwardRefTypeIds.begin()->first) +
"'");
470 std::string TentativeDLStr =
M->getDataLayoutStr();
477 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
481 if (parseSourceFileName())
490 if (
auto LayoutOverride =
491 DataLayoutCallback(
M->getTargetTriple(), TentativeDLStr)) {
492 TentativeDLStr = *LayoutOverride;
498 M->setDataLayout(MaybeDL.
get());
502bool LLParser::parseTopLevelEntities() {
510 if (parseSummaryEntry())
514 if (parseSourceFileName())
526 return tokError(
"expected top-level entity");
537 if (parseModuleAsm())
541 if (parseUnnamedType())
545 if (parseNamedType())
549 if (parseUnnamedGlobal())
553 if (parseNamedGlobal())
558 if (parseStandaloneMetadata())
562 if (parseSummaryEntry())
566 if (parseNamedMetadata())
570 if (parseUnnamedAttrGrp())
574 if (parseUseListOrder())
578 if (parseUseListOrderBB())
587bool LLParser::parseModuleAsm() {
593 parseStringConstant(AsmStr))
596 M->appendModuleInlineAsm(AsmStr);
603bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
609 return tokError(
"unknown target property");
612 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
613 parseStringConstant(Str))
615 M->setTargetTriple(Str);
619 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
622 if (parseStringConstant(TentativeDLStr))
630bool LLParser::parseSourceFileName() {
633 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
634 parseStringConstant(SourceFileName))
637 M->setSourceFileName(SourceFileName);
643bool LLParser::parseUnnamedType() {
648 if (parseToken(
lltok::equal,
"expected '=' after name") ||
653 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
656 if (!isa<StructType>(Result)) {
657 std::pair<Type*, LocTy> &Entry = NumberedTypes[
TypeID];
659 return error(TypeLoc,
"non-struct types may not be recursive");
661 Entry.second =
SMLoc();
669bool LLParser::parseNamedType() {
674 if (parseToken(
lltok::equal,
"expected '=' after name") ||
679 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
682 if (!isa<StructType>(Result)) {
683 std::pair<Type*, LocTy> &Entry = NamedTypes[
Name];
685 return error(NameLoc,
"non-struct types may not be recursive");
687 Entry.second =
SMLoc();
695bool LLParser::parseDeclare() {
699 std::vector<std::pair<unsigned, MDNode *>> MDs;
703 if (parseMetadataAttachment(MDK,
N))
705 MDs.push_back({MDK,
N});
709 unsigned FunctionNumber = -1;
711 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
714 F->addMetadata(MD.first, *MD.second);
720bool LLParser::parseDefine() {
725 unsigned FunctionNumber = -1;
727 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
728 parseOptionalFunctionMetadata(*
F) ||
729 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
735bool LLParser::parseGlobalType(
bool &IsConstant) {
742 return tokError(
"expected 'global' or 'constant'");
748bool LLParser::parseOptionalUnnamedAddr(
769bool LLParser::parseUnnamedGlobal() {
777 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(), VarID))
781 if (parseToken(
lltok::equal,
"expected '=' after name"))
784 VarID = NumberedVals.getNext();
788 unsigned Linkage, Visibility, DLLStorageClass;
792 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
794 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
799 return parseGlobal(
Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
800 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
803 return parseAliasOrIFunc(
Name, VarID, NameLoc, Linkage, Visibility,
804 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
813bool LLParser::parseNamedGlobal() {
820 unsigned Linkage, Visibility, DLLStorageClass;
824 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
825 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
827 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
832 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
833 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
836 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
837 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
841bool LLParser::parseComdat() {
851 return tokError(
"expected comdat type");
856 return tokError(
"unknown selection kind");
878 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
879 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
882 if (
I != ComdatSymTab.
end())
885 C =
M->getOrInsertComdat(
Name);
886 C->setSelectionKind(SK);
893bool LLParser::parseMDString(
MDString *&Result) {
895 if (parseStringConstant(Str))
903bool LLParser::parseMDNodeID(
MDNode *&Result) {
907 if (parseUInt32(MID))
911 if (NumberedMetadata.count(MID)) {
912 Result = NumberedMetadata[MID];
917 auto &FwdRef = ForwardRefMDNodes[MID];
920 Result = FwdRef.first.get();
921 NumberedMetadata[MID].reset(Result);
927bool LLParser::parseNamedMetadata() {
946 if (parseDIExpression(
N,
false))
952 return tokError(
"found DIArgList outside of function");
960 return parseToken(
lltok::rbrace,
"expected end of metadata node");
965bool LLParser::parseStandaloneMetadata() {
968 unsigned MetadataID = 0;
971 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
976 return tokError(
"unexpected type in metadata definition");
980 if (parseSpecializedMDNode(
Init, IsDistinct))
983 parseMDTuple(
Init, IsDistinct))
987 auto FI = ForwardRefMDNodes.find(MetadataID);
988 if (FI != ForwardRefMDNodes.end()) {
989 auto *ToReplace = FI->second.first.get();
992 if (isa<DIAssignID>(
Init)) {
993 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
994 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
995 "Inst unexpectedly already has DIAssignID attachment");
996 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
1000 ToReplace->replaceAllUsesWith(
Init);
1001 ForwardRefMDNodes.erase(FI);
1003 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
1005 if (NumberedMetadata.count(MetadataID))
1006 return tokError(
"Metadata id is already used");
1007 NumberedMetadata[MetadataID].reset(
Init);
1014bool LLParser::skipModuleSummaryEntry() {
1024 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1025 "start of summary entry");
1027 return parseSummaryIndexFlags();
1029 return parseBlockCount();
1031 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1032 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1036 unsigned NumOpenParen = 1;
1046 return tokError(
"found end of file while parsing summary entry");
1052 }
while (NumOpenParen > 0);
1058bool LLParser::parseSummaryEntry() {
1072 return skipModuleSummaryEntry();
1074 bool result =
false;
1077 result = parseGVEntry(SummaryID);
1080 result = parseModuleEntry(SummaryID);
1083 result = parseTypeIdEntry(SummaryID);
1086 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1089 result = parseSummaryIndexFlags();
1092 result = parseBlockCount();
1095 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1132bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1133 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1134 unsigned DLLStorageClass,
bool DSOLocal,
1149 return error(NameLoc,
"invalid linkage type for alias");
1152 return error(NameLoc,
1153 "symbol with local linkage must have default visibility");
1156 return error(NameLoc,
1157 "symbol with local linkage cannot have a DLL storage class");
1161 if (parseType(Ty) ||
1162 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1171 if (parseGlobalTypeAndValue(Aliasee))
1176 if (parseValID(
ID,
nullptr))
1179 return error(AliaseeLoc,
"invalid aliasee");
1180 Aliasee =
ID.ConstantVal;
1184 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1186 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1187 unsigned AddrSpace = PTy->getAddressSpace();
1193 if (!
Name.empty()) {
1194 auto I = ForwardRefVals.find(
Name);
1195 if (
I != ForwardRefVals.end()) {
1196 GVal =
I->second.first;
1197 ForwardRefVals.erase(
Name);
1198 }
else if (
M->getNamedValue(
Name)) {
1199 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1202 auto I = ForwardRefValIDs.find(NameID);
1203 if (
I != ForwardRefValIDs.end()) {
1204 GVal =
I->second.first;
1205 ForwardRefValIDs.erase(
I);
1210 std::unique_ptr<GlobalAlias> GA;
1211 std::unique_ptr<GlobalIFunc> GI;
1241 return tokError(
"unknown alias or ifunc property!");
1246 NumberedVals.add(NameID, GV);
1253 "forward reference and definition of alias have different types");
1263 M->insertAlias(GA.release());
1265 M->insertIFunc(GI.release());
1275 case lltok::kw_sanitize_memtag:
1291 Meta.NoAddress =
true;
1294 Meta.NoHWAddress =
true;
1296 case lltok::kw_sanitize_memtag:
1300 Meta.IsDynInit =
true;
1303 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1323bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1324 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1325 unsigned Visibility,
unsigned DLLStorageClass,
1329 return error(NameLoc,
1330 "symbol with local linkage must have default visibility");
1333 return error(NameLoc,
1334 "symbol with local linkage cannot have a DLL storage class");
1338 LocTy IsExternallyInitializedLoc;
1342 if (parseOptionalAddrSpace(AddrSpace) ||
1344 IsExternallyInitialized,
1345 &IsExternallyInitializedLoc) ||
1346 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1355 if (parseGlobalValue(Ty,
Init))
1360 return error(TyLoc,
"invalid type for global variable");
1365 if (!
Name.empty()) {
1366 auto I = ForwardRefVals.find(
Name);
1367 if (
I != ForwardRefVals.end()) {
1368 GVal =
I->second.first;
1369 ForwardRefVals.erase(
I);
1370 }
else if (
M->getNamedValue(
Name)) {
1371 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1376 if (NameID == (
unsigned)-1)
1377 NameID = NumberedVals.getNext();
1379 auto I = ForwardRefValIDs.find(NameID);
1380 if (
I != ForwardRefValIDs.end()) {
1381 GVal =
I->second.first;
1382 ForwardRefValIDs.erase(
I);
1391 NumberedVals.add(NameID, GV);
1409 "forward reference and definition of global have different types");
1429 }
else if (Lex.
getKind() == lltok::kw_align) {
1431 if (parseOptionalAlignment(Alignment))
1437 if (parseOptionalCodeModel(CodeModel))
1441 if (parseGlobalObjectMetadataAttachment(*GV))
1444 if (parseSanitizer(GV))
1448 if (parseOptionalComdat(
Name,
C))
1453 return tokError(
"unknown global variable property!");
1459 std::vector<unsigned> FwdRefAttrGrps;
1460 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1462 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1464 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1472bool LLParser::parseUnnamedAttrGrp() {
1478 return tokError(
"expected attribute group id");
1481 std::vector<unsigned> unused;
1489 auto R = NumberedAttrBuilders.find(VarID);
1490 if (R == NumberedAttrBuilders.end())
1491 R = NumberedAttrBuilders.emplace(VarID,
AttrBuilder(
M->getContext())).first;
1493 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1494 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1497 if (!
R->second.hasAttributes())
1498 return error(AttrGrpLoc,
"attribute group has no attributes");
1505#define GET_ATTR_NAMES
1506#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1507 case lltok::kw_##DISPLAY_NAME: \
1508 return Attribute::ENUM_NAME;
1509#include "llvm/IR/Attributes.inc"
1518 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1521 case Attribute::Alignment: {
1530 if (parseOptionalAlignment(Alignment,
true))
1533 B.addAlignmentAttr(Alignment);
1536 case Attribute::StackAlignment: {
1541 parseUInt32(Alignment))
1544 if (parseOptionalStackAlignment(Alignment))
1547 B.addStackAlignmentAttr(Alignment);
1550 case Attribute::AllocSize: {
1551 unsigned ElemSizeArg;
1552 std::optional<unsigned> NumElemsArg;
1553 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1555 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1558 case Attribute::VScaleRange: {
1559 unsigned MinValue, MaxValue;
1560 if (parseVScaleRangeArguments(MinValue, MaxValue))
1562 B.addVScaleRangeAttr(MinValue,
1563 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1566 case Attribute::Dereferenceable: {
1568 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1570 B.addDereferenceableAttr(Bytes);
1573 case Attribute::DereferenceableOrNull: {
1575 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1577 B.addDereferenceableOrNullAttr(Bytes);
1580 case Attribute::UWTable: {
1582 if (parseOptionalUWTableKind(Kind))
1584 B.addUWTableAttr(Kind);
1587 case Attribute::AllocKind: {
1589 if (parseAllocKind(Kind))
1591 B.addAllocKindAttr(Kind);
1594 case Attribute::Memory: {
1595 std::optional<MemoryEffects> ME = parseMemoryAttr();
1598 B.addMemoryAttr(*ME);
1601 case Attribute::NoFPClass: {
1604 B.addNoFPClassAttr(NoFPClass);
1610 case Attribute::Range:
1611 return parseRangeAttr(
B);
1613 B.addAttribute(Attr);
1621 case lltok::kw_readnone:
1624 case lltok::kw_readonly:
1627 case lltok::kw_writeonly:
1646bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1647 std::vector<unsigned> &FwdRefAttrGrps,
1648 bool InAttrGrp, LocTy &BuiltinLoc) {
1649 bool HaveError =
false;
1660 if (parseStringAttribute(
B))
1672 "cannot have an attribute group reference in an attribute group");
1682 if (Token == lltok::kw_builtin)
1694 return error(Lex.
getLoc(),
"unterminated attribute group");
1697 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1704 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1708 B.addMemoryAttr(ME);
1722 PTy->getAddressSpace());
1731 error(Loc,
"'" +
Name +
"' is not a basic block");
1733 error(Loc,
"'" +
Name +
"' defined with type '" +
1746 error(Loc,
"global variable reference must have pointer type");
1752 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1757 auto I = ForwardRefVals.find(
Name);
1758 if (
I != ForwardRefVals.end())
1759 Val =
I->second.first;
1764 return cast_or_null<GlobalValue>(
1765 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1769 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1776 error(Loc,
"global variable reference must have pointer type");
1785 auto I = ForwardRefValIDs.find(
ID);
1786 if (
I != ForwardRefValIDs.end())
1787 Val =
I->second.first;
1792 return cast_or_null<GlobalValue>(
1793 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1797 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1805Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1809 if (
I != ComdatSymTab.
end())
1814 ForwardRefComdats[
Name] = Loc;
1824bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1826 return tokError(ErrMsg);
1833bool LLParser::parseStringConstant(std::string &Result) {
1835 return tokError(
"expected string constant");
1843bool LLParser::parseUInt32(
uint32_t &Val) {
1845 return tokError(
"expected integer");
1847 if (Val64 !=
unsigned(Val64))
1848 return tokError(
"expected 32-bit integer (too large)");
1856bool LLParser::parseUInt64(
uint64_t &Val) {
1858 return tokError(
"expected integer");
1871 return tokError(
"expected localdynamic, initialexec or localexec");
1899 return parseTLSModel(TLM) ||
1900 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1908bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1909 AddrSpace = DefaultAS;
1913 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1916 if (AddrSpaceStr ==
"A") {
1917 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1918 }
else if (AddrSpaceStr ==
"G") {
1919 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1920 }
else if (AddrSpaceStr ==
"P") {
1921 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1923 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1929 return tokError(
"expected integer or string constant");
1931 if (parseUInt32(AddrSpace))
1933 if (!isUInt<24>(AddrSpace))
1934 return error(Loc,
"invalid address space, must be a 24-bit integer");
1938 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1939 ParseAddrspaceValue(AddrSpace) ||
1950 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1952 B.addAttribute(Attr, Val);
1957bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1958 bool HaveError =
false;
1965 if (parseStringAttribute(
B))
1975 if (parseEnumAttribute(Attr,
B,
false))
1979 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
1981 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2029bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2030 unsigned &Visibility,
2031 unsigned &DLLStorageClass,
bool &DSOLocal) {
2035 parseOptionalDSOLocal(DSOLocal);
2036 parseOptionalVisibility(Visibility);
2037 parseOptionalDLLStorageClass(DLLStorageClass);
2040 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2046void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2068void LLParser::parseOptionalVisibility(
unsigned &Res) {
2086bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2090 return tokError(
"unknown import kind. Expect definition or declaration.");
2105void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2174bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2247 return parseUInt32(
CC);
2257bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2264 return parseMDNode(MD);
2269bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2272 return tokError(
"expected metadata after comma");
2276 if (parseMetadataAttachment(MDK,
N))
2279 if (MDK == LLVMContext::MD_DIAssignID)
2280 TempDIAssignIDAttachments[
N].push_back(&Inst);
2284 if (MDK == LLVMContext::MD_tbaa)
2285 InstsWithTBAATag.push_back(&Inst);
2294bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2297 if (parseMetadataAttachment(MDK,
N))
2306bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2308 if (parseGlobalObjectMetadataAttachment(
F))
2316bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2317 Alignment = std::nullopt;
2318 if (!EatIfPresent(lltok::kw_align))
2324 bool HaveParens =
false;
2330 if (parseUInt64(
Value))
2334 return error(ParenLoc,
"expected ')'");
2337 return error(AlignLoc,
"alignment is not a power of two");
2339 return error(AlignLoc,
"huge alignments are not supported yet");
2350 auto ErrMsg =
"expected global code model string";
2351 if (StrVal ==
"tiny")
2353 else if (StrVal ==
"small")
2355 else if (StrVal ==
"kernel")
2357 else if (StrVal ==
"medium")
2359 else if (StrVal ==
"large")
2362 return tokError(ErrMsg);
2373bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2375 assert((AttrKind == lltok::kw_dereferenceable ||
2376 AttrKind == lltok::kw_dereferenceable_or_null) &&
2380 if (!EatIfPresent(AttrKind))
2384 return error(ParenLoc,
"expected '('");
2386 if (parseUInt64(Bytes))
2390 return error(ParenLoc,
"expected ')'");
2392 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2396bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2407 return error(KindLoc,
"expected unwind table kind");
2416 return error(ParenLoc,
"expected '('");
2419 if (parseStringConstant(Arg))
2420 return error(KindLoc,
"expected allockind value");
2424 }
else if (
A ==
"realloc") {
2426 }
else if (
A ==
"free") {
2428 }
else if (
A ==
"uninitialized") {
2430 }
else if (
A ==
"zeroed") {
2432 }
else if (
A ==
"aligned") {
2435 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2440 return error(ParenLoc,
"expected ')'");
2442 return error(KindLoc,
"expected allockind value");
2453 return std::nullopt;
2468 return std::nullopt;
2472std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2482 tokError(
"expected '('");
2483 return std::nullopt;
2486 bool SeenLoc =
false;
2492 tokError(
"expected ':' after location");
2493 return std::nullopt;
2500 tokError(
"expected memory location (argmem, inaccessiblemem) "
2501 "or access kind (none, read, write, readwrite)");
2503 tokError(
"expected access kind (none, read, write, readwrite)");
2504 return std::nullopt;
2513 tokError(
"default access kind must be specified first");
2514 return std::nullopt;
2523 tokError(
"unterminated memory attribute");
2524 return std::nullopt;
2566unsigned LLParser::parseNoFPClassAttr() {
2571 tokError(
"expected '('");
2578 if (TestMask != 0) {
2582 !parseUInt64(
Value)) {
2584 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2595 error(Lex.
getLoc(),
"expected nofpclass test mask");
2613bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2614 bool &AteExtraComma) {
2615 AteExtraComma =
false;
2619 AteExtraComma =
true;
2623 if (Lex.
getKind() != lltok::kw_align)
2624 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2626 if (parseOptionalAlignment(Alignment))
2639bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2640 bool &AteExtraComma) {
2641 AteExtraComma =
false;
2645 AteExtraComma =
true;
2651 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2653 if (parseOptionalAddrSpace(AddrSpace))
2660bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2661 std::optional<unsigned> &HowManyArg) {
2664 auto StartParen = Lex.
getLoc();
2666 return error(StartParen,
"expected '('");
2668 if (parseUInt32(BaseSizeArg))
2672 auto HowManyAt = Lex.
getLoc();
2674 if (parseUInt32(HowMany))
2676 if (HowMany == BaseSizeArg)
2677 return error(HowManyAt,
2678 "'allocsize' indices can't refer to the same parameter");
2679 HowManyArg = HowMany;
2681 HowManyArg = std::nullopt;
2683 auto EndParen = Lex.
getLoc();
2685 return error(EndParen,
"expected ')'");
2689bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2690 unsigned &MaxValue) {
2693 auto StartParen = Lex.
getLoc();
2695 return error(StartParen,
"expected '('");
2697 if (parseUInt32(MinValue))
2701 if (parseUInt32(MaxValue))
2704 MaxValue = MinValue;
2706 auto EndParen = Lex.
getLoc();
2708 return error(EndParen,
"expected ')'");
2717bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2722 return parseScope(SSID) || parseOrdering(Ordering);
2732 auto StartParenAt = Lex.
getLoc();
2734 return error(StartParenAt,
"Expected '(' in syncscope");
2737 auto SSNAt = Lex.
getLoc();
2738 if (parseStringConstant(SSN))
2739 return error(SSNAt,
"Expected synchronization scope name");
2741 auto EndParenAt = Lex.
getLoc();
2743 return error(EndParenAt,
"Expected ')' in syncscope");
2758 return tokError(
"Expected ordering on atomic instruction");
2777bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2779 if (!EatIfPresent(lltok::kw_alignstack))
2783 return error(ParenLoc,
"expected '('");
2785 if (parseUInt32(Alignment))
2789 return error(ParenLoc,
"expected ')'");
2791 return error(AlignLoc,
"stack alignment is not a power of two");
2805 bool &AteExtraComma) {
2806 AteExtraComma =
false;
2809 return tokError(
"expected ',' as start of index list");
2813 if (Indices.
empty())
2814 return tokError(
"expected index");
2815 AteExtraComma =
true;
2819 if (parseUInt32(
Idx))
2832bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2836 return tokError(Msg);
2845 if (
Result->isPointerTy()) {
2847 if (parseOptionalAddrSpace(AddrSpace))
2853 return tokError(
"ptr* is invalid - use ptr instead");
2864 if (parseTargetExtType(Result))
2870 if (parseAnonStructType(Result,
false))
2876 if (parseArrayVectorType(Result,
false))
2883 if (parseAnonStructType(Result,
true) ||
2884 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2886 }
else if (parseArrayVectorType(Result,
true))
2891 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.
getStrVal()];
2897 Entry.second = Lex.
getLoc();
2906 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.
getUIntVal()];
2912 Entry.second = Lex.
getLoc();
2925 if (!AllowVoid &&
Result->isVoidTy())
2926 return error(TypeLoc,
"void type only allowed for function results");
2932 return tokError(
"basic block pointers are invalid");
2934 return tokError(
"pointers to void are invalid - use i8* instead");
2936 return tokError(
"pointer to this type is invalid");
2944 return tokError(
"basic block pointers are invalid");
2946 return tokError(
"pointers to void are invalid; use i8* instead");
2948 return tokError(
"pointer to this type is invalid");
2950 if (parseOptionalAddrSpace(AddrSpace) ||
2951 parseToken(
lltok::star,
"expected '*' in address space"))
2960 if (parseFunctionType(Result))
2973 PerFunctionState &PFS,
bool IsMustTailCall,
2974 bool InVarArgsFunc) {
2980 if (!ArgList.
empty() &&
2981 parseToken(
lltok::comma,
"expected ',' in argument list"))
2986 const char *
Msg =
"unexpected ellipsis in argument list for ";
2987 if (!IsMustTailCall)
2988 return tokError(
Twine(Msg) +
"non-musttail call");
2990 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
2992 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
2997 Type *ArgTy =
nullptr;
2999 if (parseType(ArgTy, ArgLoc))
3005 if (parseMetadataAsValue(V, PFS))
3009 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3016 if (IsMustTailCall && InVarArgsFunc)
3017 return tokError(
"expected '...' at end of argument list for musttail call "
3018 "in varargs function");
3029 if (!EatIfPresent(AttrToken))
3038 B.addTypeAttr(AttrKind, Ty);
3054 return tokError(
"expected integer");
3057 "integer is too large for the bit width of specified type");
3063 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3066 return error(TyLoc,
"the range must have integer type!");
3074 return tokError(
"the range should not represent the full or empty set!");
3092bool LLParser::parseOptionalOperandBundles(
3100 if (!BundleList.
empty() &&
3101 parseToken(
lltok::comma,
"expected ',' in input list"))
3105 if (parseStringConstant(
Tag))
3108 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3111 std::vector<Value *> Inputs;
3114 if (!Inputs.empty() &&
3115 parseToken(
lltok::comma,
"expected ',' in input list"))
3119 Value *Input =
nullptr;
3120 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3122 Inputs.push_back(Input);
3130 if (BundleList.
empty())
3131 return error(BeginLoc,
"operand bundle set must not be empty");
3138 unsigned NextID,
unsigned ID)
const {
3140 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3141 Twine(NextID) +
"' or greater");
3158 unsigned CurValID = 0;
3173 Type *ArgTy =
nullptr;
3175 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3179 return error(TypeLoc,
"argument can not have void type");
3189 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3196 CurValID = ArgID + 1;
3200 return error(TypeLoc,
"invalid type for function argument");
3208 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3213bool LLParser::parseFunctionType(
Type *&Result) {
3217 return tokError(
"invalid function return type");
3222 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3226 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
3227 if (!ArgList[i].
Name.empty())
3228 return error(ArgList[i].Loc,
"argument name invalid in function type");
3229 if (ArgList[i].
Attrs.hasAttributes())
3230 return error(ArgList[i].Loc,
3231 "argument attributes invalid in function type");
3235 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
3244bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3246 if (parseStructBody(Elts))
3255 std::pair<Type *, LocTy> &Entry,
3258 if (Entry.first && !Entry.second.isValid())
3259 return error(TypeLoc,
"redefinition of type");
3265 Entry.second =
SMLoc();
3270 ResultTy = Entry.first;
3282 return error(TypeLoc,
"forward references to non-struct type");
3286 return parseArrayVectorType(ResultTy,
true);
3287 return parseType(ResultTy);
3291 Entry.second =
SMLoc();
3297 StructType *STy = cast<StructType>(Entry.first);
3300 if (parseStructBody(Body) ||
3301 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3330 return error(EltTyLoc,
"invalid element type for struct");
3338 return error(EltTyLoc,
"invalid element type for struct");
3343 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3352bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3353 bool Scalable =
false;
3357 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3365 return tokError(
"expected number in address space");
3371 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3375 Type *EltTy =
nullptr;
3376 if (parseType(EltTy))
3380 "expected end of sequential type"))
3385 return error(SizeLoc,
"zero element vector is illegal");
3387 return error(SizeLoc,
"size too large for vector");
3389 return error(TypeLoc,
"invalid vector element type");
3393 return error(TypeLoc,
"invalid array element type");
3410bool LLParser::parseTargetExtType(
Type *&Result) {
3415 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3416 parseStringConstant(TypeName))
3424 bool SeenInt =
false;
3431 if (parseUInt32(IntVal))
3434 }
else if (SeenInt) {
3437 return tokError(
"expected uint32 param");
3440 if (parseType(TypeParam,
true))
3446 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3460 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3463 auto It = UnnamedArgNums.
begin();
3466 unsigned ArgNum = *It++;
3467 NumberedVals.add(ArgNum, &
A);
3472LLParser::PerFunctionState::~PerFunctionState() {
3475 for (
const auto &
P : ForwardRefVals) {
3476 if (isa<BasicBlock>(
P.second.first))
3478 P.second.first->replaceAllUsesWith(
3480 P.second.first->deleteValue();
3483 for (
const auto &
P : ForwardRefValIDs) {
3484 if (isa<BasicBlock>(
P.second.first))
3486 P.second.first->replaceAllUsesWith(
3488 P.second.first->deleteValue();
3492bool LLParser::PerFunctionState::finishFunction() {
3493 if (!ForwardRefVals.empty())
3494 return P.error(ForwardRefVals.begin()->second.second,
3495 "use of undefined value '%" + ForwardRefVals.begin()->first +
3497 if (!ForwardRefValIDs.empty())
3498 return P.error(ForwardRefValIDs.begin()->second.second,
3499 "use of undefined value '%" +
3500 Twine(ForwardRefValIDs.begin()->first) +
"'");
3507Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3510 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3515 auto I = ForwardRefVals.find(
Name);
3516 if (
I != ForwardRefVals.end())
3517 Val =
I->second.first;
3522 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3526 P.error(Loc,
"invalid use of a non-first-class type");
3538 P.error(Loc,
"name is too long which can result in name collisions, "
3539 "consider making the name shorter or "
3540 "increasing -non-global-value-max-name-size");
3544 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3548Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3550 Value *Val = NumberedVals.get(
ID);
3555 auto I = ForwardRefValIDs.find(
ID);
3556 if (
I != ForwardRefValIDs.end())
3557 Val =
I->second.first;
3562 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3565 P.error(Loc,
"invalid use of a non-first-class type");
3577 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3583bool LLParser::PerFunctionState::setInstName(
int NameID,
3584 const std::string &NameStr,
3588 if (NameID != -1 || !NameStr.empty())
3589 return P.error(NameLoc,
"instructions returning void cannot have a name");
3595 if (NameStr.empty()) {
3598 NameID = NumberedVals.getNext();
3600 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3604 auto FI = ForwardRefValIDs.find(NameID);
3605 if (FI != ForwardRefValIDs.end()) {
3608 return P.error(NameLoc,
"instruction forward referenced with type '" +
3612 Sentinel->replaceAllUsesWith(Inst);
3614 ForwardRefValIDs.erase(FI);
3617 NumberedVals.add(NameID, Inst);
3622 auto FI = ForwardRefVals.find(NameStr);
3623 if (FI != ForwardRefVals.end()) {
3626 return P.error(NameLoc,
"instruction forward referenced with type '" +
3630 Sentinel->replaceAllUsesWith(Inst);
3632 ForwardRefVals.erase(FI);
3638 if (Inst->
getName() != NameStr)
3639 return P.error(NameLoc,
"multiple definition of local value named '" +
3646BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3648 return dyn_cast_or_null<BasicBlock>(
3652BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3653 return dyn_cast_or_null<BasicBlock>(
3660BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3661 int NameID, LocTy Loc) {
3665 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3668 NameID = NumberedVals.getNext();
3670 BB = getBB(NameID, Loc);
3672 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3676 BB = getBB(
Name, Loc);
3678 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3689 ForwardRefValIDs.erase(NameID);
3690 NumberedVals.add(NameID, BB);
3693 ForwardRefVals.erase(
Name);
3710bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3714 return tokError(
"expected value token");
3757 if (parseGlobalValueVector(Elts) ||
3758 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3761 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3762 ID.UIntVal = Elts.
size();
3763 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3764 Elts.
size() *
sizeof(Elts[0]));
3776 if (parseGlobalValueVector(Elts) ||
3778 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3782 if (isPackedStruct) {
3783 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3784 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3785 Elts.
size() *
sizeof(Elts[0]));
3786 ID.UIntVal = Elts.
size();
3792 return error(
ID.Loc,
"constant vector must not be empty");
3794 if (!Elts[0]->
getType()->isIntegerTy() &&
3795 !Elts[0]->
getType()->isFloatingPointTy() &&
3799 "vector elements must have integer, pointer or floating point type");
3802 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3804 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3805 " is not of type '" +
3816 if (parseGlobalValueVector(Elts) ||
3828 if (!Elts[0]->
getType()->isFirstClassType())
3829 return error(FirstEltLoc,
"invalid array element type: " +
3835 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3837 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3838 " is not of type '" +
3858 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3861 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3864 parseStringConstant(
ID.StrVal) ||
3865 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3870 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3881 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3882 parseValID(Fn, PFS) ||
3884 "expected comma in block address expression") ||
3885 parseValID(Label, PFS) ||
3886 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3890 return error(Fn.
Loc,
"expected function name in blockaddress");
3892 return error(
Label.Loc,
"expected basic block name in blockaddress");
3897 GV = NumberedVals.get(Fn.
UIntVal);
3898 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3899 GV =
M->getNamedValue(Fn.
StrVal);
3904 if (!isa<Function>(GV))
3905 return error(Fn.
Loc,
"expected function name in blockaddress");
3906 F = cast<Function>(GV);
3907 if (
F->isDeclaration())
3908 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3914 ForwardRefBlockAddresses.insert(std::make_pair(
3916 std::map<ValID, GlobalValue *>()))
3917 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
3926 "type of blockaddress must be a pointer and not '" +
3931 FwdDeclAS = PFS->getFunction().getAddressSpace();
3940 ID.ConstantVal = FwdRef;
3948 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
3950 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
3952 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
3954 return error(
Label.Loc,
"referenced value is not a basic block");
3957 return error(
Label.Loc,
"cannot take address of numeric label after "
3958 "the function is defined");
3959 BB = dyn_cast_or_null<BasicBlock>(
3960 F->getValueSymbolTable()->lookup(
Label.StrVal));
3962 return error(
Label.Loc,
"referenced value is not a basic block");
3976 if (parseValID(Fn, PFS))
3981 "expected global value name in dso_local_equivalent");
3986 GV = NumberedVals.get(Fn.
UIntVal);
3987 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3988 GV =
M->getNamedValue(Fn.
StrVal);
3994 ? ForwardRefDSOLocalEquivalentIDs
3995 : ForwardRefDSOLocalEquivalentNames;
3996 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
4003 ID.ConstantVal = FwdRef;
4009 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4010 "in dso_local_equivalent");
4021 if (parseValID(
ID, PFS))
4025 return error(
ID.Loc,
"expected global value name in no_cfi");
4037 Type *DestTy =
nullptr;
4040 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4041 parseGlobalTypeAndValue(SrcVal) ||
4042 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4043 parseType(DestTy) ||
4044 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4047 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4056 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4058 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4060 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4062 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4064 return error(
ID.Loc,
"urem constexprs are no longer supported");
4066 return error(
ID.Loc,
"srem constexprs are no longer supported");
4068 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4070 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4072 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4074 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4076 return error(
ID.Loc,
"frem constexprs are no longer supported");
4078 return error(
ID.Loc,
"and constexprs are no longer supported");
4080 return error(
ID.Loc,
"or constexprs are no longer supported");
4082 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4084 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4086 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4088 return error(
ID.Loc,
"select constexprs are no longer supported");
4090 return error(
ID.Loc,
"zext constexprs are no longer supported");
4092 return error(
ID.Loc,
"sext constexprs are no longer supported");
4094 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4096 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4098 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4100 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4102 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4104 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4110 if (parseCmpPredicate(PredVal, Opc) ||
4111 parseToken(
lltok::lparen,
"expected '(' in compare constantexpr") ||
4112 parseGlobalTypeAndValue(Val0) ||
4113 parseToken(
lltok::comma,
"expected comma in compare constantexpr") ||
4114 parseGlobalTypeAndValue(Val1) ||
4115 parseToken(
lltok::rparen,
"expected ')' in compare constantexpr"))
4119 return error(
ID.Loc,
"compare operands must have the same type");
4123 if (Opc == Instruction::FCmp) {
4125 return error(
ID.Loc,
"fcmp requires floating point operands");
4128 assert(Opc == Instruction::ICmp &&
"Unexpected opcode for CmpInst!");
4131 return error(
ID.Loc,
"icmp requires pointer or integer operands");
4149 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4150 Opc == Instruction::Mul || Opc == Instruction::Shl) {
4159 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4160 parseGlobalTypeAndValue(Val0) ||
4161 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4162 parseGlobalTypeAndValue(Val1) ||
4163 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4166 return error(
ID.Loc,
"operands of constexpr must have same type");
4170 "constexpr requires integer or integer vector operands");
4181 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4184 if (parseGlobalTypeAndValue(
C))
4186 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4200 bool InBounds =
false;
4201 bool HasInRange =
false;
4207 if (Opc == Instruction::GetElementPtr) {
4213 return tokError(
"expected integer");
4219 return tokError(
"expected integer");
4228 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4231 if (Opc == Instruction::GetElementPtr) {
4232 if (parseType(Ty) ||
4233 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4237 if (parseGlobalValueVector(Elts) ||
4241 if (Opc == Instruction::GetElementPtr) {
4242 if (Elts.
size() == 0 ||
4243 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4244 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4247 std::optional<ConstantRange>
InRange;
4249 unsigned IndexWidth =
4250 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4251 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4252 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4253 if (InRangeStart.
sge(InRangeEnd))
4254 return error(
ID.Loc,
"expected end to be larger than start");
4260 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4267 return error(
ID.Loc,
"getelementptr index must be an integer");
4268 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4269 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4270 if (GEPWidth && (ValNumEl != GEPWidth))
4273 "getelementptr vector index has a wrong number of elements");
4276 GEPWidth = ValNumEl;
4281 if (!Indices.empty() && !Ty->
isSized(&Visited))
4282 return error(
ID.Loc,
"base element of getelementptr must be sized");
4285 return error(
ID.Loc,
"invalid getelementptr indices");
4289 }
else if (Opc == Instruction::ShuffleVector) {
4290 if (Elts.
size() != 3)
4291 return error(
ID.Loc,
"expected three operands to shufflevector");
4293 return error(
ID.Loc,
"invalid operands to shufflevector");
4297 }
else if (Opc == Instruction::ExtractElement) {
4298 if (Elts.
size() != 2)
4299 return error(
ID.Loc,
"expected two operands to extractelement");
4301 return error(
ID.Loc,
"invalid extractelement operands");
4304 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4305 if (Elts.
size() != 3)
4306 return error(
ID.Loc,
"expected three operands to insertelement");
4308 return error(
ID.Loc,
"invalid insertelement operands");
4327 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4328 convertValIDToValue(Ty,
ID, V,
nullptr);
4329 if (V && !(
C = dyn_cast<Constant>(V)))
4330 return error(
ID.Loc,
"global values must be constants");
4334bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4336 return parseType(Ty) || parseGlobalValue(Ty, V);
4348 return tokError(
"expected comdat variable");
4351 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4354 if (GlobalName.
empty())
4355 return tokError(
"comdat cannot be unnamed");
4356 C = getComdat(std::string(GlobalName), KwLoc);
4379 if (parseGlobalTypeAndValue(
C))
4387bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4389 if (parseMDNodeVector(Elts))
4400bool LLParser::parseMDNode(
MDNode *&
N) {
4402 return parseSpecializedMDNode(
N);
4404 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4407bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4410 return parseMDTuple(
N);
4413 return parseMDNodeID(
N);
4419template <
class FieldTy>
struct MDFieldImpl {
4420 typedef MDFieldImpl ImplTy;
4424 void assign(FieldTy Val) {
4426 this->Val = std::move(Val);
4429 explicit MDFieldImpl(FieldTy
Default)
4437template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4438 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4449 void assign(FieldTypeA
A) {
4451 this->A = std::move(
A);
4455 void assign(FieldTypeB
B) {
4457 this->B = std::move(
B);
4461 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4463 WhatIs(IsInvalid) {}
4466struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4473struct LineField :
public MDUnsignedField {
4474 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4477struct ColumnField :
public MDUnsignedField {
4478 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4481struct DwarfTagField :
public MDUnsignedField {
4487struct DwarfMacinfoTypeField :
public MDUnsignedField {
4493struct DwarfAttEncodingField :
public MDUnsignedField {
4494 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4497struct DwarfVirtualityField :
public MDUnsignedField {
4501struct DwarfLangField :
public MDUnsignedField {
4505struct DwarfCCField :
public MDUnsignedField {
4506 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4509struct EmissionKindField :
public MDUnsignedField {
4510 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4513struct NameTableKindField :
public MDUnsignedField {
4514 NameTableKindField()
4517 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4520struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4521 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4524struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4525 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4528struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4529 MDAPSIntField() : ImplTy(
APSInt()) {}
4532struct MDSignedField :
public MDFieldImpl<int64_t> {
4536 MDSignedField(int64_t
Default = 0)
4538 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4542struct MDBoolField :
public MDFieldImpl<bool> {
4546struct MDField :
public MDFieldImpl<Metadata *> {
4549 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4552struct MDStringField :
public MDFieldImpl<MDString *> {
4554 MDStringField(
bool AllowEmpty =
true)
4555 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4558struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4562struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4566struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4567 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4568 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4570 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4571 bool AllowNull =
true)
4572 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4574 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4575 bool isMDField()
const {
return WhatIs == IsTypeB; }
4576 int64_t getMDSignedValue()
const {
4577 assert(isMDSignedField() &&
"Wrong field type");
4580 Metadata *getMDFieldValue()
const {
4581 assert(isMDField() &&
"Wrong field type");
4593 return tokError(
"expected integer");
4602 MDUnsignedField &Result) {
4604 return tokError(
"expected unsigned integer");
4607 if (U.ugt(Result.Max))
4608 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4610 Result.assign(U.getZExtValue());
4611 assert(Result.Val <= Result.Max &&
"Expected value in range");
4618 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4622 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4628 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4631 return tokError(
"expected DWARF tag");
4635 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4636 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4645 DwarfMacinfoTypeField &Result) {
4647 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4650 return tokError(
"expected DWARF macinfo type");
4654 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4656 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4658 Result.assign(Macinfo);
4665 DwarfVirtualityField &Result) {
4667 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4670 return tokError(
"expected DWARF virtuality code");
4674 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4676 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4677 Result.assign(Virtuality);
4685 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4688 return tokError(
"expected DWARF language");
4692 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4694 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4695 Result.assign(Lang);
4703 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4706 return tokError(
"expected DWARF calling convention");
4710 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4712 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4720 EmissionKindField &Result) {
4722 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4725 return tokError(
"expected emission kind");
4729 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4731 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4732 Result.assign(*Kind);
4739 NameTableKindField &Result) {
4741 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4744 return tokError(
"expected nameTable kind");
4748 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4750 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4751 Result.assign((
unsigned)*Kind);
4758 DwarfAttEncodingField &Result) {
4760 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4763 return tokError(
"expected DWARF type attribute encoding");
4767 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4769 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4770 Result.assign(Encoding);
4786 bool Res = parseUInt32(TempVal);
4792 return tokError(
"expected debug info flag");
4796 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4811 Result.assign(Combined);
4826 bool Res = parseUInt32(TempVal);
4832 return tokError(
"expected debug info flag");
4836 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4851 Result.assign(Combined);
4858 return tokError(
"expected signed integer");
4862 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4865 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4867 Result.assign(S.getExtValue());
4868 assert(Result.Val >= Result.Min &&
"Expected value in range");
4869 assert(Result.Val <= Result.Max &&
"Expected value in range");
4878 return tokError(
"expected 'true' or 'false'");
4880 Result.assign(
true);
4883 Result.assign(
false);
4893 if (!Result.AllowNull)
4894 return tokError(
"'" +
Name +
"' cannot be null");
4896 Result.assign(
nullptr);
4901 if (parseMetadata(MD,
nullptr))
4910 MDSignedOrMDField &Result) {
4913 MDSignedField Res = Result.A;
4914 if (!parseMDField(Loc,
Name, Res)) {
4922 MDField Res = Result.B;
4923 if (!parseMDField(Loc,
Name, Res)) {
4935 if (parseStringConstant(S))
4938 if (!Result.AllowEmpty && S.empty())
4939 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
4941 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
4948 if (parseMDNodeVector(MDs))
4951 Result.assign(std::move(MDs));
4957 ChecksumKindField &Result) {
4958 std::optional<DIFile::ChecksumKind> CSKind =
4962 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
4965 Result.assign(*CSKind);
4972template <
class ParserTy>
4973bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4976 return tokError(
"expected field label here");
4985template <
class ParserTy>
4986bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4993 if (parseMDFieldsImplBody(ParseField))
4996 ClosingLoc = Lex.
getLoc();
5000template <
class FieldTy>
5001bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5003 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5007 return parseMDField(Loc,
Name, Result);
5010bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5013#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5014 if (Lex.getStrVal() == #CLASS) \
5015 return parse##CLASS(N, IsDistinct);
5016#include "llvm/IR/Metadata.def"
5018 return tokError(
"expected metadata type");
5021#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5022#define NOP_FIELD(NAME, TYPE, INIT)
5023#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5025 return error(ClosingLoc, "missing required field '" #NAME "'");
5026#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5027 if (Lex.getStrVal() == #NAME) \
5028 return parseMDField(#NAME, NAME);
5029#define PARSE_MD_FIELDS() \
5030 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5033 if (parseMDFieldsImpl( \
5035 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5036 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5041 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5043#define GET_OR_DISTINCT(CLASS, ARGS) \
5044 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5049bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5050#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5051 OPTIONAL(line, LineField, ); \
5052 OPTIONAL(column, ColumnField, ); \
5053 REQUIRED(scope, MDField, ( false)); \
5054 OPTIONAL(inlinedAt, MDField, ); \
5055 OPTIONAL(isImplicitCode, MDBoolField, (false));
5057#undef VISIT_MD_FIELDS
5061 inlinedAt.Val, isImplicitCode.Val));
5067bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5069 return Lex.
Error(
"missing 'distinct', required for !DIAssignID()");
5085bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5086#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5087 REQUIRED(tag, DwarfTagField, ); \
5088 OPTIONAL(header, MDStringField, ); \
5089 OPTIONAL(operands, MDFieldList, );
5091#undef VISIT_MD_FIELDS
5094 (Context, tag.Val, header.Val, operands.Val));
5102bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5103#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5104 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5105 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5106 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5107 OPTIONAL(stride, MDSignedOrMDField, );
5109#undef VISIT_MD_FIELDS
5116 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5117 if (Bound.isMDSignedField())
5120 if (Bound.isMDField())
5121 return Bound.getMDFieldValue();
5125 Count = convToMetadata(
count);
5126 LowerBound = convToMetadata(lowerBound);
5128 Stride = convToMetadata(stride);
5131 (Context, Count, LowerBound, UpperBound, Stride));
5139bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5140#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5141 OPTIONAL(count, MDSignedOrMDField, ); \
5142 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5143 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5144 OPTIONAL(stride, MDSignedOrMDField, );
5146#undef VISIT_MD_FIELDS
5148 auto ConvToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5149 if (Bound.isMDSignedField())
5151 Context, {dwarf::DW_OP_consts,
5152 static_cast<uint64_t>(Bound.getMDSignedValue())});
5153 if (Bound.isMDField())
5154 return Bound.getMDFieldValue();
5159 Metadata *LowerBound = ConvToMetadata(lowerBound);
5161 Metadata *Stride = ConvToMetadata(stride);
5164 (Context, Count, LowerBound, UpperBound, Stride));
5171bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5172#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5173 REQUIRED(name, MDStringField, ); \
5174 REQUIRED(value, MDAPSIntField, ); \
5175 OPTIONAL(isUnsigned, MDBoolField, (false));
5177#undef VISIT_MD_FIELDS
5179 if (isUnsigned.Val &&
value.Val.isNegative())
5180 return tokError(
"unsigned enumerator with negative value");
5185 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5197bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5198#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5199 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5200 OPTIONAL(name, MDStringField, ); \
5201 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5202 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5203 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5204 OPTIONAL(flags, DIFlagField, );
5206#undef VISIT_MD_FIELDS
5209 align.Val, encoding.Val, flags.Val));
5215bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5216#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5217 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5218 OPTIONAL(name, MDStringField, ); \
5219 OPTIONAL(stringLength, MDField, ); \
5220 OPTIONAL(stringLengthExpression, MDField, ); \
5221 OPTIONAL(stringLocationExpression, MDField, ); \
5222 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5223 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5224 OPTIONAL(encoding, DwarfAttEncodingField, );
5226#undef VISIT_MD_FIELDS
5230 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5231 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5244bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5245#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5246 REQUIRED(tag, DwarfTagField, ); \
5247 OPTIONAL(name, MDStringField, ); \
5248 OPTIONAL(file, MDField, ); \
5249 OPTIONAL(line, LineField, ); \
5250 OPTIONAL(scope, MDField, ); \
5251 REQUIRED(baseType, MDField, ); \
5252 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5253 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5254 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5255 OPTIONAL(flags, DIFlagField, ); \
5256 OPTIONAL(extraData, MDField, ); \
5257 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5258 OPTIONAL(annotations, MDField, ); \
5259 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5260 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5261 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5262 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5263 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5265#undef VISIT_MD_FIELDS
5267 std::optional<unsigned> DWARFAddressSpace;
5268 if (dwarfAddressSpace.Val != UINT32_MAX)
5269 DWARFAddressSpace = dwarfAddressSpace.Val;
5270 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5272 PtrAuthData.emplace(
5273 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5274 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5275 ptrAuthAuthenticatesNullValues.Val);
5278 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5279 scope.Val, baseType.Val,
size.Val, align.Val,
5280 offset.Val, DWARFAddressSpace, PtrAuthData,
5281 flags.Val, extraData.Val, annotations.Val));
5285bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5286#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5287 REQUIRED(tag, DwarfTagField, ); \
5288 OPTIONAL(name, MDStringField, ); \
5289 OPTIONAL(file, MDField, ); \
5290 OPTIONAL(line, LineField, ); \
5291 OPTIONAL(scope, MDField, ); \
5292 OPTIONAL(baseType, MDField, ); \
5293 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5294 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5295 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5296 OPTIONAL(flags, DIFlagField, ); \
5297 OPTIONAL(elements, MDField, ); \
5298 OPTIONAL(runtimeLang, DwarfLangField, ); \
5299 OPTIONAL(vtableHolder, MDField, ); \
5300 OPTIONAL(templateParams, MDField, ); \
5301 OPTIONAL(identifier, MDStringField, ); \
5302 OPTIONAL(discriminator, MDField, ); \
5303 OPTIONAL(dataLocation, MDField, ); \
5304 OPTIONAL(associated, MDField, ); \
5305 OPTIONAL(allocated, MDField, ); \
5306 OPTIONAL(rank, MDSignedOrMDField, ); \
5307 OPTIONAL(annotations, MDField, );
5309#undef VISIT_MD_FIELDS
5312 if (
rank.isMDSignedField())
5315 else if (
rank.isMDField())
5316 Rank =
rank.getMDFieldValue();
5321 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5322 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val,
5323 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5324 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5325 Rank, annotations.Val)) {
5334 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5335 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5336 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5337 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5342bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5343#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5344 OPTIONAL(flags, DIFlagField, ); \
5345 OPTIONAL(cc, DwarfCCField, ); \
5346 REQUIRED(types, MDField, );
5348#undef VISIT_MD_FIELDS
5351 (Context, flags.Val, cc.Val, types.Val));
5360bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5364#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5365 REQUIRED(filename, MDStringField, ); \
5366 REQUIRED(directory, MDStringField, ); \
5367 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5368 OPTIONAL(checksum, MDStringField, ); \
5369 OPTIONAL(source, MDStringField, );
5371#undef VISIT_MD_FIELDS
5373 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5374 if (checksumkind.Seen && checksum.Seen)
5375 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5376 else if (checksumkind.Seen || checksum.Seen)
5377 return Lex.
Error(
"'checksumkind' and 'checksum' must be provided together");
5383 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5394bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5396 return Lex.
Error(
"missing 'distinct', required for !DICompileUnit");
5398#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5399 REQUIRED(language, DwarfLangField, ); \
5400 REQUIRED(file, MDField, ( false)); \
5401 OPTIONAL(producer, MDStringField, ); \
5402 OPTIONAL(isOptimized, MDBoolField, ); \
5403 OPTIONAL(flags, MDStringField, ); \
5404 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5405 OPTIONAL(splitDebugFilename, MDStringField, ); \
5406 OPTIONAL(emissionKind, EmissionKindField, ); \
5407 OPTIONAL(enums, MDField, ); \
5408 OPTIONAL(retainedTypes, MDField, ); \
5409 OPTIONAL(globals, MDField, ); \
5410 OPTIONAL(imports, MDField, ); \
5411 OPTIONAL(macros, MDField, ); \
5412 OPTIONAL(dwoId, MDUnsignedField, ); \
5413 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5414 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5415 OPTIONAL(nameTableKind, NameTableKindField, ); \
5416 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5417 OPTIONAL(sysroot, MDStringField, ); \
5418 OPTIONAL(sdk, MDStringField, );
5420#undef VISIT_MD_FIELDS
5423 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5424 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5425 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5426 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5427 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5440bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5442#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5443 OPTIONAL(scope, MDField, ); \
5444 OPTIONAL(name, MDStringField, ); \
5445 OPTIONAL(linkageName, MDStringField, ); \
5446 OPTIONAL(file, MDField, ); \
5447 OPTIONAL(line, LineField, ); \
5448 OPTIONAL(type, MDField, ); \
5449 OPTIONAL(isLocal, MDBoolField, ); \
5450 OPTIONAL(isDefinition, MDBoolField, (true)); \
5451 OPTIONAL(scopeLine, LineField, ); \
5452 OPTIONAL(containingType, MDField, ); \
5453 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5454 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5455 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5456 OPTIONAL(flags, DIFlagField, ); \
5457 OPTIONAL(spFlags, DISPFlagField, ); \
5458 OPTIONAL(isOptimized, MDBoolField, ); \
5459 OPTIONAL(unit, MDField, ); \
5460 OPTIONAL(templateParams, MDField, ); \
5461 OPTIONAL(declaration, MDField, ); \
5462 OPTIONAL(retainedNodes, MDField, ); \
5463 OPTIONAL(thrownTypes, MDField, ); \
5464 OPTIONAL(annotations, MDField, ); \
5465 OPTIONAL(targetFuncName, MDStringField, );
5467#undef VISIT_MD_FIELDS
5472 spFlags.Seen ? spFlags.Val
5474 isOptimized.Val, virtuality.Val);
5475 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5478 "missing 'distinct', required for !DISubprogram that is a Definition");
5481 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5482 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5483 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5484 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5485 targetFuncName.Val));
5491bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5492#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5493 REQUIRED(scope, MDField, ( false)); \
5494 OPTIONAL(file, MDField, ); \
5495 OPTIONAL(line, LineField, ); \
5496 OPTIONAL(column, ColumnField, );
5498#undef VISIT_MD_FIELDS
5507bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5508#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5509 REQUIRED(scope, MDField, ( false)); \
5510 OPTIONAL(file, MDField, ); \
5511 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5513#undef VISIT_MD_FIELDS
5516 (Context, scope.Val,
file.Val, discriminator.Val));
5522bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5523#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5524 REQUIRED(scope, MDField, ); \
5525 OPTIONAL(declaration, MDField, ); \
5526 OPTIONAL(name, MDStringField, ); \
5527 OPTIONAL(file, MDField, ); \
5528 OPTIONAL(line, LineField, );
5530#undef VISIT_MD_FIELDS
5533 (Context, scope.Val, declaration.Val,
name.Val,
5534 file.Val, line.Val));
5540bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5541#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5542 REQUIRED(scope, MDField, ); \
5543 OPTIONAL(name, MDStringField, ); \
5544 OPTIONAL(exportSymbols, MDBoolField, );
5546#undef VISIT_MD_FIELDS
5549 (Context, scope.Val,
name.Val, exportSymbols.Val));
5556bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5557#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5558 REQUIRED(type, DwarfMacinfoTypeField, ); \
5559 OPTIONAL(line, LineField, ); \
5560 REQUIRED(name, MDStringField, ); \
5561 OPTIONAL(value, MDStringField, );
5563#undef VISIT_MD_FIELDS
5566 (Context, type.Val, line.Val,
name.Val,
value.Val));
5572bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5573#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5574 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5575 OPTIONAL(line, LineField, ); \
5576 REQUIRED(file, MDField, ); \
5577 OPTIONAL(nodes, MDField, );
5579#undef VISIT_MD_FIELDS
5582 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5590bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5591#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5592 REQUIRED(scope, MDField, ); \
5593 REQUIRED(name, MDStringField, ); \
5594 OPTIONAL(configMacros, MDStringField, ); \
5595 OPTIONAL(includePath, MDStringField, ); \
5596 OPTIONAL(apinotes, MDStringField, ); \
5597 OPTIONAL(file, MDField, ); \
5598 OPTIONAL(line, LineField, ); \
5599 OPTIONAL(isDecl, MDBoolField, );
5601#undef VISIT_MD_FIELDS
5604 configMacros.Val, includePath.Val,
5605 apinotes.Val, line.Val, isDecl.Val));
5611bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5612#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5613 OPTIONAL(name, MDStringField, ); \
5614 REQUIRED(type, MDField, ); \
5615 OPTIONAL(defaulted, MDBoolField, );
5617#undef VISIT_MD_FIELDS
5620 (Context,
name.Val, type.Val, defaulted.Val));
5628bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5629#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5630 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5631 OPTIONAL(name, MDStringField, ); \
5632 OPTIONAL(type, MDField, ); \
5633 OPTIONAL(defaulted, MDBoolField, ); \
5634 REQUIRED(value, MDField, );
5637#undef VISIT_MD_FIELDS
5641 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5650bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5651#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5652 OPTIONAL(name, MDStringField, ( false)); \
5653 OPTIONAL(scope, MDField, ); \
5654 OPTIONAL(linkageName, MDStringField, ); \
5655 OPTIONAL(file, MDField, ); \
5656 OPTIONAL(line, LineField, ); \
5657 OPTIONAL(type, MDField, ); \
5658 OPTIONAL(isLocal, MDBoolField, ); \
5659 OPTIONAL(isDefinition, MDBoolField, (true)); \
5660 OPTIONAL(templateParams, MDField, ); \
5661 OPTIONAL(declaration, MDField, ); \
5662 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5663 OPTIONAL(annotations, MDField, );
5665#undef VISIT_MD_FIELDS
5669 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5670 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5671 declaration.Val, templateParams.Val, align.Val,
5683bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5684#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5685 REQUIRED(scope, MDField, ( false)); \
5686 OPTIONAL(name, MDStringField, ); \
5687 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5688 OPTIONAL(file, MDField, ); \
5689 OPTIONAL(line, LineField, ); \
5690 OPTIONAL(type, MDField, ); \
5691 OPTIONAL(flags, DIFlagField, ); \
5692 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5693 OPTIONAL(annotations, MDField, );
5695#undef VISIT_MD_FIELDS
5698 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5699 type.Val, arg.Val, flags.Val, align.Val,
5706bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5707#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5708 REQUIRED(scope, MDField, ( false)); \
5709 REQUIRED(name, MDStringField, ); \
5710 REQUIRED(file, MDField, ); \
5711 REQUIRED(line, LineField, );
5713#undef VISIT_MD_FIELDS
5716 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5722bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5738 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5747 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5752 return tokError(
"expected unsigned integer");
5770bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5771 assert(PFS &&
"Expected valid function state");
5782 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5784 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5796bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
5798#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5799 REQUIRED(var, MDField, ); \
5800 REQUIRED(expr, MDField, );
5802#undef VISIT_MD_FIELDS
5812bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
5813#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5814 OPTIONAL(name, MDStringField, ); \
5815 OPTIONAL(file, MDField, ); \
5816 OPTIONAL(line, LineField, ); \
5817 OPTIONAL(setter, MDStringField, ); \
5818 OPTIONAL(getter, MDStringField, ); \
5819 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5820 OPTIONAL(type, MDField, );
5822#undef VISIT_MD_FIELDS
5825 (Context,
name.Val,
file.Val, line.Val, setter.Val,
5826 getter.Val, attributes.Val, type.Val));
5833bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
5834#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5835 REQUIRED(tag, DwarfTagField, ); \
5836 REQUIRED(scope, MDField, ); \
5837 OPTIONAL(entity, MDField, ); \
5838 OPTIONAL(file, MDField, ); \
5839 OPTIONAL(line, LineField, ); \
5840 OPTIONAL(name, MDStringField, ); \
5841 OPTIONAL(elements, MDField, );
5843#undef VISIT_MD_FIELDS
5846 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
5847 line.Val,
name.Val, elements.Val));
5851#undef PARSE_MD_FIELD
5863bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
5866 if (parseMetadata(MD, &PFS))
5877bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
5878 PerFunctionState *PFS) {
5881 if (parseType(Ty, TypeMsg, Loc))
5884 return error(Loc,
"invalid metadata-value-metadata roundtrip");
5887 if (parseValue(Ty, V, PFS))
5902bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
5908 if (parseDIArgList(AL, PFS))
5914 if (parseSpecializedMDNode(
N)) {
5924 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
5934 if (parseMDString(S))
5944 if (parseMDNodeTail(
N))
5955 PerFunctionState *PFS) {
5957 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
5962 return error(
ID.Loc,
"invalid use of function-local name");
5963 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
5964 return V ==
nullptr;
5967 return error(
ID.Loc,
"invalid use of function-local name");
5968 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
5969 return V ==
nullptr;
5972 return error(
ID.Loc,
"invalid type for inline asm constraint string");
5976 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
5981 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
5984 return V ==
nullptr;
5986 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
5989 return V ==
nullptr;
5992 return error(
ID.Loc,
"integer constant must have integer type");
5994 V = ConstantInt::get(Context,
ID.APSIntVal);
5999 return error(
ID.Loc,
"floating point constant invalid for type");
6005 bool IsSNAN =
ID.APFloatVal.isSignaling();
6020 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6022 ID.APFloatVal.isNegative(), &Payload);
6025 V = ConstantFP::get(Context,
ID.APFloatVal);
6027 if (
V->getType() != Ty)
6028 return error(
ID.Loc,
"floating point constant does not have type '" +
6034 return error(
ID.Loc,
"null must be a pointer type");
6040 return error(
ID.Loc,
"invalid type for undef constant");
6044 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6045 return error(
ID.Loc,
"invalid empty array initializer");
6051 return error(
ID.Loc,
"invalid type for null constant");
6052 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6054 return error(
ID.Loc,
"invalid type for null constant");
6059 return error(
ID.Loc,
"invalid type for none constant");
6065 return error(
ID.Loc,
"invalid type for poison constant");
6069 if (
ID.ConstantVal->getType() != Ty)
6070 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6077 return error(
ID.Loc,
"vector constant must have vector type");
6079 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6081 "' but expected '" +
6088 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6089 if (
ST->getNumElements() !=
ID.UIntVal)
6091 "initializer with struct type has wrong # elements");
6093 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6096 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6097 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6100 "element " +
Twine(i) +
6101 " of struct initializer doesn't match struct element type");
6104 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6106 return error(
ID.Loc,
"constant expression type mismatch");
6116 if (parseValID(
ID,
nullptr))
6127 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6129 assert(isa<Constant>(V) &&
"Expected a constant value");
6130 C = cast<Constant>(V);
6137 return error(Loc,
"expected a constant value");
6141bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6144 return parseValID(
ID, PFS, Ty) ||
6145 convertValIDToValue(Ty,
ID, V, PFS);
6148bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6150 return parseType(Ty) || parseValue(Ty, V, PFS);
6153bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6154 PerFunctionState &PFS) {
6157 if (parseTypeAndValue(V, PFS))
6159 if (!isa<BasicBlock>(V))
6160 return error(Loc,
"expected a basic block");
6161 BB = cast<BasicBlock>(V);
6169 if (!
Name.starts_with(
"llvm.dbg."))
6172 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6173 FnID == Intrinsic::dbg_assign;
6181bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6182 unsigned &FunctionNumber,
6187 unsigned Visibility;
6188 unsigned DLLStorageClass;
6193 Type *RetType =
nullptr;
6195 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6197 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6198 parseType(RetType, RetTypeLoc,
true ))
6207 return error(LinkageLoc,
"invalid linkage for function definition");
6217 return error(LinkageLoc,
"invalid linkage for function declaration");
6221 return error(LinkageLoc,
"invalid function linkage type");
6225 return error(LinkageLoc,
6226 "symbol with local linkage must have default visibility");
6229 return error(LinkageLoc,
6230 "symbol with local linkage cannot have a DLL storage class");
6233 return error(RetTypeLoc,
"invalid function return type");
6237 std::string FunctionName;
6242 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6246 return tokError(
"expected function name");
6252 return tokError(
"expected '(' in function argument list");
6257 std::vector<unsigned> FwdRefAttrGrps;
6260 std::string Partition;
6264 unsigned AddrSpace = 0;
6270 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6271 parseOptionalUnnamedAddr(UnnamedAddr) ||
6272 parseOptionalProgramAddrSpace(AddrSpace) ||
6273 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6277 parseOptionalComdat(FunctionName,
C) ||
6278 parseOptionalAlignment(Alignment) ||
6279 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6283 parseGlobalTypeAndValue(PersonalityFn)))
6286 if (FuncAttrs.contains(Attribute::Builtin))
6287 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6292 FuncAttrs.removeAttribute(Attribute::Alignment);
6297 std::vector<Type*> ParamTypeList;
6300 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
6301 ParamTypeList.push_back(ArgList[i].Ty);
6302 Attrs.push_back(ArgList[i].Attrs);
6310 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6317 if (!FunctionName.empty()) {
6320 auto FRVI = ForwardRefVals.find(FunctionName);
6321 if (FRVI != ForwardRefVals.end()) {
6322 FwdFn = FRVI->second.first;
6324 return error(FRVI->second.second,
6325 "invalid forward reference to "
6328 "' with wrong type: "
6332 ForwardRefVals.erase(FRVI);
6333 }
else if ((Fn =
M->getFunction(FunctionName))) {
6335 return error(NameLoc,
6336 "invalid redefinition of function '" + FunctionName +
"'");
6337 }
else if (
M->getNamedValue(FunctionName)) {
6338 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6344 if (FunctionNumber == (
unsigned)-1)
6345 FunctionNumber = NumberedVals.getNext();
6349 auto I = ForwardRefValIDs.find(FunctionNumber);
6350 if (
I != ForwardRefValIDs.end()) {
6351 FwdFn =
I->second.first;
6353 return error(NameLoc,
"type of definition and forward reference of '@" +
6354 Twine(FunctionNumber) +
6359 ForwardRefValIDs.erase(
I);
6368 if (FunctionName.empty())
6369 NumberedVals.add(FunctionNumber, Fn);
6384 if (!
GC.empty()) Fn->
setGC(GC);
6387 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6391 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i, ++ArgIt) {
6393 if (ArgList[i].
Name.empty())
continue;
6398 if (ArgIt->
getName() != ArgList[i].Name)
6399 return error(ArgList[i].Loc,
6400 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6413 if (FunctionName.empty()) {
6415 ID.UIntVal = FunctionNumber;
6418 ID.StrVal = FunctionName;
6420 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6421 if (
Blocks != ForwardRefBlockAddresses.end())
6423 "cannot take blockaddress inside a declaration");
6427bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6429 if (FunctionNumber == -1) {
6431 ID.StrVal = std::string(
F.getName());
6434 ID.UIntVal = FunctionNumber;
6437 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6438 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6441 for (
const auto &
I :
Blocks->second) {
6442 const ValID &BBID =
I.first;
6446 "Expected local id or name");
6453 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6464 P.ForwardRefBlockAddresses.erase(
Blocks);
6470bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6473 return tokError(
"expected '{' in function body");
6476 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6480 if (PFS.resolveForwardRefBlockAddresses())
6486 return tokError(
"function body requires at least one basic block");
6490 if (parseBasicBlock(PFS))
6494 if (parseUseListOrder(&PFS))
6501 return PFS.finishFunction();
6506bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6523 std::string NameStr;
6528 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6529 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6536 if (SeenOldDbgInfoFormat)
6537 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6538 "containing debug info intrinsics");
6539 if (!SeenNewDbgInfoFormat)
6540 M->setNewDbgInfoFormatFlag(
true);
6541 SeenNewDbgInfoFormat =
true;
6545 if (parseDebugRecord(DR, PFS))
6547 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6559 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6564 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6568 switch (parseInstruction(Inst, BB, PFS)) {
6571 case InstError:
return true;
6578 if (parseInstructionMetadata(*Inst))
6581 case InstExtraComma:
6586 if (parseInstructionMetadata(*Inst))
6592 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6596 for (DbgRecordPtr &DR : TrailingDbgRecord)
6598 TrailingDbgRecord.clear();
6601 assert(TrailingDbgRecord.empty() &&
6602 "All debug values should have been attached to an instruction.");
6611bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6616 return error(DVRLoc,
"expected debug record type here");
6618 .
Case(
"declare", RecordKind::ValueKind)
6619 .
Case(
"value", RecordKind::ValueKind)
6620 .
Case(
"assign", RecordKind::ValueKind)
6621 .
Case(
"label", RecordKind::LabelKind);
6630 if (parseMDNode(Label))
6635 if (parseMDNode(DbgLoc))
6644 .
Case(
"declare", LocType::Declare)
6645 .
Case(
"value", LocType::Value)
6646 .
Case(
"assign", LocType::Assign);
6654 if (parseMetadata(ValLocMD, &PFS))
6661 if (parseMDNode(Variable))
6674 MDNode *AssignID =
nullptr;
6675 Metadata *AddressLocation =
nullptr;
6676 MDNode *AddressExpression =
nullptr;
6679 if (parseMDNode(AssignID))
6685 if (parseMetadata(AddressLocation, &PFS))
6691 if (parseMDNode(AddressExpression))
6716 PerFunctionState &PFS) {
6719 return tokError(
"found end of file when expecting more instructions");
6726 return error(Loc,
"expected instruction opcode");
6730 return parseRet(Inst, BB, PFS);
6732 return parseBr(Inst, PFS);
6734 return parseSwitch(Inst, PFS);
6736 return parseIndirectBr(Inst, PFS);
6738 return parseInvoke(Inst, PFS);
6740 return parseResume(Inst, PFS);
6742 return parseCleanupRet(Inst, PFS);
6744 return parseCatchRet(Inst, PFS);
6746 return parseCatchSwitch(Inst, PFS);
6748 return parseCatchPad(Inst, PFS);
6750 return parseCleanupPad(Inst, PFS);
6752 return parseCallBr(Inst, PFS);
6756 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6772 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6775 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6776 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6785 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
6799 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6801 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
6807 return parseArithmetic(Inst, PFS, KeywordVal,
6811 if (parseLogical(Inst, PFS, KeywordVal))
6814 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
6819 return parseLogical(Inst, PFS, KeywordVal);
6821 return parseCompare(Inst, PFS, KeywordVal);
6824 int Res = parseCompare(Inst, PFS, KeywordVal);
6836 bool Res = parseCast(Inst, PFS, KeywordVal);
6848 if (parseCast(Inst, PFS, KeywordVal))
6851 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
6853 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
6866 return parseCast(Inst, PFS, KeywordVal);
6870 int Res = parseSelect(Inst, PFS);
6874 if (!isa<FPMathOperator>(Inst))
6875 return error(Loc,
"fast-math-flags specified for select without "
6876 "floating-point scalar or vector return type");
6882 return parseVAArg(Inst, PFS);
6884 return parseExtractElement(Inst, PFS);
6886 return parseInsertElement(Inst, PFS);
6888 return parseShuffleVector(Inst, PFS);
6891 int Res = parsePHI(Inst, PFS);
6895 if (!isa<FPMathOperator>(Inst))
6896 return error(Loc,
"fast-math-flags specified for phi without "
6897 "floating-point scalar or vector return type");
6903 return parseLandingPad(Inst, PFS);
6905 return parseFreeze(Inst, PFS);
6917 return parseAlloc(Inst, PFS);
6919 return parseLoad(Inst, PFS);
6921 return parseStore(Inst, PFS);
6923 return parseCmpXchg(Inst, PFS);
6925 return parseAtomicRMW(Inst, PFS);
6927 return parseFence(Inst, PFS);
6929 return parseGetElementPtr(Inst, PFS);
6931 return parseExtractValue(Inst, PFS);
6933 return parseInsertValue(Inst, PFS);
6938bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
6939 if (Opc == Instruction::FCmp) {
6942 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
6963 return tokError(
"expected icmp predicate (e.g. 'eq')");
6988 PerFunctionState &PFS) {
6991 if (parseType(Ty,
true ))
6994 Type *ResType = PFS.getFunction().getReturnType();
6998 return error(TypeLoc,
"value doesn't match function result type '" +
7006 if (parseValue(Ty, RV, PFS))
7010 return error(TypeLoc,
"value doesn't match function result type '" +
7020bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7024 if (parseTypeAndValue(Op0, Loc, PFS))
7027 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7033 return error(Loc,
"branch condition must have 'i1' type");
7035 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7036 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7037 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7038 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7050bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7051 LocTy CondLoc, BBLoc;
7054 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7055 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7056 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7060 if (!
Cond->getType()->isIntegerTy())
7061 return error(CondLoc,
"switch condition must have integer type");
7070 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7071 parseToken(
lltok::comma,
"expected ',' after case value") ||
7072 parseTypeAndBasicBlock(DestBB, PFS))
7076 return error(CondLoc,
"duplicate case value in switch");
7078 return error(CondLoc,
"case value is not a constant integer");
7086 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7087 SI->addCase(Table[i].first, Table[i].second);
7095bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7098 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7099 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7103 if (!
Address->getType()->isPointerTy())
7104 return error(AddrLoc,
"indirectbr address must have pointer type");
7111 if (parseTypeAndBasicBlock(DestBB, PFS))
7116 if (parseTypeAndBasicBlock(DestBB, PFS))
7122 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7126 for (
unsigned i = 0, e = DestList.
size(); i != e; ++i)
7135bool LLParser::resolveFunctionType(
Type *RetType,
7138 FuncTy = dyn_cast<FunctionType>(RetType);
7141 std::vector<Type*> ParamTypes;
7142 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
7143 ParamTypes.push_back(ArgList[i].
V->getType());
7156bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7158 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7159 std::vector<unsigned> FwdRefAttrGrps;
7162 unsigned InvokeAddrSpace;
7163 Type *RetType =
nullptr;
7170 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7171 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7172 parseType(RetType, RetTypeLoc,
true ) ||
7173 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7174 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7176 parseOptionalOperandBundles(BundleList, PFS) ||
7178 parseTypeAndBasicBlock(NormalBB, PFS) ||
7180 parseTypeAndBasicBlock(UnwindBB, PFS))
7187 if (resolveFunctionType(RetType, ArgList, Ty))
7188 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7206 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7207 Type *ExpectedTy =
nullptr;
7210 }
else if (!Ty->isVarArg()) {
7211 return error(ArgList[i].Loc,
"too many arguments specified");
7214 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7215 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7217 Args.push_back(ArgList[i].V);
7222 return error(CallLoc,
"not enough parameters specified for call");
7233 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7240bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7242 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7251 PerFunctionState &PFS) {
7252 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7257 if (!
Args.empty() &&
7258 parseToken(
lltok::comma,
"expected ',' in argument list"))
7263 Type *ArgTy =
nullptr;
7264 if (parseType(ArgTy, ArgLoc))
7269 if (parseMetadataAsValue(V, PFS))
7272 if (parseValue(ArgTy, V, PFS))
7284bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7285 Value *CleanupPad =
nullptr;
7287 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7302 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7313bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7314 Value *CatchPad =
nullptr;
7316 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7323 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7324 parseTypeAndBasicBlock(BB, PFS))
7333bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7341 return tokError(
"expected scope value for catchswitch");
7346 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7352 if (parseTypeAndBasicBlock(DestBB, PFS))
7357 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7360 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7368 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7375 CatchSwitch->addHandler(DestBB);
7382bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7383 Value *CatchSwitch =
nullptr;
7389 return tokError(
"expected scope value for catchpad");
7395 if (parseExceptionArgs(Args, PFS))
7404bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7405 Value *ParentPad =
nullptr;
7412 return tokError(
"expected scope value for cleanuppad");
7418 if (parseExceptionArgs(Args, PFS))
7434bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7435 unsigned Opc,
bool IsFP) {
7437 if (parseTypeAndValue(LHS, Loc, PFS))
7444 return error(Loc,
"invalid operand type for instruction");
7454bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7456 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7457 std::vector<unsigned> FwdRefAttrGrps;
7460 Type *RetType =
nullptr;
7467 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7468 parseType(RetType, RetTypeLoc,
true ) ||
7469 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7470 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7472 parseOptionalOperandBundles(BundleList, PFS) ||
7474 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7483 if (parseTypeAndBasicBlock(DestBB, PFS))
7488 if (parseTypeAndBasicBlock(DestBB, PFS))
7494 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7501 if (resolveFunctionType(RetType, ArgList, Ty))
7502 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7519 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7520 Type *ExpectedTy =
nullptr;
7523 }
else if (!Ty->isVarArg()) {
7524 return error(ArgList[i].Loc,
"too many arguments specified");
7527 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7528 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7530 Args.push_back(ArgList[i].V);
7535 return error(CallLoc,
"not enough parameters specified for call");
7547 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7561bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7562 unsigned Opc,
bool IsFP) {
7564 if (parseTypeAndValue(LHS, Loc, PFS) ||
7565 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7573 return error(Loc,
"invalid operand type for instruction");
7581bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7584 if (parseTypeAndValue(LHS, Loc, PFS) ||
7585 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7591 "instruction requires integer or integer vector operands");
7600bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7606 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7607 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7611 if (Opc == Instruction::FCmp) {
7613 return error(Loc,
"fcmp requires floating point operands");
7616 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7619 return error(Loc,
"icmp requires integer operands");
7631bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7635 Type *DestTy =
nullptr;
7636 if (parseTypeAndValue(
Op, Loc, PFS) ||
7637 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7643 return error(Loc,
"invalid cast opcode for cast from '" +
7653bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7655 Value *Op0, *Op1, *Op2;
7656 if (parseTypeAndValue(Op0, Loc, PFS) ||
7657 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7658 parseTypeAndValue(Op1, PFS) ||
7659 parseToken(
lltok::comma,
"expected ',' after select value") ||
7660 parseTypeAndValue(Op2, PFS))
7664 return error(Loc, Reason);
7672bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7674 Type *EltTy =
nullptr;
7676 if (parseTypeAndValue(
Op, PFS) ||
7677 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7678 parseType(EltTy, TypeLoc))
7682 return error(TypeLoc,
"va_arg requires operand with first class type");
7690bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7693 if (parseTypeAndValue(Op0, Loc, PFS) ||
7694 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7695 parseTypeAndValue(Op1, PFS))
7699 return error(Loc,
"invalid extractelement operands");
7707bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7709 Value *Op0, *Op1, *Op2;
7710 if (parseTypeAndValue(Op0, Loc, PFS) ||
7711 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7712 parseTypeAndValue(Op1, PFS) ||
7713 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7714 parseTypeAndValue(Op2, PFS))
7718 return error(Loc,
"invalid insertelement operands");
7726bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7728 Value *Op0, *Op1, *Op2;
7729 if (parseTypeAndValue(Op0, Loc, PFS) ||
7730 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7731 parseTypeAndValue(Op1, PFS) ||
7732 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7733 parseTypeAndValue(Op2, PFS))
7737 return error(Loc,
"invalid shufflevector operands");
7745int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7749 if (parseType(Ty, TypeLoc))
7753 return error(TypeLoc,
"phi node must have first class type");
7756 bool AteExtraComma =
false;
7768 AteExtraComma =
true;
7772 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7773 parseValue(Ty, Op0, PFS) ||
7774 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7779 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7783 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
7784 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
7786 return AteExtraComma ? InstExtraComma : InstNormal;
7795bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
7798 if (parseType(Ty, TyLoc))
7811 return tokError(
"expected 'catch' or 'filter' clause type");
7815 if (parseTypeAndValue(V, VLoc, PFS))
7821 if (isa<ArrayType>(
V->getType()))
7822 error(VLoc,
"'catch' clause has an invalid type");
7824 if (!isa<ArrayType>(
V->getType()))
7825 error(VLoc,
"'filter' clause has an invalid type");
7828 Constant *CV = dyn_cast<Constant>(V);
7830 return error(VLoc,
"clause argument must be a constant");
7834 Inst = LP.release();
7840bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
7843 if (parseTypeAndValue(
Op, Loc, PFS))
7859bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
7861 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7862 std::vector<unsigned> FwdRefAttrGrps;
7864 unsigned CallAddrSpace;
7866 Type *RetType =
nullptr;
7875 "expected 'tail call', 'musttail call', or 'notail call'"))
7880 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7881 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7882 parseType(RetType, RetTypeLoc,
true ) ||
7883 parseValID(CalleeID, &PFS) ||
7885 PFS.getFunction().isVarArg()) ||
7886 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
7887 parseOptionalOperandBundles(BundleList, PFS))
7894 if (resolveFunctionType(RetType, ArgList, Ty))
7895 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7901 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7914 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7915 Type *ExpectedTy =
nullptr;
7918 }
else if (!Ty->isVarArg()) {
7919 return error(ArgList[i].Loc,
"too many arguments specified");
7922 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7923 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7925 Args.push_back(ArgList[i].V);
7926 Attrs.push_back(ArgList[i].Attrs);
7930 return error(CallLoc,
"not enough parameters specified for call");
7941 if (!isa<FPMathOperator>(CI)) {
7943 return error(CallLoc,
"fast-math-flags specified for call without "
7944 "floating-point scalar or vector return type");
7951 if (SeenNewDbgInfoFormat) {
7953 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
7954 "using non-intrinsic debug info");
7956 if (!SeenOldDbgInfoFormat)
7957 M->setNewDbgInfoFormatFlag(
false);
7958 SeenOldDbgInfoFormat =
true;
7961 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7973int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
7975 LocTy SizeLoc, TyLoc, ASLoc;
7977 unsigned AddrSpace = 0;
7980 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7981 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7983 if (parseType(Ty, TyLoc))
7987 return error(TyLoc,
"invalid type for alloca");
7989 bool AteExtraComma =
false;
7991 if (Lex.
getKind() == lltok::kw_align) {
7992 if (parseOptionalAlignment(Alignment))
7994 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7998 if (parseOptionalAddrSpace(AddrSpace))
8001 AteExtraComma =
true;
8003 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8006 if (Lex.
getKind() == lltok::kw_align) {
8007 if (parseOptionalAlignment(Alignment))
8009 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8013 if (parseOptionalAddrSpace(AddrSpace))
8016 AteExtraComma =
true;
8022 if (
Size && !
Size->getType()->isIntegerTy())
8023 return error(SizeLoc,
"element count must have integer type");
8026 if (!Alignment && !Ty->
isSized(&Visited))
8027 return error(TyLoc,
"Cannot allocate unsized type");
8029 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8034 return AteExtraComma ? InstExtraComma : InstNormal;
8041int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8044 bool AteExtraComma =
false;
8045 bool isAtomic =
false;
8054 bool isVolatile =
false;
8062 if (parseType(Ty) ||
8063 parseToken(
lltok::comma,
"expected comma after load's type") ||
8064 parseTypeAndValue(Val, Loc, PFS) ||
8065 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8066 parseOptionalCommaAlign(Alignment, AteExtraComma))
8070 return error(Loc,
"load operand must be a pointer to a first class type");
8071 if (isAtomic && !Alignment)
8072 return error(Loc,
"atomic load must have explicit non-zero alignment");
8075 return error(Loc,
"atomic load cannot use Release ordering");
8078 if (!Alignment && !Ty->
isSized(&Visited))
8079 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8081 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8082 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8083 return AteExtraComma ? InstExtraComma : InstNormal;
8091int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8094 bool AteExtraComma =
false;
8095 bool isAtomic =
false;
8104 bool isVolatile =
false;
8110 if (parseTypeAndValue(Val, Loc, PFS) ||
8111 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8112 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8113 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8114 parseOptionalCommaAlign(Alignment, AteExtraComma))
8117 if (!
Ptr->getType()->isPointerTy())
8118 return error(PtrLoc,
"store operand must be a pointer");
8120 return error(Loc,
"store operand must be a first class value");
8121 if (isAtomic && !Alignment)
8122 return error(Loc,
"atomic store must have explicit non-zero alignment");
8125 return error(Loc,
"atomic store cannot use Acquire ordering");
8128 return error(Loc,
"storing unsized types is not allowed");
8130 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8132 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8133 return AteExtraComma ? InstExtraComma : InstNormal;
8140int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8142 bool AteExtraComma =
false;
8146 bool isVolatile =
false;
8147 bool isWeak =
false;
8156 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8157 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8158 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8159 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8160 parseTypeAndValue(New, NewLoc, PFS) ||
8161 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8162 parseOrdering(FailureOrdering) ||
8163 parseOptionalCommaAlign(Alignment, AteExtraComma))
8167 return tokError(
"invalid cmpxchg success ordering");
8169 return tokError(
"invalid cmpxchg failure ordering");
8170 if (!
Ptr->getType()->isPointerTy())
8171 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8172 if (
Cmp->getType() !=
New->getType())
8173 return error(NewLoc,
"compare value and new value type do not match");
8174 if (!
New->getType()->isFirstClassType())
8175 return error(NewLoc,
"cmpxchg operand must be a first class value");
8177 const Align DefaultAlignment(
8178 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8183 SuccessOrdering, FailureOrdering, SSID);
8188 return AteExtraComma ? InstExtraComma : InstNormal;
8194int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8196 bool AteExtraComma =
false;
8199 bool isVolatile =
false;
8209 return tokError(
"expected binary operation in atomicrmw");
8246 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8247 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8248 parseTypeAndValue(Val, ValLoc, PFS) ||
8249 parseScopeAndOrdering(
true , SSID, Ordering) ||
8250 parseOptionalCommaAlign(Alignment, AteExtraComma))
8254 return tokError(
"atomicrmw cannot be unordered");
8255 if (!
Ptr->getType()->isPointerTy())
8256 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8258 return error(ValLoc,
"atomicrmw operand may not be scalable");
8267 " operand must be an integer, floating point, or pointer type");
8271 return error(ValLoc,
"atomicrmw " +
8273 " operand must be a floating point type");
8277 return error(ValLoc,
"atomicrmw " +
8279 " operand must be an integer");
8284 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
8287 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8289 const Align DefaultAlignment(
8290 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8294 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8297 return AteExtraComma ? InstExtraComma : InstNormal;
8302int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8305 if (parseScopeAndOrdering(
true , SSID, Ordering))
8309 return tokError(
"fence cannot be unordered");
8311 return tokError(
"fence cannot be monotonic");
8313 Inst =
new FenceInst(Context, Ordering, SSID);
8319int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8321 Value *Val =
nullptr;
8327 if (parseType(Ty) ||
8328 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8329 parseTypeAndValue(
Ptr, Loc, PFS))
8334 if (!BasePointerType)
8335 return error(Loc,
"base of getelementptr must be a pointer");
8338 bool AteExtraComma =
false;
8342 ? cast<VectorType>(
BaseType)->getElementCount()
8347 AteExtraComma =
true;
8350 if (parseTypeAndValue(Val, EltLoc, PFS))
8353 return error(EltLoc,
"getelementptr index must be an integer");
8355 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8360 "getelementptr vector index has a wrong number of elements");
8361 GEPWidth = ValNumEl;
8368 return error(Loc,
"base element of getelementptr must be sized");
8370 auto *STy = dyn_cast<StructType>(Ty);
8372 return error(Loc,
"getelementptr cannot target structure that contains "
8373 "scalable vector type");
8376 return error(Loc,
"invalid getelementptr indices");
8379 cast<GetElementPtrInst>(Inst)->setIsInBounds(
true);
8380 return AteExtraComma ? InstExtraComma : InstNormal;
8385int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8389 if (parseTypeAndValue(Val, Loc, PFS) ||
8390 parseIndexList(Indices, AteExtraComma))
8394 return error(Loc,
"extractvalue operand must be aggregate type");
8397 return error(Loc,
"invalid indices for extractvalue");
8399 return AteExtraComma ? InstExtraComma : InstNormal;
8404int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8408 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8409 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8410 parseTypeAndValue(Val1, Loc1, PFS) ||
8411 parseIndexList(Indices, AteExtraComma))
8415 return error(Loc0,
"insertvalue operand must be aggregate type");
8419 return error(Loc0,
"invalid indices for insertvalue");
8420 if (IndexedType != Val1->
getType())
8421 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8425 return AteExtraComma ? InstExtraComma : InstNormal;
8451 if (parseMetadata(MD,
nullptr))
8456 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8465 return error(Loc,
"value has no uses");
8467 unsigned NumUses = 0;
8469 for (
const Use &U :
V->uses()) {
8470 if (++NumUses > Indexes.
size())
8472 Order[&
U] = Indexes[NumUses - 1];
8475 return error(Loc,
"value only has one use");
8476 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8478 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8480 V->sortUseList([&](
const Use &L,
const Use &R) {
8493 return Lex.
Error(
"expected non-empty list of uselistorder indexes");
8500 bool IsOrdered =
true;
8501 assert(Indexes.
empty() &&
"Expected empty order vector");
8504 if (parseUInt32(
Index))
8518 if (Indexes.
size() < 2)
8519 return error(Loc,
"expected >= 2 uselistorder indexes");
8522 "expected distinct uselistorder indexes in range [0, size)");
8524 return error(Loc,
"expected uselistorder indexes to change the order");
8531bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8538 if (parseTypeAndValue(V, PFS) ||
8539 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8540 parseUseListOrderIndexes(Indexes))
8543 return sortUseListOrder(V, Indexes, Loc);
8548bool LLParser::parseUseListOrderBB() {
8555 if (parseValID(Fn,
nullptr) ||
8556 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8557 parseValID(Label,
nullptr) ||
8558 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8559 parseUseListOrderIndexes(Indexes))
8565 GV =
M->getNamedValue(Fn.
StrVal);
8567 GV = NumberedVals.get(Fn.
UIntVal);
8569 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8572 "invalid function forward reference in uselistorder_bb");
8573 auto *
F = dyn_cast<Function>(GV);
8575 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8576 if (
F->isDeclaration())
8577 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8581 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8583 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8584 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8586 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8587 if (!isa<BasicBlock>(V))
8588 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8590 return sortUseListOrder(V, Indexes, Loc);
8596bool LLParser::parseModuleEntry(
unsigned ID) {
8605 parseStringConstant(Path) ||
8613 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8614 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8615 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8616 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8617 parseUInt32(Hash[4]))
8624 auto ModuleEntry =
Index->addModule(Path, Hash);
8625 ModuleIdMap[
ID] = ModuleEntry->first();
8632bool LLParser::parseTypeIdEntry(
unsigned ID) {
8641 parseStringConstant(
Name))
8646 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8651 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8652 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8653 for (
auto TIDRef : FwdRefTIDs->second) {
8655 "Forward referenced type id GUID expected to be 0");
8658 ForwardRefTypeIds.erase(FwdRefTIDs);
8670 parseTypeTestResolution(TIS.
TTRes))
8675 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8686 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8692bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8701 parseStringConstant(
Name))
8705 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8712 IdToIndexMapType IdToIndexMap;
8725 if (parseGVReference(VI, GVId))
8732 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8733 TI.push_back({
Offset, VI});
8741 for (
auto I : IdToIndexMap) {
8742 auto &Infos = ForwardRefValueInfos[
I.first];
8743 for (
auto P :
I.second) {
8745 "Forward referenced ValueInfo expected to be empty");
8746 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8756 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8757 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8758 for (
auto TIDRef : FwdRefTIDs->second) {
8760 "Forward referenced type id GUID expected to be 0");
8763 ForwardRefTypeIds.erase(FwdRefTIDs);
8803 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
8830 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
8843 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
8856bool LLParser::parseOptionalWpdResolutions(
8857 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8869 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
8872 WPDResMap[
Offset] = WPDRes;
8908 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
8922 if (parseOptionalResByArg(WPDRes.
ResByArg))
8927 "expected optional WholeProgramDevirtResolution field");
8944bool LLParser::parseOptionalResByArg(
8953 std::vector<uint64_t>
Args;
8954 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
8978 "unexpected WholeProgramDevirtResolution::ByArg kind");
8988 parseUInt64(ByArg.
Info))
8994 parseUInt32(ByArg.
Byte))
9000 parseUInt32(ByArg.
Bit))
9005 "expected optional whole program devirt field");
9012 ResByArg[
Args] = ByArg;
9023bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9031 if (parseUInt64(Val))
9033 Args.push_back(Val);
9042static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9047 assert(!(ReadOnly && WriteOnly));
9057bool LLParser::addGlobalValueToIndex(
9059 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9064 VI =
Index->getOrInsertValueInfo(GUID);
9068 auto *GV =
M->getNamedValue(
Name);
9070 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9072 VI =
Index->getOrInsertValueInfo(GV);
9076 "Need a source_filename to compute GUID for local");
9084 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9085 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9086 for (
auto VIRef : FwdRefVIs->second) {
9088 "Forward referenced ValueInfo expected to be empty");
9091 ForwardRefValueInfos.erase(FwdRefVIs);
9095 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9096 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9097 for (
auto AliaseeRef : FwdRefAliasees->second) {
9098 assert(!AliaseeRef.first->hasAliasee() &&
9099 "Forward referencing alias already has aliasee");
9100 assert(Summary &&
"Aliasee must be a definition");
9101 AliaseeRef.first->setAliasee(VI,
Summary.get());
9103 ForwardRefAliasees.erase(FwdRefAliasees);
9108 Index->addGlobalValueSummary(VI, std::move(Summary));
9111 if (
ID == NumberedValueInfos.size())
9112 NumberedValueInfos.push_back(VI);
9115 if (
ID > NumberedValueInfos.size())
9116 NumberedValueInfos.resize(
ID + 1);
9117 NumberedValueInfos[
ID] =
VI;
9125bool LLParser::parseSummaryIndexFlags() {
9132 if (parseUInt64(Flags))
9135 Index->setFlags(Flags);
9141bool LLParser::parseBlockCount() {
9148 if (parseUInt64(BlockCount))
9151 Index->setBlockCount(BlockCount);
9159bool LLParser::parseGVEntry(
unsigned ID) {
9174 parseStringConstant(
Name))
9180 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9184 return error(Lex.
getLoc(),
"expected name or guid tag");
9209 if (parseFunctionSummary(
Name, GUID,
ID))
9213 if (parseVariableSummary(
Name, GUID,
ID))
9217 if (parseAliasSummary(
Name, GUID,
ID))
9221 return error(Lex.
getLoc(),
"expected summary type");
9247 false,
false,
false,
9250 std::vector<FunctionSummary::EdgeTy> Calls;
9252 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9253 std::vector<ValueInfo> Refs;
9254 std::vector<CallsiteInfo> Callsites;
9255 std::vector<AllocInfo> Allocs;
9260 parseModuleReference(ModulePath) ||
9261 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9264 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9271 if (parseOptionalFFlags(FFlags))
9275 if (parseOptionalCalls(Calls))
9279 if (parseOptionalTypeIdInfo(TypeIdInfo))
9283 if (parseOptionalRefs(Refs))
9287 if (parseOptionalParamAccesses(ParamAccesses))
9291 if (parseOptionalAllocs(Allocs))
9295 if (parseOptionalCallsites(Callsites))
9299 return error(Lex.
getLoc(),
"expected optional function summary field");
9306 auto FS = std::make_unique<FunctionSummary>(
9307 GVFlags, InstCount, FFlags, 0, std::move(Refs),
9308 std::move(Calls), std::move(TypeIdInfo.
TypeTests),
9313 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9315 FS->setModulePath(ModulePath);
9317 return addGlobalValueToIndex(
Name, GUID,
9319 std::move(FS), Loc);
9335 false,
false,
false,
9341 std::vector<ValueInfo> Refs;
9345 parseModuleReference(ModulePath) ||
9346 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9348 parseGVarFlags(GVarFlags))
9355 if (parseOptionalVTableFuncs(VTableFuncs))
9359 if (parseOptionalRefs(Refs))
9363 return error(Lex.
getLoc(),
"expected optional variable summary field");
9371 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9373 GS->setModulePath(ModulePath);
9374 GS->setVTableFuncs(std::move(VTableFuncs));
9376 return addGlobalValueToIndex(
Name, GUID,
9378 std::move(GS), Loc);
9394 false,
false,
false,
9398 parseModuleReference(ModulePath) ||
9399 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9407 if (parseGVReference(AliaseeVI, GVId))
9413 auto AS = std::make_unique<AliasSummary>(GVFlags);
9415 AS->setModulePath(ModulePath);
9419 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9421 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9422 assert(Summary &&
"Aliasee must be a definition");
9423 AS->setAliasee(AliaseeVI, Summary);
9426 return addGlobalValueToIndex(
Name, GUID,
9428 std::move(AS), Loc);
9433bool LLParser::parseFlag(
unsigned &Val) {
9435 return tokError(
"expected integer");
9456 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9465 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9471 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9477 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9483 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9489 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9495 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9501 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9507 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9513 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9519 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9524 return error(Lex.
getLoc(),
"expected function flag type");
9539bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9543 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9547 IdToIndexMapType IdToIndexMap;
9558 if (parseGVReference(VI, GVId))
9563 unsigned HasTailCall =
false;
9570 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9575 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9580 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9584 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9588 return tokError(
"Expected only one of hotness or relbf");
9593 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9603 for (
auto I : IdToIndexMap) {
9604 auto &Infos = ForwardRefValueInfos[
I.first];
9605 for (
auto P :
I.second) {
9607 "Forward referenced ValueInfo expected to be empty");
9608 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9625 case lltok::kw_cold:
9638 return error(Lex.
getLoc(),
"invalid call edge hotness");
9647bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9651 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9655 IdToIndexMapType IdToIndexMap;
9659 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9666 if (parseGVReference(VI, GVId))
9679 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9680 VTableFuncs.push_back({
VI,
Offset});
9682 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9688 for (
auto I : IdToIndexMap) {
9689 auto &Infos = ForwardRefValueInfos[
I.first];
9690 for (
auto P :
I.second) {
9692 "Forward referenced ValueInfo expected to be empty");
9693 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9697 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9704bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9706 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9712bool LLParser::parseParamAccessOffset(
ConstantRange &Range) {
9715 auto ParseAPSInt = [&](
APSInt &Val) {
9717 return tokError(
"expected integer");
9720 Val.setIsSigned(
true);
9743 IdLocListType &IdLocList) {
9752 if (parseGVReference(VI, GVId))
9756 IdLocList.emplace_back(GVId, Loc);
9759 parseParamNo(
Call.ParamNo) ||
9761 parseParamAccessOffset(
Call.Offsets))
9774 IdLocListType &IdLocList) {
9776 parseParamNo(
Param.ParamNo) ||
9778 parseParamAccessOffset(
Param.Use))
9788 if (parseParamAccessCall(Call, IdLocList))
9790 Param.Calls.push_back(Call);
9805bool LLParser::parseOptionalParamAccesses(
9806 std::vector<FunctionSummary::ParamAccess> &Params) {
9814 IdLocListType VContexts;
9815 size_t CallsNum = 0;
9818 if (parseParamAccess(ParamAccess, VContexts))
9820 CallsNum += ParamAccess.
Calls.size();
9821 assert(VContexts.size() == CallsNum);
9823 Params.emplace_back(std::move(ParamAccess));
9831 IdLocListType::const_iterator ItContext = VContexts.begin();
9832 for (
auto &PA : Params) {
9833 for (
auto &
C : PA.Calls) {
9835 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
9840 assert(ItContext == VContexts.end());
9847bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9851 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
9855 struct ValueContext {
9860 std::vector<ValueContext> VContexts;
9865 if (parseGVReference(
VC.VI,
VC.GVId))
9867 VContexts.push_back(VC);
9873 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
9874 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9877 IdToIndexMapType IdToIndexMap;
9878 for (
auto &VC : VContexts) {
9883 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.size(),
VC.Loc));
9884 Refs.push_back(
VC.VI);
9889 for (
auto I : IdToIndexMap) {
9890 auto &Infos = ForwardRefValueInfos[
I.first];
9891 for (
auto P :
I.second) {
9893 "Forward referenced ValueInfo expected to be empty");
9894 Infos.emplace_back(&Refs[
P.first],
P.second);
9908bool LLParser::parseOptionalTypeIdInfo(
9920 if (parseTypeTests(TypeIdInfo.
TypeTests))
9944 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
9948 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
9957bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9965 IdToIndexMapType IdToIndexMap;
9974 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
9976 }
else if (parseUInt64(GUID))
9978 TypeTests.push_back(GUID);
9983 for (
auto I : IdToIndexMap) {
9984 auto &Ids = ForwardRefTypeIds[
I.first];
9985 for (
auto P :
I.second) {
9986 assert(TypeTests[
P.first] == 0 &&
9987 "Forward referenced type id GUID expected to be 0");
9988 Ids.emplace_back(&TypeTests[
P.first],
P.second);
9992 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10000bool LLParser::parseVFuncIdList(
10001 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10009 IdToIndexMapType IdToIndexMap;
10012 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10014 VFuncIdList.push_back(VFuncId);
10022 for (
auto I : IdToIndexMap) {
10023 auto &Ids = ForwardRefTypeIds[
I.first];
10024 for (
auto P :
I.second) {
10025 assert(VFuncIdList[
P.first].GUID == 0 &&
10026 "Forward referenced type id GUID expected to be 0");
10027 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10036bool LLParser::parseConstVCallList(
10038 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10046 IdToIndexMapType IdToIndexMap;
10049 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10051 ConstVCallList.push_back(ConstVCall);
10059 for (
auto I : IdToIndexMap) {
10060 auto &Ids = ForwardRefTypeIds[
I.first];
10061 for (
auto P :
I.second) {
10062 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10063 "Forward referenced type id GUID expected to be 0");
10064 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10074 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10076 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap,
Index))
10080 if (parseArgs(ConstVCall.
Args))
10093 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10108 IdToIndexMap[
ID].push_back(std::make_pair(
Index, Loc));
10110 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10112 parseUInt64(VFuncId.
GUID))
10118 parseUInt64(VFuncId.
Offset) ||
10147 assert(HasLinkage &&
"Linkage not optional in summary entry");
10154 parseOptionalVisibility(Flag);
10159 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10165 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10171 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10177 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10186 if (parseOptionalImportType(Lex.
getKind(), IK))
10188 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10192 return error(Lex.
getLoc(),
"expected gv flag type");
10214 auto ParseRest = [
this](
unsigned int &Val) {
10218 return parseFlag(Val);
10224 case lltok::kw_readonly:
10225 if (ParseRest(Flag))
10229 case lltok::kw_writeonly:
10230 if (ParseRest(Flag))
10235 if (ParseRest(Flag))
10240 if (ParseRest(Flag))
10245 return error(Lex.
getLoc(),
"expected gvar flag type");
10253bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10261 auto I = ModuleIdMap.find(ModuleID);
10263 assert(
I != ModuleIdMap.end());
10264 ModulePath =
I->second;
10270bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10273 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10279 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10281 VI = NumberedValueInfos[GVId];
10298bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10302 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10317 if (parseAllocType(V))
10322 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10326 std::vector<MIBInfo> MIBs;
10327 if (parseMemProfs(MIBs))
10330 Allocs.push_back({Versions, MIBs});
10347bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10351 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10357 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10366 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10375 if (parseUInt64(StackId))
10397bool LLParser::parseAllocType(uint8_t &
AllocType) {
10405 case lltok::kw_cold:
10408 case lltok::kw_hot:
10412 return error(Lex.
getLoc(),
"invalid alloc type");
10425bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10429 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10433 IdToIndexMapType IdToIndexMap;
10436 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10445 if (parseGVReference(VI, GVId))
10449 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10458 if (parseUInt32(V))
10464 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10473 if (parseUInt64(StackId))
10485 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10486 Callsites.push_back({
VI, Clones, StackIdIndices});
10494 for (
auto I : IdToIndexMap) {
10495 auto &Infos = ForwardRefValueInfos[
I.first];
10496 for (
auto P :
I.second) {
10498 "Forward referenced ValueInfo expected to be empty");
10499 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10503 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.
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.