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);
1647 case Attribute::Captures:
1648 return parseCapturesAttr(
B);
1650 B.addAttribute(Attr);
1658 case lltok::kw_readnone:
1661 case lltok::kw_readonly:
1664 case lltok::kw_writeonly:
1683bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1684 std::vector<unsigned> &FwdRefAttrGrps,
1685 bool InAttrGrp, LocTy &BuiltinLoc) {
1686 bool HaveError =
false;
1697 if (parseStringAttribute(
B))
1709 "cannot have an attribute group reference in an attribute group");
1719 if (Token == lltok::kw_builtin)
1731 return error(Lex.
getLoc(),
"unterminated attribute group");
1734 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1741 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1745 B.addMemoryAttr(ME);
1759 PTy->getAddressSpace());
1768 error(Loc,
"'" +
Name +
"' is not a basic block");
1770 error(Loc,
"'" +
Name +
"' defined with type '" +
1783 error(Loc,
"global variable reference must have pointer type");
1789 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1794 auto I = ForwardRefVals.find(
Name);
1795 if (
I != ForwardRefVals.end())
1796 Val =
I->second.first;
1801 return cast_or_null<GlobalValue>(
1802 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1806 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1813 error(Loc,
"global variable reference must have pointer type");
1822 auto I = ForwardRefValIDs.find(
ID);
1823 if (
I != ForwardRefValIDs.end())
1824 Val =
I->second.first;
1829 return cast_or_null<GlobalValue>(
1830 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1834 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1842Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1846 if (
I != ComdatSymTab.
end())
1851 ForwardRefComdats[
Name] = Loc;
1861bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1863 return tokError(ErrMsg);
1870bool LLParser::parseStringConstant(std::string &Result) {
1872 return tokError(
"expected string constant");
1880bool LLParser::parseUInt32(
uint32_t &Val) {
1882 return tokError(
"expected integer");
1884 if (Val64 !=
unsigned(Val64))
1885 return tokError(
"expected 32-bit integer (too large)");
1893bool LLParser::parseUInt64(
uint64_t &Val) {
1895 return tokError(
"expected integer");
1908 return tokError(
"expected localdynamic, initialexec or localexec");
1936 return parseTLSModel(TLM) ||
1937 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1945bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1946 AddrSpace = DefaultAS;
1950 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1953 if (AddrSpaceStr ==
"A") {
1954 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1955 }
else if (AddrSpaceStr ==
"G") {
1956 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1957 }
else if (AddrSpaceStr ==
"P") {
1958 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1960 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1966 return tokError(
"expected integer or string constant");
1968 if (parseUInt32(AddrSpace))
1970 if (!isUInt<24>(AddrSpace))
1971 return error(Loc,
"invalid address space, must be a 24-bit integer");
1975 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1976 ParseAddrspaceValue(AddrSpace) ||
1987 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1989 B.addAttribute(Attr, Val);
1994bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1995 bool HaveError =
false;
2002 if (parseStringAttribute(
B))
2012 if (parseEnumAttribute(Attr,
B,
false))
2016 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2018 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2066bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2067 unsigned &Visibility,
2068 unsigned &DLLStorageClass,
bool &DSOLocal) {
2072 parseOptionalDSOLocal(DSOLocal);
2073 parseOptionalVisibility(Visibility);
2074 parseOptionalDLLStorageClass(DLLStorageClass);
2077 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2083void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2105void LLParser::parseOptionalVisibility(
unsigned &Res) {
2123bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2127 return tokError(
"unknown import kind. Expect definition or declaration.");
2142void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2212bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2288 return parseUInt32(
CC);
2298bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2305 return parseMDNode(MD);
2310bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2313 return tokError(
"expected metadata after comma");
2317 if (parseMetadataAttachment(MDK,
N))
2320 if (MDK == LLVMContext::MD_DIAssignID)
2321 TempDIAssignIDAttachments[
N].push_back(&Inst);
2325 if (MDK == LLVMContext::MD_tbaa)
2326 InstsWithTBAATag.push_back(&Inst);
2335bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2338 if (parseMetadataAttachment(MDK,
N))
2347bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2349 if (parseGlobalObjectMetadataAttachment(
F))
2357bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2358 Alignment = std::nullopt;
2359 if (!EatIfPresent(lltok::kw_align))
2365 bool HaveParens =
false;
2371 if (parseUInt64(
Value))
2375 return error(ParenLoc,
"expected ')'");
2378 return error(AlignLoc,
"alignment is not a power of two");
2380 return error(AlignLoc,
"huge alignments are not supported yet");
2391 auto ErrMsg =
"expected global code model string";
2392 if (StrVal ==
"tiny")
2394 else if (StrVal ==
"small")
2396 else if (StrVal ==
"kernel")
2398 else if (StrVal ==
"medium")
2400 else if (StrVal ==
"large")
2403 return tokError(ErrMsg);
2414bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2416 assert((AttrKind == lltok::kw_dereferenceable ||
2417 AttrKind == lltok::kw_dereferenceable_or_null) &&
2421 if (!EatIfPresent(AttrKind))
2425 return error(ParenLoc,
"expected '('");
2427 if (parseUInt64(Bytes))
2431 return error(ParenLoc,
"expected ')'");
2433 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2437bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2448 return error(KindLoc,
"expected unwind table kind");
2457 return error(ParenLoc,
"expected '('");
2460 if (parseStringConstant(Arg))
2461 return error(KindLoc,
"expected allockind value");
2465 }
else if (
A ==
"realloc") {
2467 }
else if (
A ==
"free") {
2469 }
else if (
A ==
"uninitialized") {
2471 }
else if (
A ==
"zeroed") {
2473 }
else if (
A ==
"aligned") {
2476 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2481 return error(ParenLoc,
"expected ')'");
2483 return error(KindLoc,
"expected allockind value");
2494 return std::nullopt;
2509 return std::nullopt;
2513std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2523 tokError(
"expected '('");
2524 return std::nullopt;
2527 bool SeenLoc =
false;
2533 tokError(
"expected ':' after location");
2534 return std::nullopt;
2541 tokError(
"expected memory location (argmem, inaccessiblemem) "
2542 "or access kind (none, read, write, readwrite)");
2544 tokError(
"expected access kind (none, read, write, readwrite)");
2545 return std::nullopt;
2554 tokError(
"default access kind must be specified first");
2555 return std::nullopt;
2564 tokError(
"unterminated memory attribute");
2565 return std::nullopt;
2607unsigned LLParser::parseNoFPClassAttr() {
2612 tokError(
"expected '('");
2619 if (TestMask != 0) {
2623 !parseUInt64(
Value)) {
2625 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2636 error(Lex.
getLoc(),
"expected nofpclass test mask");
2654bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2655 bool &AteExtraComma) {
2656 AteExtraComma =
false;
2660 AteExtraComma =
true;
2664 if (Lex.
getKind() != lltok::kw_align)
2665 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2667 if (parseOptionalAlignment(Alignment))
2680bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2681 bool &AteExtraComma) {
2682 AteExtraComma =
false;
2686 AteExtraComma =
true;
2692 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2694 if (parseOptionalAddrSpace(AddrSpace))
2701bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2702 std::optional<unsigned> &HowManyArg) {
2705 auto StartParen = Lex.
getLoc();
2707 return error(StartParen,
"expected '('");
2709 if (parseUInt32(BaseSizeArg))
2713 auto HowManyAt = Lex.
getLoc();
2715 if (parseUInt32(HowMany))
2717 if (HowMany == BaseSizeArg)
2718 return error(HowManyAt,
2719 "'allocsize' indices can't refer to the same parameter");
2720 HowManyArg = HowMany;
2722 HowManyArg = std::nullopt;
2724 auto EndParen = Lex.
getLoc();
2726 return error(EndParen,
"expected ')'");
2730bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2731 unsigned &MaxValue) {
2734 auto StartParen = Lex.
getLoc();
2736 return error(StartParen,
"expected '('");
2738 if (parseUInt32(MinValue))
2742 if (parseUInt32(MaxValue))
2745 MaxValue = MinValue;
2747 auto EndParen = Lex.
getLoc();
2749 return error(EndParen,
"expected ')'");
2758bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2763 return parseScope(SSID) || parseOrdering(Ordering);
2773 auto StartParenAt = Lex.
getLoc();
2775 return error(StartParenAt,
"Expected '(' in syncscope");
2778 auto SSNAt = Lex.
getLoc();
2779 if (parseStringConstant(SSN))
2780 return error(SSNAt,
"Expected synchronization scope name");
2782 auto EndParenAt = Lex.
getLoc();
2784 return error(EndParenAt,
"Expected ')' in syncscope");
2799 return tokError(
"Expected ordering on atomic instruction");
2818bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2820 if (!EatIfPresent(lltok::kw_alignstack))
2824 return error(ParenLoc,
"expected '('");
2826 if (parseUInt32(Alignment))
2830 return error(ParenLoc,
"expected ')'");
2832 return error(AlignLoc,
"stack alignment is not a power of two");
2846 bool &AteExtraComma) {
2847 AteExtraComma =
false;
2850 return tokError(
"expected ',' as start of index list");
2854 if (Indices.
empty())
2855 return tokError(
"expected index");
2856 AteExtraComma =
true;
2860 if (parseUInt32(
Idx))
2873bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2877 return tokError(Msg);
2886 if (
Result->isPointerTy()) {
2888 if (parseOptionalAddrSpace(AddrSpace))
2894 return tokError(
"ptr* is invalid - use ptr instead");
2905 if (parseTargetExtType(Result))
2911 if (parseAnonStructType(Result,
false))
2917 if (parseArrayVectorType(Result,
false))
2924 if (parseAnonStructType(Result,
true) ||
2925 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2927 }
else if (parseArrayVectorType(Result,
true))
2966 if (!AllowVoid &&
Result->isVoidTy())
2967 return error(TypeLoc,
"void type only allowed for function results");
2973 return tokError(
"basic block pointers are invalid");
2975 return tokError(
"pointers to void are invalid - use i8* instead");
2977 return tokError(
"pointer to this type is invalid");
2985 return tokError(
"basic block pointers are invalid");
2987 return tokError(
"pointers to void are invalid; use i8* instead");
2989 return tokError(
"pointer to this type is invalid");
2991 if (parseOptionalAddrSpace(AddrSpace) ||
2992 parseToken(
lltok::star,
"expected '*' in address space"))
3001 if (parseFunctionType(Result))
3014 PerFunctionState &PFS,
bool IsMustTailCall,
3015 bool InVarArgsFunc) {
3021 if (!ArgList.
empty() &&
3022 parseToken(
lltok::comma,
"expected ',' in argument list"))
3027 const char *Msg =
"unexpected ellipsis in argument list for ";
3028 if (!IsMustTailCall)
3029 return tokError(
Twine(Msg) +
"non-musttail call");
3031 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3033 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3038 Type *ArgTy =
nullptr;
3040 if (parseType(ArgTy, ArgLoc))
3046 if (parseMetadataAsValue(V, PFS))
3050 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3057 if (IsMustTailCall && InVarArgsFunc)
3058 return tokError(
"expected '...' at end of argument list for musttail call "
3059 "in varargs function");
3070 if (!EatIfPresent(AttrToken))
3079 B.addTypeAttr(AttrKind, Ty);
3095 return tokError(
"expected integer");
3098 "integer is too large for the bit width of specified type");
3104 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3107 return error(TyLoc,
"the range must have integer type!");
3115 return tokError(
"the range represent the empty set but limits aren't 0!");
3129 auto ParseAPSInt = [&](
APInt &Val) {
3131 return tokError(
"expected integer");
3152 return tokError(
"the range should not represent the full or empty set!");
3164 if (!CRLOrNull.has_value())
3165 return tokError(
"Invalid (unordered or overlapping) range list");
3166 B.addInitializesAttr(*CRLOrNull);
3172 std::optional<CaptureComponents>
Ret;
3184 bool SeenComponent =
false;
3190 return tokError(
"duplicate 'ret' location");
3193 SeenComponent =
false;
3198 return tokError(
"cannot use 'none' with other component");
3202 return tokError(
"cannot use 'none' with other component");
3213 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3214 "'provenance' or 'read_provenance'");
3217 SeenComponent =
true;
3238bool LLParser::parseOptionalOperandBundles(
3246 if (!BundleList.
empty() &&
3247 parseToken(
lltok::comma,
"expected ',' in input list"))
3251 if (parseStringConstant(
Tag))
3254 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3257 std::vector<Value *> Inputs;
3260 if (!Inputs.empty() &&
3261 parseToken(
lltok::comma,
"expected ',' in input list"))
3265 Value *Input =
nullptr;
3269 if (parseMetadataAsValue(Input, PFS))
3271 }
else if (parseValue(Ty, Input, PFS)) {
3274 Inputs.push_back(Input);
3282 if (BundleList.
empty())
3283 return error(BeginLoc,
"operand bundle set must not be empty");
3290 unsigned NextID,
unsigned ID) {
3292 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3293 Twine(NextID) +
"' or greater");
3310 unsigned CurValID = 0;
3325 Type *ArgTy =
nullptr;
3327 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3331 return error(TypeLoc,
"argument can not have void type");
3341 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3348 CurValID = ArgID + 1;
3352 return error(TypeLoc,
"invalid type for function argument");
3360 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3365bool LLParser::parseFunctionType(
Type *&Result) {
3369 return tokError(
"invalid function return type");
3374 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3378 for (
const ArgInfo &Arg : ArgList) {
3379 if (!Arg.Name.empty())
3380 return error(Arg.Loc,
"argument name invalid in function type");
3381 if (Arg.Attrs.hasAttributes())
3382 return error(Arg.Loc,
"argument attributes invalid in function type");
3386 for (
const ArgInfo &Arg : ArgList)
3395bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3397 if (parseStructBody(Elts))
3406 std::pair<Type *, LocTy> &Entry,
3410 return error(TypeLoc,
"redefinition of type");
3421 ResultTy =
Entry.first;
3433 return error(TypeLoc,
"forward references to non-struct type");
3437 return parseArrayVectorType(ResultTy,
true);
3438 return parseType(ResultTy);
3451 if (parseStructBody(Body) ||
3452 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3456 return tokError(
toString(std::move(E)));
3483 return error(EltTyLoc,
"invalid element type for struct");
3491 return error(EltTyLoc,
"invalid element type for struct");
3496 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3505bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3506 bool Scalable =
false;
3510 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3518 return tokError(
"expected number in address space");
3524 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3528 Type *EltTy =
nullptr;
3529 if (parseType(EltTy))
3533 "expected end of sequential type"))
3538 return error(SizeLoc,
"zero element vector is illegal");
3540 return error(SizeLoc,
"size too large for vector");
3542 return error(TypeLoc,
"invalid vector element type");
3546 return error(TypeLoc,
"invalid array element type");
3563bool LLParser::parseTargetExtType(
Type *&Result) {
3568 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3569 parseStringConstant(TypeName))
3577 bool SeenInt =
false;
3584 if (parseUInt32(IntVal))
3587 }
else if (SeenInt) {
3590 return tokError(
"expected uint32 param");
3593 if (parseType(TypeParam,
true))
3599 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3604 if (
auto E = TTy.takeError())
3605 return tokError(
toString(std::move(E)));
3618 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3621 auto It = UnnamedArgNums.
begin();
3624 unsigned ArgNum = *It++;
3625 NumberedVals.add(ArgNum, &
A);
3630LLParser::PerFunctionState::~PerFunctionState() {
3633 for (
const auto &
P : ForwardRefVals) {
3634 if (isa<BasicBlock>(
P.second.first))
3636 P.second.first->replaceAllUsesWith(
3638 P.second.first->deleteValue();
3641 for (
const auto &
P : ForwardRefValIDs) {
3642 if (isa<BasicBlock>(
P.second.first))
3644 P.second.first->replaceAllUsesWith(
3646 P.second.first->deleteValue();
3650bool LLParser::PerFunctionState::finishFunction() {
3651 if (!ForwardRefVals.empty())
3652 return P.error(ForwardRefVals.begin()->second.second,
3653 "use of undefined value '%" + ForwardRefVals.begin()->first +
3655 if (!ForwardRefValIDs.empty())
3656 return P.error(ForwardRefValIDs.begin()->second.second,
3657 "use of undefined value '%" +
3658 Twine(ForwardRefValIDs.begin()->first) +
"'");
3665Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3668 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3673 auto I = ForwardRefVals.find(
Name);
3674 if (
I != ForwardRefVals.end())
3675 Val =
I->second.first;
3680 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3684 P.error(Loc,
"invalid use of a non-first-class type");
3696 P.error(Loc,
"name is too long which can result in name collisions, "
3697 "consider making the name shorter or "
3698 "increasing -non-global-value-max-name-size");
3702 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3706Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3708 Value *Val = NumberedVals.get(
ID);
3713 auto I = ForwardRefValIDs.find(
ID);
3714 if (
I != ForwardRefValIDs.end())
3715 Val =
I->second.first;
3720 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3723 P.error(Loc,
"invalid use of a non-first-class type");
3735 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3741bool LLParser::PerFunctionState::setInstName(
int NameID,
3742 const std::string &NameStr,
3746 if (NameID != -1 || !NameStr.empty())
3747 return P.error(NameLoc,
"instructions returning void cannot have a name");
3753 if (NameStr.empty()) {
3756 NameID = NumberedVals.getNext();
3758 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3762 auto FI = ForwardRefValIDs.find(NameID);
3763 if (FI != ForwardRefValIDs.end()) {
3766 return P.error(NameLoc,
"instruction forward referenced with type '" +
3770 Sentinel->replaceAllUsesWith(Inst);
3772 ForwardRefValIDs.erase(FI);
3775 NumberedVals.add(NameID, Inst);
3780 auto FI = ForwardRefVals.find(NameStr);
3781 if (FI != ForwardRefVals.end()) {
3784 return P.error(NameLoc,
"instruction forward referenced with type '" +
3788 Sentinel->replaceAllUsesWith(Inst);
3790 ForwardRefVals.erase(FI);
3796 if (Inst->
getName() != NameStr)
3797 return P.error(NameLoc,
"multiple definition of local value named '" +
3804BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3806 return dyn_cast_or_null<BasicBlock>(
3810BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3811 return dyn_cast_or_null<BasicBlock>(
3818BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3819 int NameID, LocTy Loc) {
3823 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3826 NameID = NumberedVals.getNext();
3828 BB = getBB(NameID, Loc);
3830 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3834 BB = getBB(
Name, Loc);
3836 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3847 ForwardRefValIDs.erase(NameID);
3848 NumberedVals.add(NameID, BB);
3851 ForwardRefVals.erase(
Name);
3868bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3872 return tokError(
"expected value token");
3915 if (parseGlobalValueVector(Elts) ||
3916 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3919 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3920 ID.UIntVal = Elts.
size();
3921 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3922 Elts.
size() *
sizeof(Elts[0]));
3934 if (parseGlobalValueVector(Elts) ||
3936 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3940 if (isPackedStruct) {
3941 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3942 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3943 Elts.
size() *
sizeof(Elts[0]));
3944 ID.UIntVal = Elts.
size();
3950 return error(
ID.Loc,
"constant vector must not be empty");
3952 if (!Elts[0]->
getType()->isIntegerTy() &&
3953 !Elts[0]->
getType()->isFloatingPointTy() &&
3957 "vector elements must have integer, pointer or floating point type");
3960 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3962 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3963 " is not of type '" +
3974 if (parseGlobalValueVector(Elts) ||
3986 if (!Elts[0]->
getType()->isFirstClassType())
3987 return error(FirstEltLoc,
"invalid array element type: " +
3993 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3995 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3996 " is not of type '" +
4016 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4019 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4022 parseStringConstant(
ID.StrVal) ||
4023 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4028 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
4039 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4040 parseValID(Fn, PFS) ||
4042 "expected comma in block address expression") ||
4043 parseValID(Label, PFS) ||
4044 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4048 return error(Fn.
Loc,
"expected function name in blockaddress");
4050 return error(
Label.Loc,
"expected basic block name in blockaddress");
4055 GV = NumberedVals.get(Fn.
UIntVal);
4056 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4057 GV =
M->getNamedValue(Fn.
StrVal);
4062 if (!isa<Function>(GV))
4063 return error(Fn.
Loc,
"expected function name in blockaddress");
4064 F = cast<Function>(GV);
4065 if (
F->isDeclaration())
4066 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4072 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4080 "type of blockaddress must be a pointer and not '" +
4085 FwdDeclAS = PFS->getFunction().getAddressSpace();
4094 ID.ConstantVal = FwdRef;
4102 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4104 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4106 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4108 return error(
Label.Loc,
"referenced value is not a basic block");
4111 return error(
Label.Loc,
"cannot take address of numeric label after "
4112 "the function is defined");
4113 BB = dyn_cast_or_null<BasicBlock>(
4114 F->getValueSymbolTable()->lookup(
Label.StrVal));
4116 return error(
Label.Loc,
"referenced value is not a basic block");
4130 if (parseValID(Fn, PFS))
4135 "expected global value name in dso_local_equivalent");
4140 GV = NumberedVals.get(Fn.
UIntVal);
4141 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4142 GV =
M->getNamedValue(Fn.
StrVal);
4148 ? ForwardRefDSOLocalEquivalentIDs
4149 : ForwardRefDSOLocalEquivalentNames;
4157 ID.ConstantVal = FwdRef;
4163 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4164 "in dso_local_equivalent");
4175 if (parseValID(
ID, PFS))
4179 return error(
ID.Loc,
"expected global value name in no_cfi");
4190 Constant *Disc =
nullptr, *AddrDisc =
nullptr;
4193 "expected '(' in constant ptrauth expression") ||
4194 parseGlobalTypeAndValue(
Ptr) ||
4196 "expected comma in constant ptrauth expression") ||
4197 parseGlobalTypeAndValue(Key))
4201 if (parseGlobalTypeAndValue(Disc) ||
4202 (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4205 "expected ')' in constant ptrauth expression"))
4208 if (!
Ptr->getType()->isPointerTy())
4209 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4211 auto *KeyC = dyn_cast<ConstantInt>(Key);
4212 if (!KeyC || KeyC->getBitWidth() != 32)
4213 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4217 DiscC = dyn_cast<ConstantInt>(Disc);
4221 "constant ptrauth integer discriminator must be i64 constant");
4227 if (!AddrDisc->getType()->isPointerTy())
4229 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4245 Type *DestTy =
nullptr;
4248 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4249 parseGlobalTypeAndValue(SrcVal) ||
4250 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4251 parseType(DestTy) ||
4252 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4255 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4264 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4266 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4268 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4270 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4272 return error(
ID.Loc,
"urem constexprs are no longer supported");
4274 return error(
ID.Loc,
"srem constexprs are no longer supported");
4276 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4278 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4280 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4282 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4284 return error(
ID.Loc,
"frem constexprs are no longer supported");
4286 return error(
ID.Loc,
"and constexprs are no longer supported");
4288 return error(
ID.Loc,
"or constexprs are no longer supported");
4290 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4292 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4294 return error(
ID.Loc,
"shl constexprs are no longer supported");
4296 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4298 return error(
ID.Loc,
"select constexprs are no longer supported");
4300 return error(
ID.Loc,
"zext constexprs are no longer supported");
4302 return error(
ID.Loc,
"sext constexprs are no longer supported");
4304 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4306 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4308 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4310 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4312 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4314 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4316 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4318 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4330 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4331 Opc == Instruction::Mul) {
4340 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4341 parseGlobalTypeAndValue(Val0) ||
4342 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4343 parseGlobalTypeAndValue(Val1) ||
4344 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4347 return error(
ID.Loc,
"operands of constexpr must have same type");
4351 "constexpr requires integer or integer vector operands");
4362 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4365 if (parseGlobalTypeAndValue(
C))
4367 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4382 bool HasInRange =
false;
4388 if (Opc == Instruction::GetElementPtr) {
4404 return tokError(
"expected integer");
4410 return tokError(
"expected integer");
4419 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4422 if (Opc == Instruction::GetElementPtr) {
4423 if (parseType(Ty) ||
4424 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4428 if (parseGlobalValueVector(Elts) ||
4432 if (Opc == Instruction::GetElementPtr) {
4433 if (Elts.
size() == 0 ||
4434 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4435 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4438 std::optional<ConstantRange>
InRange;
4440 unsigned IndexWidth =
4441 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4442 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4443 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4444 if (InRangeStart.
sge(InRangeEnd))
4445 return error(
ID.Loc,
"expected end to be larger than start");
4451 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4458 return error(
ID.Loc,
"getelementptr index must be an integer");
4459 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4460 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4461 if (GEPWidth && (ValNumEl != GEPWidth))
4464 "getelementptr vector index has a wrong number of elements");
4467 GEPWidth = ValNumEl;
4472 if (!Indices.empty() && !Ty->
isSized(&Visited))
4473 return error(
ID.Loc,
"base element of getelementptr must be sized");
4476 return error(
ID.Loc,
"invalid getelementptr indices");
4480 }
else if (Opc == Instruction::ShuffleVector) {
4481 if (Elts.
size() != 3)
4482 return error(
ID.Loc,
"expected three operands to shufflevector");
4484 return error(
ID.Loc,
"invalid operands to shufflevector");
4488 }
else if (Opc == Instruction::ExtractElement) {
4489 if (Elts.
size() != 2)
4490 return error(
ID.Loc,
"expected two operands to extractelement");
4492 return error(
ID.Loc,
"invalid extractelement operands");
4495 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4496 if (Elts.
size() != 3)
4497 return error(
ID.Loc,
"expected three operands to insertelement");
4499 return error(
ID.Loc,
"invalid insertelement operands");
4518 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4519 convertValIDToValue(Ty,
ID, V,
nullptr);
4520 if (V && !(
C = dyn_cast<Constant>(V)))
4521 return error(
ID.Loc,
"global values must be constants");
4525bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4527 return parseType(Ty) || parseGlobalValue(Ty, V);
4539 return tokError(
"expected comdat variable");
4542 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4545 if (GlobalName.
empty())
4546 return tokError(
"comdat cannot be unnamed");
4547 C = getComdat(std::string(GlobalName), KwLoc);
4570 if (parseGlobalTypeAndValue(
C))
4578bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4580 if (parseMDNodeVector(Elts))
4591bool LLParser::parseMDNode(
MDNode *&
N) {
4593 return parseSpecializedMDNode(
N);
4595 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4598bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4601 return parseMDTuple(
N);
4604 return parseMDNodeID(
N);
4610template <
class FieldTy>
struct MDFieldImpl {
4611 typedef MDFieldImpl ImplTy;
4615 void assign(FieldTy Val) {
4617 this->Val = std::move(Val);
4620 explicit MDFieldImpl(FieldTy
Default)
4628template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4629 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4640 void assign(FieldTypeA
A) {
4642 this->A = std::move(
A);
4646 void assign(FieldTypeB
B) {
4648 this->B = std::move(
B);
4652 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4654 WhatIs(IsInvalid) {}
4657struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4664struct LineField :
public MDUnsignedField {
4665 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4668struct ColumnField :
public MDUnsignedField {
4669 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4672struct DwarfTagField :
public MDUnsignedField {
4678struct DwarfMacinfoTypeField :
public MDUnsignedField {
4684struct DwarfAttEncodingField :
public MDUnsignedField {
4685 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4688struct DwarfVirtualityField :
public MDUnsignedField {
4692struct DwarfLangField :
public MDUnsignedField {
4696struct DwarfCCField :
public MDUnsignedField {
4697 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4700struct EmissionKindField :
public MDUnsignedField {
4701 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4704struct NameTableKindField :
public MDUnsignedField {
4705 NameTableKindField()
4708 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4711struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4712 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4715struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4716 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4719struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4720 MDAPSIntField() : ImplTy(
APSInt()) {}
4723struct MDSignedField :
public MDFieldImpl<int64_t> {
4727 MDSignedField(int64_t
Default = 0)
4729 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4733struct MDBoolField :
public MDFieldImpl<bool> {
4737struct MDField :
public MDFieldImpl<Metadata *> {
4740 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4743struct MDStringField :
public MDFieldImpl<MDString *> {
4745 MDStringField(
bool AllowEmpty =
true)
4746 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4749struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4753struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4757struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4758 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4759 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4761 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4762 bool AllowNull =
true)
4763 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4765 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4766 bool isMDField()
const {
return WhatIs == IsTypeB; }
4767 int64_t getMDSignedValue()
const {
4768 assert(isMDSignedField() &&
"Wrong field type");
4771 Metadata *getMDFieldValue()
const {
4772 assert(isMDField() &&
"Wrong field type");
4784 return tokError(
"expected integer");
4793 MDUnsignedField &Result) {
4795 return tokError(
"expected unsigned integer");
4798 if (U.ugt(Result.Max))
4799 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4801 Result.assign(U.getZExtValue());
4802 assert(Result.Val <= Result.Max &&
"Expected value in range");
4809 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4813 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4819 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4822 return tokError(
"expected DWARF tag");
4826 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4827 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4836 DwarfMacinfoTypeField &Result) {
4838 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4841 return tokError(
"expected DWARF macinfo type");
4845 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4847 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4849 Result.assign(Macinfo);
4856 DwarfVirtualityField &Result) {
4858 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4861 return tokError(
"expected DWARF virtuality code");
4865 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4867 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4868 Result.assign(Virtuality);
4876 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4879 return tokError(
"expected DWARF language");
4883 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4885 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4886 Result.assign(Lang);
4894 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4897 return tokError(
"expected DWARF calling convention");
4901 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4903 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4911 EmissionKindField &Result) {
4913 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4916 return tokError(
"expected emission kind");
4920 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4922 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4923 Result.assign(*Kind);
4930 NameTableKindField &Result) {
4932 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4935 return tokError(
"expected nameTable kind");
4939 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4941 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4942 Result.assign((
unsigned)*Kind);
4949 DwarfAttEncodingField &Result) {
4951 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4954 return tokError(
"expected DWARF type attribute encoding");
4958 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4960 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4961 Result.assign(Encoding);
4977 bool Res = parseUInt32(TempVal);
4983 return tokError(
"expected debug info flag");
4987 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
5002 Result.assign(Combined);
5017 bool Res = parseUInt32(TempVal);
5023 return tokError(
"expected debug info flag");
5027 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5042 Result.assign(Combined);
5049 return tokError(
"expected signed integer");
5053 return tokError(
"value for '" +
Name +
"' too small, limit is " +
5056 return tokError(
"value for '" +
Name +
"' too large, limit is " +
5058 Result.assign(S.getExtValue());
5059 assert(Result.Val >= Result.Min &&
"Expected value in range");
5060 assert(Result.Val <= Result.Max &&
"Expected value in range");
5069 return tokError(
"expected 'true' or 'false'");
5071 Result.assign(
true);
5074 Result.assign(
false);
5084 if (!Result.AllowNull)
5085 return tokError(
"'" +
Name +
"' cannot be null");
5087 Result.assign(
nullptr);
5092 if (parseMetadata(MD,
nullptr))
5101 MDSignedOrMDField &Result) {
5104 MDSignedField Res = Result.A;
5105 if (!parseMDField(Loc,
Name, Res)) {
5113 MDField Res = Result.B;
5114 if (!parseMDField(Loc,
Name, Res)) {
5126 if (parseStringConstant(S))
5129 if (!Result.AllowEmpty && S.empty())
5130 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
5132 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
5139 if (parseMDNodeVector(MDs))
5142 Result.assign(std::move(MDs));
5148 ChecksumKindField &Result) {
5149 std::optional<DIFile::ChecksumKind> CSKind =
5153 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
5156 Result.assign(*CSKind);
5163template <
class ParserTy>
5164bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5167 return tokError(
"expected field label here");
5176template <
class ParserTy>
5177bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5184 if (parseMDFieldsImplBody(ParseField))
5187 ClosingLoc = Lex.
getLoc();
5191template <
class FieldTy>
5192bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5194 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5198 return parseMDField(Loc,
Name, Result);
5201bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5204#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5205 if (Lex.getStrVal() == #CLASS) \
5206 return parse##CLASS(N, IsDistinct);
5207#include "llvm/IR/Metadata.def"
5209 return tokError(
"expected metadata type");
5212#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5213#define NOP_FIELD(NAME, TYPE, INIT)
5214#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5216 return error(ClosingLoc, "missing required field '" #NAME "'");
5217#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5218 if (Lex.getStrVal() == #NAME) \
5219 return parseMDField(#NAME, NAME);
5220#define PARSE_MD_FIELDS() \
5221 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5224 if (parseMDFieldsImpl( \
5226 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5227 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5232 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5234#define GET_OR_DISTINCT(CLASS, ARGS) \
5235 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5240bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5241#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5242 OPTIONAL(line, LineField, ); \
5243 OPTIONAL(column, ColumnField, ); \
5244 REQUIRED(scope, MDField, ( false)); \
5245 OPTIONAL(inlinedAt, MDField, ); \
5246 OPTIONAL(isImplicitCode, MDBoolField, (false));
5248#undef VISIT_MD_FIELDS
5252 inlinedAt.Val, isImplicitCode.Val));
5258bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5260 return tokError(
"missing 'distinct', required for !DIAssignID()");
5276bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5277#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5278 REQUIRED(tag, DwarfTagField, ); \
5279 OPTIONAL(header, MDStringField, ); \
5280 OPTIONAL(operands, MDFieldList, );
5282#undef VISIT_MD_FIELDS
5285 (Context, tag.Val, header.Val, operands.Val));
5293bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5294#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5295 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5296 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5297 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5298 OPTIONAL(stride, MDSignedOrMDField, );
5300#undef VISIT_MD_FIELDS
5307 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5308 if (Bound.isMDSignedField())
5311 if (Bound.isMDField())
5312 return Bound.getMDFieldValue();
5316 Count = convToMetadata(
count);
5317 LowerBound = convToMetadata(lowerBound);
5319 Stride = convToMetadata(stride);
5322 (Context, Count, LowerBound, UpperBound, Stride));
5330bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5331#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5332 OPTIONAL(count, MDSignedOrMDField, ); \
5333 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5334 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5335 OPTIONAL(stride, MDSignedOrMDField, );
5337#undef VISIT_MD_FIELDS
5339 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5340 if (Bound.isMDSignedField())
5342 Context, {dwarf::DW_OP_consts,
5343 static_cast<uint64_t>(Bound.getMDSignedValue())});
5344 if (Bound.isMDField())
5345 return Bound.getMDFieldValue();
5350 Metadata *LowerBound = ConvToMetadata(lowerBound);
5352 Metadata *Stride = ConvToMetadata(stride);
5355 (Context, Count, LowerBound, UpperBound, Stride));
5362bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5363#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5364 REQUIRED(name, MDStringField, ); \
5365 REQUIRED(value, MDAPSIntField, ); \
5366 OPTIONAL(isUnsigned, MDBoolField, (false));
5368#undef VISIT_MD_FIELDS
5370 if (isUnsigned.Val &&
value.Val.isNegative())
5371 return tokError(
"unsigned enumerator with negative value");
5376 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5388bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5389#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5390 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5391 OPTIONAL(name, MDStringField, ); \
5392 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5393 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5394 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5395 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5396 OPTIONAL(flags, DIFlagField, );
5398#undef VISIT_MD_FIELDS
5401 align.Val, encoding.Val,
5402 num_extra_inhabitants.Val, flags.Val));
5408bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5409#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5410 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5411 OPTIONAL(name, MDStringField, ); \
5412 OPTIONAL(stringLength, MDField, ); \
5413 OPTIONAL(stringLengthExpression, MDField, ); \
5414 OPTIONAL(stringLocationExpression, MDField, ); \
5415 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5416 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5417 OPTIONAL(encoding, DwarfAttEncodingField, );
5419#undef VISIT_MD_FIELDS
5423 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5424 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5437bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5438#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5439 REQUIRED(tag, DwarfTagField, ); \
5440 OPTIONAL(name, MDStringField, ); \
5441 OPTIONAL(file, MDField, ); \
5442 OPTIONAL(line, LineField, ); \
5443 OPTIONAL(scope, MDField, ); \
5444 REQUIRED(baseType, MDField, ); \
5445 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5446 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5447 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5448 OPTIONAL(flags, DIFlagField, ); \
5449 OPTIONAL(extraData, MDField, ); \
5450 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5451 OPTIONAL(annotations, MDField, ); \
5452 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5453 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5454 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5455 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5456 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5458#undef VISIT_MD_FIELDS
5460 std::optional<unsigned> DWARFAddressSpace;
5461 if (dwarfAddressSpace.Val != UINT32_MAX)
5462 DWARFAddressSpace = dwarfAddressSpace.Val;
5463 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5465 PtrAuthData.emplace(
5466 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5467 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5468 ptrAuthAuthenticatesNullValues.Val);
5471 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5472 scope.Val, baseType.Val,
size.Val, align.Val,
5473 offset.Val, DWARFAddressSpace, PtrAuthData,
5474 flags.Val, extraData.Val, annotations.Val));
5478bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5479#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5480 REQUIRED(tag, DwarfTagField, ); \
5481 OPTIONAL(name, MDStringField, ); \
5482 OPTIONAL(file, MDField, ); \
5483 OPTIONAL(line, LineField, ); \
5484 OPTIONAL(scope, MDField, ); \
5485 OPTIONAL(baseType, MDField, ); \
5486 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5487 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5488 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5489 OPTIONAL(flags, DIFlagField, ); \
5490 OPTIONAL(elements, MDField, ); \
5491 OPTIONAL(runtimeLang, DwarfLangField, ); \
5492 OPTIONAL(vtableHolder, MDField, ); \
5493 OPTIONAL(templateParams, MDField, ); \
5494 OPTIONAL(identifier, MDStringField, ); \
5495 OPTIONAL(discriminator, MDField, ); \
5496 OPTIONAL(dataLocation, MDField, ); \
5497 OPTIONAL(associated, MDField, ); \
5498 OPTIONAL(allocated, MDField, ); \
5499 OPTIONAL(rank, MDSignedOrMDField, ); \
5500 OPTIONAL(annotations, MDField, ); \
5501 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5502 OPTIONAL(specification, MDField, );
5504#undef VISIT_MD_FIELDS
5507 if (
rank.isMDSignedField())
5510 else if (
rank.isMDField())
5511 Rank =
rank.getMDFieldValue();
5516 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5517 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val,
5518 specification.Val, num_extra_inhabitants.Val, flags.Val,
5519 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5520 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5521 Rank, annotations.Val)) {
5530 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5531 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5532 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5533 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5534 annotations.Val, specification.Val, num_extra_inhabitants.Val));
5538bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5539#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5540 OPTIONAL(flags, DIFlagField, ); \
5541 OPTIONAL(cc, DwarfCCField, ); \
5542 REQUIRED(types, MDField, );
5544#undef VISIT_MD_FIELDS
5547 (Context, flags.Val, cc.Val, types.Val));
5556bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5560#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5561 REQUIRED(filename, MDStringField, ); \
5562 REQUIRED(directory, MDStringField, ); \
5563 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5564 OPTIONAL(checksum, MDStringField, ); \
5565 OPTIONAL(source, MDStringField, );
5567#undef VISIT_MD_FIELDS
5569 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5570 if (checksumkind.Seen && checksum.Seen)
5571 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5572 else if (checksumkind.Seen || checksum.Seen)
5573 return tokError(
"'checksumkind' and 'checksum' must be provided together");
5579 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5590bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5592 return tokError(
"missing 'distinct', required for !DICompileUnit");
5594#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5595 REQUIRED(language, DwarfLangField, ); \
5596 REQUIRED(file, MDField, ( false)); \
5597 OPTIONAL(producer, MDStringField, ); \
5598 OPTIONAL(isOptimized, MDBoolField, ); \
5599 OPTIONAL(flags, MDStringField, ); \
5600 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5601 OPTIONAL(splitDebugFilename, MDStringField, ); \
5602 OPTIONAL(emissionKind, EmissionKindField, ); \
5603 OPTIONAL(enums, MDField, ); \
5604 OPTIONAL(retainedTypes, MDField, ); \
5605 OPTIONAL(globals, MDField, ); \
5606 OPTIONAL(imports, MDField, ); \
5607 OPTIONAL(macros, MDField, ); \
5608 OPTIONAL(dwoId, MDUnsignedField, ); \
5609 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5610 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5611 OPTIONAL(nameTableKind, NameTableKindField, ); \
5612 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5613 OPTIONAL(sysroot, MDStringField, ); \
5614 OPTIONAL(sdk, MDStringField, );
5616#undef VISIT_MD_FIELDS
5619 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5620 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5621 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5622 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5623 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5636bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5638#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5639 OPTIONAL(scope, MDField, ); \
5640 OPTIONAL(name, MDStringField, ); \
5641 OPTIONAL(linkageName, MDStringField, ); \
5642 OPTIONAL(file, MDField, ); \
5643 OPTIONAL(line, LineField, ); \
5644 OPTIONAL(type, MDField, ); \
5645 OPTIONAL(isLocal, MDBoolField, ); \
5646 OPTIONAL(isDefinition, MDBoolField, (true)); \
5647 OPTIONAL(scopeLine, LineField, ); \
5648 OPTIONAL(containingType, MDField, ); \
5649 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5650 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5651 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5652 OPTIONAL(flags, DIFlagField, ); \
5653 OPTIONAL(spFlags, DISPFlagField, ); \
5654 OPTIONAL(isOptimized, MDBoolField, ); \
5655 OPTIONAL(unit, MDField, ); \
5656 OPTIONAL(templateParams, MDField, ); \
5657 OPTIONAL(declaration, MDField, ); \
5658 OPTIONAL(retainedNodes, MDField, ); \
5659 OPTIONAL(thrownTypes, MDField, ); \
5660 OPTIONAL(annotations, MDField, ); \
5661 OPTIONAL(targetFuncName, MDStringField, );
5663#undef VISIT_MD_FIELDS
5668 spFlags.Seen ? spFlags.Val
5670 isOptimized.Val, virtuality.Val);
5671 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5674 "missing 'distinct', required for !DISubprogram that is a Definition");
5677 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5678 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5679 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5680 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5681 targetFuncName.Val));
5687bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5688#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5689 REQUIRED(scope, MDField, ( false)); \
5690 OPTIONAL(file, MDField, ); \
5691 OPTIONAL(line, LineField, ); \
5692 OPTIONAL(column, ColumnField, );
5694#undef VISIT_MD_FIELDS
5703bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5704#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5705 REQUIRED(scope, MDField, ( false)); \
5706 OPTIONAL(file, MDField, ); \
5707 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5709#undef VISIT_MD_FIELDS
5712 (Context, scope.Val,
file.Val, discriminator.Val));
5718bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5719#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5720 REQUIRED(scope, MDField, ); \
5721 OPTIONAL(declaration, MDField, ); \
5722 OPTIONAL(name, MDStringField, ); \
5723 OPTIONAL(file, MDField, ); \
5724 OPTIONAL(line, LineField, );
5726#undef VISIT_MD_FIELDS
5729 (Context, scope.Val, declaration.Val,
name.Val,
5730 file.Val, line.Val));
5736bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5737#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5738 REQUIRED(scope, MDField, ); \
5739 OPTIONAL(name, MDStringField, ); \
5740 OPTIONAL(exportSymbols, MDBoolField, );
5742#undef VISIT_MD_FIELDS
5745 (Context, scope.Val,
name.Val, exportSymbols.Val));
5752bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5753#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5754 REQUIRED(type, DwarfMacinfoTypeField, ); \
5755 OPTIONAL(line, LineField, ); \
5756 REQUIRED(name, MDStringField, ); \
5757 OPTIONAL(value, MDStringField, );
5759#undef VISIT_MD_FIELDS
5762 (Context, type.Val, line.Val,
name.Val,
value.Val));
5768bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5769#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5770 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5771 OPTIONAL(line, LineField, ); \
5772 REQUIRED(file, MDField, ); \
5773 OPTIONAL(nodes, MDField, );
5775#undef VISIT_MD_FIELDS
5778 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5786bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5787#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5788 REQUIRED(scope, MDField, ); \
5789 REQUIRED(name, MDStringField, ); \
5790 OPTIONAL(configMacros, MDStringField, ); \
5791 OPTIONAL(includePath, MDStringField, ); \
5792 OPTIONAL(apinotes, MDStringField, ); \
5793 OPTIONAL(file, MDField, ); \
5794 OPTIONAL(line, LineField, ); \
5795 OPTIONAL(isDecl, MDBoolField, );
5797#undef VISIT_MD_FIELDS
5800 configMacros.Val, includePath.Val,
5801 apinotes.Val, line.Val, isDecl.Val));
5807bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5808#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5809 OPTIONAL(name, MDStringField, ); \
5810 REQUIRED(type, MDField, ); \
5811 OPTIONAL(defaulted, MDBoolField, );
5813#undef VISIT_MD_FIELDS
5816 (Context,
name.Val, type.Val, defaulted.Val));
5824bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5826 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5827 OPTIONAL(name, MDStringField, ); \
5828 OPTIONAL(type, MDField, ); \
5829 OPTIONAL(defaulted, MDBoolField, ); \
5830 REQUIRED(value, MDField, );
5833#undef VISIT_MD_FIELDS
5837 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5846bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5847#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5848 OPTIONAL(name, MDStringField, ( false)); \
5849 OPTIONAL(scope, MDField, ); \
5850 OPTIONAL(linkageName, MDStringField, ); \
5851 OPTIONAL(file, MDField, ); \
5852 OPTIONAL(line, LineField, ); \
5853 OPTIONAL(type, MDField, ); \
5854 OPTIONAL(isLocal, MDBoolField, ); \
5855 OPTIONAL(isDefinition, MDBoolField, (true)); \
5856 OPTIONAL(templateParams, MDField, ); \
5857 OPTIONAL(declaration, MDField, ); \
5858 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5859 OPTIONAL(annotations, MDField, );
5861#undef VISIT_MD_FIELDS
5865 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5866 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5867 declaration.Val, templateParams.Val, align.Val,
5879bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5880#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5881 REQUIRED(scope, MDField, ( false)); \
5882 OPTIONAL(name, MDStringField, ); \
5883 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5884 OPTIONAL(file, MDField, ); \
5885 OPTIONAL(line, LineField, ); \
5886 OPTIONAL(type, MDField, ); \
5887 OPTIONAL(flags, DIFlagField, ); \
5888 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5889 OPTIONAL(annotations, MDField, );
5891#undef VISIT_MD_FIELDS
5894 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5895 type.Val, arg.Val, flags.Val, align.Val,
5902bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5903#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5904 REQUIRED(scope, MDField, ( false)); \
5905 REQUIRED(name, MDStringField, ); \
5906 REQUIRED(file, MDField, ); \
5907 REQUIRED(line, LineField, );
5909#undef VISIT_MD_FIELDS
5912 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5918bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
5931 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5940 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5945 return tokError(
"expected unsigned integer");
5963bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5965 assert(Lex.
getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
5968 return parseDIExpressionBody(Result, IsDistinct);
5973bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5974 assert(PFS &&
"Expected valid function state");
5985 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5987 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5999bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6001#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6002 REQUIRED(var, MDField, ); \
6003 REQUIRED(expr, MDField, );
6005#undef VISIT_MD_FIELDS
6015bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6016#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6017 OPTIONAL(name, MDStringField, ); \
6018 OPTIONAL(file, MDField, ); \
6019 OPTIONAL(line, LineField, ); \
6020 OPTIONAL(setter, MDStringField, ); \
6021 OPTIONAL(getter, MDStringField, ); \
6022 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6023 OPTIONAL(type, MDField, );
6025#undef VISIT_MD_FIELDS
6028 (Context,
name.Val,
file.Val, line.Val, setter.Val,
6029 getter.Val, attributes.Val, type.Val));
6036bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6037#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6038 REQUIRED(tag, DwarfTagField, ); \
6039 REQUIRED(scope, MDField, ); \
6040 OPTIONAL(entity, MDField, ); \
6041 OPTIONAL(file, MDField, ); \
6042 OPTIONAL(line, LineField, ); \
6043 OPTIONAL(name, MDStringField, ); \
6044 OPTIONAL(elements, MDField, );
6046#undef VISIT_MD_FIELDS
6049 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6050 line.Val,
name.Val, elements.Val));
6054#undef PARSE_MD_FIELD
6066bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6069 if (parseMetadata(MD, &PFS))
6080bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6081 PerFunctionState *PFS) {
6084 if (parseType(Ty, TypeMsg, Loc))
6087 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6090 if (parseValue(Ty, V, PFS))
6105bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6111 if (parseDIArgList(AL, PFS))
6117 if (parseSpecializedMDNode(
N)) {
6127 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6137 if (parseMDString(S))
6147 if (parseMDNodeTail(
N))
6158 PerFunctionState *PFS) {
6160 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6165 return error(
ID.Loc,
"invalid use of function-local name");
6166 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6167 return V ==
nullptr;
6170 return error(
ID.Loc,
"invalid use of function-local name");
6171 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6172 return V ==
nullptr;
6175 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6179 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6184 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6187 return V ==
nullptr;
6189 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6192 return V ==
nullptr;
6195 return error(
ID.Loc,
"integer constant must have integer type");
6197 V = ConstantInt::get(Context,
ID.APSIntVal);
6202 return error(
ID.Loc,
"floating point constant invalid for type");
6208 bool IsSNAN =
ID.APFloatVal.isSignaling();
6223 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6225 ID.APFloatVal.isNegative(), &Payload);
6228 V = ConstantFP::get(Context,
ID.APFloatVal);
6230 if (
V->getType() != Ty)
6231 return error(
ID.Loc,
"floating point constant does not have type '" +
6237 return error(
ID.Loc,
"null must be a pointer type");
6243 return error(
ID.Loc,
"invalid type for undef constant");
6247 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6248 return error(
ID.Loc,
"invalid empty array initializer");
6254 return error(
ID.Loc,
"invalid type for null constant");
6255 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6257 return error(
ID.Loc,
"invalid type for null constant");
6262 return error(
ID.Loc,
"invalid type for none constant");
6268 return error(
ID.Loc,
"invalid type for poison constant");
6272 if (
ID.ConstantVal->getType() != Ty)
6273 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6280 return error(
ID.Loc,
"vector constant must have vector type");
6282 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6284 "' but expected '" +
6291 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6292 if (
ST->getNumElements() !=
ID.UIntVal)
6294 "initializer with struct type has wrong # elements");
6296 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6299 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6300 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6303 "element " +
Twine(i) +
6304 " of struct initializer doesn't match struct element type");
6307 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6309 return error(
ID.Loc,
"constant expression type mismatch");
6319 if (parseValID(
ID,
nullptr))
6332 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6334 assert(isa<Constant>(V) &&
"Expected a constant value");
6335 C = cast<Constant>(V);
6342 return error(Loc,
"expected a constant value");
6346bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6349 return parseValID(
ID, PFS, Ty) ||
6350 convertValIDToValue(Ty,
ID, V, PFS);
6353bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6355 return parseType(Ty) || parseValue(Ty, V, PFS);
6358bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6359 PerFunctionState &PFS) {
6362 if (parseTypeAndValue(V, PFS))
6364 if (!isa<BasicBlock>(V))
6365 return error(Loc,
"expected a basic block");
6366 BB = cast<BasicBlock>(V);
6374 if (!
Name.starts_with(
"llvm.dbg."))
6377 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6378 FnID == Intrinsic::dbg_assign;
6386bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6387 unsigned &FunctionNumber,
6392 unsigned Visibility;
6393 unsigned DLLStorageClass;
6398 Type *RetType =
nullptr;
6400 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6402 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6403 parseType(RetType, RetTypeLoc,
true ))
6412 return error(LinkageLoc,
"invalid linkage for function definition");
6422 return error(LinkageLoc,
"invalid linkage for function declaration");
6426 return error(LinkageLoc,
"invalid function linkage type");
6430 return error(LinkageLoc,
6431 "symbol with local linkage must have default visibility");
6434 return error(LinkageLoc,
6435 "symbol with local linkage cannot have a DLL storage class");
6438 return error(RetTypeLoc,
"invalid function return type");
6442 std::string FunctionName;
6447 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6451 return tokError(
"expected function name");
6457 return tokError(
"expected '(' in function argument list");
6462 std::vector<unsigned> FwdRefAttrGrps;
6465 std::string Partition;
6469 unsigned AddrSpace = 0;
6475 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6476 parseOptionalUnnamedAddr(UnnamedAddr) ||
6477 parseOptionalProgramAddrSpace(AddrSpace) ||
6478 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6482 parseOptionalComdat(FunctionName,
C) ||
6483 parseOptionalAlignment(Alignment) ||
6484 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6488 parseGlobalTypeAndValue(PersonalityFn)))
6491 if (FuncAttrs.contains(Attribute::Builtin))
6492 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6497 FuncAttrs.removeAttribute(Attribute::Alignment);
6502 std::vector<Type*> ParamTypeList;
6505 for (
const ArgInfo &Arg : ArgList) {
6506 ParamTypeList.push_back(Arg.Ty);
6507 Attrs.push_back(Arg.Attrs);
6515 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6522 if (!FunctionName.empty()) {
6525 auto FRVI = ForwardRefVals.find(FunctionName);
6526 if (FRVI != ForwardRefVals.end()) {
6527 FwdFn = FRVI->second.first;
6529 return error(FRVI->second.second,
6530 "invalid forward reference to "
6533 "' with wrong type: "
6537 ForwardRefVals.erase(FRVI);
6538 }
else if ((Fn =
M->getFunction(FunctionName))) {
6540 return error(NameLoc,
6541 "invalid redefinition of function '" + FunctionName +
"'");
6542 }
else if (
M->getNamedValue(FunctionName)) {
6543 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6549 if (FunctionNumber == (
unsigned)-1)
6550 FunctionNumber = NumberedVals.getNext();
6554 auto I = ForwardRefValIDs.find(FunctionNumber);
6555 if (
I != ForwardRefValIDs.end()) {
6556 FwdFn =
I->second.first;
6558 return error(NameLoc,
"type of definition and forward reference of '@" +
6559 Twine(FunctionNumber) +
6564 ForwardRefValIDs.erase(
I);
6573 if (FunctionName.empty())
6574 NumberedVals.add(FunctionNumber, Fn);
6589 if (!
GC.empty()) Fn->
setGC(GC);
6592 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6596 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6598 if (ArgList[i].
Name.empty())
continue;
6603 if (ArgIt->
getName() != ArgList[i].Name)
6604 return error(ArgList[i].Loc,
6605 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6618 if (FunctionName.empty()) {
6620 ID.UIntVal = FunctionNumber;
6623 ID.StrVal = FunctionName;
6625 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6626 if (
Blocks != ForwardRefBlockAddresses.end())
6628 "cannot take blockaddress inside a declaration");
6632bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6634 if (FunctionNumber == -1) {
6636 ID.StrVal = std::string(
F.getName());
6639 ID.UIntVal = FunctionNumber;
6642 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6643 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6646 for (
const auto &
I :
Blocks->second) {
6647 const ValID &BBID =
I.first;
6651 "Expected local id or name");
6658 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6669 P.ForwardRefBlockAddresses.erase(
Blocks);
6675bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6678 return tokError(
"expected '{' in function body");
6681 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6685 if (PFS.resolveForwardRefBlockAddresses())
6691 return tokError(
"function body requires at least one basic block");
6695 if (parseBasicBlock(PFS))
6699 if (parseUseListOrder(&PFS))
6706 return PFS.finishFunction();
6711bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6728 std::string NameStr;
6733 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6734 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6741 if (SeenOldDbgInfoFormat)
6742 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6743 "containing debug info intrinsics");
6744 if (!SeenNewDbgInfoFormat)
6745 M->setNewDbgInfoFormatFlag(
true);
6746 SeenNewDbgInfoFormat =
true;
6750 if (parseDebugRecord(DR, PFS))
6752 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6764 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6769 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6773 switch (parseInstruction(Inst, BB, PFS)) {
6776 case InstError:
return true;
6783 if (parseInstructionMetadata(*Inst))
6786 case InstExtraComma:
6791 if (parseInstructionMetadata(*Inst))
6797 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6801 for (DbgRecordPtr &DR : TrailingDbgRecord)
6803 TrailingDbgRecord.clear();
6806 assert(TrailingDbgRecord.empty() &&
6807 "All debug values should have been attached to an instruction.");
6816bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6821 return error(DVRLoc,
"expected debug record type here");
6823 .
Case(
"declare", RecordKind::ValueKind)
6824 .
Case(
"value", RecordKind::ValueKind)
6825 .
Case(
"assign", RecordKind::ValueKind)
6826 .
Case(
"label", RecordKind::LabelKind);
6835 if (parseMDNode(Label))
6840 if (parseMDNode(DbgLoc))
6849 .
Case(
"declare", LocType::Declare)
6850 .
Case(
"value", LocType::Value)
6851 .
Case(
"assign", LocType::Assign);
6859 if (parseMetadata(ValLocMD, &PFS))
6866 if (parseMDNode(Variable))
6879 MDNode *AssignID =
nullptr;
6880 Metadata *AddressLocation =
nullptr;
6881 MDNode *AddressExpression =
nullptr;
6884 if (parseMDNode(AssignID))
6890 if (parseMetadata(AddressLocation, &PFS))
6896 if (parseMDNode(AddressExpression))
6921 PerFunctionState &PFS) {
6924 return tokError(
"found end of file when expecting more instructions");
6931 return error(Loc,
"expected instruction opcode");
6935 return parseRet(Inst, BB, PFS);
6937 return parseBr(Inst, PFS);
6939 return parseSwitch(Inst, PFS);
6941 return parseIndirectBr(Inst, PFS);
6943 return parseInvoke(Inst, PFS);
6945 return parseResume(Inst, PFS);
6947 return parseCleanupRet(Inst, PFS);
6949 return parseCatchRet(Inst, PFS);
6951 return parseCatchSwitch(Inst, PFS);
6953 return parseCatchPad(Inst, PFS);
6955 return parseCleanupPad(Inst, PFS);
6957 return parseCallBr(Inst, PFS);
6961 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6977 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6980 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6981 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6990 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7004 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7006 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
7012 return parseArithmetic(Inst, PFS, KeywordVal,
7016 if (parseLogical(Inst, PFS, KeywordVal))
7019 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
7024 return parseLogical(Inst, PFS, KeywordVal);
7027 if (parseCompare(Inst, PFS, KeywordVal))
7030 cast<ICmpInst>(Inst)->setSameSign();
7035 int Res = parseCompare(Inst, PFS, KeywordVal);
7047 bool Res = parseCast(Inst, PFS, KeywordVal);
7059 if (parseCast(Inst, PFS, KeywordVal))
7062 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
7064 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
7075 return parseCast(Inst, PFS, KeywordVal);
7079 if (parseCast(Inst, PFS, KeywordVal))
7089 int Res = parseSelect(Inst, PFS);
7093 if (!isa<FPMathOperator>(Inst))
7094 return error(Loc,
"fast-math-flags specified for select without "
7095 "floating-point scalar or vector return type");
7101 return parseVAArg(Inst, PFS);
7103 return parseExtractElement(Inst, PFS);
7105 return parseInsertElement(Inst, PFS);
7107 return parseShuffleVector(Inst, PFS);
7110 int Res = parsePHI(Inst, PFS);
7114 if (!isa<FPMathOperator>(Inst))
7115 return error(Loc,
"fast-math-flags specified for phi without "
7116 "floating-point scalar or vector return type");
7122 return parseLandingPad(Inst, PFS);
7124 return parseFreeze(Inst, PFS);
7136 return parseAlloc(Inst, PFS);
7138 return parseLoad(Inst, PFS);
7140 return parseStore(Inst, PFS);
7142 return parseCmpXchg(Inst, PFS);
7144 return parseAtomicRMW(Inst, PFS);
7146 return parseFence(Inst, PFS);
7148 return parseGetElementPtr(Inst, PFS);
7150 return parseExtractValue(Inst, PFS);
7152 return parseInsertValue(Inst, PFS);
7157bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7158 if (Opc == Instruction::FCmp) {
7161 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7182 return tokError(
"expected icmp predicate (e.g. 'eq')");
7207 PerFunctionState &PFS) {
7210 if (parseType(Ty,
true ))
7213 Type *ResType = PFS.getFunction().getReturnType();
7217 return error(TypeLoc,
"value doesn't match function result type '" +
7225 if (parseValue(Ty, RV, PFS))
7229 return error(TypeLoc,
"value doesn't match function result type '" +
7239bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7243 if (parseTypeAndValue(Op0, Loc, PFS))
7246 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7252 return error(Loc,
"branch condition must have 'i1' type");
7254 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7255 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7256 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7257 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7269bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7270 LocTy CondLoc, BBLoc;
7273 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7274 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7275 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7279 if (!
Cond->getType()->isIntegerTy())
7280 return error(CondLoc,
"switch condition must have integer type");
7289 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7290 parseToken(
lltok::comma,
"expected ',' after case value") ||
7291 parseTypeAndBasicBlock(DestBB, PFS))
7295 return error(CondLoc,
"duplicate case value in switch");
7297 return error(CondLoc,
"case value is not a constant integer");
7305 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7306 SI->addCase(Table[i].first, Table[i].second);
7314bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7317 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7318 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7322 if (!
Address->getType()->isPointerTy())
7323 return error(AddrLoc,
"indirectbr address must have pointer type");
7330 if (parseTypeAndBasicBlock(DestBB, PFS))
7335 if (parseTypeAndBasicBlock(DestBB, PFS))
7341 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7356 FuncTy = dyn_cast<FunctionType>(RetType);
7361 for (
const ParamInfo &Arg : ArgList)
7375bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7377 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7378 std::vector<unsigned> FwdRefAttrGrps;
7381 unsigned InvokeAddrSpace;
7382 Type *RetType =
nullptr;
7389 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7390 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7391 parseType(RetType, RetTypeLoc,
true ) ||
7392 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7393 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7395 parseOptionalOperandBundles(BundleList, PFS) ||
7397 parseTypeAndBasicBlock(NormalBB, PFS) ||
7399 parseTypeAndBasicBlock(UnwindBB, PFS))
7406 if (resolveFunctionType(RetType, ArgList, Ty))
7407 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7425 for (
const ParamInfo &Arg : ArgList) {
7426 Type *ExpectedTy =
nullptr;
7429 }
else if (!Ty->isVarArg()) {
7430 return error(Arg.Loc,
"too many arguments specified");
7433 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7434 return error(Arg.Loc,
"argument is not of expected type '" +
7436 Args.push_back(Arg.V);
7441 return error(CallLoc,
"not enough parameters specified for call");
7450 II->setCallingConv(
CC);
7451 II->setAttributes(PAL);
7452 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
7459bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7461 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7470 PerFunctionState &PFS) {
7471 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7476 if (!
Args.empty() &&
7477 parseToken(
lltok::comma,
"expected ',' in argument list"))
7482 Type *ArgTy =
nullptr;
7483 if (parseType(ArgTy, ArgLoc))
7488 if (parseMetadataAsValue(V, PFS))
7491 if (parseValue(ArgTy, V, PFS))
7503bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7504 Value *CleanupPad =
nullptr;
7506 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7521 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7532bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7533 Value *CatchPad =
nullptr;
7535 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7542 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7543 parseTypeAndBasicBlock(BB, PFS))
7552bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7560 return tokError(
"expected scope value for catchswitch");
7565 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7571 if (parseTypeAndBasicBlock(DestBB, PFS))
7576 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7579 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7587 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7594 CatchSwitch->addHandler(DestBB);
7601bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7602 Value *CatchSwitch =
nullptr;
7608 return tokError(
"expected scope value for catchpad");
7614 if (parseExceptionArgs(Args, PFS))
7623bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7624 Value *ParentPad =
nullptr;
7631 return tokError(
"expected scope value for cleanuppad");
7637 if (parseExceptionArgs(Args, PFS))
7653bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7654 unsigned Opc,
bool IsFP) {
7656 if (parseTypeAndValue(LHS, Loc, PFS))
7663 return error(Loc,
"invalid operand type for instruction");
7673bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7675 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7676 std::vector<unsigned> FwdRefAttrGrps;
7679 Type *RetType =
nullptr;
7686 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7687 parseType(RetType, RetTypeLoc,
true ) ||
7688 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7689 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7691 parseOptionalOperandBundles(BundleList, PFS) ||
7693 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7702 if (parseTypeAndBasicBlock(DestBB, PFS))
7707 if (parseTypeAndBasicBlock(DestBB, PFS))
7713 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7720 if (resolveFunctionType(RetType, ArgList, Ty))
7721 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7738 for (
const ParamInfo &Arg : ArgList) {
7739 Type *ExpectedTy =
nullptr;
7742 }
else if (!Ty->isVarArg()) {
7743 return error(Arg.Loc,
"too many arguments specified");
7746 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7747 return error(Arg.Loc,
"argument is not of expected type '" +
7749 Args.push_back(Arg.V);
7754 return error(CallLoc,
"not enough parameters specified for call");
7766 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7780bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7781 unsigned Opc,
bool IsFP) {
7783 if (parseTypeAndValue(LHS, Loc, PFS) ||
7784 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7792 return error(Loc,
"invalid operand type for instruction");
7800bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7803 if (parseTypeAndValue(LHS, Loc, PFS) ||
7804 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7810 "instruction requires integer or integer vector operands");
7819bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7825 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7826 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7830 if (Opc == Instruction::FCmp) {
7832 return error(Loc,
"fcmp requires floating point operands");
7835 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7838 return error(Loc,
"icmp requires integer operands");
7850bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7854 Type *DestTy =
nullptr;
7855 if (parseTypeAndValue(
Op, Loc, PFS) ||
7856 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7861 return error(Loc,
"invalid cast opcode for cast from '" +
7870bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7872 Value *Op0, *Op1, *Op2;
7873 if (parseTypeAndValue(Op0, Loc, PFS) ||
7874 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7875 parseTypeAndValue(Op1, PFS) ||
7876 parseToken(
lltok::comma,
"expected ',' after select value") ||
7877 parseTypeAndValue(Op2, PFS))
7881 return error(Loc, Reason);
7889bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7891 Type *EltTy =
nullptr;
7893 if (parseTypeAndValue(
Op, PFS) ||
7894 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7895 parseType(EltTy, TypeLoc))
7899 return error(TypeLoc,
"va_arg requires operand with first class type");
7907bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7910 if (parseTypeAndValue(Op0, Loc, PFS) ||
7911 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7912 parseTypeAndValue(Op1, PFS))
7916 return error(Loc,
"invalid extractelement operands");
7924bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7926 Value *Op0, *Op1, *Op2;
7927 if (parseTypeAndValue(Op0, Loc, PFS) ||
7928 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7929 parseTypeAndValue(Op1, PFS) ||
7930 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7931 parseTypeAndValue(Op2, PFS))
7935 return error(Loc,
"invalid insertelement operands");
7943bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7945 Value *Op0, *Op1, *Op2;
7946 if (parseTypeAndValue(Op0, Loc, PFS) ||
7947 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7948 parseTypeAndValue(Op1, PFS) ||
7949 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7950 parseTypeAndValue(Op2, PFS))
7954 return error(Loc,
"invalid shufflevector operands");
7962int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7966 if (parseType(Ty, TypeLoc))
7970 return error(TypeLoc,
"phi node must have first class type");
7973 bool AteExtraComma =
false;
7985 AteExtraComma =
true;
7989 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7990 parseValue(Ty, Op0, PFS) ||
7991 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7996 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8000 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
8001 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
8003 return AteExtraComma ? InstExtraComma : InstNormal;
8012bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
8015 if (parseType(Ty, TyLoc))
8028 return tokError(
"expected 'catch' or 'filter' clause type");
8032 if (parseTypeAndValue(V, VLoc, PFS))
8038 if (isa<ArrayType>(
V->getType()))
8039 return error(VLoc,
"'catch' clause has an invalid type");
8041 if (!isa<ArrayType>(
V->getType()))
8042 return error(VLoc,
"'filter' clause has an invalid type");
8045 Constant *CV = dyn_cast<Constant>(V);
8047 return error(VLoc,
"clause argument must be a constant");
8051 Inst = LP.release();
8057bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
8060 if (parseTypeAndValue(
Op, Loc, PFS))
8076bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
8078 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
8079 std::vector<unsigned> FwdRefAttrGrps;
8081 unsigned CallAddrSpace;
8083 Type *RetType =
nullptr;
8092 "expected 'tail call', 'musttail call', or 'notail call'"))
8097 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8098 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8099 parseType(RetType, RetTypeLoc,
true ) ||
8100 parseValID(CalleeID, &PFS) ||
8102 PFS.getFunction().isVarArg()) ||
8103 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8104 parseOptionalOperandBundles(BundleList, PFS))
8111 if (resolveFunctionType(RetType, ArgList, Ty))
8112 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8118 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
8131 for (
const ParamInfo &Arg : ArgList) {
8132 Type *ExpectedTy =
nullptr;
8135 }
else if (!Ty->isVarArg()) {
8136 return error(Arg.Loc,
"too many arguments specified");
8139 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8140 return error(Arg.Loc,
"argument is not of expected type '" +
8142 Args.push_back(Arg.V);
8143 Attrs.push_back(Arg.Attrs);
8147 return error(CallLoc,
"not enough parameters specified for call");
8158 if (!isa<FPMathOperator>(CI)) {
8160 return error(CallLoc,
"fast-math-flags specified for call without "
8161 "floating-point scalar or vector return type");
8168 if (SeenNewDbgInfoFormat) {
8170 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8171 "using non-intrinsic debug info");
8173 if (!SeenOldDbgInfoFormat)
8174 M->setNewDbgInfoFormatFlag(
false);
8175 SeenOldDbgInfoFormat =
true;
8178 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8190int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
8192 LocTy SizeLoc, TyLoc, ASLoc;
8194 unsigned AddrSpace = 0;
8197 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8198 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8200 if (parseType(Ty, TyLoc))
8204 return error(TyLoc,
"invalid type for alloca");
8206 bool AteExtraComma =
false;
8208 if (Lex.
getKind() == lltok::kw_align) {
8209 if (parseOptionalAlignment(Alignment))
8211 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8215 if (parseOptionalAddrSpace(AddrSpace))
8218 AteExtraComma =
true;
8220 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8223 if (Lex.
getKind() == lltok::kw_align) {
8224 if (parseOptionalAlignment(Alignment))
8226 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8230 if (parseOptionalAddrSpace(AddrSpace))
8233 AteExtraComma =
true;
8239 if (
Size && !
Size->getType()->isIntegerTy())
8240 return error(SizeLoc,
"element count must have integer type");
8243 if (!Alignment && !Ty->
isSized(&Visited))
8244 return error(TyLoc,
"Cannot allocate unsized type");
8246 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8251 return AteExtraComma ? InstExtraComma : InstNormal;
8258int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8261 bool AteExtraComma =
false;
8262 bool isAtomic =
false;
8271 bool isVolatile =
false;
8279 if (parseType(Ty) ||
8280 parseToken(
lltok::comma,
"expected comma after load's type") ||
8281 parseTypeAndValue(Val, Loc, PFS) ||
8282 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8283 parseOptionalCommaAlign(Alignment, AteExtraComma))
8287 return error(Loc,
"load operand must be a pointer to a first class type");
8288 if (isAtomic && !Alignment)
8289 return error(Loc,
"atomic load must have explicit non-zero alignment");
8292 return error(Loc,
"atomic load cannot use Release ordering");
8295 if (!Alignment && !Ty->
isSized(&Visited))
8296 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8298 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8299 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8300 return AteExtraComma ? InstExtraComma : InstNormal;
8308int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8311 bool AteExtraComma =
false;
8312 bool isAtomic =
false;
8321 bool isVolatile =
false;
8327 if (parseTypeAndValue(Val, Loc, PFS) ||
8328 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8329 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8330 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8331 parseOptionalCommaAlign(Alignment, AteExtraComma))
8334 if (!
Ptr->getType()->isPointerTy())
8335 return error(PtrLoc,
"store operand must be a pointer");
8337 return error(Loc,
"store operand must be a first class value");
8338 if (isAtomic && !Alignment)
8339 return error(Loc,
"atomic store must have explicit non-zero alignment");
8342 return error(Loc,
"atomic store cannot use Acquire ordering");
8345 return error(Loc,
"storing unsized types is not allowed");
8347 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8349 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8350 return AteExtraComma ? InstExtraComma : InstNormal;
8357int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8359 bool AteExtraComma =
false;
8363 bool isVolatile =
false;
8364 bool isWeak =
false;
8373 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8374 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8375 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8376 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8377 parseTypeAndValue(New, NewLoc, PFS) ||
8378 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8379 parseOrdering(FailureOrdering) ||
8380 parseOptionalCommaAlign(Alignment, AteExtraComma))
8384 return tokError(
"invalid cmpxchg success ordering");
8386 return tokError(
"invalid cmpxchg failure ordering");
8387 if (!
Ptr->getType()->isPointerTy())
8388 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8389 if (
Cmp->getType() !=
New->getType())
8390 return error(NewLoc,
"compare value and new value type do not match");
8391 if (!
New->getType()->isFirstClassType())
8392 return error(NewLoc,
"cmpxchg operand must be a first class value");
8394 const Align DefaultAlignment(
8395 PFS.getFunction().getDataLayout().getTypeStoreSize(
8400 SuccessOrdering, FailureOrdering, SSID);
8405 return AteExtraComma ? InstExtraComma : InstNormal;
8411int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8413 bool AteExtraComma =
false;
8416 bool isVolatile =
false;
8426 return tokError(
"expected binary operation in atomicrmw");
8469 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8470 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8471 parseTypeAndValue(Val, ValLoc, PFS) ||
8472 parseScopeAndOrdering(
true , SSID, Ordering) ||
8473 parseOptionalCommaAlign(Alignment, AteExtraComma))
8477 return tokError(
"atomicrmw cannot be unordered");
8478 if (!
Ptr->getType()->isPointerTy())
8479 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8481 return error(ValLoc,
"atomicrmw operand may not be scalable");
8490 " operand must be an integer, floating point, or pointer type");
8494 return error(ValLoc,
"atomicrmw " +
8496 " operand must be a floating point type");
8500 return error(ValLoc,
"atomicrmw " +
8502 " operand must be an integer");
8507 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8510 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8512 const Align DefaultAlignment(
8513 PFS.getFunction().getDataLayout().getTypeStoreSize(
8517 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8520 return AteExtraComma ? InstExtraComma : InstNormal;
8525int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8528 if (parseScopeAndOrdering(
true , SSID, Ordering))
8532 return tokError(
"fence cannot be unordered");
8534 return tokError(
"fence cannot be monotonic");
8536 Inst =
new FenceInst(Context, Ordering, SSID);
8542int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8544 Value *Val =
nullptr;
8560 if (parseType(Ty) ||
8561 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8562 parseTypeAndValue(
Ptr, Loc, PFS))
8567 if (!BasePointerType)
8568 return error(Loc,
"base of getelementptr must be a pointer");
8571 bool AteExtraComma =
false;
8575 ? cast<VectorType>(
BaseType)->getElementCount()
8580 AteExtraComma =
true;
8583 if (parseTypeAndValue(Val, EltLoc, PFS))
8586 return error(EltLoc,
"getelementptr index must be an integer");
8588 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8593 "getelementptr vector index has a wrong number of elements");
8594 GEPWidth = ValNumEl;
8601 return error(Loc,
"base element of getelementptr must be sized");
8603 auto *STy = dyn_cast<StructType>(Ty);
8605 return error(Loc,
"getelementptr cannot target structure that contains "
8606 "scalable vector type");
8609 return error(Loc,
"invalid getelementptr indices");
8612 GEP->setNoWrapFlags(NW);
8613 return AteExtraComma ? InstExtraComma : InstNormal;
8618int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8622 if (parseTypeAndValue(Val, Loc, PFS) ||
8623 parseIndexList(Indices, AteExtraComma))
8627 return error(Loc,
"extractvalue operand must be aggregate type");
8630 return error(Loc,
"invalid indices for extractvalue");
8632 return AteExtraComma ? InstExtraComma : InstNormal;
8637int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8641 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8642 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8643 parseTypeAndValue(Val1, Loc1, PFS) ||
8644 parseIndexList(Indices, AteExtraComma))
8648 return error(Loc0,
"insertvalue operand must be aggregate type");
8652 return error(Loc0,
"invalid indices for insertvalue");
8653 if (IndexedType != Val1->
getType())
8654 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8658 return AteExtraComma ? InstExtraComma : InstNormal;
8684 if (parseMetadata(MD,
nullptr))
8689 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8698 return error(Loc,
"value has no uses");
8700 unsigned NumUses = 0;
8702 for (
const Use &U :
V->uses()) {
8703 if (++NumUses > Indexes.
size())
8705 Order[&
U] = Indexes[NumUses - 1];
8708 return error(Loc,
"value only has one use");
8709 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8711 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8713 V->sortUseList([&](
const Use &L,
const Use &R) {
8726 return tokError(
"expected non-empty list of uselistorder indexes");
8733 bool IsOrdered =
true;
8734 assert(Indexes.
empty() &&
"Expected empty order vector");
8737 if (parseUInt32(Index))
8742 Max = std::max(Max, Index);
8751 if (Indexes.
size() < 2)
8752 return error(Loc,
"expected >= 2 uselistorder indexes");
8755 "expected distinct uselistorder indexes in range [0, size)");
8757 return error(Loc,
"expected uselistorder indexes to change the order");
8764bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8771 if (parseTypeAndValue(V, PFS) ||
8772 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8773 parseUseListOrderIndexes(Indexes))
8776 return sortUseListOrder(V, Indexes, Loc);
8781bool LLParser::parseUseListOrderBB() {
8788 if (parseValID(Fn,
nullptr) ||
8789 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8790 parseValID(Label,
nullptr) ||
8791 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8792 parseUseListOrderIndexes(Indexes))
8798 GV =
M->getNamedValue(Fn.
StrVal);
8800 GV = NumberedVals.get(Fn.
UIntVal);
8802 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8805 "invalid function forward reference in uselistorder_bb");
8806 auto *
F = dyn_cast<Function>(GV);
8808 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8809 if (
F->isDeclaration())
8810 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8814 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8816 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8817 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8819 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8820 if (!isa<BasicBlock>(V))
8821 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8823 return sortUseListOrder(V, Indexes, Loc);
8829bool LLParser::parseModuleEntry(
unsigned ID) {
8838 parseStringConstant(Path) ||
8846 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8847 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8848 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8849 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8850 parseUInt32(Hash[4]))
8857 auto ModuleEntry =
Index->addModule(Path, Hash);
8858 ModuleIdMap[
ID] = ModuleEntry->first();
8865bool LLParser::parseTypeIdEntry(
unsigned ID) {
8874 parseStringConstant(
Name))
8879 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8884 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8885 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8886 for (
auto TIDRef : FwdRefTIDs->second) {
8888 "Forward referenced type id GUID expected to be 0");
8891 ForwardRefTypeIds.erase(FwdRefTIDs);
8903 parseTypeTestResolution(TIS.
TTRes))
8908 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8919 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8925bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8934 parseStringConstant(
Name))
8938 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8945 IdToIndexMapType IdToIndexMap;
8958 if (parseGVReference(VI, GVId))
8965 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8966 TI.push_back({
Offset, VI});
8974 for (
auto I : IdToIndexMap) {
8975 auto &Infos = ForwardRefValueInfos[
I.first];
8976 for (
auto P :
I.second) {
8978 "Forward referenced ValueInfo expected to be empty");
8979 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8989 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8990 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8991 for (
auto TIDRef : FwdRefTIDs->second) {
8993 "Forward referenced type id GUID expected to be 0");
8996 ForwardRefTypeIds.erase(FwdRefTIDs);
9036 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
9063 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9076 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
9089bool LLParser::parseOptionalWpdResolutions(
9090 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9102 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9105 WPDResMap[
Offset] = WPDRes;
9141 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9155 if (parseOptionalResByArg(WPDRes.
ResByArg))
9160 "expected optional WholeProgramDevirtResolution field");
9177bool LLParser::parseOptionalResByArg(
9186 std::vector<uint64_t>
Args;
9187 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9211 "unexpected WholeProgramDevirtResolution::ByArg kind");
9221 parseUInt64(ByArg.
Info))
9227 parseUInt32(ByArg.
Byte))
9233 parseUInt32(ByArg.
Bit))
9238 "expected optional whole program devirt field");
9245 ResByArg[
Args] = ByArg;
9256bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9264 if (parseUInt64(Val))
9266 Args.push_back(Val);
9275static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9280 assert(!(ReadOnly && WriteOnly));
9290bool LLParser::addGlobalValueToIndex(
9292 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9297 VI =
Index->getOrInsertValueInfo(GUID);
9301 auto *GV =
M->getNamedValue(
Name);
9303 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9305 VI =
Index->getOrInsertValueInfo(GV);
9309 "Need a source_filename to compute GUID for local");
9317 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9318 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9319 for (
auto VIRef : FwdRefVIs->second) {
9321 "Forward referenced ValueInfo expected to be empty");
9324 ForwardRefValueInfos.erase(FwdRefVIs);
9328 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9329 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9330 for (
auto AliaseeRef : FwdRefAliasees->second) {
9331 assert(!AliaseeRef.first->hasAliasee() &&
9332 "Forward referencing alias already has aliasee");
9333 assert(Summary &&
"Aliasee must be a definition");
9334 AliaseeRef.first->setAliasee(VI,
Summary.get());
9336 ForwardRefAliasees.erase(FwdRefAliasees);
9341 Index->addGlobalValueSummary(VI, std::move(Summary));
9344 if (
ID == NumberedValueInfos.size())
9345 NumberedValueInfos.push_back(VI);
9348 if (
ID > NumberedValueInfos.size())
9349 NumberedValueInfos.resize(
ID + 1);
9350 NumberedValueInfos[
ID] =
VI;
9358bool LLParser::parseSummaryIndexFlags() {
9365 if (parseUInt64(Flags))
9368 Index->setFlags(Flags);
9374bool LLParser::parseBlockCount() {
9381 if (parseUInt64(BlockCount))
9384 Index->setBlockCount(BlockCount);
9392bool LLParser::parseGVEntry(
unsigned ID) {
9407 parseStringConstant(
Name))
9413 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9417 return error(Lex.
getLoc(),
"expected name or guid tag");
9442 if (parseFunctionSummary(
Name, GUID,
ID))
9446 if (parseVariableSummary(
Name, GUID,
ID))
9450 if (parseAliasSummary(
Name, GUID,
ID))
9454 return error(Lex.
getLoc(),
"expected summary type");
9480 false,
false,
false,
9485 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9487 std::vector<CallsiteInfo> Callsites;
9488 std::vector<AllocInfo> Allocs;
9493 parseModuleReference(ModulePath) ||
9494 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9497 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9504 if (parseOptionalFFlags(FFlags))
9508 if (parseOptionalCalls(Calls))
9512 if (parseOptionalTypeIdInfo(TypeIdInfo))
9516 if (parseOptionalRefs(Refs))
9520 if (parseOptionalParamAccesses(ParamAccesses))
9524 if (parseOptionalAllocs(Allocs))
9528 if (parseOptionalCallsites(Callsites))
9532 return error(Lex.
getLoc(),
"expected optional function summary field");
9539 auto FS = std::make_unique<FunctionSummary>(
9540 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9546 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9548 FS->setModulePath(ModulePath);
9550 return addGlobalValueToIndex(
Name, GUID,
9552 std::move(FS), Loc);
9568 false,
false,
false,
9578 parseModuleReference(ModulePath) ||
9579 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9581 parseGVarFlags(GVarFlags))
9588 if (parseOptionalVTableFuncs(VTableFuncs))
9592 if (parseOptionalRefs(Refs))
9596 return error(Lex.
getLoc(),
"expected optional variable summary field");
9604 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9606 GS->setModulePath(ModulePath);
9607 GS->setVTableFuncs(std::move(VTableFuncs));
9609 return addGlobalValueToIndex(
Name, GUID,
9611 std::move(GS), Loc);
9627 false,
false,
false,
9631 parseModuleReference(ModulePath) ||
9632 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9640 if (parseGVReference(AliaseeVI, GVId))
9646 auto AS = std::make_unique<AliasSummary>(GVFlags);
9648 AS->setModulePath(ModulePath);
9652 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9654 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9655 assert(Summary &&
"Aliasee must be a definition");
9656 AS->setAliasee(AliaseeVI, Summary);
9659 return addGlobalValueToIndex(
Name, GUID,
9661 std::move(AS), Loc);
9666bool LLParser::parseFlag(
unsigned &Val) {
9668 return tokError(
"expected integer");
9689 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9698 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9704 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9710 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9716 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9722 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9728 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9734 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9740 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9746 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9752 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9757 return error(Lex.
getLoc(),
"expected function flag type");
9772bool LLParser::parseOptionalCalls(
9777 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9781 IdToIndexMapType IdToIndexMap;
9792 if (parseGVReference(VI, GVId))
9797 unsigned HasTailCall =
false;
9804 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9809 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9814 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9818 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9822 return tokError(
"Expected only one of hotness or relbf");
9827 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
9837 for (
auto I : IdToIndexMap) {
9838 auto &Infos = ForwardRefValueInfos[
I.first];
9839 for (
auto P :
I.second) {
9841 "Forward referenced ValueInfo expected to be empty");
9842 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9859 case lltok::kw_cold:
9872 return error(Lex.
getLoc(),
"invalid call edge hotness");
9881bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9885 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9889 IdToIndexMapType IdToIndexMap;
9893 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9900 if (parseGVReference(VI, GVId))
9913 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9914 VTableFuncs.push_back({
VI,
Offset});
9916 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9922 for (
auto I : IdToIndexMap) {
9923 auto &Infos = ForwardRefValueInfos[
I.first];
9924 for (
auto P :
I.second) {
9926 "Forward referenced ValueInfo expected to be empty");
9927 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9931 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9938bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9940 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9949 auto ParseAPSInt = [&](
APSInt &Val) {
9951 return tokError(
"expected integer");
9954 Val.setIsSigned(
true);
9977 IdLocListType &IdLocList) {
9986 if (parseGVReference(VI, GVId))
9990 IdLocList.emplace_back(GVId, Loc);
9993 parseParamNo(
Call.ParamNo) ||
9995 parseParamAccessOffset(
Call.Offsets))
10008 IdLocListType &IdLocList) {
10010 parseParamNo(
Param.ParamNo) ||
10012 parseParamAccessOffset(
Param.Use))
10022 if (parseParamAccessCall(Call, IdLocList))
10024 Param.Calls.push_back(Call);
10039bool LLParser::parseOptionalParamAccesses(
10040 std::vector<FunctionSummary::ParamAccess> &Params) {
10048 IdLocListType VContexts;
10049 size_t CallsNum = 0;
10052 if (parseParamAccess(ParamAccess, VContexts))
10054 CallsNum += ParamAccess.
Calls.size();
10055 assert(VContexts.size() == CallsNum);
10057 Params.emplace_back(std::move(ParamAccess));
10065 IdLocListType::const_iterator ItContext = VContexts.begin();
10066 for (
auto &PA : Params) {
10067 for (
auto &
C : PA.Calls) {
10069 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10070 ItContext->second);
10074 assert(ItContext == VContexts.end());
10085 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10089 struct ValueContext {
10094 std::vector<ValueContext> VContexts;
10099 if (parseGVReference(
VC.VI,
VC.GVId))
10101 VContexts.push_back(VC);
10107 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10108 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10111 IdToIndexMapType IdToIndexMap;
10112 for (
auto &VC : VContexts) {
10117 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10123 for (
auto I : IdToIndexMap) {
10124 auto &Infos = ForwardRefValueInfos[
I.first];
10125 for (
auto P :
I.second) {
10127 "Forward referenced ValueInfo expected to be empty");
10128 Infos.emplace_back(&Refs[
P.first],
P.second);
10142bool LLParser::parseOptionalTypeIdInfo(
10154 if (parseTypeTests(TypeIdInfo.
TypeTests))
10178 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
10182 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10191bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10199 IdToIndexMapType IdToIndexMap;
10208 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10210 }
else if (parseUInt64(GUID))
10212 TypeTests.push_back(GUID);
10217 for (
auto I : IdToIndexMap) {
10218 auto &Ids = ForwardRefTypeIds[
I.first];
10219 for (
auto P :
I.second) {
10220 assert(TypeTests[
P.first] == 0 &&
10221 "Forward referenced type id GUID expected to be 0");
10222 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10226 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10234bool LLParser::parseVFuncIdList(
10235 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10243 IdToIndexMapType IdToIndexMap;
10246 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10248 VFuncIdList.push_back(VFuncId);
10256 for (
auto I : IdToIndexMap) {
10257 auto &Ids = ForwardRefTypeIds[
I.first];
10258 for (
auto P :
I.second) {
10259 assert(VFuncIdList[
P.first].GUID == 0 &&
10260 "Forward referenced type id GUID expected to be 0");
10261 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10270bool LLParser::parseConstVCallList(
10272 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10280 IdToIndexMapType IdToIndexMap;
10283 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10285 ConstVCallList.push_back(ConstVCall);
10293 for (
auto I : IdToIndexMap) {
10294 auto &Ids = ForwardRefTypeIds[
I.first];
10295 for (
auto P :
I.second) {
10296 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10297 "Forward referenced type id GUID expected to be 0");
10298 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10308 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10310 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10314 if (parseArgs(ConstVCall.
Args))
10327 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10342 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
10344 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10346 parseUInt64(VFuncId.
GUID))
10352 parseUInt64(VFuncId.
Offset) ||
10381 assert(HasLinkage &&
"Linkage not optional in summary entry");
10388 parseOptionalVisibility(Flag);
10393 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10399 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10405 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10411 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10420 if (parseOptionalImportType(Lex.
getKind(), IK))
10422 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10426 return error(Lex.
getLoc(),
"expected gv flag type");
10448 auto ParseRest = [
this](
unsigned int &Val) {
10452 return parseFlag(Val);
10458 case lltok::kw_readonly:
10459 if (ParseRest(Flag))
10463 case lltok::kw_writeonly:
10464 if (ParseRest(Flag))
10469 if (ParseRest(Flag))
10474 if (ParseRest(Flag))
10479 return error(Lex.
getLoc(),
"expected gvar flag type");
10487bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10495 auto I = ModuleIdMap.find(ModuleID);
10497 assert(
I != ModuleIdMap.end());
10498 ModulePath =
I->second;
10504bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10507 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10513 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10515 VI = NumberedValueInfos[GVId];
10532bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10536 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10551 if (parseAllocType(V))
10556 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10560 std::vector<MIBInfo> MIBs;
10561 if (parseMemProfs(MIBs))
10564 Allocs.push_back({Versions, MIBs});
10581bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10585 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10591 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10600 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10609 if (parseUInt64(StackId))
10639 case lltok::kw_cold:
10642 case lltok::kw_hot:
10646 return error(Lex.
getLoc(),
"invalid alloc type");
10659bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10663 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10667 IdToIndexMapType IdToIndexMap;
10670 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10679 if (parseGVReference(VI, GVId))
10683 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10692 if (parseUInt32(V))
10698 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10707 if (parseUInt64(StackId))
10719 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10720 Callsites.push_back({
VI, Clones, StackIdIndices});
10728 for (
auto I : IdToIndexMap) {
10729 auto &Infos = ForwardRefValueInfos[
I.first];
10730 for (
auto P :
I.second) {
10732 "Forward referenced ValueInfo expected to be empty");
10733 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10737 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)
Represents which components of the pointer may be captured in which location.
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)
CaptureComponents
Components of the pointer that may be captured.
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
bool capturesNothing(CaptureComponents CC)
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.