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())
1524 R = NumberedAttrBuilders.emplace(VarID,
AttrBuilder(
M->getContext())).first;
1526 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1527 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1530 if (!
R->second.hasAttributes())
1531 return error(AttrGrpLoc,
"attribute group has no attributes");
1538#define GET_ATTR_NAMES
1539#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1540 case lltok::kw_##DISPLAY_NAME: \
1541 return Attribute::ENUM_NAME;
1542#include "llvm/IR/Attributes.inc"
1551 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1554 case Attribute::Alignment: {
1563 if (parseOptionalAlignment(Alignment,
true))
1566 B.addAlignmentAttr(Alignment);
1569 case Attribute::StackAlignment: {
1574 parseUInt32(Alignment))
1577 if (parseOptionalStackAlignment(Alignment))
1580 B.addStackAlignmentAttr(Alignment);
1583 case Attribute::AllocSize: {
1584 unsigned ElemSizeArg;
1585 std::optional<unsigned> NumElemsArg;
1586 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1588 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1591 case Attribute::VScaleRange: {
1592 unsigned MinValue, MaxValue;
1593 if (parseVScaleRangeArguments(MinValue, MaxValue))
1595 B.addVScaleRangeAttr(MinValue,
1596 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1599 case Attribute::Dereferenceable: {
1601 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1603 B.addDereferenceableAttr(Bytes);
1606 case Attribute::DereferenceableOrNull: {
1608 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1610 B.addDereferenceableOrNullAttr(Bytes);
1613 case Attribute::UWTable: {
1615 if (parseOptionalUWTableKind(Kind))
1617 B.addUWTableAttr(Kind);
1620 case Attribute::AllocKind: {
1622 if (parseAllocKind(Kind))
1624 B.addAllocKindAttr(Kind);
1627 case Attribute::Memory: {
1628 std::optional<MemoryEffects> ME = parseMemoryAttr();
1631 B.addMemoryAttr(*ME);
1634 case Attribute::NoFPClass: {
1637 B.addNoFPClassAttr(NoFPClass);
1643 case Attribute::Range:
1644 return parseRangeAttr(
B);
1645 case Attribute::Initializes:
1646 return parseInitializesAttr(
B);
1648 B.addAttribute(Attr);
1656 case lltok::kw_readnone:
1659 case lltok::kw_readonly:
1662 case lltok::kw_writeonly:
1681bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1682 std::vector<unsigned> &FwdRefAttrGrps,
1683 bool InAttrGrp, LocTy &BuiltinLoc) {
1684 bool HaveError =
false;
1695 if (parseStringAttribute(
B))
1707 "cannot have an attribute group reference in an attribute group");
1717 if (Token == lltok::kw_builtin)
1729 return error(Lex.
getLoc(),
"unterminated attribute group");
1732 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1739 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1743 B.addMemoryAttr(ME);
1757 PTy->getAddressSpace());
1766 error(Loc,
"'" +
Name +
"' is not a basic block");
1768 error(Loc,
"'" +
Name +
"' defined with type '" +
1781 error(Loc,
"global variable reference must have pointer type");
1787 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1792 auto I = ForwardRefVals.find(
Name);
1793 if (
I != ForwardRefVals.end())
1794 Val =
I->second.first;
1799 return cast_or_null<GlobalValue>(
1800 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1804 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1811 error(Loc,
"global variable reference must have pointer type");
1820 auto I = ForwardRefValIDs.find(
ID);
1821 if (
I != ForwardRefValIDs.end())
1822 Val =
I->second.first;
1827 return cast_or_null<GlobalValue>(
1828 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1832 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1840Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1844 if (
I != ComdatSymTab.
end())
1849 ForwardRefComdats[
Name] = Loc;
1859bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1861 return tokError(ErrMsg);
1868bool LLParser::parseStringConstant(std::string &Result) {
1870 return tokError(
"expected string constant");
1878bool LLParser::parseUInt32(
uint32_t &Val) {
1880 return tokError(
"expected integer");
1882 if (Val64 !=
unsigned(Val64))
1883 return tokError(
"expected 32-bit integer (too large)");
1891bool LLParser::parseUInt64(
uint64_t &Val) {
1893 return tokError(
"expected integer");
1906 return tokError(
"expected localdynamic, initialexec or localexec");
1934 return parseTLSModel(TLM) ||
1935 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1943bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1944 AddrSpace = DefaultAS;
1948 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1951 if (AddrSpaceStr ==
"A") {
1952 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1953 }
else if (AddrSpaceStr ==
"G") {
1954 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1955 }
else if (AddrSpaceStr ==
"P") {
1956 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1958 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1964 return tokError(
"expected integer or string constant");
1966 if (parseUInt32(AddrSpace))
1968 if (!isUInt<24>(AddrSpace))
1969 return error(Loc,
"invalid address space, must be a 24-bit integer");
1973 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1974 ParseAddrspaceValue(AddrSpace) ||
1985 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1987 B.addAttribute(Attr, Val);
1992bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1993 bool HaveError =
false;
2000 if (parseStringAttribute(
B))
2010 if (parseEnumAttribute(Attr,
B,
false))
2014 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2016 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2064bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2065 unsigned &Visibility,
2066 unsigned &DLLStorageClass,
bool &DSOLocal) {
2070 parseOptionalDSOLocal(DSOLocal);
2071 parseOptionalVisibility(Visibility);
2072 parseOptionalDLLStorageClass(DLLStorageClass);
2075 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2081void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2103void LLParser::parseOptionalVisibility(
unsigned &Res) {
2121bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2125 return tokError(
"unknown import kind. Expect definition or declaration.");
2140void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2210bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2286 return parseUInt32(
CC);
2296bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2303 return parseMDNode(MD);
2308bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2311 return tokError(
"expected metadata after comma");
2315 if (parseMetadataAttachment(MDK,
N))
2318 if (MDK == LLVMContext::MD_DIAssignID)
2319 TempDIAssignIDAttachments[
N].push_back(&Inst);
2323 if (MDK == LLVMContext::MD_tbaa)
2324 InstsWithTBAATag.push_back(&Inst);
2333bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2336 if (parseMetadataAttachment(MDK,
N))
2345bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2347 if (parseGlobalObjectMetadataAttachment(
F))
2355bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2356 Alignment = std::nullopt;
2357 if (!EatIfPresent(lltok::kw_align))
2363 bool HaveParens =
false;
2369 if (parseUInt64(
Value))
2373 return error(ParenLoc,
"expected ')'");
2376 return error(AlignLoc,
"alignment is not a power of two");
2378 return error(AlignLoc,
"huge alignments are not supported yet");
2389 auto ErrMsg =
"expected global code model string";
2390 if (StrVal ==
"tiny")
2392 else if (StrVal ==
"small")
2394 else if (StrVal ==
"kernel")
2396 else if (StrVal ==
"medium")
2398 else if (StrVal ==
"large")
2401 return tokError(ErrMsg);
2412bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2414 assert((AttrKind == lltok::kw_dereferenceable ||
2415 AttrKind == lltok::kw_dereferenceable_or_null) &&
2419 if (!EatIfPresent(AttrKind))
2423 return error(ParenLoc,
"expected '('");
2425 if (parseUInt64(Bytes))
2429 return error(ParenLoc,
"expected ')'");
2431 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2435bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2446 return error(KindLoc,
"expected unwind table kind");
2455 return error(ParenLoc,
"expected '('");
2458 if (parseStringConstant(Arg))
2459 return error(KindLoc,
"expected allockind value");
2463 }
else if (
A ==
"realloc") {
2465 }
else if (
A ==
"free") {
2467 }
else if (
A ==
"uninitialized") {
2469 }
else if (
A ==
"zeroed") {
2471 }
else if (
A ==
"aligned") {
2474 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2479 return error(ParenLoc,
"expected ')'");
2481 return error(KindLoc,
"expected allockind value");
2492 return std::nullopt;
2507 return std::nullopt;
2511std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2521 tokError(
"expected '('");
2522 return std::nullopt;
2525 bool SeenLoc =
false;
2531 tokError(
"expected ':' after location");
2532 return std::nullopt;
2539 tokError(
"expected memory location (argmem, inaccessiblemem) "
2540 "or access kind (none, read, write, readwrite)");
2542 tokError(
"expected access kind (none, read, write, readwrite)");
2543 return std::nullopt;
2552 tokError(
"default access kind must be specified first");
2553 return std::nullopt;
2562 tokError(
"unterminated memory attribute");
2563 return std::nullopt;
2605unsigned LLParser::parseNoFPClassAttr() {
2610 tokError(
"expected '('");
2617 if (TestMask != 0) {
2621 !parseUInt64(
Value)) {
2623 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2634 error(Lex.
getLoc(),
"expected nofpclass test mask");
2652bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2653 bool &AteExtraComma) {
2654 AteExtraComma =
false;
2658 AteExtraComma =
true;
2662 if (Lex.
getKind() != lltok::kw_align)
2663 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2665 if (parseOptionalAlignment(Alignment))
2678bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2679 bool &AteExtraComma) {
2680 AteExtraComma =
false;
2684 AteExtraComma =
true;
2690 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2692 if (parseOptionalAddrSpace(AddrSpace))
2699bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2700 std::optional<unsigned> &HowManyArg) {
2703 auto StartParen = Lex.
getLoc();
2705 return error(StartParen,
"expected '('");
2707 if (parseUInt32(BaseSizeArg))
2711 auto HowManyAt = Lex.
getLoc();
2713 if (parseUInt32(HowMany))
2715 if (HowMany == BaseSizeArg)
2716 return error(HowManyAt,
2717 "'allocsize' indices can't refer to the same parameter");
2718 HowManyArg = HowMany;
2720 HowManyArg = std::nullopt;
2722 auto EndParen = Lex.
getLoc();
2724 return error(EndParen,
"expected ')'");
2728bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2729 unsigned &MaxValue) {
2732 auto StartParen = Lex.
getLoc();
2734 return error(StartParen,
"expected '('");
2736 if (parseUInt32(MinValue))
2740 if (parseUInt32(MaxValue))
2743 MaxValue = MinValue;
2745 auto EndParen = Lex.
getLoc();
2747 return error(EndParen,
"expected ')'");
2756bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2761 return parseScope(SSID) || parseOrdering(Ordering);
2771 auto StartParenAt = Lex.
getLoc();
2773 return error(StartParenAt,
"Expected '(' in syncscope");
2776 auto SSNAt = Lex.
getLoc();
2777 if (parseStringConstant(SSN))
2778 return error(SSNAt,
"Expected synchronization scope name");
2780 auto EndParenAt = Lex.
getLoc();
2782 return error(EndParenAt,
"Expected ')' in syncscope");
2797 return tokError(
"Expected ordering on atomic instruction");
2816bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2818 if (!EatIfPresent(lltok::kw_alignstack))
2822 return error(ParenLoc,
"expected '('");
2824 if (parseUInt32(Alignment))
2828 return error(ParenLoc,
"expected ')'");
2830 return error(AlignLoc,
"stack alignment is not a power of two");
2844 bool &AteExtraComma) {
2845 AteExtraComma =
false;
2848 return tokError(
"expected ',' as start of index list");
2852 if (Indices.
empty())
2853 return tokError(
"expected index");
2854 AteExtraComma =
true;
2858 if (parseUInt32(
Idx))
2871bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2875 return tokError(Msg);
2884 if (
Result->isPointerTy()) {
2886 if (parseOptionalAddrSpace(AddrSpace))
2892 return tokError(
"ptr* is invalid - use ptr instead");
2903 if (parseTargetExtType(Result))
2909 if (parseAnonStructType(Result,
false))
2915 if (parseArrayVectorType(Result,
false))
2922 if (parseAnonStructType(Result,
true) ||
2923 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2925 }
else if (parseArrayVectorType(Result,
true))
2964 if (!AllowVoid &&
Result->isVoidTy())
2965 return error(TypeLoc,
"void type only allowed for function results");
2971 return tokError(
"basic block pointers are invalid");
2973 return tokError(
"pointers to void are invalid - use i8* instead");
2975 return tokError(
"pointer to this type is invalid");
2983 return tokError(
"basic block pointers are invalid");
2985 return tokError(
"pointers to void are invalid; use i8* instead");
2987 return tokError(
"pointer to this type is invalid");
2989 if (parseOptionalAddrSpace(AddrSpace) ||
2990 parseToken(
lltok::star,
"expected '*' in address space"))
2999 if (parseFunctionType(Result))
3012 PerFunctionState &PFS,
bool IsMustTailCall,
3013 bool InVarArgsFunc) {
3019 if (!ArgList.
empty() &&
3020 parseToken(
lltok::comma,
"expected ',' in argument list"))
3025 const char *Msg =
"unexpected ellipsis in argument list for ";
3026 if (!IsMustTailCall)
3027 return tokError(
Twine(Msg) +
"non-musttail call");
3029 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3031 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3036 Type *ArgTy =
nullptr;
3038 if (parseType(ArgTy, ArgLoc))
3044 if (parseMetadataAsValue(V, PFS))
3048 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3055 if (IsMustTailCall && InVarArgsFunc)
3056 return tokError(
"expected '...' at end of argument list for musttail call "
3057 "in varargs function");
3068 if (!EatIfPresent(AttrToken))
3077 B.addTypeAttr(AttrKind, Ty);
3093 return tokError(
"expected integer");
3096 "integer is too large for the bit width of specified type");
3102 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3105 return error(TyLoc,
"the range must have integer type!");
3113 return tokError(
"the range represent the empty set but limits aren't 0!");
3127 auto ParseAPSInt = [&](
APInt &Val) {
3129 return tokError(
"expected integer");
3150 return tokError(
"the range should not represent the full or empty set!");
3162 if (!CRLOrNull.has_value())
3163 return tokError(
"Invalid (unordered or overlapping) range list");
3164 B.addInitializesAttr(*CRLOrNull);
3177bool LLParser::parseOptionalOperandBundles(
3185 if (!BundleList.
empty() &&
3186 parseToken(
lltok::comma,
"expected ',' in input list"))
3190 if (parseStringConstant(
Tag))
3193 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3196 std::vector<Value *> Inputs;
3199 if (!Inputs.empty() &&
3200 parseToken(
lltok::comma,
"expected ',' in input list"))
3204 Value *Input =
nullptr;
3205 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3207 Inputs.push_back(Input);
3215 if (BundleList.
empty())
3216 return error(BeginLoc,
"operand bundle set must not be empty");
3223 unsigned NextID,
unsigned ID)
const {
3225 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3226 Twine(NextID) +
"' or greater");
3243 unsigned CurValID = 0;
3258 Type *ArgTy =
nullptr;
3260 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3264 return error(TypeLoc,
"argument can not have void type");
3274 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3281 CurValID = ArgID + 1;
3285 return error(TypeLoc,
"invalid type for function argument");
3293 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3298bool LLParser::parseFunctionType(
Type *&Result) {
3302 return tokError(
"invalid function return type");
3307 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3311 for (
const ArgInfo &Arg : ArgList) {
3312 if (!Arg.Name.empty())
3313 return error(Arg.Loc,
"argument name invalid in function type");
3314 if (Arg.Attrs.hasAttributes())
3315 return error(Arg.Loc,
"argument attributes invalid in function type");
3319 for (
const ArgInfo &Arg : ArgList)
3328bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3330 if (parseStructBody(Elts))
3339 std::pair<Type *, LocTy> &Entry,
3343 return error(TypeLoc,
"redefinition of type");
3354 ResultTy =
Entry.first;
3366 return error(TypeLoc,
"forward references to non-struct type");
3370 return parseArrayVectorType(ResultTy,
true);
3371 return parseType(ResultTy);
3384 if (parseStructBody(Body) ||
3385 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3414 return error(EltTyLoc,
"invalid element type for struct");
3422 return error(EltTyLoc,
"invalid element type for struct");
3427 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3436bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3437 bool Scalable =
false;
3441 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3449 return tokError(
"expected number in address space");
3455 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3459 Type *EltTy =
nullptr;
3460 if (parseType(EltTy))
3464 "expected end of sequential type"))
3469 return error(SizeLoc,
"zero element vector is illegal");
3471 return error(SizeLoc,
"size too large for vector");
3473 return error(TypeLoc,
"invalid vector element type");
3477 return error(TypeLoc,
"invalid array element type");
3494bool LLParser::parseTargetExtType(
Type *&Result) {
3499 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3500 parseStringConstant(TypeName))
3508 bool SeenInt =
false;
3515 if (parseUInt32(IntVal))
3518 }
else if (SeenInt) {
3521 return tokError(
"expected uint32 param");
3524 if (parseType(TypeParam,
true))
3530 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3544 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3547 auto It = UnnamedArgNums.
begin();
3550 unsigned ArgNum = *It++;
3551 NumberedVals.add(ArgNum, &
A);
3556LLParser::PerFunctionState::~PerFunctionState() {
3559 for (
const auto &
P : ForwardRefVals) {
3560 if (isa<BasicBlock>(
P.second.first))
3562 P.second.first->replaceAllUsesWith(
3564 P.second.first->deleteValue();
3567 for (
const auto &
P : ForwardRefValIDs) {
3568 if (isa<BasicBlock>(
P.second.first))
3570 P.second.first->replaceAllUsesWith(
3572 P.second.first->deleteValue();
3576bool LLParser::PerFunctionState::finishFunction() {
3577 if (!ForwardRefVals.empty())
3578 return P.error(ForwardRefVals.begin()->second.second,
3579 "use of undefined value '%" + ForwardRefVals.begin()->first +
3581 if (!ForwardRefValIDs.empty())
3582 return P.error(ForwardRefValIDs.begin()->second.second,
3583 "use of undefined value '%" +
3584 Twine(ForwardRefValIDs.begin()->first) +
"'");
3591Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3594 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3599 auto I = ForwardRefVals.find(
Name);
3600 if (
I != ForwardRefVals.end())
3601 Val =
I->second.first;
3606 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3610 P.error(Loc,
"invalid use of a non-first-class type");
3622 P.error(Loc,
"name is too long which can result in name collisions, "
3623 "consider making the name shorter or "
3624 "increasing -non-global-value-max-name-size");
3628 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3632Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3634 Value *Val = NumberedVals.get(
ID);
3639 auto I = ForwardRefValIDs.find(
ID);
3640 if (
I != ForwardRefValIDs.end())
3641 Val =
I->second.first;
3646 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3649 P.error(Loc,
"invalid use of a non-first-class type");
3661 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3667bool LLParser::PerFunctionState::setInstName(
int NameID,
3668 const std::string &NameStr,
3672 if (NameID != -1 || !NameStr.empty())
3673 return P.error(NameLoc,
"instructions returning void cannot have a name");
3679 if (NameStr.empty()) {
3682 NameID = NumberedVals.getNext();
3684 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3688 auto FI = ForwardRefValIDs.find(NameID);
3689 if (FI != ForwardRefValIDs.end()) {
3692 return P.error(NameLoc,
"instruction forward referenced with type '" +
3696 Sentinel->replaceAllUsesWith(Inst);
3698 ForwardRefValIDs.erase(FI);
3701 NumberedVals.add(NameID, Inst);
3706 auto FI = ForwardRefVals.find(NameStr);
3707 if (FI != ForwardRefVals.end()) {
3710 return P.error(NameLoc,
"instruction forward referenced with type '" +
3714 Sentinel->replaceAllUsesWith(Inst);
3716 ForwardRefVals.erase(FI);
3722 if (Inst->
getName() != NameStr)
3723 return P.error(NameLoc,
"multiple definition of local value named '" +
3730BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3732 return dyn_cast_or_null<BasicBlock>(
3736BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3737 return dyn_cast_or_null<BasicBlock>(
3744BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3745 int NameID, LocTy Loc) {
3749 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3752 NameID = NumberedVals.getNext();
3754 BB = getBB(NameID, Loc);
3756 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3760 BB = getBB(
Name, Loc);
3762 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3773 ForwardRefValIDs.erase(NameID);
3774 NumberedVals.add(NameID, BB);
3777 ForwardRefVals.erase(
Name);
3794bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3798 return tokError(
"expected value token");
3841 if (parseGlobalValueVector(Elts) ||
3842 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3845 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3846 ID.UIntVal = Elts.
size();
3847 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3848 Elts.
size() *
sizeof(Elts[0]));
3860 if (parseGlobalValueVector(Elts) ||
3862 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3866 if (isPackedStruct) {
3867 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3868 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3869 Elts.
size() *
sizeof(Elts[0]));
3870 ID.UIntVal = Elts.
size();
3876 return error(
ID.Loc,
"constant vector must not be empty");
3878 if (!Elts[0]->
getType()->isIntegerTy() &&
3879 !Elts[0]->
getType()->isFloatingPointTy() &&
3883 "vector elements must have integer, pointer or floating point type");
3886 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3888 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3889 " is not of type '" +
3900 if (parseGlobalValueVector(Elts) ||
3912 if (!Elts[0]->
getType()->isFirstClassType())
3913 return error(FirstEltLoc,
"invalid array element type: " +
3919 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3921 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3922 " is not of type '" +
3942 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3945 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3948 parseStringConstant(
ID.StrVal) ||
3949 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3954 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3965 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3966 parseValID(Fn, PFS) ||
3968 "expected comma in block address expression") ||
3969 parseValID(Label, PFS) ||
3970 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3974 return error(Fn.
Loc,
"expected function name in blockaddress");
3976 return error(
Label.Loc,
"expected basic block name in blockaddress");
3981 GV = NumberedVals.get(Fn.
UIntVal);
3982 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3983 GV =
M->getNamedValue(Fn.
StrVal);
3988 if (!isa<Function>(GV))
3989 return error(Fn.
Loc,
"expected function name in blockaddress");
3990 F = cast<Function>(GV);
3991 if (
F->isDeclaration())
3992 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3998 ForwardRefBlockAddresses.insert(std::make_pair(
4000 std::map<ValID, GlobalValue *>()))
4001 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
4010 "type of blockaddress must be a pointer and not '" +
4015 FwdDeclAS = PFS->getFunction().getAddressSpace();
4024 ID.ConstantVal = FwdRef;
4032 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4034 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4036 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4038 return error(
Label.Loc,
"referenced value is not a basic block");
4041 return error(
Label.Loc,
"cannot take address of numeric label after "
4042 "the function is defined");
4043 BB = dyn_cast_or_null<BasicBlock>(
4044 F->getValueSymbolTable()->lookup(
Label.StrVal));
4046 return error(
Label.Loc,
"referenced value is not a basic block");
4060 if (parseValID(Fn, PFS))
4065 "expected global value name in dso_local_equivalent");
4070 GV = NumberedVals.get(Fn.
UIntVal);
4071 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4072 GV =
M->getNamedValue(Fn.
StrVal);
4078 ? ForwardRefDSOLocalEquivalentIDs
4079 : ForwardRefDSOLocalEquivalentNames;
4080 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
4087 ID.ConstantVal = FwdRef;
4093 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4094 "in dso_local_equivalent");
4105 if (parseValID(
ID, PFS))
4109 return error(
ID.Loc,
"expected global value name in no_cfi");
4120 Constant *Disc =
nullptr, *AddrDisc =
nullptr;
4123 "expected '(' in constant ptrauth expression") ||
4124 parseGlobalTypeAndValue(
Ptr) ||
4126 "expected comma in constant ptrauth expression") ||
4127 parseGlobalTypeAndValue(Key))
4131 if (parseGlobalTypeAndValue(Disc) ||
4132 (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4135 "expected ')' in constant ptrauth expression"))
4138 if (!
Ptr->getType()->isPointerTy())
4139 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4141 auto *KeyC = dyn_cast<ConstantInt>(Key);
4142 if (!KeyC || KeyC->getBitWidth() != 32)
4143 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4147 DiscC = dyn_cast<ConstantInt>(Disc);
4151 "constant ptrauth integer discriminator must be i64 constant");
4157 if (!AddrDisc->getType()->isPointerTy())
4159 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4175 Type *DestTy =
nullptr;
4178 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4179 parseGlobalTypeAndValue(SrcVal) ||
4180 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4181 parseType(DestTy) ||
4182 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4185 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4194 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4196 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4198 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4200 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4202 return error(
ID.Loc,
"urem constexprs are no longer supported");
4204 return error(
ID.Loc,
"srem constexprs are no longer supported");
4206 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4208 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4210 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4212 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4214 return error(
ID.Loc,
"frem constexprs are no longer supported");
4216 return error(
ID.Loc,
"and constexprs are no longer supported");
4218 return error(
ID.Loc,
"or constexprs are no longer supported");
4220 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4222 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4224 return error(
ID.Loc,
"shl constexprs are no longer supported");
4226 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4228 return error(
ID.Loc,
"select constexprs are no longer supported");
4230 return error(
ID.Loc,
"zext constexprs are no longer supported");
4232 return error(
ID.Loc,
"sext constexprs are no longer supported");
4234 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4236 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4238 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4240 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4242 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4244 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4246 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4248 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4260 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4261 Opc == Instruction::Mul) {
4270 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4271 parseGlobalTypeAndValue(Val0) ||
4272 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4273 parseGlobalTypeAndValue(Val1) ||
4274 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4277 return error(
ID.Loc,
"operands of constexpr must have same type");
4281 "constexpr requires integer or integer vector operands");
4292 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4295 if (parseGlobalTypeAndValue(
C))
4297 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4312 bool HasInRange =
false;
4318 if (Opc == Instruction::GetElementPtr) {
4334 return tokError(
"expected integer");
4340 return tokError(
"expected integer");
4349 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4352 if (Opc == Instruction::GetElementPtr) {
4353 if (parseType(Ty) ||
4354 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4358 if (parseGlobalValueVector(Elts) ||
4362 if (Opc == Instruction::GetElementPtr) {
4363 if (Elts.
size() == 0 ||
4364 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4365 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4368 std::optional<ConstantRange>
InRange;
4370 unsigned IndexWidth =
4371 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4372 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4373 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4374 if (InRangeStart.
sge(InRangeEnd))
4375 return error(
ID.Loc,
"expected end to be larger than start");
4381 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4388 return error(
ID.Loc,
"getelementptr index must be an integer");
4389 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4390 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4391 if (GEPWidth && (ValNumEl != GEPWidth))
4394 "getelementptr vector index has a wrong number of elements");
4397 GEPWidth = ValNumEl;
4402 if (!Indices.empty() && !Ty->
isSized(&Visited))
4403 return error(
ID.Loc,
"base element of getelementptr must be sized");
4406 return error(
ID.Loc,
"invalid getelementptr indices");
4410 }
else if (Opc == Instruction::ShuffleVector) {
4411 if (Elts.
size() != 3)
4412 return error(
ID.Loc,
"expected three operands to shufflevector");
4414 return error(
ID.Loc,
"invalid operands to shufflevector");
4418 }
else if (Opc == Instruction::ExtractElement) {
4419 if (Elts.
size() != 2)
4420 return error(
ID.Loc,
"expected two operands to extractelement");
4422 return error(
ID.Loc,
"invalid extractelement operands");
4425 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4426 if (Elts.
size() != 3)
4427 return error(
ID.Loc,
"expected three operands to insertelement");
4429 return error(
ID.Loc,
"invalid insertelement operands");
4448 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4449 convertValIDToValue(Ty,
ID, V,
nullptr);
4450 if (V && !(
C = dyn_cast<Constant>(V)))
4451 return error(
ID.Loc,
"global values must be constants");
4455bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4457 return parseType(Ty) || parseGlobalValue(Ty, V);
4469 return tokError(
"expected comdat variable");
4472 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4475 if (GlobalName.
empty())
4476 return tokError(
"comdat cannot be unnamed");
4477 C = getComdat(std::string(GlobalName), KwLoc);
4500 if (parseGlobalTypeAndValue(
C))
4508bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4510 if (parseMDNodeVector(Elts))
4521bool LLParser::parseMDNode(
MDNode *&
N) {
4523 return parseSpecializedMDNode(
N);
4525 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4528bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4531 return parseMDTuple(
N);
4534 return parseMDNodeID(
N);
4540template <
class FieldTy>
struct MDFieldImpl {
4541 typedef MDFieldImpl ImplTy;
4545 void assign(FieldTy Val) {
4547 this->Val = std::move(Val);
4550 explicit MDFieldImpl(FieldTy
Default)
4558template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4559 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4570 void assign(FieldTypeA
A) {
4572 this->A = std::move(
A);
4576 void assign(FieldTypeB
B) {
4578 this->B = std::move(
B);
4582 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4584 WhatIs(IsInvalid) {}
4587struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4594struct LineField :
public MDUnsignedField {
4595 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4598struct ColumnField :
public MDUnsignedField {
4599 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4602struct DwarfTagField :
public MDUnsignedField {
4608struct DwarfMacinfoTypeField :
public MDUnsignedField {
4614struct DwarfAttEncodingField :
public MDUnsignedField {
4615 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4618struct DwarfVirtualityField :
public MDUnsignedField {
4622struct DwarfLangField :
public MDUnsignedField {
4626struct DwarfCCField :
public MDUnsignedField {
4627 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4630struct EmissionKindField :
public MDUnsignedField {
4631 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4634struct NameTableKindField :
public MDUnsignedField {
4635 NameTableKindField()
4638 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4641struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4642 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4645struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4646 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4649struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4650 MDAPSIntField() : ImplTy(
APSInt()) {}
4653struct MDSignedField :
public MDFieldImpl<int64_t> {
4657 MDSignedField(int64_t
Default = 0)
4659 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4663struct MDBoolField :
public MDFieldImpl<bool> {
4667struct MDField :
public MDFieldImpl<Metadata *> {
4670 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4673struct MDStringField :
public MDFieldImpl<MDString *> {
4675 MDStringField(
bool AllowEmpty =
true)
4676 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4679struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4683struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4687struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4688 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4689 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4691 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4692 bool AllowNull =
true)
4693 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4695 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4696 bool isMDField()
const {
return WhatIs == IsTypeB; }
4697 int64_t getMDSignedValue()
const {
4698 assert(isMDSignedField() &&
"Wrong field type");
4701 Metadata *getMDFieldValue()
const {
4702 assert(isMDField() &&
"Wrong field type");
4714 return tokError(
"expected integer");
4723 MDUnsignedField &Result) {
4725 return tokError(
"expected unsigned integer");
4728 if (U.ugt(Result.Max))
4729 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4731 Result.assign(U.getZExtValue());
4732 assert(Result.Val <= Result.Max &&
"Expected value in range");
4739 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4743 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4749 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4752 return tokError(
"expected DWARF tag");
4756 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4757 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4766 DwarfMacinfoTypeField &Result) {
4768 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4771 return tokError(
"expected DWARF macinfo type");
4775 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4777 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4779 Result.assign(Macinfo);
4786 DwarfVirtualityField &Result) {
4788 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4791 return tokError(
"expected DWARF virtuality code");
4795 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4797 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4798 Result.assign(Virtuality);
4806 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4809 return tokError(
"expected DWARF language");
4813 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4815 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4816 Result.assign(Lang);
4824 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4827 return tokError(
"expected DWARF calling convention");
4831 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4833 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4841 EmissionKindField &Result) {
4843 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4846 return tokError(
"expected emission kind");
4850 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4852 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4853 Result.assign(*Kind);
4860 NameTableKindField &Result) {
4862 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4865 return tokError(
"expected nameTable kind");
4869 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4871 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4872 Result.assign((
unsigned)*Kind);
4879 DwarfAttEncodingField &Result) {
4881 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4884 return tokError(
"expected DWARF type attribute encoding");
4888 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4890 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4891 Result.assign(Encoding);
4907 bool Res = parseUInt32(TempVal);
4913 return tokError(
"expected debug info flag");
4917 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4932 Result.assign(Combined);
4947 bool Res = parseUInt32(TempVal);
4953 return tokError(
"expected debug info flag");
4957 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4972 Result.assign(Combined);
4979 return tokError(
"expected signed integer");
4983 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4986 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4988 Result.assign(S.getExtValue());
4989 assert(Result.Val >= Result.Min &&
"Expected value in range");
4990 assert(Result.Val <= Result.Max &&
"Expected value in range");
4999 return tokError(
"expected 'true' or 'false'");
5001 Result.assign(
true);
5004 Result.assign(
false);
5014 if (!Result.AllowNull)
5015 return tokError(
"'" +
Name +
"' cannot be null");
5017 Result.assign(
nullptr);
5022 if (parseMetadata(MD,
nullptr))
5031 MDSignedOrMDField &Result) {
5034 MDSignedField Res = Result.A;
5035 if (!parseMDField(Loc,
Name, Res)) {
5043 MDField Res = Result.B;
5044 if (!parseMDField(Loc,
Name, Res)) {
5056 if (parseStringConstant(S))
5059 if (!Result.AllowEmpty && S.empty())
5060 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
5062 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
5069 if (parseMDNodeVector(MDs))
5072 Result.assign(std::move(MDs));
5078 ChecksumKindField &Result) {
5079 std::optional<DIFile::ChecksumKind> CSKind =
5083 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
5086 Result.assign(*CSKind);
5093template <
class ParserTy>
5094bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5097 return tokError(
"expected field label here");
5106template <
class ParserTy>
5107bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5114 if (parseMDFieldsImplBody(ParseField))
5117 ClosingLoc = Lex.
getLoc();
5121template <
class FieldTy>
5122bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5124 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5128 return parseMDField(Loc,
Name, Result);
5131bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5134#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5135 if (Lex.getStrVal() == #CLASS) \
5136 return parse##CLASS(N, IsDistinct);
5137#include "llvm/IR/Metadata.def"
5139 return tokError(
"expected metadata type");
5142#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5143#define NOP_FIELD(NAME, TYPE, INIT)
5144#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5146 return error(ClosingLoc, "missing required field '" #NAME "'");
5147#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5148 if (Lex.getStrVal() == #NAME) \
5149 return parseMDField(#NAME, NAME);
5150#define PARSE_MD_FIELDS() \
5151 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5154 if (parseMDFieldsImpl( \
5156 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5157 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5162 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5164#define GET_OR_DISTINCT(CLASS, ARGS) \
5165 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5170bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5171#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5172 OPTIONAL(line, LineField, ); \
5173 OPTIONAL(column, ColumnField, ); \
5174 REQUIRED(scope, MDField, ( false)); \
5175 OPTIONAL(inlinedAt, MDField, ); \
5176 OPTIONAL(isImplicitCode, MDBoolField, (false));
5178#undef VISIT_MD_FIELDS
5182 inlinedAt.Val, isImplicitCode.Val));
5188bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5190 return Lex.
Error(
"missing 'distinct', required for !DIAssignID()");
5206bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5207#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5208 REQUIRED(tag, DwarfTagField, ); \
5209 OPTIONAL(header, MDStringField, ); \
5210 OPTIONAL(operands, MDFieldList, );
5212#undef VISIT_MD_FIELDS
5215 (Context, tag.Val, header.Val, operands.Val));
5223bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5224#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5225 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5226 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5227 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5228 OPTIONAL(stride, MDSignedOrMDField, );
5230#undef VISIT_MD_FIELDS
5237 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5238 if (Bound.isMDSignedField())
5241 if (Bound.isMDField())
5242 return Bound.getMDFieldValue();
5246 Count = convToMetadata(
count);
5247 LowerBound = convToMetadata(lowerBound);
5249 Stride = convToMetadata(stride);
5252 (Context, Count, LowerBound, UpperBound, Stride));
5260bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5261#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5262 OPTIONAL(count, MDSignedOrMDField, ); \
5263 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5264 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5265 OPTIONAL(stride, MDSignedOrMDField, );
5267#undef VISIT_MD_FIELDS
5269 auto ConvToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5270 if (Bound.isMDSignedField())
5272 Context, {dwarf::DW_OP_consts,
5273 static_cast<uint64_t>(Bound.getMDSignedValue())});
5274 if (Bound.isMDField())
5275 return Bound.getMDFieldValue();
5280 Metadata *LowerBound = ConvToMetadata(lowerBound);
5282 Metadata *Stride = ConvToMetadata(stride);
5285 (Context, Count, LowerBound, UpperBound, Stride));
5292bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5293#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5294 REQUIRED(name, MDStringField, ); \
5295 REQUIRED(value, MDAPSIntField, ); \
5296 OPTIONAL(isUnsigned, MDBoolField, (false));
5298#undef VISIT_MD_FIELDS
5300 if (isUnsigned.Val &&
value.Val.isNegative())
5301 return tokError(
"unsigned enumerator with negative value");
5306 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5318bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5319#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5320 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5321 OPTIONAL(name, MDStringField, ); \
5322 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5323 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5324 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5325 OPTIONAL(flags, DIFlagField, );
5327#undef VISIT_MD_FIELDS
5330 align.Val, encoding.Val, flags.Val));
5336bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5337#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5338 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5339 OPTIONAL(name, MDStringField, ); \
5340 OPTIONAL(stringLength, MDField, ); \
5341 OPTIONAL(stringLengthExpression, MDField, ); \
5342 OPTIONAL(stringLocationExpression, MDField, ); \
5343 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5344 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5345 OPTIONAL(encoding, DwarfAttEncodingField, );
5347#undef VISIT_MD_FIELDS
5351 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5352 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5365bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5366#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5367 REQUIRED(tag, DwarfTagField, ); \
5368 OPTIONAL(name, MDStringField, ); \
5369 OPTIONAL(file, MDField, ); \
5370 OPTIONAL(line, LineField, ); \
5371 OPTIONAL(scope, MDField, ); \
5372 REQUIRED(baseType, MDField, ); \
5373 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5374 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5375 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5376 OPTIONAL(flags, DIFlagField, ); \
5377 OPTIONAL(extraData, MDField, ); \
5378 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5379 OPTIONAL(annotations, MDField, ); \
5380 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5381 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5382 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5383 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5384 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5386#undef VISIT_MD_FIELDS
5388 std::optional<unsigned> DWARFAddressSpace;
5389 if (dwarfAddressSpace.Val != UINT32_MAX)
5390 DWARFAddressSpace = dwarfAddressSpace.Val;
5391 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5393 PtrAuthData.emplace(
5394 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5395 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5396 ptrAuthAuthenticatesNullValues.Val);
5399 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5400 scope.Val, baseType.Val,
size.Val, align.Val,
5401 offset.Val, DWARFAddressSpace, PtrAuthData,
5402 flags.Val, extraData.Val, annotations.Val));
5406bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5407#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5408 REQUIRED(tag, DwarfTagField, ); \
5409 OPTIONAL(name, MDStringField, ); \
5410 OPTIONAL(file, MDField, ); \
5411 OPTIONAL(line, LineField, ); \
5412 OPTIONAL(scope, MDField, ); \
5413 OPTIONAL(baseType, MDField, ); \
5414 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5415 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5416 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5417 OPTIONAL(flags, DIFlagField, ); \
5418 OPTIONAL(elements, MDField, ); \
5419 OPTIONAL(runtimeLang, DwarfLangField, ); \
5420 OPTIONAL(vtableHolder, MDField, ); \
5421 OPTIONAL(templateParams, MDField, ); \
5422 OPTIONAL(identifier, MDStringField, ); \
5423 OPTIONAL(discriminator, MDField, ); \
5424 OPTIONAL(dataLocation, MDField, ); \
5425 OPTIONAL(associated, MDField, ); \
5426 OPTIONAL(allocated, MDField, ); \
5427 OPTIONAL(rank, MDSignedOrMDField, ); \
5428 OPTIONAL(annotations, MDField, );
5430#undef VISIT_MD_FIELDS
5433 if (
rank.isMDSignedField())
5436 else if (
rank.isMDField())
5437 Rank =
rank.getMDFieldValue();
5442 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5443 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val,
5444 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5445 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5446 Rank, annotations.Val)) {
5455 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5456 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5457 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5458 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5463bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5464#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5465 OPTIONAL(flags, DIFlagField, ); \
5466 OPTIONAL(cc, DwarfCCField, ); \
5467 REQUIRED(types, MDField, );
5469#undef VISIT_MD_FIELDS
5472 (Context, flags.Val, cc.Val, types.Val));
5481bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5485#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5486 REQUIRED(filename, MDStringField, ); \
5487 REQUIRED(directory, MDStringField, ); \
5488 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5489 OPTIONAL(checksum, MDStringField, ); \
5490 OPTIONAL(source, MDStringField, );
5492#undef VISIT_MD_FIELDS
5494 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5495 if (checksumkind.Seen && checksum.Seen)
5496 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5497 else if (checksumkind.Seen || checksum.Seen)
5498 return Lex.
Error(
"'checksumkind' and 'checksum' must be provided together");
5504 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5515bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5517 return Lex.
Error(
"missing 'distinct', required for !DICompileUnit");
5519#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5520 REQUIRED(language, DwarfLangField, ); \
5521 REQUIRED(file, MDField, ( false)); \
5522 OPTIONAL(producer, MDStringField, ); \
5523 OPTIONAL(isOptimized, MDBoolField, ); \
5524 OPTIONAL(flags, MDStringField, ); \
5525 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5526 OPTIONAL(splitDebugFilename, MDStringField, ); \
5527 OPTIONAL(emissionKind, EmissionKindField, ); \
5528 OPTIONAL(enums, MDField, ); \
5529 OPTIONAL(retainedTypes, MDField, ); \
5530 OPTIONAL(globals, MDField, ); \
5531 OPTIONAL(imports, MDField, ); \
5532 OPTIONAL(macros, MDField, ); \
5533 OPTIONAL(dwoId, MDUnsignedField, ); \
5534 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5535 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5536 OPTIONAL(nameTableKind, NameTableKindField, ); \
5537 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5538 OPTIONAL(sysroot, MDStringField, ); \
5539 OPTIONAL(sdk, MDStringField, );
5541#undef VISIT_MD_FIELDS
5544 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5545 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5546 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5547 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5548 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5561bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5563#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5564 OPTIONAL(scope, MDField, ); \
5565 OPTIONAL(name, MDStringField, ); \
5566 OPTIONAL(linkageName, MDStringField, ); \
5567 OPTIONAL(file, MDField, ); \
5568 OPTIONAL(line, LineField, ); \
5569 OPTIONAL(type, MDField, ); \
5570 OPTIONAL(isLocal, MDBoolField, ); \
5571 OPTIONAL(isDefinition, MDBoolField, (true)); \
5572 OPTIONAL(scopeLine, LineField, ); \
5573 OPTIONAL(containingType, MDField, ); \
5574 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5575 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5576 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5577 OPTIONAL(flags, DIFlagField, ); \
5578 OPTIONAL(spFlags, DISPFlagField, ); \
5579 OPTIONAL(isOptimized, MDBoolField, ); \
5580 OPTIONAL(unit, MDField, ); \
5581 OPTIONAL(templateParams, MDField, ); \
5582 OPTIONAL(declaration, MDField, ); \
5583 OPTIONAL(retainedNodes, MDField, ); \
5584 OPTIONAL(thrownTypes, MDField, ); \
5585 OPTIONAL(annotations, MDField, ); \
5586 OPTIONAL(targetFuncName, MDStringField, );
5588#undef VISIT_MD_FIELDS
5593 spFlags.Seen ? spFlags.Val
5595 isOptimized.Val, virtuality.Val);
5596 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5599 "missing 'distinct', required for !DISubprogram that is a Definition");
5602 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5603 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5604 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5605 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5606 targetFuncName.Val));
5612bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5613#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5614 REQUIRED(scope, MDField, ( false)); \
5615 OPTIONAL(file, MDField, ); \
5616 OPTIONAL(line, LineField, ); \
5617 OPTIONAL(column, ColumnField, );
5619#undef VISIT_MD_FIELDS
5628bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5629#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5630 REQUIRED(scope, MDField, ( false)); \
5631 OPTIONAL(file, MDField, ); \
5632 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5634#undef VISIT_MD_FIELDS
5637 (Context, scope.Val,
file.Val, discriminator.Val));
5643bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5644#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5645 REQUIRED(scope, MDField, ); \
5646 OPTIONAL(declaration, MDField, ); \
5647 OPTIONAL(name, MDStringField, ); \
5648 OPTIONAL(file, MDField, ); \
5649 OPTIONAL(line, LineField, );
5651#undef VISIT_MD_FIELDS
5654 (Context, scope.Val, declaration.Val,
name.Val,
5655 file.Val, line.Val));
5661bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5662#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5663 REQUIRED(scope, MDField, ); \
5664 OPTIONAL(name, MDStringField, ); \
5665 OPTIONAL(exportSymbols, MDBoolField, );
5667#undef VISIT_MD_FIELDS
5670 (Context, scope.Val,
name.Val, exportSymbols.Val));
5677bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5678#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5679 REQUIRED(type, DwarfMacinfoTypeField, ); \
5680 OPTIONAL(line, LineField, ); \
5681 REQUIRED(name, MDStringField, ); \
5682 OPTIONAL(value, MDStringField, );
5684#undef VISIT_MD_FIELDS
5687 (Context, type.Val, line.Val,
name.Val,
value.Val));
5693bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5694#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5695 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5696 OPTIONAL(line, LineField, ); \
5697 REQUIRED(file, MDField, ); \
5698 OPTIONAL(nodes, MDField, );
5700#undef VISIT_MD_FIELDS
5703 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5711bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5712#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5713 REQUIRED(scope, MDField, ); \
5714 REQUIRED(name, MDStringField, ); \
5715 OPTIONAL(configMacros, MDStringField, ); \
5716 OPTIONAL(includePath, MDStringField, ); \
5717 OPTIONAL(apinotes, MDStringField, ); \
5718 OPTIONAL(file, MDField, ); \
5719 OPTIONAL(line, LineField, ); \
5720 OPTIONAL(isDecl, MDBoolField, );
5722#undef VISIT_MD_FIELDS
5725 configMacros.Val, includePath.Val,
5726 apinotes.Val, line.Val, isDecl.Val));
5732bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5733#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5734 OPTIONAL(name, MDStringField, ); \
5735 REQUIRED(type, MDField, ); \
5736 OPTIONAL(defaulted, MDBoolField, );
5738#undef VISIT_MD_FIELDS
5741 (Context,
name.Val, type.Val, defaulted.Val));
5749bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5750#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5751 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5752 OPTIONAL(name, MDStringField, ); \
5753 OPTIONAL(type, MDField, ); \
5754 OPTIONAL(defaulted, MDBoolField, ); \
5755 REQUIRED(value, MDField, );
5758#undef VISIT_MD_FIELDS
5762 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5771bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5772#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5773 OPTIONAL(name, MDStringField, ( false)); \
5774 OPTIONAL(scope, MDField, ); \
5775 OPTIONAL(linkageName, MDStringField, ); \
5776 OPTIONAL(file, MDField, ); \
5777 OPTIONAL(line, LineField, ); \
5778 OPTIONAL(type, MDField, ); \
5779 OPTIONAL(isLocal, MDBoolField, ); \
5780 OPTIONAL(isDefinition, MDBoolField, (true)); \
5781 OPTIONAL(templateParams, MDField, ); \
5782 OPTIONAL(declaration, MDField, ); \
5783 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5784 OPTIONAL(annotations, MDField, );
5786#undef VISIT_MD_FIELDS
5790 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5791 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5792 declaration.Val, templateParams.Val, align.Val,
5804bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5805#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5806 REQUIRED(scope, MDField, ( false)); \
5807 OPTIONAL(name, MDStringField, ); \
5808 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5809 OPTIONAL(file, MDField, ); \
5810 OPTIONAL(line, LineField, ); \
5811 OPTIONAL(type, MDField, ); \
5812 OPTIONAL(flags, DIFlagField, ); \
5813 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5814 OPTIONAL(annotations, MDField, );
5816#undef VISIT_MD_FIELDS
5819 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5820 type.Val, arg.Val, flags.Val, align.Val,
5827bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5828#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5829 REQUIRED(scope, MDField, ( false)); \
5830 REQUIRED(name, MDStringField, ); \
5831 REQUIRED(file, MDField, ); \
5832 REQUIRED(line, LineField, );
5834#undef VISIT_MD_FIELDS
5837 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5843bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
5856 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5865 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5870 return tokError(
"expected unsigned integer");
5888bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5890 assert(Lex.
getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
5893 return parseDIExpressionBody(Result, IsDistinct);
5898bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5899 assert(PFS &&
"Expected valid function state");
5910 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5912 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5924bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
5926#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5927 REQUIRED(var, MDField, ); \
5928 REQUIRED(expr, MDField, );
5930#undef VISIT_MD_FIELDS
5940bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 OPTIONAL(name, MDStringField, ); \
5943 OPTIONAL(file, MDField, ); \
5944 OPTIONAL(line, LineField, ); \
5945 OPTIONAL(setter, MDStringField, ); \
5946 OPTIONAL(getter, MDStringField, ); \
5947 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5948 OPTIONAL(type, MDField, );
5950#undef VISIT_MD_FIELDS
5953 (Context,
name.Val,
file.Val, line.Val, setter.Val,
5954 getter.Val, attributes.Val, type.Val));
5961bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
5962#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5963 REQUIRED(tag, DwarfTagField, ); \
5964 REQUIRED(scope, MDField, ); \
5965 OPTIONAL(entity, MDField, ); \
5966 OPTIONAL(file, MDField, ); \
5967 OPTIONAL(line, LineField, ); \
5968 OPTIONAL(name, MDStringField, ); \
5969 OPTIONAL(elements, MDField, );
5971#undef VISIT_MD_FIELDS
5974 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
5975 line.Val,
name.Val, elements.Val));
5979#undef PARSE_MD_FIELD
5991bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
5994 if (parseMetadata(MD, &PFS))
6005bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6006 PerFunctionState *PFS) {
6009 if (parseType(Ty, TypeMsg, Loc))
6012 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6015 if (parseValue(Ty, V, PFS))
6030bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6036 if (parseDIArgList(AL, PFS))
6042 if (parseSpecializedMDNode(
N)) {
6052 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6062 if (parseMDString(S))
6072 if (parseMDNodeTail(
N))
6083 PerFunctionState *PFS) {
6085 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6090 return error(
ID.Loc,
"invalid use of function-local name");
6091 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6092 return V ==
nullptr;
6095 return error(
ID.Loc,
"invalid use of function-local name");
6096 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6097 return V ==
nullptr;
6100 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6104 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6109 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6112 return V ==
nullptr;
6114 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6117 return V ==
nullptr;
6120 return error(
ID.Loc,
"integer constant must have integer type");
6122 V = ConstantInt::get(Context,
ID.APSIntVal);
6127 return error(
ID.Loc,
"floating point constant invalid for type");
6133 bool IsSNAN =
ID.APFloatVal.isSignaling();
6148 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6150 ID.APFloatVal.isNegative(), &Payload);
6153 V = ConstantFP::get(Context,
ID.APFloatVal);
6155 if (
V->getType() != Ty)
6156 return error(
ID.Loc,
"floating point constant does not have type '" +
6162 return error(
ID.Loc,
"null must be a pointer type");
6168 return error(
ID.Loc,
"invalid type for undef constant");
6172 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6173 return error(
ID.Loc,
"invalid empty array initializer");
6179 return error(
ID.Loc,
"invalid type for null constant");
6180 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6182 return error(
ID.Loc,
"invalid type for null constant");
6187 return error(
ID.Loc,
"invalid type for none constant");
6193 return error(
ID.Loc,
"invalid type for poison constant");
6197 if (
ID.ConstantVal->getType() != Ty)
6198 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6205 return error(
ID.Loc,
"vector constant must have vector type");
6207 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6209 "' but expected '" +
6216 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6217 if (
ST->getNumElements() !=
ID.UIntVal)
6219 "initializer with struct type has wrong # elements");
6221 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6224 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6225 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6228 "element " +
Twine(i) +
6229 " of struct initializer doesn't match struct element type");
6232 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6234 return error(
ID.Loc,
"constant expression type mismatch");
6244 if (parseValID(
ID,
nullptr))
6255 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6257 assert(isa<Constant>(V) &&
"Expected a constant value");
6258 C = cast<Constant>(V);
6265 return error(Loc,
"expected a constant value");
6269bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6272 return parseValID(
ID, PFS, Ty) ||
6273 convertValIDToValue(Ty,
ID, V, PFS);
6276bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6278 return parseType(Ty) || parseValue(Ty, V, PFS);
6281bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6282 PerFunctionState &PFS) {
6285 if (parseTypeAndValue(V, PFS))
6287 if (!isa<BasicBlock>(V))
6288 return error(Loc,
"expected a basic block");
6289 BB = cast<BasicBlock>(V);
6297 if (!
Name.starts_with(
"llvm.dbg."))
6300 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6301 FnID == Intrinsic::dbg_assign;
6309bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6310 unsigned &FunctionNumber,
6315 unsigned Visibility;
6316 unsigned DLLStorageClass;
6321 Type *RetType =
nullptr;
6323 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6325 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6326 parseType(RetType, RetTypeLoc,
true ))
6335 return error(LinkageLoc,
"invalid linkage for function definition");
6345 return error(LinkageLoc,
"invalid linkage for function declaration");
6349 return error(LinkageLoc,
"invalid function linkage type");
6353 return error(LinkageLoc,
6354 "symbol with local linkage must have default visibility");
6357 return error(LinkageLoc,
6358 "symbol with local linkage cannot have a DLL storage class");
6361 return error(RetTypeLoc,
"invalid function return type");
6365 std::string FunctionName;
6370 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6374 return tokError(
"expected function name");
6380 return tokError(
"expected '(' in function argument list");
6385 std::vector<unsigned> FwdRefAttrGrps;
6388 std::string Partition;
6392 unsigned AddrSpace = 0;
6398 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6399 parseOptionalUnnamedAddr(UnnamedAddr) ||
6400 parseOptionalProgramAddrSpace(AddrSpace) ||
6401 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6405 parseOptionalComdat(FunctionName,
C) ||
6406 parseOptionalAlignment(Alignment) ||
6407 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6411 parseGlobalTypeAndValue(PersonalityFn)))
6414 if (FuncAttrs.contains(Attribute::Builtin))
6415 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6420 FuncAttrs.removeAttribute(Attribute::Alignment);
6425 std::vector<Type*> ParamTypeList;
6428 for (
const ArgInfo &Arg : ArgList) {
6429 ParamTypeList.push_back(Arg.Ty);
6430 Attrs.push_back(Arg.Attrs);
6438 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6445 if (!FunctionName.empty()) {
6448 auto FRVI = ForwardRefVals.find(FunctionName);
6449 if (FRVI != ForwardRefVals.end()) {
6450 FwdFn = FRVI->second.first;
6452 return error(FRVI->second.second,
6453 "invalid forward reference to "
6456 "' with wrong type: "
6460 ForwardRefVals.erase(FRVI);
6461 }
else if ((Fn =
M->getFunction(FunctionName))) {
6463 return error(NameLoc,
6464 "invalid redefinition of function '" + FunctionName +
"'");
6465 }
else if (
M->getNamedValue(FunctionName)) {
6466 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6472 if (FunctionNumber == (
unsigned)-1)
6473 FunctionNumber = NumberedVals.getNext();
6477 auto I = ForwardRefValIDs.find(FunctionNumber);
6478 if (
I != ForwardRefValIDs.end()) {
6479 FwdFn =
I->second.first;
6481 return error(NameLoc,
"type of definition and forward reference of '@" +
6482 Twine(FunctionNumber) +
6487 ForwardRefValIDs.erase(
I);
6496 if (FunctionName.empty())
6497 NumberedVals.add(FunctionNumber, Fn);
6512 if (!
GC.empty()) Fn->
setGC(GC);
6515 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6519 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6521 if (ArgList[i].
Name.empty())
continue;
6526 if (ArgIt->
getName() != ArgList[i].Name)
6527 return error(ArgList[i].Loc,
6528 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6541 if (FunctionName.empty()) {
6543 ID.UIntVal = FunctionNumber;
6546 ID.StrVal = FunctionName;
6548 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6549 if (
Blocks != ForwardRefBlockAddresses.end())
6551 "cannot take blockaddress inside a declaration");
6555bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6557 if (FunctionNumber == -1) {
6559 ID.StrVal = std::string(
F.getName());
6562 ID.UIntVal = FunctionNumber;
6565 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6566 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6569 for (
const auto &
I :
Blocks->second) {
6570 const ValID &BBID =
I.first;
6574 "Expected local id or name");
6581 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6592 P.ForwardRefBlockAddresses.erase(
Blocks);
6598bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6601 return tokError(
"expected '{' in function body");
6604 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6608 if (PFS.resolveForwardRefBlockAddresses())
6614 return tokError(
"function body requires at least one basic block");
6618 if (parseBasicBlock(PFS))
6622 if (parseUseListOrder(&PFS))
6629 return PFS.finishFunction();
6634bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6651 std::string NameStr;
6656 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6657 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6664 if (SeenOldDbgInfoFormat)
6665 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6666 "containing debug info intrinsics");
6667 if (!SeenNewDbgInfoFormat)
6668 M->setNewDbgInfoFormatFlag(
true);
6669 SeenNewDbgInfoFormat =
true;
6673 if (parseDebugRecord(DR, PFS))
6675 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6687 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6692 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6696 switch (parseInstruction(Inst, BB, PFS)) {
6699 case InstError:
return true;
6706 if (parseInstructionMetadata(*Inst))
6709 case InstExtraComma:
6714 if (parseInstructionMetadata(*Inst))
6720 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6724 for (DbgRecordPtr &DR : TrailingDbgRecord)
6726 TrailingDbgRecord.clear();
6729 assert(TrailingDbgRecord.empty() &&
6730 "All debug values should have been attached to an instruction.");
6739bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6744 return error(DVRLoc,
"expected debug record type here");
6746 .
Case(
"declare", RecordKind::ValueKind)
6747 .
Case(
"value", RecordKind::ValueKind)
6748 .
Case(
"assign", RecordKind::ValueKind)
6749 .
Case(
"label", RecordKind::LabelKind);
6758 if (parseMDNode(Label))
6763 if (parseMDNode(DbgLoc))
6772 .
Case(
"declare", LocType::Declare)
6773 .
Case(
"value", LocType::Value)
6774 .
Case(
"assign", LocType::Assign);
6782 if (parseMetadata(ValLocMD, &PFS))
6789 if (parseMDNode(Variable))
6802 MDNode *AssignID =
nullptr;
6803 Metadata *AddressLocation =
nullptr;
6804 MDNode *AddressExpression =
nullptr;
6807 if (parseMDNode(AssignID))
6813 if (parseMetadata(AddressLocation, &PFS))
6819 if (parseMDNode(AddressExpression))
6844 PerFunctionState &PFS) {
6847 return tokError(
"found end of file when expecting more instructions");
6854 return error(Loc,
"expected instruction opcode");
6858 return parseRet(Inst, BB, PFS);
6860 return parseBr(Inst, PFS);
6862 return parseSwitch(Inst, PFS);
6864 return parseIndirectBr(Inst, PFS);
6866 return parseInvoke(Inst, PFS);
6868 return parseResume(Inst, PFS);
6870 return parseCleanupRet(Inst, PFS);
6872 return parseCatchRet(Inst, PFS);
6874 return parseCatchSwitch(Inst, PFS);
6876 return parseCatchPad(Inst, PFS);
6878 return parseCleanupPad(Inst, PFS);
6880 return parseCallBr(Inst, PFS);
6884 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6900 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6903 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6904 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6913 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
6927 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6929 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
6935 return parseArithmetic(Inst, PFS, KeywordVal,
6939 if (parseLogical(Inst, PFS, KeywordVal))
6942 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
6947 return parseLogical(Inst, PFS, KeywordVal);
6949 return parseCompare(Inst, PFS, KeywordVal);
6952 int Res = parseCompare(Inst, PFS, KeywordVal);
6964 bool Res = parseCast(Inst, PFS, KeywordVal);
6976 if (parseCast(Inst, PFS, KeywordVal))
6979 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
6981 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
6994 return parseCast(Inst, PFS, KeywordVal);
6998 int Res = parseSelect(Inst, PFS);
7002 if (!isa<FPMathOperator>(Inst))
7003 return error(Loc,
"fast-math-flags specified for select without "
7004 "floating-point scalar or vector return type");
7010 return parseVAArg(Inst, PFS);
7012 return parseExtractElement(Inst, PFS);
7014 return parseInsertElement(Inst, PFS);
7016 return parseShuffleVector(Inst, PFS);
7019 int Res = parsePHI(Inst, PFS);
7023 if (!isa<FPMathOperator>(Inst))
7024 return error(Loc,
"fast-math-flags specified for phi without "
7025 "floating-point scalar or vector return type");
7031 return parseLandingPad(Inst, PFS);
7033 return parseFreeze(Inst, PFS);
7045 return parseAlloc(Inst, PFS);
7047 return parseLoad(Inst, PFS);
7049 return parseStore(Inst, PFS);
7051 return parseCmpXchg(Inst, PFS);
7053 return parseAtomicRMW(Inst, PFS);
7055 return parseFence(Inst, PFS);
7057 return parseGetElementPtr(Inst, PFS);
7059 return parseExtractValue(Inst, PFS);
7061 return parseInsertValue(Inst, PFS);
7066bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7067 if (Opc == Instruction::FCmp) {
7070 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7091 return tokError(
"expected icmp predicate (e.g. 'eq')");
7116 PerFunctionState &PFS) {
7119 if (parseType(Ty,
true ))
7122 Type *ResType = PFS.getFunction().getReturnType();
7126 return error(TypeLoc,
"value doesn't match function result type '" +
7134 if (parseValue(Ty, RV, PFS))
7138 return error(TypeLoc,
"value doesn't match function result type '" +
7148bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7152 if (parseTypeAndValue(Op0, Loc, PFS))
7155 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7161 return error(Loc,
"branch condition must have 'i1' type");
7163 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7164 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7165 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7166 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7178bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7179 LocTy CondLoc, BBLoc;
7182 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7183 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7184 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7188 if (!
Cond->getType()->isIntegerTy())
7189 return error(CondLoc,
"switch condition must have integer type");
7198 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7199 parseToken(
lltok::comma,
"expected ',' after case value") ||
7200 parseTypeAndBasicBlock(DestBB, PFS))
7204 return error(CondLoc,
"duplicate case value in switch");
7206 return error(CondLoc,
"case value is not a constant integer");
7214 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7215 SI->addCase(Table[i].first, Table[i].second);
7223bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7226 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7227 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7231 if (!
Address->getType()->isPointerTy())
7232 return error(AddrLoc,
"indirectbr address must have pointer type");
7239 if (parseTypeAndBasicBlock(DestBB, PFS))
7244 if (parseTypeAndBasicBlock(DestBB, PFS))
7250 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7265 FuncTy = dyn_cast<FunctionType>(RetType);
7270 for (
const ParamInfo &Arg : ArgList)
7284bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7286 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7287 std::vector<unsigned> FwdRefAttrGrps;
7290 unsigned InvokeAddrSpace;
7291 Type *RetType =
nullptr;
7298 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7299 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7300 parseType(RetType, RetTypeLoc,
true ) ||
7301 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7302 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7304 parseOptionalOperandBundles(BundleList, PFS) ||
7306 parseTypeAndBasicBlock(NormalBB, PFS) ||
7308 parseTypeAndBasicBlock(UnwindBB, PFS))
7315 if (resolveFunctionType(RetType, ArgList, Ty))
7316 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7334 for (
const ParamInfo &Arg : ArgList) {
7335 Type *ExpectedTy =
nullptr;
7338 }
else if (!Ty->isVarArg()) {
7339 return error(Arg.Loc,
"too many arguments specified");
7342 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7343 return error(Arg.Loc,
"argument is not of expected type '" +
7345 Args.push_back(Arg.V);
7350 return error(CallLoc,
"not enough parameters specified for call");
7359 II->setCallingConv(
CC);
7360 II->setAttributes(PAL);
7361 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
7368bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7370 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7379 PerFunctionState &PFS) {
7380 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7385 if (!
Args.empty() &&
7386 parseToken(
lltok::comma,
"expected ',' in argument list"))
7391 Type *ArgTy =
nullptr;
7392 if (parseType(ArgTy, ArgLoc))
7397 if (parseMetadataAsValue(V, PFS))
7400 if (parseValue(ArgTy, V, PFS))
7412bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7413 Value *CleanupPad =
nullptr;
7415 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7430 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7441bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7442 Value *CatchPad =
nullptr;
7444 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7451 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7452 parseTypeAndBasicBlock(BB, PFS))
7461bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7469 return tokError(
"expected scope value for catchswitch");
7474 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7480 if (parseTypeAndBasicBlock(DestBB, PFS))
7485 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7488 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7496 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7503 CatchSwitch->addHandler(DestBB);
7510bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7511 Value *CatchSwitch =
nullptr;
7517 return tokError(
"expected scope value for catchpad");
7523 if (parseExceptionArgs(Args, PFS))
7532bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7533 Value *ParentPad =
nullptr;
7540 return tokError(
"expected scope value for cleanuppad");
7546 if (parseExceptionArgs(Args, PFS))
7562bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7563 unsigned Opc,
bool IsFP) {
7565 if (parseTypeAndValue(LHS, Loc, PFS))
7572 return error(Loc,
"invalid operand type for instruction");
7582bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7584 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7585 std::vector<unsigned> FwdRefAttrGrps;
7588 Type *RetType =
nullptr;
7595 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7596 parseType(RetType, RetTypeLoc,
true ) ||
7597 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7598 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7600 parseOptionalOperandBundles(BundleList, PFS) ||
7602 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7611 if (parseTypeAndBasicBlock(DestBB, PFS))
7616 if (parseTypeAndBasicBlock(DestBB, PFS))
7622 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7629 if (resolveFunctionType(RetType, ArgList, Ty))
7630 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7647 for (
const ParamInfo &Arg : ArgList) {
7648 Type *ExpectedTy =
nullptr;
7651 }
else if (!Ty->isVarArg()) {
7652 return error(Arg.Loc,
"too many arguments specified");
7655 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7656 return error(Arg.Loc,
"argument is not of expected type '" +
7658 Args.push_back(Arg.V);
7663 return error(CallLoc,
"not enough parameters specified for call");
7675 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7689bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7690 unsigned Opc,
bool IsFP) {
7692 if (parseTypeAndValue(LHS, Loc, PFS) ||
7693 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7701 return error(Loc,
"invalid operand type for instruction");
7709bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7712 if (parseTypeAndValue(LHS, Loc, PFS) ||
7713 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7719 "instruction requires integer or integer vector operands");
7728bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7734 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7735 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7739 if (Opc == Instruction::FCmp) {
7741 return error(Loc,
"fcmp requires floating point operands");
7744 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7747 return error(Loc,
"icmp requires integer operands");
7759bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7763 Type *DestTy =
nullptr;
7764 if (parseTypeAndValue(
Op, Loc, PFS) ||
7765 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7771 return error(Loc,
"invalid cast opcode for cast from '" +
7781bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7783 Value *Op0, *Op1, *Op2;
7784 if (parseTypeAndValue(Op0, Loc, PFS) ||
7785 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7786 parseTypeAndValue(Op1, PFS) ||
7787 parseToken(
lltok::comma,
"expected ',' after select value") ||
7788 parseTypeAndValue(Op2, PFS))
7792 return error(Loc, Reason);
7800bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7802 Type *EltTy =
nullptr;
7804 if (parseTypeAndValue(
Op, PFS) ||
7805 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7806 parseType(EltTy, TypeLoc))
7810 return error(TypeLoc,
"va_arg requires operand with first class type");
7818bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7821 if (parseTypeAndValue(Op0, Loc, PFS) ||
7822 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7823 parseTypeAndValue(Op1, PFS))
7827 return error(Loc,
"invalid extractelement operands");
7835bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7837 Value *Op0, *Op1, *Op2;
7838 if (parseTypeAndValue(Op0, Loc, PFS) ||
7839 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7840 parseTypeAndValue(Op1, PFS) ||
7841 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7842 parseTypeAndValue(Op2, PFS))
7846 return error(Loc,
"invalid insertelement operands");
7854bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7856 Value *Op0, *Op1, *Op2;
7857 if (parseTypeAndValue(Op0, Loc, PFS) ||
7858 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7859 parseTypeAndValue(Op1, PFS) ||
7860 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7861 parseTypeAndValue(Op2, PFS))
7865 return error(Loc,
"invalid shufflevector operands");
7873int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7877 if (parseType(Ty, TypeLoc))
7881 return error(TypeLoc,
"phi node must have first class type");
7884 bool AteExtraComma =
false;
7896 AteExtraComma =
true;
7900 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7901 parseValue(Ty, Op0, PFS) ||
7902 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7907 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7911 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
7912 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
7914 return AteExtraComma ? InstExtraComma : InstNormal;
7923bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
7926 if (parseType(Ty, TyLoc))
7939 return tokError(
"expected 'catch' or 'filter' clause type");
7943 if (parseTypeAndValue(V, VLoc, PFS))
7949 if (isa<ArrayType>(
V->getType()))
7950 error(VLoc,
"'catch' clause has an invalid type");
7952 if (!isa<ArrayType>(
V->getType()))
7953 error(VLoc,
"'filter' clause has an invalid type");
7956 Constant *CV = dyn_cast<Constant>(V);
7958 return error(VLoc,
"clause argument must be a constant");
7962 Inst = LP.release();
7968bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
7971 if (parseTypeAndValue(
Op, Loc, PFS))
7987bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
7989 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7990 std::vector<unsigned> FwdRefAttrGrps;
7992 unsigned CallAddrSpace;
7994 Type *RetType =
nullptr;
8003 "expected 'tail call', 'musttail call', or 'notail call'"))
8008 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8009 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8010 parseType(RetType, RetTypeLoc,
true ) ||
8011 parseValID(CalleeID, &PFS) ||
8013 PFS.getFunction().isVarArg()) ||
8014 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8015 parseOptionalOperandBundles(BundleList, PFS))
8022 if (resolveFunctionType(RetType, ArgList, Ty))
8023 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8029 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
8042 for (
const ParamInfo &Arg : ArgList) {
8043 Type *ExpectedTy =
nullptr;
8046 }
else if (!Ty->isVarArg()) {
8047 return error(Arg.Loc,
"too many arguments specified");
8050 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8051 return error(Arg.Loc,
"argument is not of expected type '" +
8053 Args.push_back(Arg.V);
8054 Attrs.push_back(Arg.Attrs);
8058 return error(CallLoc,
"not enough parameters specified for call");
8069 if (!isa<FPMathOperator>(CI)) {
8071 return error(CallLoc,
"fast-math-flags specified for call without "
8072 "floating-point scalar or vector return type");
8079 if (SeenNewDbgInfoFormat) {
8081 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8082 "using non-intrinsic debug info");
8084 if (!SeenOldDbgInfoFormat)
8085 M->setNewDbgInfoFormatFlag(
false);
8086 SeenOldDbgInfoFormat =
true;
8089 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8101int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
8103 LocTy SizeLoc, TyLoc, ASLoc;
8105 unsigned AddrSpace = 0;
8108 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8109 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8111 if (parseType(Ty, TyLoc))
8115 return error(TyLoc,
"invalid type for alloca");
8117 bool AteExtraComma =
false;
8119 if (Lex.
getKind() == lltok::kw_align) {
8120 if (parseOptionalAlignment(Alignment))
8122 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8126 if (parseOptionalAddrSpace(AddrSpace))
8129 AteExtraComma =
true;
8131 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8134 if (Lex.
getKind() == lltok::kw_align) {
8135 if (parseOptionalAlignment(Alignment))
8137 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8141 if (parseOptionalAddrSpace(AddrSpace))
8144 AteExtraComma =
true;
8150 if (
Size && !
Size->getType()->isIntegerTy())
8151 return error(SizeLoc,
"element count must have integer type");
8154 if (!Alignment && !Ty->
isSized(&Visited))
8155 return error(TyLoc,
"Cannot allocate unsized type");
8157 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8162 return AteExtraComma ? InstExtraComma : InstNormal;
8169int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8172 bool AteExtraComma =
false;
8173 bool isAtomic =
false;
8182 bool isVolatile =
false;
8190 if (parseType(Ty) ||
8191 parseToken(
lltok::comma,
"expected comma after load's type") ||
8192 parseTypeAndValue(Val, Loc, PFS) ||
8193 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8194 parseOptionalCommaAlign(Alignment, AteExtraComma))
8198 return error(Loc,
"load operand must be a pointer to a first class type");
8199 if (isAtomic && !Alignment)
8200 return error(Loc,
"atomic load must have explicit non-zero alignment");
8203 return error(Loc,
"atomic load cannot use Release ordering");
8206 if (!Alignment && !Ty->
isSized(&Visited))
8207 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8209 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8210 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8211 return AteExtraComma ? InstExtraComma : InstNormal;
8219int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8222 bool AteExtraComma =
false;
8223 bool isAtomic =
false;
8232 bool isVolatile =
false;
8238 if (parseTypeAndValue(Val, Loc, PFS) ||
8239 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8240 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8241 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8242 parseOptionalCommaAlign(Alignment, AteExtraComma))
8245 if (!
Ptr->getType()->isPointerTy())
8246 return error(PtrLoc,
"store operand must be a pointer");
8248 return error(Loc,
"store operand must be a first class value");
8249 if (isAtomic && !Alignment)
8250 return error(Loc,
"atomic store must have explicit non-zero alignment");
8253 return error(Loc,
"atomic store cannot use Acquire ordering");
8256 return error(Loc,
"storing unsized types is not allowed");
8258 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8260 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8261 return AteExtraComma ? InstExtraComma : InstNormal;
8268int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8270 bool AteExtraComma =
false;
8274 bool isVolatile =
false;
8275 bool isWeak =
false;
8284 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8285 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8286 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8287 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8288 parseTypeAndValue(New, NewLoc, PFS) ||
8289 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8290 parseOrdering(FailureOrdering) ||
8291 parseOptionalCommaAlign(Alignment, AteExtraComma))
8295 return tokError(
"invalid cmpxchg success ordering");
8297 return tokError(
"invalid cmpxchg failure ordering");
8298 if (!
Ptr->getType()->isPointerTy())
8299 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8300 if (
Cmp->getType() !=
New->getType())
8301 return error(NewLoc,
"compare value and new value type do not match");
8302 if (!
New->getType()->isFirstClassType())
8303 return error(NewLoc,
"cmpxchg operand must be a first class value");
8305 const Align DefaultAlignment(
8306 PFS.getFunction().getDataLayout().getTypeStoreSize(
8311 SuccessOrdering, FailureOrdering, SSID);
8316 return AteExtraComma ? InstExtraComma : InstNormal;
8322int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8324 bool AteExtraComma =
false;
8327 bool isVolatile =
false;
8337 return tokError(
"expected binary operation in atomicrmw");
8374 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8375 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8376 parseTypeAndValue(Val, ValLoc, PFS) ||
8377 parseScopeAndOrdering(
true , SSID, Ordering) ||
8378 parseOptionalCommaAlign(Alignment, AteExtraComma))
8382 return tokError(
"atomicrmw cannot be unordered");
8383 if (!
Ptr->getType()->isPointerTy())
8384 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8386 return error(ValLoc,
"atomicrmw operand may not be scalable");
8395 " operand must be an integer, floating point, or pointer type");
8399 return error(ValLoc,
"atomicrmw " +
8401 " operand must be a floating point type");
8405 return error(ValLoc,
"atomicrmw " +
8407 " operand must be an integer");
8412 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8415 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8417 const Align DefaultAlignment(
8418 PFS.getFunction().getDataLayout().getTypeStoreSize(
8422 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8425 return AteExtraComma ? InstExtraComma : InstNormal;
8430int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8433 if (parseScopeAndOrdering(
true , SSID, Ordering))
8437 return tokError(
"fence cannot be unordered");
8439 return tokError(
"fence cannot be monotonic");
8441 Inst =
new FenceInst(Context, Ordering, SSID);
8447int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8449 Value *Val =
nullptr;
8465 if (parseType(Ty) ||
8466 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8467 parseTypeAndValue(
Ptr, Loc, PFS))
8472 if (!BasePointerType)
8473 return error(Loc,
"base of getelementptr must be a pointer");
8476 bool AteExtraComma =
false;
8480 ? cast<VectorType>(
BaseType)->getElementCount()
8485 AteExtraComma =
true;
8488 if (parseTypeAndValue(Val, EltLoc, PFS))
8491 return error(EltLoc,
"getelementptr index must be an integer");
8493 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8498 "getelementptr vector index has a wrong number of elements");
8499 GEPWidth = ValNumEl;
8506 return error(Loc,
"base element of getelementptr must be sized");
8508 auto *STy = dyn_cast<StructType>(Ty);
8510 return error(Loc,
"getelementptr cannot target structure that contains "
8511 "scalable vector type");
8514 return error(Loc,
"invalid getelementptr indices");
8517 GEP->setNoWrapFlags(NW);
8518 return AteExtraComma ? InstExtraComma : InstNormal;
8523int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8527 if (parseTypeAndValue(Val, Loc, PFS) ||
8528 parseIndexList(Indices, AteExtraComma))
8532 return error(Loc,
"extractvalue operand must be aggregate type");
8535 return error(Loc,
"invalid indices for extractvalue");
8537 return AteExtraComma ? InstExtraComma : InstNormal;
8542int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8546 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8547 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8548 parseTypeAndValue(Val1, Loc1, PFS) ||
8549 parseIndexList(Indices, AteExtraComma))
8553 return error(Loc0,
"insertvalue operand must be aggregate type");
8557 return error(Loc0,
"invalid indices for insertvalue");
8558 if (IndexedType != Val1->
getType())
8559 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8563 return AteExtraComma ? InstExtraComma : InstNormal;
8589 if (parseMetadata(MD,
nullptr))
8594 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8603 return error(Loc,
"value has no uses");
8605 unsigned NumUses = 0;
8607 for (
const Use &U :
V->uses()) {
8608 if (++NumUses > Indexes.
size())
8610 Order[&
U] = Indexes[NumUses - 1];
8613 return error(Loc,
"value only has one use");
8614 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8616 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8618 V->sortUseList([&](
const Use &L,
const Use &R) {
8631 return Lex.
Error(
"expected non-empty list of uselistorder indexes");
8638 bool IsOrdered =
true;
8639 assert(Indexes.
empty() &&
"Expected empty order vector");
8642 if (parseUInt32(
Index))
8656 if (Indexes.
size() < 2)
8657 return error(Loc,
"expected >= 2 uselistorder indexes");
8660 "expected distinct uselistorder indexes in range [0, size)");
8662 return error(Loc,
"expected uselistorder indexes to change the order");
8669bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8676 if (parseTypeAndValue(V, PFS) ||
8677 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8678 parseUseListOrderIndexes(Indexes))
8681 return sortUseListOrder(V, Indexes, Loc);
8686bool LLParser::parseUseListOrderBB() {
8693 if (parseValID(Fn,
nullptr) ||
8694 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8695 parseValID(Label,
nullptr) ||
8696 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8697 parseUseListOrderIndexes(Indexes))
8703 GV =
M->getNamedValue(Fn.
StrVal);
8705 GV = NumberedVals.get(Fn.
UIntVal);
8707 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8710 "invalid function forward reference in uselistorder_bb");
8711 auto *
F = dyn_cast<Function>(GV);
8713 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8714 if (
F->isDeclaration())
8715 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8719 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8721 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8722 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8724 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8725 if (!isa<BasicBlock>(V))
8726 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8728 return sortUseListOrder(V, Indexes, Loc);
8734bool LLParser::parseModuleEntry(
unsigned ID) {
8743 parseStringConstant(Path) ||
8751 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8752 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8753 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8754 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8755 parseUInt32(Hash[4]))
8762 auto ModuleEntry =
Index->addModule(Path, Hash);
8763 ModuleIdMap[
ID] = ModuleEntry->first();
8770bool LLParser::parseTypeIdEntry(
unsigned ID) {
8779 parseStringConstant(
Name))
8784 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8789 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8790 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8791 for (
auto TIDRef : FwdRefTIDs->second) {
8793 "Forward referenced type id GUID expected to be 0");
8796 ForwardRefTypeIds.erase(FwdRefTIDs);
8808 parseTypeTestResolution(TIS.
TTRes))
8813 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8824 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8830bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8839 parseStringConstant(
Name))
8843 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8850 IdToIndexMapType IdToIndexMap;
8863 if (parseGVReference(VI, GVId))
8870 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8871 TI.push_back({
Offset, VI});
8879 for (
auto I : IdToIndexMap) {
8880 auto &Infos = ForwardRefValueInfos[
I.first];
8881 for (
auto P :
I.second) {
8883 "Forward referenced ValueInfo expected to be empty");
8884 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8894 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8895 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8896 for (
auto TIDRef : FwdRefTIDs->second) {
8898 "Forward referenced type id GUID expected to be 0");
8901 ForwardRefTypeIds.erase(FwdRefTIDs);
8941 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
8968 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
8981 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
8994bool LLParser::parseOptionalWpdResolutions(
8995 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9007 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9010 WPDResMap[
Offset] = WPDRes;
9046 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9060 if (parseOptionalResByArg(WPDRes.
ResByArg))
9065 "expected optional WholeProgramDevirtResolution field");
9082bool LLParser::parseOptionalResByArg(
9091 std::vector<uint64_t>
Args;
9092 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9116 "unexpected WholeProgramDevirtResolution::ByArg kind");
9126 parseUInt64(ByArg.
Info))
9132 parseUInt32(ByArg.
Byte))
9138 parseUInt32(ByArg.
Bit))
9143 "expected optional whole program devirt field");
9150 ResByArg[
Args] = ByArg;
9161bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9169 if (parseUInt64(Val))
9171 Args.push_back(Val);
9180static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9185 assert(!(ReadOnly && WriteOnly));
9195bool LLParser::addGlobalValueToIndex(
9197 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9202 VI =
Index->getOrInsertValueInfo(GUID);
9206 auto *GV =
M->getNamedValue(
Name);
9208 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9210 VI =
Index->getOrInsertValueInfo(GV);
9214 "Need a source_filename to compute GUID for local");
9222 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9223 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9224 for (
auto VIRef : FwdRefVIs->second) {
9226 "Forward referenced ValueInfo expected to be empty");
9229 ForwardRefValueInfos.erase(FwdRefVIs);
9233 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9234 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9235 for (
auto AliaseeRef : FwdRefAliasees->second) {
9236 assert(!AliaseeRef.first->hasAliasee() &&
9237 "Forward referencing alias already has aliasee");
9238 assert(Summary &&
"Aliasee must be a definition");
9239 AliaseeRef.first->setAliasee(VI,
Summary.get());
9241 ForwardRefAliasees.erase(FwdRefAliasees);
9246 Index->addGlobalValueSummary(VI, std::move(Summary));
9249 if (
ID == NumberedValueInfos.size())
9250 NumberedValueInfos.push_back(VI);
9253 if (
ID > NumberedValueInfos.size())
9254 NumberedValueInfos.resize(
ID + 1);
9255 NumberedValueInfos[
ID] =
VI;
9263bool LLParser::parseSummaryIndexFlags() {
9270 if (parseUInt64(Flags))
9273 Index->setFlags(Flags);
9279bool LLParser::parseBlockCount() {
9286 if (parseUInt64(BlockCount))
9289 Index->setBlockCount(BlockCount);
9297bool LLParser::parseGVEntry(
unsigned ID) {
9312 parseStringConstant(
Name))
9318 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9322 return error(Lex.
getLoc(),
"expected name or guid tag");
9347 if (parseFunctionSummary(
Name, GUID,
ID))
9351 if (parseVariableSummary(
Name, GUID,
ID))
9355 if (parseAliasSummary(
Name, GUID,
ID))
9359 return error(Lex.
getLoc(),
"expected summary type");
9385 false,
false,
false,
9388 std::vector<FunctionSummary::EdgeTy> Calls;
9390 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9391 std::vector<ValueInfo> Refs;
9392 std::vector<CallsiteInfo> Callsites;
9393 std::vector<AllocInfo> Allocs;
9398 parseModuleReference(ModulePath) ||
9399 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9402 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9409 if (parseOptionalFFlags(FFlags))
9413 if (parseOptionalCalls(Calls))
9417 if (parseOptionalTypeIdInfo(TypeIdInfo))
9421 if (parseOptionalRefs(Refs))
9425 if (parseOptionalParamAccesses(ParamAccesses))
9429 if (parseOptionalAllocs(Allocs))
9433 if (parseOptionalCallsites(Callsites))
9437 return error(Lex.
getLoc(),
"expected optional function summary field");
9444 auto FS = std::make_unique<FunctionSummary>(
9445 GVFlags, InstCount, FFlags, 0, std::move(Refs),
9446 std::move(Calls), std::move(TypeIdInfo.
TypeTests),
9451 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9453 FS->setModulePath(ModulePath);
9455 return addGlobalValueToIndex(
Name, GUID,
9457 std::move(FS), Loc);
9473 false,
false,
false,
9479 std::vector<ValueInfo> Refs;
9483 parseModuleReference(ModulePath) ||
9484 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9486 parseGVarFlags(GVarFlags))
9493 if (parseOptionalVTableFuncs(VTableFuncs))
9497 if (parseOptionalRefs(Refs))
9501 return error(Lex.
getLoc(),
"expected optional variable summary field");
9509 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9511 GS->setModulePath(ModulePath);
9512 GS->setVTableFuncs(std::move(VTableFuncs));
9514 return addGlobalValueToIndex(
Name, GUID,
9516 std::move(GS), Loc);
9532 false,
false,
false,
9536 parseModuleReference(ModulePath) ||
9537 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9545 if (parseGVReference(AliaseeVI, GVId))
9551 auto AS = std::make_unique<AliasSummary>(GVFlags);
9553 AS->setModulePath(ModulePath);
9557 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9559 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9560 assert(Summary &&
"Aliasee must be a definition");
9561 AS->setAliasee(AliaseeVI, Summary);
9564 return addGlobalValueToIndex(
Name, GUID,
9566 std::move(AS), Loc);
9571bool LLParser::parseFlag(
unsigned &Val) {
9573 return tokError(
"expected integer");
9594 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9603 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9609 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9615 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9621 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9627 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9633 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9639 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9645 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9651 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9657 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9662 return error(Lex.
getLoc(),
"expected function flag type");
9677bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9681 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9685 IdToIndexMapType IdToIndexMap;
9696 if (parseGVReference(VI, GVId))
9701 unsigned HasTailCall =
false;
9708 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9713 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9718 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9722 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9726 return tokError(
"Expected only one of hotness or relbf");
9731 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9741 for (
auto I : IdToIndexMap) {
9742 auto &Infos = ForwardRefValueInfos[
I.first];
9743 for (
auto P :
I.second) {
9745 "Forward referenced ValueInfo expected to be empty");
9746 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9763 case lltok::kw_cold:
9776 return error(Lex.
getLoc(),
"invalid call edge hotness");
9785bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9789 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9793 IdToIndexMapType IdToIndexMap;
9797 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9804 if (parseGVReference(VI, GVId))
9817 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9818 VTableFuncs.push_back({
VI,
Offset});
9820 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9826 for (
auto I : IdToIndexMap) {
9827 auto &Infos = ForwardRefValueInfos[
I.first];
9828 for (
auto P :
I.second) {
9830 "Forward referenced ValueInfo expected to be empty");
9831 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9835 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9842bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9844 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9853 auto ParseAPSInt = [&](
APSInt &Val) {
9855 return tokError(
"expected integer");
9858 Val.setIsSigned(
true);
9881 IdLocListType &IdLocList) {
9890 if (parseGVReference(VI, GVId))
9894 IdLocList.emplace_back(GVId, Loc);
9897 parseParamNo(
Call.ParamNo) ||
9899 parseParamAccessOffset(
Call.Offsets))
9912 IdLocListType &IdLocList) {
9914 parseParamNo(
Param.ParamNo) ||
9916 parseParamAccessOffset(
Param.Use))
9926 if (parseParamAccessCall(Call, IdLocList))
9928 Param.Calls.push_back(Call);
9943bool LLParser::parseOptionalParamAccesses(
9944 std::vector<FunctionSummary::ParamAccess> &Params) {
9952 IdLocListType VContexts;
9953 size_t CallsNum = 0;
9956 if (parseParamAccess(ParamAccess, VContexts))
9958 CallsNum += ParamAccess.
Calls.size();
9959 assert(VContexts.size() == CallsNum);
9961 Params.emplace_back(std::move(ParamAccess));
9969 IdLocListType::const_iterator ItContext = VContexts.begin();
9970 for (
auto &PA : Params) {
9971 for (
auto &
C : PA.Calls) {
9973 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
9978 assert(ItContext == VContexts.end());
9985bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9989 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
9993 struct ValueContext {
9998 std::vector<ValueContext> VContexts;
10003 if (parseGVReference(
VC.VI,
VC.GVId))
10005 VContexts.push_back(VC);
10011 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10012 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10015 IdToIndexMapType IdToIndexMap;
10016 for (
auto &VC : VContexts) {
10021 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.size(),
VC.Loc));
10022 Refs.push_back(
VC.VI);
10027 for (
auto I : IdToIndexMap) {
10028 auto &Infos = ForwardRefValueInfos[
I.first];
10029 for (
auto P :
I.second) {
10031 "Forward referenced ValueInfo expected to be empty");
10032 Infos.emplace_back(&Refs[
P.first],
P.second);
10046bool LLParser::parseOptionalTypeIdInfo(
10058 if (parseTypeTests(TypeIdInfo.
TypeTests))
10082 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
10086 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10095bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10103 IdToIndexMapType IdToIndexMap;
10112 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10114 }
else if (parseUInt64(GUID))
10116 TypeTests.push_back(GUID);
10121 for (
auto I : IdToIndexMap) {
10122 auto &Ids = ForwardRefTypeIds[
I.first];
10123 for (
auto P :
I.second) {
10124 assert(TypeTests[
P.first] == 0 &&
10125 "Forward referenced type id GUID expected to be 0");
10126 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10130 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10138bool LLParser::parseVFuncIdList(
10139 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10147 IdToIndexMapType IdToIndexMap;
10150 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10152 VFuncIdList.push_back(VFuncId);
10160 for (
auto I : IdToIndexMap) {
10161 auto &Ids = ForwardRefTypeIds[
I.first];
10162 for (
auto P :
I.second) {
10163 assert(VFuncIdList[
P.first].GUID == 0 &&
10164 "Forward referenced type id GUID expected to be 0");
10165 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10174bool LLParser::parseConstVCallList(
10176 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10184 IdToIndexMapType IdToIndexMap;
10187 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10189 ConstVCallList.push_back(ConstVCall);
10197 for (
auto I : IdToIndexMap) {
10198 auto &Ids = ForwardRefTypeIds[
I.first];
10199 for (
auto P :
I.second) {
10200 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10201 "Forward referenced type id GUID expected to be 0");
10202 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10212 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10214 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap,
Index))
10218 if (parseArgs(ConstVCall.
Args))
10231 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10246 IdToIndexMap[
ID].push_back(std::make_pair(
Index, Loc));
10248 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10250 parseUInt64(VFuncId.
GUID))
10256 parseUInt64(VFuncId.
Offset) ||
10285 assert(HasLinkage &&
"Linkage not optional in summary entry");
10292 parseOptionalVisibility(Flag);
10297 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10303 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10309 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10315 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10324 if (parseOptionalImportType(Lex.
getKind(), IK))
10326 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10330 return error(Lex.
getLoc(),
"expected gv flag type");
10352 auto ParseRest = [
this](
unsigned int &Val) {
10356 return parseFlag(Val);
10362 case lltok::kw_readonly:
10363 if (ParseRest(Flag))
10367 case lltok::kw_writeonly:
10368 if (ParseRest(Flag))
10373 if (ParseRest(Flag))
10378 if (ParseRest(Flag))
10383 return error(Lex.
getLoc(),
"expected gvar flag type");
10391bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10399 auto I = ModuleIdMap.find(ModuleID);
10401 assert(
I != ModuleIdMap.end());
10402 ModulePath =
I->second;
10408bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10411 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10417 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10419 VI = NumberedValueInfos[GVId];
10436bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10440 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10455 if (parseAllocType(V))
10460 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10464 std::vector<MIBInfo> MIBs;
10465 if (parseMemProfs(MIBs))
10468 Allocs.push_back({Versions, MIBs});
10485bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10489 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10495 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10504 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10513 if (parseUInt64(StackId))
10535bool LLParser::parseAllocType(uint8_t &
AllocType) {
10543 case lltok::kw_cold:
10546 case lltok::kw_hot:
10550 return error(Lex.
getLoc(),
"invalid alloc type");
10563bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10567 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10571 IdToIndexMapType IdToIndexMap;
10574 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10583 if (parseGVReference(VI, GVId))
10587 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10596 if (parseUInt32(V))
10602 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10611 if (parseUInt64(StackId))
10623 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10624 Callsites.push_back({
VI, Clones, StackIdIndices});
10632 for (
auto I : IdToIndexMap) {
10633 auto &Infos = ForwardRefValueInfos[
I.first];
10634 for (
auto P :
I.second) {
10636 "Forward referenced ValueInfo expected to be empty");
10637 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10641 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
static int64_t upperBound(StackOffset Size)
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
DenseMap< Block *, BlockRelaxAux > Blocks
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
cl::opt< bool > WriteNewDbgInfoFormat
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
bool WriteNewDbgInfoFormatToBitcode
static unsigned keywordToFPClassTest(lltok::Kind Tok)
llvm::cl::opt< bool > UseNewDbgInfoFormat
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
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.
@ Min
*p = old <signed v ? old : v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
static StringRef getOperationName(BinOp Op)
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
AttributeList removeFnAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the function index from this attribute list.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=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 parameter attributes for this call.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args=std::nullopt, 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, 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)
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
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
bool Error(LocTy ErrorLoc, const Twine &Msg) const
const std::string & getStrVal() const
const APSInt & getAPSIntVal() const
void setIgnoreColonInIdentifiers(bool val)
const APFloat & getAPFloatVal() const
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.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
bool containsScalableVectorType(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
static TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types=std::nullopt, ArrayRef< unsigned > Ints=std::nullopt)
Return a target extension type having the specified name and optional type and integer parameters.
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=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 bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
unsigned getOperationEncoding(StringRef OperationEncodingString)
unsigned getAttributeEncoding(StringRef EncodingString)
unsigned getTag(StringRef TagString)
unsigned getCallingConvention(StringRef LanguageString)
unsigned getLanguage(StringRef LanguageString)
unsigned getVirtuality(StringRef VirtualityString)
unsigned getMacinfo(StringRef MacinfoString)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CXX_FAST_TLS
Used for access functions.
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ 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.
bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
initializer< Ty > init(const Ty &Val)
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
@ kw_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.
bool isPointerTy(const Type *T)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
static const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static const fltSemantics & IEEEdouble() LLVM_READNONE
static const fltSemantics & IEEEhalf() LLVM_READNONE
static const fltSemantics & BFloat() LLVM_READNONE
This struct is a compact representation of a valid (non-zero power of two) alignment.
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::@43 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.