63 "Allow incomplete IR on a best effort basis (references to unknown "
64 "metadata will be dropped)"));
87 "Can't read textual IR with a Context that discards named Values");
90 if (parseTargetDefinitions(DataLayoutCallback))
100 restoreParsingState(Slots);
104 if (parseType(Ty) || parseConstantValue(Ty,
C))
107 return error(Lex.
getLoc(),
"expected end of string");
113 restoreParsingState(Slots);
122 Read =
End.getPointer() - Start.getPointer();
129 restoreParsingState(Slots);
135 bool Status = parseDIExpressionBody(Result,
false);
137 Read =
End.getPointer() - Start.getPointer();
142void LLParser::restoreParsingState(
const SlotMapping *Slots) {
149 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
150 for (
const auto &
I : Slots->
Types)
151 NumberedTypes.insert(
152 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
157 if (!isa<DbgInfoIntrinsic>(
II) &&
158 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
163 if (
auto *MV = dyn_cast<MetadataAsValue>(V))
164 if (
auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
165 if (MD->isTemporary())
169 assert(
II->use_empty() &&
"Cannot have uses");
170 II->eraseFromParent();
179void LLParser::dropUnknownMetadataReferences() {
180 auto Pred = [](
unsigned MDKind,
MDNode *
Node) {
return Node->isTemporary(); };
182 F.eraseMetadataIf(Pred);
184 I.eraseMetadataIf(Pred);
186 if (
auto *
II = dyn_cast<IntrinsicInst>(&
I))
192 GV.eraseMetadataIf(Pred);
197 if (
Info.first->getNumTemporaryUses() == 1) {
198 NumberedMetadata.erase(
ID);
199 ForwardRefMDNodes.erase(
ID);
212 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
213 "Mixed debug intrinsics/records seen without a parsing error?");
218 M->setNewDbgInfoFormatFlag(SeenNewDbgInfoFormat);
222 for (
const auto &RAG : ForwardRefAttrGroups) {
224 const std::vector<unsigned> &
Attrs = RAG.second;
227 for (
const auto &Attr : Attrs) {
228 auto R = NumberedAttrBuilders.find(Attr);
229 if (R != NumberedAttrBuilders.end())
233 if (
Function *Fn = dyn_cast<Function>(V)) {
243 Fn->setAlignment(*
A);
248 Fn->setAttributes(AS);
249 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
255 CI->setAttributes(AS);
262 II->setAttributes(AS);
263 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
269 CBI->setAttributes(AS);
270 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
281 if (!ForwardRefBlockAddresses.empty())
282 return error(ForwardRefBlockAddresses.begin()->first.Loc,
283 "expected function name in blockaddress");
285 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
289 GV =
M->getNamedValue(GVRef.
StrVal);
291 GV = NumberedVals.get(GVRef.
UIntVal);
296 "' referenced by dso_local_equivalent");
300 "expected a function, alias to function, or ifunc "
301 "in dso_local_equivalent");
304 FwdRef->replaceAllUsesWith(Equiv);
305 FwdRef->eraseFromParent();
312 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
313 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
316 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
317 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
320 ForwardRefDSOLocalEquivalentIDs.clear();
321 ForwardRefDSOLocalEquivalentNames.clear();
323 for (
const auto &NT : NumberedTypes)
324 if (
NT.second.second.isValid())
326 "use of undefined type '%" +
Twine(
NT.first) +
"'");
328 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
329 NamedTypes.begin(), E = NamedTypes.end();
I != E; ++
I)
330 if (
I->second.second.isValid())
331 return error(
I->second.second,
332 "use of undefined type named '" +
I->getKey() +
"'");
334 if (!ForwardRefComdats.empty())
335 return error(ForwardRefComdats.begin()->second,
336 "use of undefined comdat '$" +
337 ForwardRefComdats.begin()->first +
"'");
354 auto *CB = dyn_cast<CallBase>(
U.getUser());
355 if (!CB || !CB->isCallee(&U))
356 return error(
Info.second,
"intrinsic can only be used as callee");
361 return error(
Info.second,
"invalid intrinsic signature");
366 Info.first->eraseFromParent();
367 ForwardRefVals.erase(
Name);
378 for (
Use &U :
V->uses()) {
379 auto *CB = dyn_cast<CallBase>(
U.getUser());
380 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
382 FTy = CB->getFunctionType();
390 Type *Ty = GetCommonFunctionType(
Info.first);
395 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
401 Info.first->replaceAllUsesWith(GV);
402 Info.first->eraseFromParent();
403 ForwardRefVals.erase(
Name);
406 if (!ForwardRefVals.empty())
407 return error(ForwardRefVals.begin()->second.second,
408 "use of undefined value '@" + ForwardRefVals.begin()->first +
411 if (!ForwardRefValIDs.empty())
412 return error(ForwardRefValIDs.begin()->second.second,
413 "use of undefined value '@" +
414 Twine(ForwardRefValIDs.begin()->first) +
"'");
417 dropUnknownMetadataReferences();
419 if (!ForwardRefMDNodes.empty())
420 return error(ForwardRefMDNodes.begin()->second.second,
421 "use of undefined metadata '!" +
422 Twine(ForwardRefMDNodes.begin()->first) +
"'");
425 for (
auto &
N : NumberedMetadata) {
426 if (
N.second && !
N.second->isResolved())
427 N.second->resolveCycles();
430 for (
auto *Inst : InstsWithTBAATag) {
431 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
434 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
437 if (MD != UpgradedMD)
438 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
447 if (UpgradeDebugInfo)
463 for (
const auto &
I : NamedTypes)
464 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
465 for (
const auto &
I : NumberedTypes)
466 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
472bool LLParser::validateEndOfIndex() {
476 if (!ForwardRefValueInfos.empty())
477 return error(ForwardRefValueInfos.begin()->second.front().second,
478 "use of undefined summary '^" +
479 Twine(ForwardRefValueInfos.begin()->first) +
"'");
481 if (!ForwardRefAliasees.empty())
482 return error(ForwardRefAliasees.begin()->second.front().second,
483 "use of undefined summary '^" +
484 Twine(ForwardRefAliasees.begin()->first) +
"'");
486 if (!ForwardRefTypeIds.empty())
487 return error(ForwardRefTypeIds.begin()->second.front().second,
488 "use of undefined type id summary '^" +
489 Twine(ForwardRefTypeIds.begin()->first) +
"'");
503 std::string TentativeDLStr =
M->getDataLayoutStr();
510 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
514 if (parseSourceFileName())
523 if (
auto LayoutOverride =
524 DataLayoutCallback(
M->getTargetTriple(), TentativeDLStr)) {
525 TentativeDLStr = *LayoutOverride;
531 M->setDataLayout(MaybeDL.
get());
535bool LLParser::parseTopLevelEntities() {
543 if (parseSummaryEntry())
547 if (parseSourceFileName())
559 return tokError(
"expected top-level entity");
570 if (parseModuleAsm())
574 if (parseUnnamedType())
578 if (parseNamedType())
582 if (parseUnnamedGlobal())
586 if (parseNamedGlobal())
591 if (parseStandaloneMetadata())
595 if (parseSummaryEntry())
599 if (parseNamedMetadata())
603 if (parseUnnamedAttrGrp())
607 if (parseUseListOrder())
611 if (parseUseListOrderBB())
620bool LLParser::parseModuleAsm() {
626 parseStringConstant(AsmStr))
629 M->appendModuleInlineAsm(AsmStr);
636bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
642 return tokError(
"unknown target property");
645 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
646 parseStringConstant(Str))
648 M->setTargetTriple(Str);
652 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
655 if (parseStringConstant(TentativeDLStr))
663bool LLParser::parseSourceFileName() {
666 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
667 parseStringConstant(SourceFileName))
670 M->setSourceFileName(SourceFileName);
676bool LLParser::parseUnnamedType() {
681 if (parseToken(
lltok::equal,
"expected '=' after name") ||
686 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
689 if (!isa<StructType>(Result)) {
690 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
692 return error(TypeLoc,
"non-struct types may not be recursive");
702bool LLParser::parseNamedType() {
707 if (parseToken(
lltok::equal,
"expected '=' after name") ||
712 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
715 if (!isa<StructType>(Result)) {
716 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
718 return error(NameLoc,
"non-struct types may not be recursive");
728bool LLParser::parseDeclare() {
732 std::vector<std::pair<unsigned, MDNode *>> MDs;
736 if (parseMetadataAttachment(MDK,
N))
738 MDs.push_back({MDK,
N});
742 unsigned FunctionNumber = -1;
744 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
747 F->addMetadata(MD.first, *MD.second);
753bool LLParser::parseDefine() {
758 unsigned FunctionNumber = -1;
760 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
761 parseOptionalFunctionMetadata(*
F) ||
762 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
768bool LLParser::parseGlobalType(
bool &IsConstant) {
775 return tokError(
"expected 'global' or 'constant'");
781bool LLParser::parseOptionalUnnamedAddr(
802bool LLParser::parseUnnamedGlobal() {
810 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
814 if (parseToken(
lltok::equal,
"expected '=' after name"))
817 VarID = NumberedVals.getNext();
821 unsigned Linkage, Visibility, DLLStorageClass;
825 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
827 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
832 return parseGlobal(
Name,
VarID, NameLoc, Linkage, HasLinkage, Visibility,
833 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
836 return parseAliasOrIFunc(
Name,
VarID, NameLoc, Linkage, Visibility,
837 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
846bool LLParser::parseNamedGlobal() {
853 unsigned Linkage, Visibility, DLLStorageClass;
857 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
858 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
860 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
865 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
866 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
869 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
870 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
874bool LLParser::parseComdat() {
884 return tokError(
"expected comdat type");
889 return tokError(
"unknown selection kind");
911 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
912 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
915 if (
I != ComdatSymTab.
end())
918 C =
M->getOrInsertComdat(
Name);
919 C->setSelectionKind(SK);
926bool LLParser::parseMDString(
MDString *&Result) {
928 if (parseStringConstant(Str))
936bool LLParser::parseMDNodeID(
MDNode *&Result) {
940 if (parseUInt32(MID))
944 if (NumberedMetadata.count(MID)) {
945 Result = NumberedMetadata[MID];
950 auto &FwdRef = ForwardRefMDNodes[MID];
953 Result = FwdRef.first.get();
954 NumberedMetadata[MID].reset(Result);
960bool LLParser::parseNamedMetadata() {
979 if (parseDIExpression(
N,
false))
985 return tokError(
"found DIArgList outside of function");
993 return parseToken(
lltok::rbrace,
"expected end of metadata node");
998bool LLParser::parseStandaloneMetadata() {
1001 unsigned MetadataID = 0;
1004 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1009 return tokError(
"unexpected type in metadata definition");
1013 if (parseSpecializedMDNode(
Init, IsDistinct))
1016 parseMDTuple(
Init, IsDistinct))
1020 auto FI = ForwardRefMDNodes.find(MetadataID);
1021 if (FI != ForwardRefMDNodes.end()) {
1022 auto *ToReplace = FI->second.first.get();
1025 if (isa<DIAssignID>(
Init)) {
1026 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1027 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1028 "Inst unexpectedly already has DIAssignID attachment");
1029 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
1033 ToReplace->replaceAllUsesWith(
Init);
1034 ForwardRefMDNodes.erase(FI);
1036 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
1038 if (NumberedMetadata.count(MetadataID))
1039 return tokError(
"Metadata id is already used");
1040 NumberedMetadata[MetadataID].reset(
Init);
1047bool LLParser::skipModuleSummaryEntry() {
1057 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1058 "start of summary entry");
1060 return parseSummaryIndexFlags();
1062 return parseBlockCount();
1064 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1065 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1069 unsigned NumOpenParen = 1;
1079 return tokError(
"found end of file while parsing summary entry");
1085 }
while (NumOpenParen > 0);
1091bool LLParser::parseSummaryEntry() {
1105 return skipModuleSummaryEntry();
1107 bool result =
false;
1110 result = parseGVEntry(SummaryID);
1113 result = parseModuleEntry(SummaryID);
1116 result = parseTypeIdEntry(SummaryID);
1119 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1122 result = parseSummaryIndexFlags();
1125 result = parseBlockCount();
1128 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1165bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1166 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1167 unsigned DLLStorageClass,
bool DSOLocal,
1182 return error(NameLoc,
"invalid linkage type for alias");
1185 return error(NameLoc,
1186 "symbol with local linkage must have default visibility");
1189 return error(NameLoc,
1190 "symbol with local linkage cannot have a DLL storage class");
1194 if (parseType(Ty) ||
1195 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1204 if (parseGlobalTypeAndValue(Aliasee))
1209 if (parseValID(
ID,
nullptr))
1212 return error(AliaseeLoc,
"invalid aliasee");
1213 Aliasee =
ID.ConstantVal;
1217 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1219 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1220 unsigned AddrSpace = PTy->getAddressSpace();
1226 if (!
Name.empty()) {
1227 auto I = ForwardRefVals.find(
Name);
1228 if (
I != ForwardRefVals.end()) {
1229 GVal =
I->second.first;
1230 ForwardRefVals.erase(
Name);
1231 }
else if (
M->getNamedValue(
Name)) {
1232 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1235 auto I = ForwardRefValIDs.find(NameID);
1236 if (
I != ForwardRefValIDs.end()) {
1237 GVal =
I->second.first;
1238 ForwardRefValIDs.erase(
I);
1243 std::unique_ptr<GlobalAlias> GA;
1244 std::unique_ptr<GlobalIFunc> GI;
1274 return tokError(
"unknown alias or ifunc property!");
1279 NumberedVals.add(NameID, GV);
1286 "forward reference and definition of alias have different types");
1296 M->insertAlias(GA.release());
1298 M->insertIFunc(GI.release());
1308 case lltok::kw_sanitize_memtag:
1324 Meta.NoAddress =
true;
1327 Meta.NoHWAddress =
true;
1329 case lltok::kw_sanitize_memtag:
1333 Meta.IsDynInit =
true;
1336 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1356bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1357 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1358 unsigned Visibility,
unsigned DLLStorageClass,
1362 return error(NameLoc,
1363 "symbol with local linkage must have default visibility");
1366 return error(NameLoc,
1367 "symbol with local linkage cannot have a DLL storage class");
1371 LocTy IsExternallyInitializedLoc;
1375 if (parseOptionalAddrSpace(AddrSpace) ||
1377 IsExternallyInitialized,
1378 &IsExternallyInitializedLoc) ||
1379 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1388 if (parseGlobalValue(Ty,
Init))
1393 return error(TyLoc,
"invalid type for global variable");
1398 if (!
Name.empty()) {
1399 auto I = ForwardRefVals.find(
Name);
1400 if (
I != ForwardRefVals.end()) {
1401 GVal =
I->second.first;
1402 ForwardRefVals.erase(
I);
1403 }
else if (
M->getNamedValue(
Name)) {
1404 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1409 if (NameID == (
unsigned)-1)
1410 NameID = NumberedVals.getNext();
1412 auto I = ForwardRefValIDs.find(NameID);
1413 if (
I != ForwardRefValIDs.end()) {
1414 GVal =
I->second.first;
1415 ForwardRefValIDs.erase(
I);
1424 NumberedVals.add(NameID, GV);
1442 "forward reference and definition of global have different types");
1462 }
else if (Lex.
getKind() == lltok::kw_align) {
1464 if (parseOptionalAlignment(Alignment))
1470 if (parseOptionalCodeModel(CodeModel))
1474 if (parseGlobalObjectMetadataAttachment(*GV))
1477 if (parseSanitizer(GV))
1481 if (parseOptionalComdat(
Name,
C))
1486 return tokError(
"unknown global variable property!");
1492 std::vector<unsigned> FwdRefAttrGrps;
1493 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1495 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1497 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1505bool LLParser::parseUnnamedAttrGrp() {
1511 return tokError(
"expected attribute group id");
1514 std::vector<unsigned> unused;
1522 auto R = NumberedAttrBuilders.find(
VarID);
1523 if (R == NumberedAttrBuilders.end())
1526 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1527 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1530 if (!
R->second.hasAttributes())
1531 return error(AttrGrpLoc,
"attribute group has no attributes");
1538#define GET_ATTR_NAMES
1539#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1540 case lltok::kw_##DISPLAY_NAME: \
1541 return Attribute::ENUM_NAME;
1542#include "llvm/IR/Attributes.inc"
1551 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1554 case Attribute::Alignment: {
1563 if (parseOptionalAlignment(Alignment,
true))
1566 B.addAlignmentAttr(Alignment);
1569 case Attribute::StackAlignment: {
1574 parseUInt32(Alignment))
1577 if (parseOptionalStackAlignment(Alignment))
1580 B.addStackAlignmentAttr(Alignment);
1583 case Attribute::AllocSize: {
1584 unsigned ElemSizeArg;
1585 std::optional<unsigned> NumElemsArg;
1586 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1588 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1591 case Attribute::VScaleRange: {
1592 unsigned MinValue, MaxValue;
1593 if (parseVScaleRangeArguments(MinValue, MaxValue))
1595 B.addVScaleRangeAttr(MinValue,
1596 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1599 case Attribute::Dereferenceable: {
1601 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1603 B.addDereferenceableAttr(Bytes);
1606 case Attribute::DereferenceableOrNull: {
1608 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1610 B.addDereferenceableOrNullAttr(Bytes);
1613 case Attribute::UWTable: {
1615 if (parseOptionalUWTableKind(Kind))
1617 B.addUWTableAttr(Kind);
1620 case Attribute::AllocKind: {
1622 if (parseAllocKind(Kind))
1624 B.addAllocKindAttr(Kind);
1627 case Attribute::Memory: {
1628 std::optional<MemoryEffects> ME = parseMemoryAttr();
1631 B.addMemoryAttr(*ME);
1634 case Attribute::NoFPClass: {
1637 B.addNoFPClassAttr(NoFPClass);
1643 case Attribute::Range:
1644 return parseRangeAttr(
B);
1645 case Attribute::Initializes:
1646 return parseInitializesAttr(
B);
1648 B.addAttribute(Attr);
1656 case lltok::kw_readnone:
1659 case lltok::kw_readonly:
1662 case lltok::kw_writeonly:
1681bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1682 std::vector<unsigned> &FwdRefAttrGrps,
1683 bool InAttrGrp, LocTy &BuiltinLoc) {
1684 bool HaveError =
false;
1695 if (parseStringAttribute(
B))
1707 "cannot have an attribute group reference in an attribute group");
1717 if (Token == lltok::kw_builtin)
1729 return error(Lex.
getLoc(),
"unterminated attribute group");
1732 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1739 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1743 B.addMemoryAttr(ME);
1757 PTy->getAddressSpace());
1766 error(Loc,
"'" +
Name +
"' is not a basic block");
1768 error(Loc,
"'" +
Name +
"' defined with type '" +
1781 error(Loc,
"global variable reference must have pointer type");
1787 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1792 auto I = ForwardRefVals.find(
Name);
1793 if (
I != ForwardRefVals.end())
1794 Val =
I->second.first;
1799 return cast_or_null<GlobalValue>(
1800 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1804 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1811 error(Loc,
"global variable reference must have pointer type");
1820 auto I = ForwardRefValIDs.find(
ID);
1821 if (
I != ForwardRefValIDs.end())
1822 Val =
I->second.first;
1827 return cast_or_null<GlobalValue>(
1828 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1832 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1840Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1844 if (
I != ComdatSymTab.
end())
1849 ForwardRefComdats[
Name] = Loc;
1859bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1861 return tokError(ErrMsg);
1868bool LLParser::parseStringConstant(std::string &Result) {
1870 return tokError(
"expected string constant");
1878bool LLParser::parseUInt32(
uint32_t &Val) {
1880 return tokError(
"expected integer");
1882 if (Val64 !=
unsigned(Val64))
1883 return tokError(
"expected 32-bit integer (too large)");
1891bool LLParser::parseUInt64(
uint64_t &Val) {
1893 return tokError(
"expected integer");
1906 return tokError(
"expected localdynamic, initialexec or localexec");
1934 return parseTLSModel(TLM) ||
1935 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1943bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1944 AddrSpace = DefaultAS;
1948 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1951 if (AddrSpaceStr ==
"A") {
1952 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1953 }
else if (AddrSpaceStr ==
"G") {
1954 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1955 }
else if (AddrSpaceStr ==
"P") {
1956 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1958 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1964 return tokError(
"expected integer or string constant");
1966 if (parseUInt32(AddrSpace))
1968 if (!isUInt<24>(AddrSpace))
1969 return error(Loc,
"invalid address space, must be a 24-bit integer");
1973 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1974 ParseAddrspaceValue(AddrSpace) ||
1985 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1987 B.addAttribute(Attr, Val);
1992bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1993 bool HaveError =
false;
2000 if (parseStringAttribute(
B))
2010 if (parseEnumAttribute(Attr,
B,
false))
2014 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2016 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2064bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2065 unsigned &Visibility,
2066 unsigned &DLLStorageClass,
bool &DSOLocal) {
2070 parseOptionalDSOLocal(DSOLocal);
2071 parseOptionalVisibility(Visibility);
2072 parseOptionalDLLStorageClass(DLLStorageClass);
2075 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2081void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2103void LLParser::parseOptionalVisibility(
unsigned &Res) {
2121bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2125 return tokError(
"unknown import kind. Expect definition or declaration.");
2140void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2210bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2286 return parseUInt32(
CC);
2296bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2303 return parseMDNode(MD);
2308bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2311 return tokError(
"expected metadata after comma");
2315 if (parseMetadataAttachment(MDK,
N))
2318 if (MDK == LLVMContext::MD_DIAssignID)
2319 TempDIAssignIDAttachments[
N].push_back(&Inst);
2323 if (MDK == LLVMContext::MD_tbaa)
2324 InstsWithTBAATag.push_back(&Inst);
2333bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2336 if (parseMetadataAttachment(MDK,
N))
2345bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2347 if (parseGlobalObjectMetadataAttachment(
F))
2355bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2356 Alignment = std::nullopt;
2357 if (!EatIfPresent(lltok::kw_align))
2363 bool HaveParens =
false;
2369 if (parseUInt64(
Value))
2373 return error(ParenLoc,
"expected ')'");
2376 return error(AlignLoc,
"alignment is not a power of two");
2378 return error(AlignLoc,
"huge alignments are not supported yet");
2389 auto ErrMsg =
"expected global code model string";
2390 if (StrVal ==
"tiny")
2392 else if (StrVal ==
"small")
2394 else if (StrVal ==
"kernel")
2396 else if (StrVal ==
"medium")
2398 else if (StrVal ==
"large")
2401 return tokError(ErrMsg);
2412bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2414 assert((AttrKind == lltok::kw_dereferenceable ||
2415 AttrKind == lltok::kw_dereferenceable_or_null) &&
2419 if (!EatIfPresent(AttrKind))
2423 return error(ParenLoc,
"expected '('");
2425 if (parseUInt64(Bytes))
2429 return error(ParenLoc,
"expected ')'");
2431 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2435bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2446 return error(KindLoc,
"expected unwind table kind");
2455 return error(ParenLoc,
"expected '('");
2458 if (parseStringConstant(Arg))
2459 return error(KindLoc,
"expected allockind value");
2463 }
else if (
A ==
"realloc") {
2465 }
else if (
A ==
"free") {
2467 }
else if (
A ==
"uninitialized") {
2469 }
else if (
A ==
"zeroed") {
2471 }
else if (
A ==
"aligned") {
2474 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2479 return error(ParenLoc,
"expected ')'");
2481 return error(KindLoc,
"expected allockind value");
2492 return std::nullopt;
2507 return std::nullopt;
2511std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2521 tokError(
"expected '('");
2522 return std::nullopt;
2525 bool SeenLoc =
false;
2531 tokError(
"expected ':' after location");
2532 return std::nullopt;
2539 tokError(
"expected memory location (argmem, inaccessiblemem) "
2540 "or access kind (none, read, write, readwrite)");
2542 tokError(
"expected access kind (none, read, write, readwrite)");
2543 return std::nullopt;
2552 tokError(
"default access kind must be specified first");
2553 return std::nullopt;
2562 tokError(
"unterminated memory attribute");
2563 return std::nullopt;
2605unsigned LLParser::parseNoFPClassAttr() {
2610 tokError(
"expected '('");
2617 if (TestMask != 0) {
2621 !parseUInt64(
Value)) {
2623 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2634 error(Lex.
getLoc(),
"expected nofpclass test mask");
2652bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2653 bool &AteExtraComma) {
2654 AteExtraComma =
false;
2658 AteExtraComma =
true;
2662 if (Lex.
getKind() != lltok::kw_align)
2663 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2665 if (parseOptionalAlignment(Alignment))
2678bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2679 bool &AteExtraComma) {
2680 AteExtraComma =
false;
2684 AteExtraComma =
true;
2690 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2692 if (parseOptionalAddrSpace(AddrSpace))
2699bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2700 std::optional<unsigned> &HowManyArg) {
2703 auto StartParen = Lex.
getLoc();
2705 return error(StartParen,
"expected '('");
2707 if (parseUInt32(BaseSizeArg))
2711 auto HowManyAt = Lex.
getLoc();
2713 if (parseUInt32(HowMany))
2715 if (HowMany == BaseSizeArg)
2716 return error(HowManyAt,
2717 "'allocsize' indices can't refer to the same parameter");
2718 HowManyArg = HowMany;
2720 HowManyArg = std::nullopt;
2722 auto EndParen = Lex.
getLoc();
2724 return error(EndParen,
"expected ')'");
2728bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2729 unsigned &MaxValue) {
2732 auto StartParen = Lex.
getLoc();
2734 return error(StartParen,
"expected '('");
2736 if (parseUInt32(MinValue))
2740 if (parseUInt32(MaxValue))
2743 MaxValue = MinValue;
2745 auto EndParen = Lex.
getLoc();
2747 return error(EndParen,
"expected ')'");
2756bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2761 return parseScope(SSID) || parseOrdering(Ordering);
2771 auto StartParenAt = Lex.
getLoc();
2773 return error(StartParenAt,
"Expected '(' in syncscope");
2776 auto SSNAt = Lex.
getLoc();
2777 if (parseStringConstant(SSN))
2778 return error(SSNAt,
"Expected synchronization scope name");
2780 auto EndParenAt = Lex.
getLoc();
2782 return error(EndParenAt,
"Expected ')' in syncscope");
2797 return tokError(
"Expected ordering on atomic instruction");
2816bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2818 if (!EatIfPresent(lltok::kw_alignstack))
2822 return error(ParenLoc,
"expected '('");
2824 if (parseUInt32(Alignment))
2828 return error(ParenLoc,
"expected ')'");
2830 return error(AlignLoc,
"stack alignment is not a power of two");
2844 bool &AteExtraComma) {
2845 AteExtraComma =
false;
2848 return tokError(
"expected ',' as start of index list");
2852 if (Indices.
empty())
2853 return tokError(
"expected index");
2854 AteExtraComma =
true;
2858 if (parseUInt32(
Idx))
2871bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2875 return tokError(Msg);
2884 if (
Result->isPointerTy()) {
2886 if (parseOptionalAddrSpace(AddrSpace))
2892 return tokError(
"ptr* is invalid - use ptr instead");
2903 if (parseTargetExtType(Result))
2909 if (parseAnonStructType(Result,
false))
2915 if (parseArrayVectorType(Result,
false))
2922 if (parseAnonStructType(Result,
true) ||
2923 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2925 }
else if (parseArrayVectorType(Result,
true))
2964 if (!AllowVoid &&
Result->isVoidTy())
2965 return error(TypeLoc,
"void type only allowed for function results");
2971 return tokError(
"basic block pointers are invalid");
2973 return tokError(
"pointers to void are invalid - use i8* instead");
2975 return tokError(
"pointer to this type is invalid");
2983 return tokError(
"basic block pointers are invalid");
2985 return tokError(
"pointers to void are invalid; use i8* instead");
2987 return tokError(
"pointer to this type is invalid");
2989 if (parseOptionalAddrSpace(AddrSpace) ||
2990 parseToken(
lltok::star,
"expected '*' in address space"))
2999 if (parseFunctionType(Result))
3012 PerFunctionState &PFS,
bool IsMustTailCall,
3013 bool InVarArgsFunc) {
3019 if (!ArgList.
empty() &&
3020 parseToken(
lltok::comma,
"expected ',' in argument list"))
3025 const char *Msg =
"unexpected ellipsis in argument list for ";
3026 if (!IsMustTailCall)
3027 return tokError(
Twine(Msg) +
"non-musttail call");
3029 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3031 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3036 Type *ArgTy =
nullptr;
3038 if (parseType(ArgTy, ArgLoc))
3044 if (parseMetadataAsValue(V, PFS))
3048 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3055 if (IsMustTailCall && InVarArgsFunc)
3056 return tokError(
"expected '...' at end of argument list for musttail call "
3057 "in varargs function");
3068 if (!EatIfPresent(AttrToken))
3077 B.addTypeAttr(AttrKind, Ty);
3093 return tokError(
"expected integer");
3096 "integer is too large for the bit width of specified type");
3102 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3105 return error(TyLoc,
"the range must have integer type!");
3113 return tokError(
"the range represent the empty set but limits aren't 0!");
3127 auto ParseAPSInt = [&](
APInt &Val) {
3129 return tokError(
"expected integer");
3150 return tokError(
"the range should not represent the full or empty set!");
3162 if (!CRLOrNull.has_value())
3163 return tokError(
"Invalid (unordered or overlapping) range list");
3164 B.addInitializesAttr(*CRLOrNull);
3177bool LLParser::parseOptionalOperandBundles(
3185 if (!BundleList.
empty() &&
3186 parseToken(
lltok::comma,
"expected ',' in input list"))
3190 if (parseStringConstant(
Tag))
3193 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3196 std::vector<Value *> Inputs;
3199 if (!Inputs.empty() &&
3200 parseToken(
lltok::comma,
"expected ',' in input list"))
3204 Value *Input =
nullptr;
3208 if (parseMetadataAsValue(Input, PFS))
3210 }
else if (parseValue(Ty, Input, PFS)) {
3213 Inputs.push_back(Input);
3221 if (BundleList.
empty())
3222 return error(BeginLoc,
"operand bundle set must not be empty");
3229 unsigned NextID,
unsigned ID) {
3231 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3232 Twine(NextID) +
"' or greater");
3249 unsigned CurValID = 0;
3264 Type *ArgTy =
nullptr;
3266 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3270 return error(TypeLoc,
"argument can not have void type");
3280 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3287 CurValID = ArgID + 1;
3291 return error(TypeLoc,
"invalid type for function argument");
3299 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3304bool LLParser::parseFunctionType(
Type *&Result) {
3308 return tokError(
"invalid function return type");
3313 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3317 for (
const ArgInfo &Arg : ArgList) {
3318 if (!Arg.Name.empty())
3319 return error(Arg.Loc,
"argument name invalid in function type");
3320 if (Arg.Attrs.hasAttributes())
3321 return error(Arg.Loc,
"argument attributes invalid in function type");
3325 for (
const ArgInfo &Arg : ArgList)
3334bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3336 if (parseStructBody(Elts))
3345 std::pair<Type *, LocTy> &Entry,
3349 return error(TypeLoc,
"redefinition of type");
3360 ResultTy =
Entry.first;
3372 return error(TypeLoc,
"forward references to non-struct type");
3376 return parseArrayVectorType(ResultTy,
true);
3377 return parseType(ResultTy);
3390 if (parseStructBody(Body) ||
3391 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3395 return tokError(
toString(std::move(E)));
3422 return error(EltTyLoc,
"invalid element type for struct");
3430 return error(EltTyLoc,
"invalid element type for struct");
3435 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3444bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3445 bool Scalable =
false;
3449 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3457 return tokError(
"expected number in address space");
3463 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3467 Type *EltTy =
nullptr;
3468 if (parseType(EltTy))
3472 "expected end of sequential type"))
3477 return error(SizeLoc,
"zero element vector is illegal");
3479 return error(SizeLoc,
"size too large for vector");
3481 return error(TypeLoc,
"invalid vector element type");
3485 return error(TypeLoc,
"invalid array element type");
3502bool LLParser::parseTargetExtType(
Type *&Result) {
3507 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3508 parseStringConstant(TypeName))
3516 bool SeenInt =
false;
3523 if (parseUInt32(IntVal))
3526 }
else if (SeenInt) {
3529 return tokError(
"expected uint32 param");
3532 if (parseType(TypeParam,
true))
3538 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3543 if (
auto E = TTy.takeError())
3544 return tokError(
toString(std::move(E)));
3557 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3560 auto It = UnnamedArgNums.
begin();
3563 unsigned ArgNum = *It++;
3564 NumberedVals.add(ArgNum, &
A);
3569LLParser::PerFunctionState::~PerFunctionState() {
3572 for (
const auto &
P : ForwardRefVals) {
3573 if (isa<BasicBlock>(
P.second.first))
3575 P.second.first->replaceAllUsesWith(
3577 P.second.first->deleteValue();
3580 for (
const auto &
P : ForwardRefValIDs) {
3581 if (isa<BasicBlock>(
P.second.first))
3583 P.second.first->replaceAllUsesWith(
3585 P.second.first->deleteValue();
3589bool LLParser::PerFunctionState::finishFunction() {
3590 if (!ForwardRefVals.empty())
3591 return P.error(ForwardRefVals.begin()->second.second,
3592 "use of undefined value '%" + ForwardRefVals.begin()->first +
3594 if (!ForwardRefValIDs.empty())
3595 return P.error(ForwardRefValIDs.begin()->second.second,
3596 "use of undefined value '%" +
3597 Twine(ForwardRefValIDs.begin()->first) +
"'");
3604Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3607 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3612 auto I = ForwardRefVals.find(
Name);
3613 if (
I != ForwardRefVals.end())
3614 Val =
I->second.first;
3619 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3623 P.error(Loc,
"invalid use of a non-first-class type");
3635 P.error(Loc,
"name is too long which can result in name collisions, "
3636 "consider making the name shorter or "
3637 "increasing -non-global-value-max-name-size");
3641 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3645Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3647 Value *Val = NumberedVals.get(
ID);
3652 auto I = ForwardRefValIDs.find(
ID);
3653 if (
I != ForwardRefValIDs.end())
3654 Val =
I->second.first;
3659 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3662 P.error(Loc,
"invalid use of a non-first-class type");
3674 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3680bool LLParser::PerFunctionState::setInstName(
int NameID,
3681 const std::string &NameStr,
3685 if (NameID != -1 || !NameStr.empty())
3686 return P.error(NameLoc,
"instructions returning void cannot have a name");
3692 if (NameStr.empty()) {
3695 NameID = NumberedVals.getNext();
3697 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3701 auto FI = ForwardRefValIDs.find(NameID);
3702 if (FI != ForwardRefValIDs.end()) {
3705 return P.error(NameLoc,
"instruction forward referenced with type '" +
3709 Sentinel->replaceAllUsesWith(Inst);
3711 ForwardRefValIDs.erase(FI);
3714 NumberedVals.add(NameID, Inst);
3719 auto FI = ForwardRefVals.find(NameStr);
3720 if (FI != ForwardRefVals.end()) {
3723 return P.error(NameLoc,
"instruction forward referenced with type '" +
3727 Sentinel->replaceAllUsesWith(Inst);
3729 ForwardRefVals.erase(FI);
3735 if (Inst->
getName() != NameStr)
3736 return P.error(NameLoc,
"multiple definition of local value named '" +
3743BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3745 return dyn_cast_or_null<BasicBlock>(
3749BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3750 return dyn_cast_or_null<BasicBlock>(
3757BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3758 int NameID, LocTy Loc) {
3762 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3765 NameID = NumberedVals.getNext();
3767 BB = getBB(NameID, Loc);
3769 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3773 BB = getBB(
Name, Loc);
3775 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3786 ForwardRefValIDs.erase(NameID);
3787 NumberedVals.add(NameID, BB);
3790 ForwardRefVals.erase(
Name);
3807bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3811 return tokError(
"expected value token");
3854 if (parseGlobalValueVector(Elts) ||
3855 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3858 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3859 ID.UIntVal = Elts.
size();
3860 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3861 Elts.
size() *
sizeof(Elts[0]));
3873 if (parseGlobalValueVector(Elts) ||
3875 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3879 if (isPackedStruct) {
3880 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3881 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3882 Elts.
size() *
sizeof(Elts[0]));
3883 ID.UIntVal = Elts.
size();
3889 return error(
ID.Loc,
"constant vector must not be empty");
3891 if (!Elts[0]->
getType()->isIntegerTy() &&
3892 !Elts[0]->
getType()->isFloatingPointTy() &&
3896 "vector elements must have integer, pointer or floating point type");
3899 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3901 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3902 " is not of type '" +
3913 if (parseGlobalValueVector(Elts) ||
3925 if (!Elts[0]->
getType()->isFirstClassType())
3926 return error(FirstEltLoc,
"invalid array element type: " +
3932 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3934 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3935 " is not of type '" +
3955 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3958 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3961 parseStringConstant(
ID.StrVal) ||
3962 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3967 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3978 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3979 parseValID(Fn, PFS) ||
3981 "expected comma in block address expression") ||
3982 parseValID(Label, PFS) ||
3983 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3987 return error(Fn.
Loc,
"expected function name in blockaddress");
3989 return error(
Label.Loc,
"expected basic block name in blockaddress");
3994 GV = NumberedVals.get(Fn.
UIntVal);
3995 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3996 GV =
M->getNamedValue(Fn.
StrVal);
4001 if (!isa<Function>(GV))
4002 return error(Fn.
Loc,
"expected function name in blockaddress");
4003 F = cast<Function>(GV);
4004 if (
F->isDeclaration())
4005 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4011 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4019 "type of blockaddress must be a pointer and not '" +
4024 FwdDeclAS = PFS->getFunction().getAddressSpace();
4033 ID.ConstantVal = FwdRef;
4041 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4043 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4045 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4047 return error(
Label.Loc,
"referenced value is not a basic block");
4050 return error(
Label.Loc,
"cannot take address of numeric label after "
4051 "the function is defined");
4052 BB = dyn_cast_or_null<BasicBlock>(
4053 F->getValueSymbolTable()->lookup(
Label.StrVal));
4055 return error(
Label.Loc,
"referenced value is not a basic block");
4069 if (parseValID(Fn, PFS))
4074 "expected global value name in dso_local_equivalent");
4079 GV = NumberedVals.get(Fn.
UIntVal);
4080 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4081 GV =
M->getNamedValue(Fn.
StrVal);
4087 ? ForwardRefDSOLocalEquivalentIDs
4088 : ForwardRefDSOLocalEquivalentNames;
4096 ID.ConstantVal = FwdRef;
4102 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4103 "in dso_local_equivalent");
4114 if (parseValID(
ID, PFS))
4118 return error(
ID.Loc,
"expected global value name in no_cfi");
4129 Constant *Disc =
nullptr, *AddrDisc =
nullptr;
4132 "expected '(' in constant ptrauth expression") ||
4133 parseGlobalTypeAndValue(
Ptr) ||
4135 "expected comma in constant ptrauth expression") ||
4136 parseGlobalTypeAndValue(Key))
4140 if (parseGlobalTypeAndValue(Disc) ||
4141 (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4144 "expected ')' in constant ptrauth expression"))
4147 if (!
Ptr->getType()->isPointerTy())
4148 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4150 auto *KeyC = dyn_cast<ConstantInt>(Key);
4151 if (!KeyC || KeyC->getBitWidth() != 32)
4152 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4156 DiscC = dyn_cast<ConstantInt>(Disc);
4160 "constant ptrauth integer discriminator must be i64 constant");
4166 if (!AddrDisc->getType()->isPointerTy())
4168 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4184 Type *DestTy =
nullptr;
4187 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4188 parseGlobalTypeAndValue(SrcVal) ||
4189 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4190 parseType(DestTy) ||
4191 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4194 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4203 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4205 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4207 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4209 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4211 return error(
ID.Loc,
"urem constexprs are no longer supported");
4213 return error(
ID.Loc,
"srem constexprs are no longer supported");
4215 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4217 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4219 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4221 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4223 return error(
ID.Loc,
"frem constexprs are no longer supported");
4225 return error(
ID.Loc,
"and constexprs are no longer supported");
4227 return error(
ID.Loc,
"or constexprs are no longer supported");
4229 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4231 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4233 return error(
ID.Loc,
"shl constexprs are no longer supported");
4235 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4237 return error(
ID.Loc,
"select constexprs are no longer supported");
4239 return error(
ID.Loc,
"zext constexprs are no longer supported");
4241 return error(
ID.Loc,
"sext constexprs are no longer supported");
4243 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4245 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4247 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4249 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4251 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4253 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4255 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4257 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4269 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4270 Opc == Instruction::Mul) {
4279 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4280 parseGlobalTypeAndValue(Val0) ||
4281 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4282 parseGlobalTypeAndValue(Val1) ||
4283 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4286 return error(
ID.Loc,
"operands of constexpr must have same type");
4290 "constexpr requires integer or integer vector operands");
4301 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4304 if (parseGlobalTypeAndValue(
C))
4306 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4321 bool HasInRange =
false;
4327 if (Opc == Instruction::GetElementPtr) {
4343 return tokError(
"expected integer");
4349 return tokError(
"expected integer");
4358 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4361 if (Opc == Instruction::GetElementPtr) {
4362 if (parseType(Ty) ||
4363 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4367 if (parseGlobalValueVector(Elts) ||
4371 if (Opc == Instruction::GetElementPtr) {
4372 if (Elts.
size() == 0 ||
4373 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4374 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4377 std::optional<ConstantRange>
InRange;
4379 unsigned IndexWidth =
4380 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4381 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4382 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4383 if (InRangeStart.
sge(InRangeEnd))
4384 return error(
ID.Loc,
"expected end to be larger than start");
4390 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4397 return error(
ID.Loc,
"getelementptr index must be an integer");
4398 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4399 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4400 if (GEPWidth && (ValNumEl != GEPWidth))
4403 "getelementptr vector index has a wrong number of elements");
4406 GEPWidth = ValNumEl;
4411 if (!Indices.empty() && !Ty->
isSized(&Visited))
4412 return error(
ID.Loc,
"base element of getelementptr must be sized");
4415 return error(
ID.Loc,
"invalid getelementptr indices");
4419 }
else if (Opc == Instruction::ShuffleVector) {
4420 if (Elts.
size() != 3)
4421 return error(
ID.Loc,
"expected three operands to shufflevector");
4423 return error(
ID.Loc,
"invalid operands to shufflevector");
4427 }
else if (Opc == Instruction::ExtractElement) {
4428 if (Elts.
size() != 2)
4429 return error(
ID.Loc,
"expected two operands to extractelement");
4431 return error(
ID.Loc,
"invalid extractelement operands");
4434 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4435 if (Elts.
size() != 3)
4436 return error(
ID.Loc,
"expected three operands to insertelement");
4438 return error(
ID.Loc,
"invalid insertelement operands");
4457 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4458 convertValIDToValue(Ty,
ID, V,
nullptr);
4459 if (V && !(
C = dyn_cast<Constant>(V)))
4460 return error(
ID.Loc,
"global values must be constants");
4464bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4466 return parseType(Ty) || parseGlobalValue(Ty, V);
4478 return tokError(
"expected comdat variable");
4481 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4484 if (GlobalName.
empty())
4485 return tokError(
"comdat cannot be unnamed");
4486 C = getComdat(std::string(GlobalName), KwLoc);
4509 if (parseGlobalTypeAndValue(
C))
4517bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4519 if (parseMDNodeVector(Elts))
4530bool LLParser::parseMDNode(
MDNode *&
N) {
4532 return parseSpecializedMDNode(
N);
4534 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4537bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4540 return parseMDTuple(
N);
4543 return parseMDNodeID(
N);
4549template <
class FieldTy>
struct MDFieldImpl {
4550 typedef MDFieldImpl ImplTy;
4554 void assign(FieldTy Val) {
4556 this->Val = std::move(Val);
4559 explicit MDFieldImpl(FieldTy
Default)
4567template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4568 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4579 void assign(FieldTypeA
A) {
4581 this->A = std::move(
A);
4585 void assign(FieldTypeB
B) {
4587 this->B = std::move(
B);
4591 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4593 WhatIs(IsInvalid) {}
4596struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4603struct LineField :
public MDUnsignedField {
4604 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4607struct ColumnField :
public MDUnsignedField {
4608 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4611struct DwarfTagField :
public MDUnsignedField {
4617struct DwarfMacinfoTypeField :
public MDUnsignedField {
4623struct DwarfAttEncodingField :
public MDUnsignedField {
4624 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4627struct DwarfVirtualityField :
public MDUnsignedField {
4631struct DwarfLangField :
public MDUnsignedField {
4635struct DwarfCCField :
public MDUnsignedField {
4636 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4639struct EmissionKindField :
public MDUnsignedField {
4640 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4643struct NameTableKindField :
public MDUnsignedField {
4644 NameTableKindField()
4647 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4650struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4651 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4654struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4655 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4658struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4659 MDAPSIntField() : ImplTy(
APSInt()) {}
4662struct MDSignedField :
public MDFieldImpl<int64_t> {
4666 MDSignedField(int64_t
Default = 0)
4668 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4672struct MDBoolField :
public MDFieldImpl<bool> {
4676struct MDField :
public MDFieldImpl<Metadata *> {
4679 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4682struct MDStringField :
public MDFieldImpl<MDString *> {
4684 MDStringField(
bool AllowEmpty =
true)
4685 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4688struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4692struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4696struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4697 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4698 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4700 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4701 bool AllowNull =
true)
4702 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4704 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4705 bool isMDField()
const {
return WhatIs == IsTypeB; }
4706 int64_t getMDSignedValue()
const {
4707 assert(isMDSignedField() &&
"Wrong field type");
4710 Metadata *getMDFieldValue()
const {
4711 assert(isMDField() &&
"Wrong field type");
4723 return tokError(
"expected integer");
4732 MDUnsignedField &Result) {
4734 return tokError(
"expected unsigned integer");
4737 if (U.ugt(Result.Max))
4738 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4740 Result.assign(U.getZExtValue());
4741 assert(Result.Val <= Result.Max &&
"Expected value in range");
4748 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4752 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4758 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4761 return tokError(
"expected DWARF tag");
4765 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4766 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4775 DwarfMacinfoTypeField &Result) {
4777 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4780 return tokError(
"expected DWARF macinfo type");
4784 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4786 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4788 Result.assign(Macinfo);
4795 DwarfVirtualityField &Result) {
4797 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4800 return tokError(
"expected DWARF virtuality code");
4804 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4806 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4807 Result.assign(Virtuality);
4815 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4818 return tokError(
"expected DWARF language");
4822 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4824 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4825 Result.assign(Lang);
4833 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4836 return tokError(
"expected DWARF calling convention");
4840 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4842 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4850 EmissionKindField &Result) {
4852 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4855 return tokError(
"expected emission kind");
4859 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4861 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4862 Result.assign(*Kind);
4869 NameTableKindField &Result) {
4871 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4874 return tokError(
"expected nameTable kind");
4878 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4880 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4881 Result.assign((
unsigned)*Kind);
4888 DwarfAttEncodingField &Result) {
4890 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4893 return tokError(
"expected DWARF type attribute encoding");
4897 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4899 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4900 Result.assign(Encoding);
4916 bool Res = parseUInt32(TempVal);
4922 return tokError(
"expected debug info flag");
4926 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4941 Result.assign(Combined);
4956 bool Res = parseUInt32(TempVal);
4962 return tokError(
"expected debug info flag");
4966 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4981 Result.assign(Combined);
4988 return tokError(
"expected signed integer");
4992 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4995 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4997 Result.assign(S.getExtValue());
4998 assert(Result.Val >= Result.Min &&
"Expected value in range");
4999 assert(Result.Val <= Result.Max &&
"Expected value in range");
5008 return tokError(
"expected 'true' or 'false'");
5010 Result.assign(
true);
5013 Result.assign(
false);
5023 if (!Result.AllowNull)
5024 return tokError(
"'" +
Name +
"' cannot be null");
5026 Result.assign(
nullptr);
5031 if (parseMetadata(MD,
nullptr))
5040 MDSignedOrMDField &Result) {
5043 MDSignedField Res = Result.A;
5044 if (!parseMDField(Loc,
Name, Res)) {
5052 MDField Res = Result.B;
5053 if (!parseMDField(Loc,
Name, Res)) {
5065 if (parseStringConstant(S))
5068 if (!Result.AllowEmpty && S.empty())
5069 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
5071 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
5078 if (parseMDNodeVector(MDs))
5081 Result.assign(std::move(MDs));
5087 ChecksumKindField &Result) {
5088 std::optional<DIFile::ChecksumKind> CSKind =
5092 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
5095 Result.assign(*CSKind);
5102template <
class ParserTy>
5103bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5106 return tokError(
"expected field label here");
5115template <
class ParserTy>
5116bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5123 if (parseMDFieldsImplBody(ParseField))
5126 ClosingLoc = Lex.
getLoc();
5130template <
class FieldTy>
5131bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5133 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5137 return parseMDField(Loc,
Name, Result);
5140bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5143#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5144 if (Lex.getStrVal() == #CLASS) \
5145 return parse##CLASS(N, IsDistinct);
5146#include "llvm/IR/Metadata.def"
5148 return tokError(
"expected metadata type");
5151#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5152#define NOP_FIELD(NAME, TYPE, INIT)
5153#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5155 return error(ClosingLoc, "missing required field '" #NAME "'");
5156#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5157 if (Lex.getStrVal() == #NAME) \
5158 return parseMDField(#NAME, NAME);
5159#define PARSE_MD_FIELDS() \
5160 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5163 if (parseMDFieldsImpl( \
5165 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5166 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5171 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5173#define GET_OR_DISTINCT(CLASS, ARGS) \
5174 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5179bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5180#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5181 OPTIONAL(line, LineField, ); \
5182 OPTIONAL(column, ColumnField, ); \
5183 REQUIRED(scope, MDField, ( false)); \
5184 OPTIONAL(inlinedAt, MDField, ); \
5185 OPTIONAL(isImplicitCode, MDBoolField, (false));
5187#undef VISIT_MD_FIELDS
5191 inlinedAt.Val, isImplicitCode.Val));
5197bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5199 return tokError(
"missing 'distinct', required for !DIAssignID()");
5215bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5216#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5217 REQUIRED(tag, DwarfTagField, ); \
5218 OPTIONAL(header, MDStringField, ); \
5219 OPTIONAL(operands, MDFieldList, );
5221#undef VISIT_MD_FIELDS
5224 (Context, tag.Val, header.Val, operands.Val));
5232bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5233#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5234 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5235 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5236 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5237 OPTIONAL(stride, MDSignedOrMDField, );
5239#undef VISIT_MD_FIELDS
5246 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5247 if (Bound.isMDSignedField())
5250 if (Bound.isMDField())
5251 return Bound.getMDFieldValue();
5255 Count = convToMetadata(
count);
5256 LowerBound = convToMetadata(lowerBound);
5258 Stride = convToMetadata(stride);
5261 (Context, Count, LowerBound, UpperBound, Stride));
5269bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5270#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5271 OPTIONAL(count, MDSignedOrMDField, ); \
5272 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5273 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5274 OPTIONAL(stride, MDSignedOrMDField, );
5276#undef VISIT_MD_FIELDS
5278 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5279 if (Bound.isMDSignedField())
5281 Context, {dwarf::DW_OP_consts,
5282 static_cast<uint64_t>(Bound.getMDSignedValue())});
5283 if (Bound.isMDField())
5284 return Bound.getMDFieldValue();
5289 Metadata *LowerBound = ConvToMetadata(lowerBound);
5291 Metadata *Stride = ConvToMetadata(stride);
5294 (Context, Count, LowerBound, UpperBound, Stride));
5301bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5302#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5303 REQUIRED(name, MDStringField, ); \
5304 REQUIRED(value, MDAPSIntField, ); \
5305 OPTIONAL(isUnsigned, MDBoolField, (false));
5307#undef VISIT_MD_FIELDS
5309 if (isUnsigned.Val &&
value.Val.isNegative())
5310 return tokError(
"unsigned enumerator with negative value");
5315 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5327bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5328#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5329 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5330 OPTIONAL(name, MDStringField, ); \
5331 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5332 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5333 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5334 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5335 OPTIONAL(flags, DIFlagField, );
5337#undef VISIT_MD_FIELDS
5340 align.Val, encoding.Val,
5341 num_extra_inhabitants.Val, flags.Val));
5347bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5348#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5349 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5350 OPTIONAL(name, MDStringField, ); \
5351 OPTIONAL(stringLength, MDField, ); \
5352 OPTIONAL(stringLengthExpression, MDField, ); \
5353 OPTIONAL(stringLocationExpression, MDField, ); \
5354 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5355 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5356 OPTIONAL(encoding, DwarfAttEncodingField, );
5358#undef VISIT_MD_FIELDS
5362 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5363 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5376bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5377#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5378 REQUIRED(tag, DwarfTagField, ); \
5379 OPTIONAL(name, MDStringField, ); \
5380 OPTIONAL(file, MDField, ); \
5381 OPTIONAL(line, LineField, ); \
5382 OPTIONAL(scope, MDField, ); \
5383 REQUIRED(baseType, MDField, ); \
5384 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5385 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5386 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5387 OPTIONAL(flags, DIFlagField, ); \
5388 OPTIONAL(extraData, MDField, ); \
5389 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5390 OPTIONAL(annotations, MDField, ); \
5391 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5392 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5393 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5394 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5395 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5397#undef VISIT_MD_FIELDS
5399 std::optional<unsigned> DWARFAddressSpace;
5400 if (dwarfAddressSpace.Val != UINT32_MAX)
5401 DWARFAddressSpace = dwarfAddressSpace.Val;
5402 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5404 PtrAuthData.emplace(
5405 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5406 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5407 ptrAuthAuthenticatesNullValues.Val);
5410 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5411 scope.Val, baseType.Val,
size.Val, align.Val,
5412 offset.Val, DWARFAddressSpace, PtrAuthData,
5413 flags.Val, extraData.Val, annotations.Val));
5417bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5418#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5419 REQUIRED(tag, DwarfTagField, ); \
5420 OPTIONAL(name, MDStringField, ); \
5421 OPTIONAL(file, MDField, ); \
5422 OPTIONAL(line, LineField, ); \
5423 OPTIONAL(scope, MDField, ); \
5424 OPTIONAL(baseType, MDField, ); \
5425 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5426 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5427 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5428 OPTIONAL(flags, DIFlagField, ); \
5429 OPTIONAL(elements, MDField, ); \
5430 OPTIONAL(runtimeLang, DwarfLangField, ); \
5431 OPTIONAL(vtableHolder, MDField, ); \
5432 OPTIONAL(templateParams, MDField, ); \
5433 OPTIONAL(identifier, MDStringField, ); \
5434 OPTIONAL(discriminator, MDField, ); \
5435 OPTIONAL(dataLocation, MDField, ); \
5436 OPTIONAL(associated, MDField, ); \
5437 OPTIONAL(allocated, MDField, ); \
5438 OPTIONAL(rank, MDSignedOrMDField, ); \
5439 OPTIONAL(annotations, MDField, ); \
5440 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5441 OPTIONAL(specification, MDField, );
5443#undef VISIT_MD_FIELDS
5446 if (
rank.isMDSignedField())
5449 else if (
rank.isMDField())
5450 Rank =
rank.getMDFieldValue();
5455 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5456 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val,
5457 specification.Val, num_extra_inhabitants.Val, flags.Val,
5458 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5459 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5460 Rank, annotations.Val)) {
5469 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5470 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5471 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5472 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5473 annotations.Val, specification.Val, num_extra_inhabitants.Val));
5477bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5478#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5479 OPTIONAL(flags, DIFlagField, ); \
5480 OPTIONAL(cc, DwarfCCField, ); \
5481 REQUIRED(types, MDField, );
5483#undef VISIT_MD_FIELDS
5486 (Context, flags.Val, cc.Val, types.Val));
5495bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5499#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5500 REQUIRED(filename, MDStringField, ); \
5501 REQUIRED(directory, MDStringField, ); \
5502 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5503 OPTIONAL(checksum, MDStringField, ); \
5504 OPTIONAL(source, MDStringField, );
5506#undef VISIT_MD_FIELDS
5508 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5509 if (checksumkind.Seen && checksum.Seen)
5510 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5511 else if (checksumkind.Seen || checksum.Seen)
5512 return tokError(
"'checksumkind' and 'checksum' must be provided together");
5518 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5529bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5531 return tokError(
"missing 'distinct', required for !DICompileUnit");
5533#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5534 REQUIRED(language, DwarfLangField, ); \
5535 REQUIRED(file, MDField, ( false)); \
5536 OPTIONAL(producer, MDStringField, ); \
5537 OPTIONAL(isOptimized, MDBoolField, ); \
5538 OPTIONAL(flags, MDStringField, ); \
5539 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5540 OPTIONAL(splitDebugFilename, MDStringField, ); \
5541 OPTIONAL(emissionKind, EmissionKindField, ); \
5542 OPTIONAL(enums, MDField, ); \
5543 OPTIONAL(retainedTypes, MDField, ); \
5544 OPTIONAL(globals, MDField, ); \
5545 OPTIONAL(imports, MDField, ); \
5546 OPTIONAL(macros, MDField, ); \
5547 OPTIONAL(dwoId, MDUnsignedField, ); \
5548 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5549 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5550 OPTIONAL(nameTableKind, NameTableKindField, ); \
5551 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5552 OPTIONAL(sysroot, MDStringField, ); \
5553 OPTIONAL(sdk, MDStringField, );
5555#undef VISIT_MD_FIELDS
5558 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5559 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5560 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5561 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5562 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5575bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5577#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5578 OPTIONAL(scope, MDField, ); \
5579 OPTIONAL(name, MDStringField, ); \
5580 OPTIONAL(linkageName, MDStringField, ); \
5581 OPTIONAL(file, MDField, ); \
5582 OPTIONAL(line, LineField, ); \
5583 OPTIONAL(type, MDField, ); \
5584 OPTIONAL(isLocal, MDBoolField, ); \
5585 OPTIONAL(isDefinition, MDBoolField, (true)); \
5586 OPTIONAL(scopeLine, LineField, ); \
5587 OPTIONAL(containingType, MDField, ); \
5588 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5589 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5590 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5591 OPTIONAL(flags, DIFlagField, ); \
5592 OPTIONAL(spFlags, DISPFlagField, ); \
5593 OPTIONAL(isOptimized, MDBoolField, ); \
5594 OPTIONAL(unit, MDField, ); \
5595 OPTIONAL(templateParams, MDField, ); \
5596 OPTIONAL(declaration, MDField, ); \
5597 OPTIONAL(retainedNodes, MDField, ); \
5598 OPTIONAL(thrownTypes, MDField, ); \
5599 OPTIONAL(annotations, MDField, ); \
5600 OPTIONAL(targetFuncName, MDStringField, );
5602#undef VISIT_MD_FIELDS
5607 spFlags.Seen ? spFlags.Val
5609 isOptimized.Val, virtuality.Val);
5610 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5613 "missing 'distinct', required for !DISubprogram that is a Definition");
5616 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5617 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5618 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5619 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5620 targetFuncName.Val));
5626bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5627#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5628 REQUIRED(scope, MDField, ( false)); \
5629 OPTIONAL(file, MDField, ); \
5630 OPTIONAL(line, LineField, ); \
5631 OPTIONAL(column, ColumnField, );
5633#undef VISIT_MD_FIELDS
5642bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5643#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5644 REQUIRED(scope, MDField, ( false)); \
5645 OPTIONAL(file, MDField, ); \
5646 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5648#undef VISIT_MD_FIELDS
5651 (Context, scope.Val,
file.Val, discriminator.Val));
5657bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5658#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5659 REQUIRED(scope, MDField, ); \
5660 OPTIONAL(declaration, MDField, ); \
5661 OPTIONAL(name, MDStringField, ); \
5662 OPTIONAL(file, MDField, ); \
5663 OPTIONAL(line, LineField, );
5665#undef VISIT_MD_FIELDS
5668 (Context, scope.Val, declaration.Val,
name.Val,
5669 file.Val, line.Val));
5675bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5676#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5677 REQUIRED(scope, MDField, ); \
5678 OPTIONAL(name, MDStringField, ); \
5679 OPTIONAL(exportSymbols, MDBoolField, );
5681#undef VISIT_MD_FIELDS
5684 (Context, scope.Val,
name.Val, exportSymbols.Val));
5691bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5692#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5693 REQUIRED(type, DwarfMacinfoTypeField, ); \
5694 OPTIONAL(line, LineField, ); \
5695 REQUIRED(name, MDStringField, ); \
5696 OPTIONAL(value, MDStringField, );
5698#undef VISIT_MD_FIELDS
5701 (Context, type.Val, line.Val,
name.Val,
value.Val));
5707bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5708#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5709 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5710 OPTIONAL(line, LineField, ); \
5711 REQUIRED(file, MDField, ); \
5712 OPTIONAL(nodes, MDField, );
5714#undef VISIT_MD_FIELDS
5717 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5725bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5726#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5727 REQUIRED(scope, MDField, ); \
5728 REQUIRED(name, MDStringField, ); \
5729 OPTIONAL(configMacros, MDStringField, ); \
5730 OPTIONAL(includePath, MDStringField, ); \
5731 OPTIONAL(apinotes, MDStringField, ); \
5732 OPTIONAL(file, MDField, ); \
5733 OPTIONAL(line, LineField, ); \
5734 OPTIONAL(isDecl, MDBoolField, );
5736#undef VISIT_MD_FIELDS
5739 configMacros.Val, includePath.Val,
5740 apinotes.Val, line.Val, isDecl.Val));
5746bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5747#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5748 OPTIONAL(name, MDStringField, ); \
5749 REQUIRED(type, MDField, ); \
5750 OPTIONAL(defaulted, MDBoolField, );
5752#undef VISIT_MD_FIELDS
5755 (Context,
name.Val, type.Val, defaulted.Val));
5763bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5764#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5765 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5766 OPTIONAL(name, MDStringField, ); \
5767 OPTIONAL(type, MDField, ); \
5768 OPTIONAL(defaulted, MDBoolField, ); \
5769 REQUIRED(value, MDField, );
5772#undef VISIT_MD_FIELDS
5776 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5785bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5786#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5787 OPTIONAL(name, MDStringField, ( false)); \
5788 OPTIONAL(scope, MDField, ); \
5789 OPTIONAL(linkageName, MDStringField, ); \
5790 OPTIONAL(file, MDField, ); \
5791 OPTIONAL(line, LineField, ); \
5792 OPTIONAL(type, MDField, ); \
5793 OPTIONAL(isLocal, MDBoolField, ); \
5794 OPTIONAL(isDefinition, MDBoolField, (true)); \
5795 OPTIONAL(templateParams, MDField, ); \
5796 OPTIONAL(declaration, MDField, ); \
5797 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5798 OPTIONAL(annotations, MDField, );
5800#undef VISIT_MD_FIELDS
5804 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5805 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5806 declaration.Val, templateParams.Val, align.Val,
5818bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5819#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5820 REQUIRED(scope, MDField, ( false)); \
5821 OPTIONAL(name, MDStringField, ); \
5822 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5823 OPTIONAL(file, MDField, ); \
5824 OPTIONAL(line, LineField, ); \
5825 OPTIONAL(type, MDField, ); \
5826 OPTIONAL(flags, DIFlagField, ); \
5827 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5828 OPTIONAL(annotations, MDField, );
5830#undef VISIT_MD_FIELDS
5833 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5834 type.Val, arg.Val, flags.Val, align.Val,
5841bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5842#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5843 REQUIRED(scope, MDField, ( false)); \
5844 REQUIRED(name, MDStringField, ); \
5845 REQUIRED(file, MDField, ); \
5846 REQUIRED(line, LineField, );
5848#undef VISIT_MD_FIELDS
5851 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5857bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
5870 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5879 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5884 return tokError(
"expected unsigned integer");
5902bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5904 assert(Lex.
getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
5907 return parseDIExpressionBody(Result, IsDistinct);
5912bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5913 assert(PFS &&
"Expected valid function state");
5924 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5926 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5938bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
5940#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5941 REQUIRED(var, MDField, ); \
5942 REQUIRED(expr, MDField, );
5944#undef VISIT_MD_FIELDS
5954bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
5955#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5956 OPTIONAL(name, MDStringField, ); \
5957 OPTIONAL(file, MDField, ); \
5958 OPTIONAL(line, LineField, ); \
5959 OPTIONAL(setter, MDStringField, ); \
5960 OPTIONAL(getter, MDStringField, ); \
5961 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5962 OPTIONAL(type, MDField, );
5964#undef VISIT_MD_FIELDS
5967 (Context,
name.Val,
file.Val, line.Val, setter.Val,
5968 getter.Val, attributes.Val, type.Val));
5975bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
5976#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5977 REQUIRED(tag, DwarfTagField, ); \
5978 REQUIRED(scope, MDField, ); \
5979 OPTIONAL(entity, MDField, ); \
5980 OPTIONAL(file, MDField, ); \
5981 OPTIONAL(line, LineField, ); \
5982 OPTIONAL(name, MDStringField, ); \
5983 OPTIONAL(elements, MDField, );
5985#undef VISIT_MD_FIELDS
5988 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
5989 line.Val,
name.Val, elements.Val));
5993#undef PARSE_MD_FIELD
6005bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6008 if (parseMetadata(MD, &PFS))
6019bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6020 PerFunctionState *PFS) {
6023 if (parseType(Ty, TypeMsg, Loc))
6026 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6029 if (parseValue(Ty, V, PFS))
6044bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6050 if (parseDIArgList(AL, PFS))
6056 if (parseSpecializedMDNode(
N)) {
6066 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6076 if (parseMDString(S))
6086 if (parseMDNodeTail(
N))
6097 PerFunctionState *PFS) {
6099 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6104 return error(
ID.Loc,
"invalid use of function-local name");
6105 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6106 return V ==
nullptr;
6109 return error(
ID.Loc,
"invalid use of function-local name");
6110 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6111 return V ==
nullptr;
6114 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6118 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6123 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6126 return V ==
nullptr;
6128 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6131 return V ==
nullptr;
6134 return error(
ID.Loc,
"integer constant must have integer type");
6136 V = ConstantInt::get(Context,
ID.APSIntVal);
6141 return error(
ID.Loc,
"floating point constant invalid for type");
6147 bool IsSNAN =
ID.APFloatVal.isSignaling();
6162 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6164 ID.APFloatVal.isNegative(), &Payload);
6167 V = ConstantFP::get(Context,
ID.APFloatVal);
6169 if (
V->getType() != Ty)
6170 return error(
ID.Loc,
"floating point constant does not have type '" +
6176 return error(
ID.Loc,
"null must be a pointer type");
6182 return error(
ID.Loc,
"invalid type for undef constant");
6186 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6187 return error(
ID.Loc,
"invalid empty array initializer");
6193 return error(
ID.Loc,
"invalid type for null constant");
6194 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6196 return error(
ID.Loc,
"invalid type for null constant");
6201 return error(
ID.Loc,
"invalid type for none constant");
6207 return error(
ID.Loc,
"invalid type for poison constant");
6211 if (
ID.ConstantVal->getType() != Ty)
6212 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6219 return error(
ID.Loc,
"vector constant must have vector type");
6221 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6223 "' but expected '" +
6230 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6231 if (
ST->getNumElements() !=
ID.UIntVal)
6233 "initializer with struct type has wrong # elements");
6235 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6238 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6239 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6242 "element " +
Twine(i) +
6243 " of struct initializer doesn't match struct element type");
6246 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6248 return error(
ID.Loc,
"constant expression type mismatch");
6258 if (parseValID(
ID,
nullptr))
6271 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6273 assert(isa<Constant>(V) &&
"Expected a constant value");
6274 C = cast<Constant>(V);
6281 return error(Loc,
"expected a constant value");
6285bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6288 return parseValID(
ID, PFS, Ty) ||
6289 convertValIDToValue(Ty,
ID, V, PFS);
6292bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6294 return parseType(Ty) || parseValue(Ty, V, PFS);
6297bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6298 PerFunctionState &PFS) {
6301 if (parseTypeAndValue(V, PFS))
6303 if (!isa<BasicBlock>(V))
6304 return error(Loc,
"expected a basic block");
6305 BB = cast<BasicBlock>(V);
6313 if (!
Name.starts_with(
"llvm.dbg."))
6316 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6317 FnID == Intrinsic::dbg_assign;
6325bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6326 unsigned &FunctionNumber,
6331 unsigned Visibility;
6332 unsigned DLLStorageClass;
6337 Type *RetType =
nullptr;
6339 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6341 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6342 parseType(RetType, RetTypeLoc,
true ))
6351 return error(LinkageLoc,
"invalid linkage for function definition");
6361 return error(LinkageLoc,
"invalid linkage for function declaration");
6365 return error(LinkageLoc,
"invalid function linkage type");
6369 return error(LinkageLoc,
6370 "symbol with local linkage must have default visibility");
6373 return error(LinkageLoc,
6374 "symbol with local linkage cannot have a DLL storage class");
6377 return error(RetTypeLoc,
"invalid function return type");
6381 std::string FunctionName;
6386 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6390 return tokError(
"expected function name");
6396 return tokError(
"expected '(' in function argument list");
6401 std::vector<unsigned> FwdRefAttrGrps;
6404 std::string Partition;
6408 unsigned AddrSpace = 0;
6414 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6415 parseOptionalUnnamedAddr(UnnamedAddr) ||
6416 parseOptionalProgramAddrSpace(AddrSpace) ||
6417 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6421 parseOptionalComdat(FunctionName,
C) ||
6422 parseOptionalAlignment(Alignment) ||
6423 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6427 parseGlobalTypeAndValue(PersonalityFn)))
6430 if (FuncAttrs.contains(Attribute::Builtin))
6431 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6436 FuncAttrs.removeAttribute(Attribute::Alignment);
6441 std::vector<Type*> ParamTypeList;
6444 for (
const ArgInfo &Arg : ArgList) {
6445 ParamTypeList.push_back(Arg.Ty);
6446 Attrs.push_back(Arg.Attrs);
6454 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6461 if (!FunctionName.empty()) {
6464 auto FRVI = ForwardRefVals.find(FunctionName);
6465 if (FRVI != ForwardRefVals.end()) {
6466 FwdFn = FRVI->second.first;
6468 return error(FRVI->second.second,
6469 "invalid forward reference to "
6472 "' with wrong type: "
6476 ForwardRefVals.erase(FRVI);
6477 }
else if ((Fn =
M->getFunction(FunctionName))) {
6479 return error(NameLoc,
6480 "invalid redefinition of function '" + FunctionName +
"'");
6481 }
else if (
M->getNamedValue(FunctionName)) {
6482 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6488 if (FunctionNumber == (
unsigned)-1)
6489 FunctionNumber = NumberedVals.getNext();
6493 auto I = ForwardRefValIDs.find(FunctionNumber);
6494 if (
I != ForwardRefValIDs.end()) {
6495 FwdFn =
I->second.first;
6497 return error(NameLoc,
"type of definition and forward reference of '@" +
6498 Twine(FunctionNumber) +
6503 ForwardRefValIDs.erase(
I);
6512 if (FunctionName.empty())
6513 NumberedVals.add(FunctionNumber, Fn);
6528 if (!
GC.empty()) Fn->
setGC(GC);
6531 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6535 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6537 if (ArgList[i].
Name.empty())
continue;
6542 if (ArgIt->
getName() != ArgList[i].Name)
6543 return error(ArgList[i].Loc,
6544 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6557 if (FunctionName.empty()) {
6559 ID.UIntVal = FunctionNumber;
6562 ID.StrVal = FunctionName;
6564 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6565 if (
Blocks != ForwardRefBlockAddresses.end())
6567 "cannot take blockaddress inside a declaration");
6571bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6573 if (FunctionNumber == -1) {
6575 ID.StrVal = std::string(
F.getName());
6578 ID.UIntVal = FunctionNumber;
6581 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6582 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6585 for (
const auto &
I :
Blocks->second) {
6586 const ValID &BBID =
I.first;
6590 "Expected local id or name");
6597 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6608 P.ForwardRefBlockAddresses.erase(
Blocks);
6614bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6617 return tokError(
"expected '{' in function body");
6620 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6624 if (PFS.resolveForwardRefBlockAddresses())
6630 return tokError(
"function body requires at least one basic block");
6634 if (parseBasicBlock(PFS))
6638 if (parseUseListOrder(&PFS))
6645 return PFS.finishFunction();
6650bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6667 std::string NameStr;
6672 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6673 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6680 if (SeenOldDbgInfoFormat)
6681 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6682 "containing debug info intrinsics");
6683 if (!SeenNewDbgInfoFormat)
6684 M->setNewDbgInfoFormatFlag(
true);
6685 SeenNewDbgInfoFormat =
true;
6689 if (parseDebugRecord(DR, PFS))
6691 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6703 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6708 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6712 switch (parseInstruction(Inst, BB, PFS)) {
6715 case InstError:
return true;
6722 if (parseInstructionMetadata(*Inst))
6725 case InstExtraComma:
6730 if (parseInstructionMetadata(*Inst))
6736 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6740 for (DbgRecordPtr &DR : TrailingDbgRecord)
6742 TrailingDbgRecord.clear();
6745 assert(TrailingDbgRecord.empty() &&
6746 "All debug values should have been attached to an instruction.");
6755bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6760 return error(DVRLoc,
"expected debug record type here");
6762 .
Case(
"declare", RecordKind::ValueKind)
6763 .
Case(
"value", RecordKind::ValueKind)
6764 .
Case(
"assign", RecordKind::ValueKind)
6765 .
Case(
"label", RecordKind::LabelKind);
6774 if (parseMDNode(Label))
6779 if (parseMDNode(DbgLoc))
6788 .
Case(
"declare", LocType::Declare)
6789 .
Case(
"value", LocType::Value)
6790 .
Case(
"assign", LocType::Assign);
6798 if (parseMetadata(ValLocMD, &PFS))
6805 if (parseMDNode(Variable))
6818 MDNode *AssignID =
nullptr;
6819 Metadata *AddressLocation =
nullptr;
6820 MDNode *AddressExpression =
nullptr;
6823 if (parseMDNode(AssignID))
6829 if (parseMetadata(AddressLocation, &PFS))
6835 if (parseMDNode(AddressExpression))
6860 PerFunctionState &PFS) {
6863 return tokError(
"found end of file when expecting more instructions");
6870 return error(Loc,
"expected instruction opcode");
6874 return parseRet(Inst, BB, PFS);
6876 return parseBr(Inst, PFS);
6878 return parseSwitch(Inst, PFS);
6880 return parseIndirectBr(Inst, PFS);
6882 return parseInvoke(Inst, PFS);
6884 return parseResume(Inst, PFS);
6886 return parseCleanupRet(Inst, PFS);
6888 return parseCatchRet(Inst, PFS);
6890 return parseCatchSwitch(Inst, PFS);
6892 return parseCatchPad(Inst, PFS);
6894 return parseCleanupPad(Inst, PFS);
6896 return parseCallBr(Inst, PFS);
6900 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6916 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6919 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6920 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6929 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
6943 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6945 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
6951 return parseArithmetic(Inst, PFS, KeywordVal,
6955 if (parseLogical(Inst, PFS, KeywordVal))
6958 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
6963 return parseLogical(Inst, PFS, KeywordVal);
6966 if (parseCompare(Inst, PFS, KeywordVal))
6969 cast<ICmpInst>(Inst)->setSameSign();
6974 int Res = parseCompare(Inst, PFS, KeywordVal);
6986 bool Res = parseCast(Inst, PFS, KeywordVal);
6998 if (parseCast(Inst, PFS, KeywordVal))
7001 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
7003 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
7014 return parseCast(Inst, PFS, KeywordVal);
7018 if (parseCast(Inst, PFS, KeywordVal))
7028 int Res = parseSelect(Inst, PFS);
7032 if (!isa<FPMathOperator>(Inst))
7033 return error(Loc,
"fast-math-flags specified for select without "
7034 "floating-point scalar or vector return type");
7040 return parseVAArg(Inst, PFS);
7042 return parseExtractElement(Inst, PFS);
7044 return parseInsertElement(Inst, PFS);
7046 return parseShuffleVector(Inst, PFS);
7049 int Res = parsePHI(Inst, PFS);
7053 if (!isa<FPMathOperator>(Inst))
7054 return error(Loc,
"fast-math-flags specified for phi without "
7055 "floating-point scalar or vector return type");
7061 return parseLandingPad(Inst, PFS);
7063 return parseFreeze(Inst, PFS);
7075 return parseAlloc(Inst, PFS);
7077 return parseLoad(Inst, PFS);
7079 return parseStore(Inst, PFS);
7081 return parseCmpXchg(Inst, PFS);
7083 return parseAtomicRMW(Inst, PFS);
7085 return parseFence(Inst, PFS);
7087 return parseGetElementPtr(Inst, PFS);
7089 return parseExtractValue(Inst, PFS);
7091 return parseInsertValue(Inst, PFS);
7096bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7097 if (Opc == Instruction::FCmp) {
7100 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7121 return tokError(
"expected icmp predicate (e.g. 'eq')");
7146 PerFunctionState &PFS) {
7149 if (parseType(Ty,
true ))
7152 Type *ResType = PFS.getFunction().getReturnType();
7156 return error(TypeLoc,
"value doesn't match function result type '" +
7164 if (parseValue(Ty, RV, PFS))
7168 return error(TypeLoc,
"value doesn't match function result type '" +
7178bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7182 if (parseTypeAndValue(Op0, Loc, PFS))
7185 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7191 return error(Loc,
"branch condition must have 'i1' type");
7193 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7194 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7195 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7196 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7208bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7209 LocTy CondLoc, BBLoc;
7212 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7213 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7214 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7218 if (!
Cond->getType()->isIntegerTy())
7219 return error(CondLoc,
"switch condition must have integer type");
7228 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7229 parseToken(
lltok::comma,
"expected ',' after case value") ||
7230 parseTypeAndBasicBlock(DestBB, PFS))
7234 return error(CondLoc,
"duplicate case value in switch");
7236 return error(CondLoc,
"case value is not a constant integer");
7244 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7245 SI->addCase(Table[i].first, Table[i].second);
7253bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7256 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7257 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7261 if (!
Address->getType()->isPointerTy())
7262 return error(AddrLoc,
"indirectbr address must have pointer type");
7269 if (parseTypeAndBasicBlock(DestBB, PFS))
7274 if (parseTypeAndBasicBlock(DestBB, PFS))
7280 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7295 FuncTy = dyn_cast<FunctionType>(RetType);
7300 for (
const ParamInfo &Arg : ArgList)
7314bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7316 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7317 std::vector<unsigned> FwdRefAttrGrps;
7320 unsigned InvokeAddrSpace;
7321 Type *RetType =
nullptr;
7328 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7329 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7330 parseType(RetType, RetTypeLoc,
true ) ||
7331 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7332 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7334 parseOptionalOperandBundles(BundleList, PFS) ||
7336 parseTypeAndBasicBlock(NormalBB, PFS) ||
7338 parseTypeAndBasicBlock(UnwindBB, PFS))
7345 if (resolveFunctionType(RetType, ArgList, Ty))
7346 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7364 for (
const ParamInfo &Arg : ArgList) {
7365 Type *ExpectedTy =
nullptr;
7368 }
else if (!Ty->isVarArg()) {
7369 return error(Arg.Loc,
"too many arguments specified");
7372 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7373 return error(Arg.Loc,
"argument is not of expected type '" +
7375 Args.push_back(Arg.V);
7380 return error(CallLoc,
"not enough parameters specified for call");
7389 II->setCallingConv(
CC);
7390 II->setAttributes(PAL);
7391 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
7398bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7400 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7409 PerFunctionState &PFS) {
7410 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7415 if (!
Args.empty() &&
7416 parseToken(
lltok::comma,
"expected ',' in argument list"))
7421 Type *ArgTy =
nullptr;
7422 if (parseType(ArgTy, ArgLoc))
7427 if (parseMetadataAsValue(V, PFS))
7430 if (parseValue(ArgTy, V, PFS))
7442bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7443 Value *CleanupPad =
nullptr;
7445 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7460 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7471bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7472 Value *CatchPad =
nullptr;
7474 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7481 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7482 parseTypeAndBasicBlock(BB, PFS))
7491bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7499 return tokError(
"expected scope value for catchswitch");
7504 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7510 if (parseTypeAndBasicBlock(DestBB, PFS))
7515 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7518 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7526 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7533 CatchSwitch->addHandler(DestBB);
7540bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7541 Value *CatchSwitch =
nullptr;
7547 return tokError(
"expected scope value for catchpad");
7553 if (parseExceptionArgs(Args, PFS))
7562bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7563 Value *ParentPad =
nullptr;
7570 return tokError(
"expected scope value for cleanuppad");
7576 if (parseExceptionArgs(Args, PFS))
7592bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7593 unsigned Opc,
bool IsFP) {
7595 if (parseTypeAndValue(LHS, Loc, PFS))
7602 return error(Loc,
"invalid operand type for instruction");
7612bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7614 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7615 std::vector<unsigned> FwdRefAttrGrps;
7618 Type *RetType =
nullptr;
7625 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7626 parseType(RetType, RetTypeLoc,
true ) ||
7627 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7628 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7630 parseOptionalOperandBundles(BundleList, PFS) ||
7632 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7641 if (parseTypeAndBasicBlock(DestBB, PFS))
7646 if (parseTypeAndBasicBlock(DestBB, PFS))
7652 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7659 if (resolveFunctionType(RetType, ArgList, Ty))
7660 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7677 for (
const ParamInfo &Arg : ArgList) {
7678 Type *ExpectedTy =
nullptr;
7681 }
else if (!Ty->isVarArg()) {
7682 return error(Arg.Loc,
"too many arguments specified");
7685 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7686 return error(Arg.Loc,
"argument is not of expected type '" +
7688 Args.push_back(Arg.V);
7693 return error(CallLoc,
"not enough parameters specified for call");
7705 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7719bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7720 unsigned Opc,
bool IsFP) {
7722 if (parseTypeAndValue(LHS, Loc, PFS) ||
7723 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7731 return error(Loc,
"invalid operand type for instruction");
7739bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7742 if (parseTypeAndValue(LHS, Loc, PFS) ||
7743 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7749 "instruction requires integer or integer vector operands");
7758bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7764 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7765 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7769 if (Opc == Instruction::FCmp) {
7771 return error(Loc,
"fcmp requires floating point operands");
7774 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7777 return error(Loc,
"icmp requires integer operands");
7789bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7793 Type *DestTy =
nullptr;
7794 if (parseTypeAndValue(
Op, Loc, PFS) ||
7795 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7800 return error(Loc,
"invalid cast opcode for cast from '" +
7809bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7811 Value *Op0, *Op1, *Op2;
7812 if (parseTypeAndValue(Op0, Loc, PFS) ||
7813 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7814 parseTypeAndValue(Op1, PFS) ||
7815 parseToken(
lltok::comma,
"expected ',' after select value") ||
7816 parseTypeAndValue(Op2, PFS))
7820 return error(Loc, Reason);
7828bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7830 Type *EltTy =
nullptr;
7832 if (parseTypeAndValue(
Op, PFS) ||
7833 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7834 parseType(EltTy, TypeLoc))
7838 return error(TypeLoc,
"va_arg requires operand with first class type");
7846bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7849 if (parseTypeAndValue(Op0, Loc, PFS) ||
7850 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7851 parseTypeAndValue(Op1, PFS))
7855 return error(Loc,
"invalid extractelement operands");
7863bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7865 Value *Op0, *Op1, *Op2;
7866 if (parseTypeAndValue(Op0, Loc, PFS) ||
7867 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7868 parseTypeAndValue(Op1, PFS) ||
7869 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7870 parseTypeAndValue(Op2, PFS))
7874 return error(Loc,
"invalid insertelement operands");
7882bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7884 Value *Op0, *Op1, *Op2;
7885 if (parseTypeAndValue(Op0, Loc, PFS) ||
7886 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7887 parseTypeAndValue(Op1, PFS) ||
7888 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7889 parseTypeAndValue(Op2, PFS))
7893 return error(Loc,
"invalid shufflevector operands");
7901int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7905 if (parseType(Ty, TypeLoc))
7909 return error(TypeLoc,
"phi node must have first class type");
7912 bool AteExtraComma =
false;
7924 AteExtraComma =
true;
7928 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7929 parseValue(Ty, Op0, PFS) ||
7930 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7935 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7939 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
7940 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
7942 return AteExtraComma ? InstExtraComma : InstNormal;
7951bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
7954 if (parseType(Ty, TyLoc))
7967 return tokError(
"expected 'catch' or 'filter' clause type");
7971 if (parseTypeAndValue(V, VLoc, PFS))
7977 if (isa<ArrayType>(
V->getType()))
7978 return error(VLoc,
"'catch' clause has an invalid type");
7980 if (!isa<ArrayType>(
V->getType()))
7981 return error(VLoc,
"'filter' clause has an invalid type");
7984 Constant *CV = dyn_cast<Constant>(V);
7986 return error(VLoc,
"clause argument must be a constant");
7990 Inst = LP.release();
7996bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
7999 if (parseTypeAndValue(
Op, Loc, PFS))
8015bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
8017 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
8018 std::vector<unsigned> FwdRefAttrGrps;
8020 unsigned CallAddrSpace;
8022 Type *RetType =
nullptr;
8031 "expected 'tail call', 'musttail call', or 'notail call'"))
8036 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8037 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8038 parseType(RetType, RetTypeLoc,
true ) ||
8039 parseValID(CalleeID, &PFS) ||
8041 PFS.getFunction().isVarArg()) ||
8042 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8043 parseOptionalOperandBundles(BundleList, PFS))
8050 if (resolveFunctionType(RetType, ArgList, Ty))
8051 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8057 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
8070 for (
const ParamInfo &Arg : ArgList) {
8071 Type *ExpectedTy =
nullptr;
8074 }
else if (!Ty->isVarArg()) {
8075 return error(Arg.Loc,
"too many arguments specified");
8078 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8079 return error(Arg.Loc,
"argument is not of expected type '" +
8081 Args.push_back(Arg.V);
8082 Attrs.push_back(Arg.Attrs);
8086 return error(CallLoc,
"not enough parameters specified for call");
8097 if (!isa<FPMathOperator>(CI)) {
8099 return error(CallLoc,
"fast-math-flags specified for call without "
8100 "floating-point scalar or vector return type");
8107 if (SeenNewDbgInfoFormat) {
8109 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8110 "using non-intrinsic debug info");
8112 if (!SeenOldDbgInfoFormat)
8113 M->setNewDbgInfoFormatFlag(
false);
8114 SeenOldDbgInfoFormat =
true;
8117 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8129int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
8131 LocTy SizeLoc, TyLoc, ASLoc;
8133 unsigned AddrSpace = 0;
8136 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8137 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8139 if (parseType(Ty, TyLoc))
8143 return error(TyLoc,
"invalid type for alloca");
8145 bool AteExtraComma =
false;
8147 if (Lex.
getKind() == lltok::kw_align) {
8148 if (parseOptionalAlignment(Alignment))
8150 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8154 if (parseOptionalAddrSpace(AddrSpace))
8157 AteExtraComma =
true;
8159 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8162 if (Lex.
getKind() == lltok::kw_align) {
8163 if (parseOptionalAlignment(Alignment))
8165 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8169 if (parseOptionalAddrSpace(AddrSpace))
8172 AteExtraComma =
true;
8178 if (
Size && !
Size->getType()->isIntegerTy())
8179 return error(SizeLoc,
"element count must have integer type");
8182 if (!Alignment && !Ty->
isSized(&Visited))
8183 return error(TyLoc,
"Cannot allocate unsized type");
8185 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8190 return AteExtraComma ? InstExtraComma : InstNormal;
8197int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8200 bool AteExtraComma =
false;
8201 bool isAtomic =
false;
8210 bool isVolatile =
false;
8218 if (parseType(Ty) ||
8219 parseToken(
lltok::comma,
"expected comma after load's type") ||
8220 parseTypeAndValue(Val, Loc, PFS) ||
8221 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8222 parseOptionalCommaAlign(Alignment, AteExtraComma))
8226 return error(Loc,
"load operand must be a pointer to a first class type");
8227 if (isAtomic && !Alignment)
8228 return error(Loc,
"atomic load must have explicit non-zero alignment");
8231 return error(Loc,
"atomic load cannot use Release ordering");
8234 if (!Alignment && !Ty->
isSized(&Visited))
8235 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8237 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8238 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8239 return AteExtraComma ? InstExtraComma : InstNormal;
8247int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8250 bool AteExtraComma =
false;
8251 bool isAtomic =
false;
8260 bool isVolatile =
false;
8266 if (parseTypeAndValue(Val, Loc, PFS) ||
8267 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8268 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8269 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8270 parseOptionalCommaAlign(Alignment, AteExtraComma))
8273 if (!
Ptr->getType()->isPointerTy())
8274 return error(PtrLoc,
"store operand must be a pointer");
8276 return error(Loc,
"store operand must be a first class value");
8277 if (isAtomic && !Alignment)
8278 return error(Loc,
"atomic store must have explicit non-zero alignment");
8281 return error(Loc,
"atomic store cannot use Acquire ordering");
8284 return error(Loc,
"storing unsized types is not allowed");
8286 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8288 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8289 return AteExtraComma ? InstExtraComma : InstNormal;
8296int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8298 bool AteExtraComma =
false;
8302 bool isVolatile =
false;
8303 bool isWeak =
false;
8312 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8313 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8314 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8315 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8316 parseTypeAndValue(New, NewLoc, PFS) ||
8317 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8318 parseOrdering(FailureOrdering) ||
8319 parseOptionalCommaAlign(Alignment, AteExtraComma))
8323 return tokError(
"invalid cmpxchg success ordering");
8325 return tokError(
"invalid cmpxchg failure ordering");
8326 if (!
Ptr->getType()->isPointerTy())
8327 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8328 if (
Cmp->getType() !=
New->getType())
8329 return error(NewLoc,
"compare value and new value type do not match");
8330 if (!
New->getType()->isFirstClassType())
8331 return error(NewLoc,
"cmpxchg operand must be a first class value");
8333 const Align DefaultAlignment(
8334 PFS.getFunction().getDataLayout().getTypeStoreSize(
8339 SuccessOrdering, FailureOrdering, SSID);
8344 return AteExtraComma ? InstExtraComma : InstNormal;
8350int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8352 bool AteExtraComma =
false;
8355 bool isVolatile =
false;
8365 return tokError(
"expected binary operation in atomicrmw");
8408 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8409 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8410 parseTypeAndValue(Val, ValLoc, PFS) ||
8411 parseScopeAndOrdering(
true , SSID, Ordering) ||
8412 parseOptionalCommaAlign(Alignment, AteExtraComma))
8416 return tokError(
"atomicrmw cannot be unordered");
8417 if (!
Ptr->getType()->isPointerTy())
8418 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8420 return error(ValLoc,
"atomicrmw operand may not be scalable");
8429 " operand must be an integer, floating point, or pointer type");
8433 return error(ValLoc,
"atomicrmw " +
8435 " operand must be a floating point type");
8439 return error(ValLoc,
"atomicrmw " +
8441 " operand must be an integer");
8446 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8449 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8451 const Align DefaultAlignment(
8452 PFS.getFunction().getDataLayout().getTypeStoreSize(
8456 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8459 return AteExtraComma ? InstExtraComma : InstNormal;
8464int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8467 if (parseScopeAndOrdering(
true , SSID, Ordering))
8471 return tokError(
"fence cannot be unordered");
8473 return tokError(
"fence cannot be monotonic");
8475 Inst =
new FenceInst(Context, Ordering, SSID);
8481int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8483 Value *Val =
nullptr;
8499 if (parseType(Ty) ||
8500 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8501 parseTypeAndValue(
Ptr, Loc, PFS))
8506 if (!BasePointerType)
8507 return error(Loc,
"base of getelementptr must be a pointer");
8510 bool AteExtraComma =
false;
8514 ? cast<VectorType>(
BaseType)->getElementCount()
8519 AteExtraComma =
true;
8522 if (parseTypeAndValue(Val, EltLoc, PFS))
8525 return error(EltLoc,
"getelementptr index must be an integer");
8527 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8532 "getelementptr vector index has a wrong number of elements");
8533 GEPWidth = ValNumEl;
8540 return error(Loc,
"base element of getelementptr must be sized");
8542 auto *STy = dyn_cast<StructType>(Ty);
8544 return error(Loc,
"getelementptr cannot target structure that contains "
8545 "scalable vector type");
8548 return error(Loc,
"invalid getelementptr indices");
8551 GEP->setNoWrapFlags(NW);
8552 return AteExtraComma ? InstExtraComma : InstNormal;
8557int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8561 if (parseTypeAndValue(Val, Loc, PFS) ||
8562 parseIndexList(Indices, AteExtraComma))
8566 return error(Loc,
"extractvalue operand must be aggregate type");
8569 return error(Loc,
"invalid indices for extractvalue");
8571 return AteExtraComma ? InstExtraComma : InstNormal;
8576int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8580 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8581 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8582 parseTypeAndValue(Val1, Loc1, PFS) ||
8583 parseIndexList(Indices, AteExtraComma))
8587 return error(Loc0,
"insertvalue operand must be aggregate type");
8591 return error(Loc0,
"invalid indices for insertvalue");
8592 if (IndexedType != Val1->
getType())
8593 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8597 return AteExtraComma ? InstExtraComma : InstNormal;
8623 if (parseMetadata(MD,
nullptr))
8628 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8637 return error(Loc,
"value has no uses");
8639 unsigned NumUses = 0;
8641 for (
const Use &U :
V->uses()) {
8642 if (++NumUses > Indexes.
size())
8644 Order[&
U] = Indexes[NumUses - 1];
8647 return error(Loc,
"value only has one use");
8648 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8650 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8652 V->sortUseList([&](
const Use &L,
const Use &R) {
8665 return tokError(
"expected non-empty list of uselistorder indexes");
8672 bool IsOrdered =
true;
8673 assert(Indexes.
empty() &&
"Expected empty order vector");
8676 if (parseUInt32(Index))
8681 Max = std::max(Max, Index);
8690 if (Indexes.
size() < 2)
8691 return error(Loc,
"expected >= 2 uselistorder indexes");
8694 "expected distinct uselistorder indexes in range [0, size)");
8696 return error(Loc,
"expected uselistorder indexes to change the order");
8703bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8710 if (parseTypeAndValue(V, PFS) ||
8711 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8712 parseUseListOrderIndexes(Indexes))
8715 return sortUseListOrder(V, Indexes, Loc);
8720bool LLParser::parseUseListOrderBB() {
8727 if (parseValID(Fn,
nullptr) ||
8728 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8729 parseValID(Label,
nullptr) ||
8730 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8731 parseUseListOrderIndexes(Indexes))
8737 GV =
M->getNamedValue(Fn.
StrVal);
8739 GV = NumberedVals.get(Fn.
UIntVal);
8741 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8744 "invalid function forward reference in uselistorder_bb");
8745 auto *
F = dyn_cast<Function>(GV);
8747 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8748 if (
F->isDeclaration())
8749 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8753 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8755 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8756 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8758 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8759 if (!isa<BasicBlock>(V))
8760 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8762 return sortUseListOrder(V, Indexes, Loc);
8768bool LLParser::parseModuleEntry(
unsigned ID) {
8777 parseStringConstant(Path) ||
8785 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8786 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8787 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8788 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8789 parseUInt32(Hash[4]))
8796 auto ModuleEntry =
Index->addModule(Path, Hash);
8797 ModuleIdMap[
ID] = ModuleEntry->first();
8804bool LLParser::parseTypeIdEntry(
unsigned ID) {
8813 parseStringConstant(
Name))
8818 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8823 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8824 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8825 for (
auto TIDRef : FwdRefTIDs->second) {
8827 "Forward referenced type id GUID expected to be 0");
8830 ForwardRefTypeIds.erase(FwdRefTIDs);
8842 parseTypeTestResolution(TIS.
TTRes))
8847 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8858 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8864bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8873 parseStringConstant(
Name))
8877 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8884 IdToIndexMapType IdToIndexMap;
8897 if (parseGVReference(VI, GVId))
8904 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8905 TI.push_back({
Offset, VI});
8913 for (
auto I : IdToIndexMap) {
8914 auto &Infos = ForwardRefValueInfos[
I.first];
8915 for (
auto P :
I.second) {
8917 "Forward referenced ValueInfo expected to be empty");
8918 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8928 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8929 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8930 for (
auto TIDRef : FwdRefTIDs->second) {
8932 "Forward referenced type id GUID expected to be 0");
8935 ForwardRefTypeIds.erase(FwdRefTIDs);
8975 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
9002 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9015 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
9028bool LLParser::parseOptionalWpdResolutions(
9029 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9041 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9044 WPDResMap[
Offset] = WPDRes;
9080 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9094 if (parseOptionalResByArg(WPDRes.
ResByArg))
9099 "expected optional WholeProgramDevirtResolution field");
9116bool LLParser::parseOptionalResByArg(
9125 std::vector<uint64_t>
Args;
9126 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9150 "unexpected WholeProgramDevirtResolution::ByArg kind");
9160 parseUInt64(ByArg.
Info))
9166 parseUInt32(ByArg.
Byte))
9172 parseUInt32(ByArg.
Bit))
9177 "expected optional whole program devirt field");
9184 ResByArg[
Args] = ByArg;
9195bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9203 if (parseUInt64(Val))
9205 Args.push_back(Val);
9214static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9219 assert(!(ReadOnly && WriteOnly));
9229bool LLParser::addGlobalValueToIndex(
9231 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9236 VI =
Index->getOrInsertValueInfo(GUID);
9240 auto *GV =
M->getNamedValue(
Name);
9242 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9244 VI =
Index->getOrInsertValueInfo(GV);
9248 "Need a source_filename to compute GUID for local");
9256 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9257 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9258 for (
auto VIRef : FwdRefVIs->second) {
9260 "Forward referenced ValueInfo expected to be empty");
9263 ForwardRefValueInfos.erase(FwdRefVIs);
9267 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9268 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9269 for (
auto AliaseeRef : FwdRefAliasees->second) {
9270 assert(!AliaseeRef.first->hasAliasee() &&
9271 "Forward referencing alias already has aliasee");
9272 assert(Summary &&
"Aliasee must be a definition");
9273 AliaseeRef.first->setAliasee(VI,
Summary.get());
9275 ForwardRefAliasees.erase(FwdRefAliasees);
9280 Index->addGlobalValueSummary(VI, std::move(Summary));
9283 if (
ID == NumberedValueInfos.size())
9284 NumberedValueInfos.push_back(VI);
9287 if (
ID > NumberedValueInfos.size())
9288 NumberedValueInfos.resize(
ID + 1);
9289 NumberedValueInfos[
ID] =
VI;
9297bool LLParser::parseSummaryIndexFlags() {
9304 if (parseUInt64(Flags))
9307 Index->setFlags(Flags);
9313bool LLParser::parseBlockCount() {
9320 if (parseUInt64(BlockCount))
9323 Index->setBlockCount(BlockCount);
9331bool LLParser::parseGVEntry(
unsigned ID) {
9346 parseStringConstant(
Name))
9352 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9356 return error(Lex.
getLoc(),
"expected name or guid tag");
9381 if (parseFunctionSummary(
Name, GUID,
ID))
9385 if (parseVariableSummary(
Name, GUID,
ID))
9389 if (parseAliasSummary(
Name, GUID,
ID))
9393 return error(Lex.
getLoc(),
"expected summary type");
9419 false,
false,
false,
9424 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9426 std::vector<CallsiteInfo> Callsites;
9427 std::vector<AllocInfo> Allocs;
9432 parseModuleReference(ModulePath) ||
9433 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9436 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9443 if (parseOptionalFFlags(FFlags))
9447 if (parseOptionalCalls(Calls))
9451 if (parseOptionalTypeIdInfo(TypeIdInfo))
9455 if (parseOptionalRefs(Refs))
9459 if (parseOptionalParamAccesses(ParamAccesses))
9463 if (parseOptionalAllocs(Allocs))
9467 if (parseOptionalCallsites(Callsites))
9471 return error(Lex.
getLoc(),
"expected optional function summary field");
9478 auto FS = std::make_unique<FunctionSummary>(
9479 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9485 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9487 FS->setModulePath(ModulePath);
9489 return addGlobalValueToIndex(
Name, GUID,
9491 std::move(FS), Loc);
9507 false,
false,
false,
9517 parseModuleReference(ModulePath) ||
9518 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9520 parseGVarFlags(GVarFlags))
9527 if (parseOptionalVTableFuncs(VTableFuncs))
9531 if (parseOptionalRefs(Refs))
9535 return error(Lex.
getLoc(),
"expected optional variable summary field");
9543 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9545 GS->setModulePath(ModulePath);
9546 GS->setVTableFuncs(std::move(VTableFuncs));
9548 return addGlobalValueToIndex(
Name, GUID,
9550 std::move(GS), Loc);
9566 false,
false,
false,
9570 parseModuleReference(ModulePath) ||
9571 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9579 if (parseGVReference(AliaseeVI, GVId))
9585 auto AS = std::make_unique<AliasSummary>(GVFlags);
9587 AS->setModulePath(ModulePath);
9591 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9593 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9594 assert(Summary &&
"Aliasee must be a definition");
9595 AS->setAliasee(AliaseeVI, Summary);
9598 return addGlobalValueToIndex(
Name, GUID,
9600 std::move(AS), Loc);
9605bool LLParser::parseFlag(
unsigned &Val) {
9607 return tokError(
"expected integer");
9628 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9637 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9643 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9649 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9655 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9661 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9667 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9673 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9679 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9685 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9691 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9696 return error(Lex.
getLoc(),
"expected function flag type");
9711bool LLParser::parseOptionalCalls(
9716 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9720 IdToIndexMapType IdToIndexMap;
9731 if (parseGVReference(VI, GVId))
9736 unsigned HasTailCall =
false;
9743 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9748 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9753 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9757 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9761 return tokError(
"Expected only one of hotness or relbf");
9766 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
9776 for (
auto I : IdToIndexMap) {
9777 auto &Infos = ForwardRefValueInfos[
I.first];
9778 for (
auto P :
I.second) {
9780 "Forward referenced ValueInfo expected to be empty");
9781 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9798 case lltok::kw_cold:
9811 return error(Lex.
getLoc(),
"invalid call edge hotness");
9820bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9824 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9828 IdToIndexMapType IdToIndexMap;
9832 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9839 if (parseGVReference(VI, GVId))
9852 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9853 VTableFuncs.push_back({
VI,
Offset});
9855 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9861 for (
auto I : IdToIndexMap) {
9862 auto &Infos = ForwardRefValueInfos[
I.first];
9863 for (
auto P :
I.second) {
9865 "Forward referenced ValueInfo expected to be empty");
9866 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9870 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9877bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9879 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9888 auto ParseAPSInt = [&](
APSInt &Val) {
9890 return tokError(
"expected integer");
9893 Val.setIsSigned(
true);
9916 IdLocListType &IdLocList) {
9925 if (parseGVReference(VI, GVId))
9929 IdLocList.emplace_back(GVId, Loc);
9932 parseParamNo(
Call.ParamNo) ||
9934 parseParamAccessOffset(
Call.Offsets))
9947 IdLocListType &IdLocList) {
9949 parseParamNo(
Param.ParamNo) ||
9951 parseParamAccessOffset(
Param.Use))
9961 if (parseParamAccessCall(Call, IdLocList))
9963 Param.Calls.push_back(Call);
9978bool LLParser::parseOptionalParamAccesses(
9979 std::vector<FunctionSummary::ParamAccess> &Params) {
9987 IdLocListType VContexts;
9988 size_t CallsNum = 0;
9991 if (parseParamAccess(ParamAccess, VContexts))
9993 CallsNum += ParamAccess.
Calls.size();
9994 assert(VContexts.size() == CallsNum);
9996 Params.emplace_back(std::move(ParamAccess));
10004 IdLocListType::const_iterator ItContext = VContexts.begin();
10005 for (
auto &PA : Params) {
10006 for (
auto &
C : PA.Calls) {
10008 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10009 ItContext->second);
10013 assert(ItContext == VContexts.end());
10024 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10028 struct ValueContext {
10033 std::vector<ValueContext> VContexts;
10038 if (parseGVReference(
VC.VI,
VC.GVId))
10040 VContexts.push_back(VC);
10046 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10047 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10050 IdToIndexMapType IdToIndexMap;
10051 for (
auto &VC : VContexts) {
10056 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10062 for (
auto I : IdToIndexMap) {
10063 auto &Infos = ForwardRefValueInfos[
I.first];
10064 for (
auto P :
I.second) {
10066 "Forward referenced ValueInfo expected to be empty");
10067 Infos.emplace_back(&Refs[
P.first],
P.second);
10081bool LLParser::parseOptionalTypeIdInfo(
10093 if (parseTypeTests(TypeIdInfo.
TypeTests))
10117 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
10121 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10130bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10138 IdToIndexMapType IdToIndexMap;
10147 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10149 }
else if (parseUInt64(GUID))
10151 TypeTests.push_back(GUID);
10156 for (
auto I : IdToIndexMap) {
10157 auto &Ids = ForwardRefTypeIds[
I.first];
10158 for (
auto P :
I.second) {
10159 assert(TypeTests[
P.first] == 0 &&
10160 "Forward referenced type id GUID expected to be 0");
10161 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10165 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10173bool LLParser::parseVFuncIdList(
10174 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10182 IdToIndexMapType IdToIndexMap;
10185 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10187 VFuncIdList.push_back(VFuncId);
10195 for (
auto I : IdToIndexMap) {
10196 auto &Ids = ForwardRefTypeIds[
I.first];
10197 for (
auto P :
I.second) {
10198 assert(VFuncIdList[
P.first].GUID == 0 &&
10199 "Forward referenced type id GUID expected to be 0");
10200 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10209bool LLParser::parseConstVCallList(
10211 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10219 IdToIndexMapType IdToIndexMap;
10222 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10224 ConstVCallList.push_back(ConstVCall);
10232 for (
auto I : IdToIndexMap) {
10233 auto &Ids = ForwardRefTypeIds[
I.first];
10234 for (
auto P :
I.second) {
10235 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10236 "Forward referenced type id GUID expected to be 0");
10237 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10247 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10249 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10253 if (parseArgs(ConstVCall.
Args))
10266 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10281 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
10283 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10285 parseUInt64(VFuncId.
GUID))
10291 parseUInt64(VFuncId.
Offset) ||
10320 assert(HasLinkage &&
"Linkage not optional in summary entry");
10327 parseOptionalVisibility(Flag);
10332 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10338 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10344 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10350 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10359 if (parseOptionalImportType(Lex.
getKind(), IK))
10361 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10365 return error(Lex.
getLoc(),
"expected gv flag type");
10387 auto ParseRest = [
this](
unsigned int &Val) {
10391 return parseFlag(Val);
10397 case lltok::kw_readonly:
10398 if (ParseRest(Flag))
10402 case lltok::kw_writeonly:
10403 if (ParseRest(Flag))
10408 if (ParseRest(Flag))
10413 if (ParseRest(Flag))
10418 return error(Lex.
getLoc(),
"expected gvar flag type");
10426bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10434 auto I = ModuleIdMap.find(ModuleID);
10436 assert(
I != ModuleIdMap.end());
10437 ModulePath =
I->second;
10443bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10446 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10452 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10454 VI = NumberedValueInfos[GVId];
10471bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10475 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10490 if (parseAllocType(V))
10495 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10499 std::vector<MIBInfo> MIBs;
10500 if (parseMemProfs(MIBs))
10503 Allocs.push_back({Versions, MIBs});
10520bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10524 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10530 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10539 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10548 if (parseUInt64(StackId))
10578 case lltok::kw_cold:
10581 case lltok::kw_hot:
10585 return error(Lex.
getLoc(),
"invalid alloc type");
10598bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10602 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10606 IdToIndexMapType IdToIndexMap;
10609 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10618 if (parseGVReference(VI, GVId))
10622 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10631 if (parseUInt32(V))
10637 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10646 if (parseUInt64(StackId))
10658 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10659 Callsites.push_back({
VI, Clones, StackIdIndices});
10667 for (
auto I : IdToIndexMap) {
10668 auto &Infos = ForwardRefValueInfos[
I.first];
10669 for (
auto P :
I.second) {
10671 "Forward referenced ValueInfo expected to be empty");
10672 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10676 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...
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
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)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
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.
@ USubCond
Subtract only if no unsigned overflow.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ 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=Twine(), InsertPosition InsertBefore=nullptr)
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, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
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, InsertPosition InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static 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 * 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 * 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 Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
This is the shared class of boolean and integer constants.
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)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
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, Metadata *Specification, uint32_t NumExtraInhabitants, 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 LayoutString)
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)
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)
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
Generic tagged DWARF-like metadata node.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
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, InsertPosition InsertBefore=nullptr)
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 InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
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 InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
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.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
unsigned getUIntVal() const
lltok::Kind getKind() const
const std::string & getStrVal() const
const APSInt & getAPSIntVal() const
void setIgnoreColonInIdentifiers(bool val)
const APFloat & getAPFloatVal() const
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
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="", InsertPosition InsertBefore=nullptr)
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="", InsertPosition InsertBefore=nullptr)
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, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
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.
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 reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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.
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.
Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
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.
bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
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.
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=Twine(), InsertPosition InsertBefore=nullptr)
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 VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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.
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.
@ 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...
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
initializer< Ty > init(const Ty &Val)
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
@ kw_aarch64_sme_preservemost_from_x1
@ 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.
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
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.
const char * toString(DWARFSectionKind Kind)
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.
Helper struct shared between Function Specialization and SCCP Solver.
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::@40 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.