64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
80 if (Context.shouldDiscardValueNames())
83 "Can't read textual IR with a Context that discards named Values");
86 if (parseTargetDefinitions(DataLayoutCallback))
90 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
96 restoreParsingState(Slots);
100 if (parseType(Ty) || parseConstantValue(Ty,
C))
103 return error(Lex.getLoc(),
"expected end of string");
109 restoreParsingState(Slots);
113 SMLoc Start = Lex.getLoc();
117 SMLoc End = Lex.getLoc();
125 restoreParsingState(Slots);
129 SMLoc Start = Lex.getLoc();
131 bool Status = parseDIExpressionBody(Result,
false);
132 SMLoc End = Lex.getLoc();
138void LLParser::restoreParsingState(
const SlotMapping *Slots) {
145 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
146 for (
const auto &
I : Slots->
Types)
147 NumberedTypes.insert(
148 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
161 if (MD->isTemporary())
165 assert(
II->use_empty() &&
"Cannot have uses");
166 II->eraseFromParent();
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](
unsigned MDKind, MDNode *
Node) {
return Node->isTemporary(); };
177 for (Function &
F : *M) {
178 F.eraseMetadataIf(Pred);
180 I.eraseMetadataIf(Pred);
187 for (GlobalVariable &GV : M->globals())
188 GV.eraseMetadataIf(Pred);
193 if (
Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(
ID);
195 ForwardRefMDNodes.erase(
ID);
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
212 for (
const auto &RAG : ForwardRefAttrGroups) {
214 const std::vector<unsigned> &
Attrs = RAG.second;
215 AttrBuilder
B(Context);
217 for (
const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
224 AttributeList AS = Fn->getAttributes();
225 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
226 AS = AS.removeFnAttributes(Context);
232 if (MaybeAlign
A = FnAttrs.getAlignment()) {
233 Fn->setAlignment(*
A);
234 FnAttrs.removeAttribute(Attribute::Alignment);
237 AS = AS.addFnAttributes(Context, FnAttrs);
238 Fn->setAttributes(AS);
240 AttributeList AS = CI->getAttributes();
241 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
242 AS = AS.removeFnAttributes(Context);
244 AS = AS.addFnAttributes(Context, FnAttrs);
245 CI->setAttributes(AS);
247 AttributeList AS =
II->getAttributes();
248 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
249 AS = AS.removeFnAttributes(Context);
251 AS = AS.addFnAttributes(Context, FnAttrs);
252 II->setAttributes(AS);
254 AttributeList AS = CBI->getAttributes();
255 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
256 AS = AS.removeFnAttributes(Context);
258 AS = AS.addFnAttributes(Context, FnAttrs);
259 CBI->setAttributes(AS);
261 AttrBuilder
Attrs(M->getContext(), GV->getAttributes());
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
275 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
276 GlobalValue *FwdRef) {
277 GlobalValue *GV =
nullptr;
279 GV = M->getNamedValue(GVRef.
StrVal);
281 GV = NumberedVals.get(GVRef.
UIntVal);
286 "' referenced by dso_local_equivalent");
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
302 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
306 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
313 for (
const auto &NT : NumberedTypes)
314 if (
NT.second.second.isValid())
316 "use of undefined type '%" + Twine(
NT.first) +
"'");
318 for (StringMap<std::pair<Type*, LocTy> >::iterator
I =
319 NamedTypes.begin(),
E = NamedTypes.end();
I !=
E; ++
I)
320 if (
I->second.second.isValid())
321 return error(
I->second.second,
322 "use of undefined type named '" +
I->getKey() +
"'");
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first +
"'");
345 if (!CB || !CB->isCallee(&U))
346 return error(
Info.second,
"intrinsic can only be used as callee");
351 return error(
Info.second,
"invalid intrinsic signature");
356 Info.first->eraseFromParent();
357 ForwardRefVals.erase(Name);
366 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
367 FunctionType *FTy =
nullptr;
368 for (Use &U :
V->uses()) {
370 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
372 FTy = CB->getFunctionType();
380 Type *Ty = GetCommonFunctionType(
Info.first);
388 GV =
new GlobalVariable(*M, Ty,
false,
391 Info.first->replaceAllUsesWith(GV);
392 Info.first->eraseFromParent();
393 ForwardRefVals.erase(Name);
396 if (!ForwardRefVals.empty())
397 return error(ForwardRefVals.begin()->second.second,
398 "use of undefined value '@" + ForwardRefVals.begin()->first +
401 if (!ForwardRefValIDs.empty())
402 return error(ForwardRefValIDs.begin()->second.second,
403 "use of undefined value '@" +
404 Twine(ForwardRefValIDs.begin()->first) +
"'");
407 dropUnknownMetadataReferences();
409 if (!ForwardRefMDNodes.empty())
410 return error(ForwardRefMDNodes.begin()->second.second,
411 "use of undefined metadata '!" +
412 Twine(ForwardRefMDNodes.begin()->first) +
"'");
415 for (
auto &
N : NumberedMetadata) {
416 if (
N.second && !
N.second->isResolved())
417 N.second->resolveCycles();
420 for (
auto *Inst : InstsWithTBAATag) {
421 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
424 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
427 if (MD != UpgradedMD)
428 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
437 if (UpgradeDebugInfo)
449 Slots->GlobalValues = std::move(NumberedVals);
450 Slots->MetadataNodes = std::move(NumberedMetadata);
451 for (
const auto &
I : NamedTypes)
452 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
453 for (
const auto &
I : NumberedTypes)
454 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
460bool LLParser::validateEndOfIndex() {
464 if (!ForwardRefValueInfos.empty())
465 return error(ForwardRefValueInfos.begin()->second.front().second,
466 "use of undefined summary '^" +
467 Twine(ForwardRefValueInfos.begin()->first) +
"'");
469 if (!ForwardRefAliasees.empty())
470 return error(ForwardRefAliasees.begin()->second.front().second,
471 "use of undefined summary '^" +
472 Twine(ForwardRefAliasees.begin()->first) +
"'");
474 if (!ForwardRefTypeIds.empty())
475 return error(ForwardRefTypeIds.begin()->second.front().second,
476 "use of undefined type id summary '^" +
477 Twine(ForwardRefTypeIds.begin()->first) +
"'");
491 std::string TentativeDLStr = M->getDataLayoutStr();
496 switch (Lex.getKind()) {
498 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
502 if (parseSourceFileName())
511 if (
auto LayoutOverride =
512 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
513 TentativeDLStr = *LayoutOverride;
519 M->setDataLayout(MaybeDL.
get());
523bool LLParser::parseTopLevelEntities() {
527 switch (Lex.getKind()) {
531 if (parseSummaryEntry())
535 if (parseSourceFileName())
545 switch (Lex.getKind()) {
547 return tokError(
"expected top-level entity");
558 if (parseModuleAsm())
562 if (parseUnnamedType())
566 if (parseNamedType())
570 if (parseUnnamedGlobal())
574 if (parseNamedGlobal())
579 if (parseStandaloneMetadata())
583 if (parseSummaryEntry())
587 if (parseNamedMetadata())
591 if (parseUnnamedAttrGrp())
595 if (parseUseListOrder())
599 if (parseUseListOrderBB())
608bool LLParser::parseModuleAsm() {
614 parseStringConstant(AsmStr))
617 M->appendModuleInlineAsm(AsmStr);
624bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
630 return tokError(
"unknown target property");
633 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
634 parseStringConstant(Str))
636 M->setTargetTriple(Triple(std::move(Str)));
640 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
642 DLStrLoc = Lex.getLoc();
643 if (parseStringConstant(TentativeDLStr))
651bool LLParser::parseSourceFileName() {
654 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
655 parseStringConstant(SourceFileName))
658 M->setSourceFileName(SourceFileName);
664bool LLParser::parseUnnamedType() {
665 LocTy TypeLoc = Lex.getLoc();
666 unsigned TypeID = Lex.getUIntVal();
669 if (parseToken(
lltok::equal,
"expected '=' after name") ||
674 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
678 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
680 return error(TypeLoc,
"non-struct types may not be recursive");
682 Entry.second = SMLoc();
690bool LLParser::parseNamedType() {
691 std::string
Name = Lex.getStrVal();
692 LocTy NameLoc = Lex.getLoc();
695 if (parseToken(
lltok::equal,
"expected '=' after name") ||
700 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
704 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
706 return error(NameLoc,
"non-struct types may not be recursive");
708 Entry.second = SMLoc();
716bool LLParser::parseDeclare() {
720 std::vector<std::pair<unsigned, MDNode *>> MDs;
724 if (parseMetadataAttachment(MDK,
N))
726 MDs.push_back({MDK,
N});
730 unsigned FunctionNumber = -1;
731 SmallVector<unsigned> UnnamedArgNums;
732 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
735 F->addMetadata(MD.first, *MD.second);
741bool LLParser::parseDefine() {
746 unsigned FunctionNumber = -1;
747 SmallVector<unsigned> UnnamedArgNums;
748 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
749 parseOptionalFunctionMetadata(*
F) ||
750 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
756bool LLParser::parseGlobalType(
bool &IsConstant) {
763 return tokError(
"expected 'global' or 'constant'");
769bool LLParser::parseOptionalUnnamedAddr(
790bool LLParser::parseUnnamedGlobal() {
793 LocTy NameLoc = Lex.getLoc();
797 VarID = Lex.getUIntVal();
798 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
802 if (parseToken(
lltok::equal,
"expected '=' after name"))
805 VarID = NumberedVals.getNext();
809 unsigned Linkage, Visibility, DLLStorageClass;
813 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
815 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
818 switch (Lex.getKind()) {
820 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
821 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
824 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
825 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
834bool LLParser::parseNamedGlobal() {
836 LocTy NameLoc = Lex.getLoc();
837 std::string
Name = Lex.getStrVal();
841 unsigned Linkage, Visibility, DLLStorageClass;
845 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
846 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
848 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
851 switch (Lex.getKind()) {
853 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
854 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
857 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
858 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
862bool LLParser::parseComdat() {
864 std::string
Name = Lex.getStrVal();
865 LocTy NameLoc = Lex.getLoc();
872 return tokError(
"expected comdat type");
875 switch (Lex.getKind()) {
877 return tokError(
"unknown selection kind");
899 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
900 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
903 if (
I != ComdatSymTab.
end())
906 C = M->getOrInsertComdat(Name);
907 C->setSelectionKind(SK);
914bool LLParser::parseMDString(
MDString *&Result) {
916 if (parseStringConstant(Str))
924bool LLParser::parseMDNodeID(
MDNode *&Result) {
926 LocTy IDLoc = Lex.getLoc();
928 if (parseUInt32(MID))
932 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
939 auto &FwdRef = ForwardRefMDNodes[MID];
942 Result = FwdRef.first.get();
943 It->second.reset(Result);
949bool LLParser::parseNamedMetadata() {
951 std::string
Name = Lex.getStrVal();
959 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
967 Lex.getStrVal() ==
"DIExpression") {
968 if (parseDIExpression(
N,
false))
973 Lex.getStrVal() ==
"DIArgList") {
974 return tokError(
"found DIArgList outside of function");
982 return parseToken(
lltok::rbrace,
"expected end of metadata node");
987bool LLParser::parseStandaloneMetadata() {
990 unsigned MetadataID = 0;
993 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
998 return tokError(
"unexpected type in metadata definition");
1002 if (parseSpecializedMDNode(Init, IsDistinct))
1005 parseMDTuple(Init, IsDistinct))
1009 auto FI = ForwardRefMDNodes.find(MetadataID);
1010 if (FI != ForwardRefMDNodes.end()) {
1011 auto *ToReplace = FI->second.first.get();
1015 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1016 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1017 "Inst unexpectedly already has DIAssignID attachment");
1018 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1022 ToReplace->replaceAllUsesWith(Init);
1023 ForwardRefMDNodes.erase(FI);
1025 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1027 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1029 return tokError(
"Metadata id is already used");
1030 It->second.reset(Init);
1037bool LLParser::skipModuleSummaryEntry() {
1047 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1048 "start of summary entry");
1050 return parseSummaryIndexFlags();
1052 return parseBlockCount();
1054 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1055 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1059 unsigned NumOpenParen = 1;
1061 switch (Lex.getKind()) {
1069 return tokError(
"found end of file while parsing summary entry");
1075 }
while (NumOpenParen > 0);
1081bool LLParser::parseSummaryEntry() {
1087 Lex.setIgnoreColonInIdentifiers(
true);
1095 return skipModuleSummaryEntry();
1097 bool result =
false;
1098 switch (Lex.getKind()) {
1100 result = parseGVEntry(SummaryID);
1103 result = parseModuleEntry(SummaryID);
1106 result = parseTypeIdEntry(SummaryID);
1109 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1112 result = parseSummaryIndexFlags();
1115 result = parseBlockCount();
1118 result =
error(Lex.getLoc(),
"unexpected summary kind");
1121 Lex.setIgnoreColonInIdentifiers(
false);
1155bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1156 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1157 unsigned DLLStorageClass,
bool DSOLocal,
1172 return error(NameLoc,
"invalid linkage type for alias");
1175 return error(NameLoc,
1176 "symbol with local linkage must have default visibility");
1179 return error(NameLoc,
1180 "symbol with local linkage cannot have a DLL storage class");
1183 LocTy ExplicitTypeLoc = Lex.getLoc();
1184 if (parseType(Ty) ||
1185 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1189 LocTy AliaseeLoc = Lex.getLoc();
1194 if (parseGlobalTypeAndValue(Aliasee))
1199 if (parseValID(
ID,
nullptr))
1202 return error(AliaseeLoc,
"invalid aliasee");
1203 Aliasee =
ID.ConstantVal;
1209 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1210 unsigned AddrSpace = PTy->getAddressSpace();
1212 GlobalValue *GVal =
nullptr;
1216 if (!
Name.empty()) {
1217 auto I = ForwardRefVals.find(Name);
1218 if (
I != ForwardRefVals.end()) {
1219 GVal =
I->second.first;
1220 ForwardRefVals.erase(Name);
1221 }
else if (M->getNamedValue(Name)) {
1222 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1225 auto I = ForwardRefValIDs.find(NameID);
1226 if (
I != ForwardRefValIDs.end()) {
1227 GVal =
I->second.first;
1228 ForwardRefValIDs.erase(
I);
1233 std::unique_ptr<GlobalAlias> GA;
1234 std::unique_ptr<GlobalIFunc> GI;
1262 if (parseGlobalObjectMetadataAttachment(*GI.get()))
1265 return tokError(
"unknown alias or ifunc property!");
1270 NumberedVals.add(NameID, GV);
1277 "forward reference and definition of alias have different types");
1287 M->insertAlias(GA.release());
1289 M->insertIFunc(GI.release());
1290 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1299 case lltok::kw_sanitize_memtag:
1313 switch (Lex.getKind()) {
1315 Meta.NoAddress =
true;
1318 Meta.NoHWAddress =
true;
1320 case lltok::kw_sanitize_memtag:
1324 Meta.IsDynInit =
true;
1327 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1347bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1348 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1349 unsigned Visibility,
unsigned DLLStorageClass,
1353 return error(NameLoc,
1354 "symbol with local linkage must have default visibility");
1357 return error(NameLoc,
1358 "symbol with local linkage cannot have a DLL storage class");
1362 LocTy IsExternallyInitializedLoc;
1366 if (parseOptionalAddrSpace(AddrSpace) ||
1368 IsExternallyInitialized,
1369 &IsExternallyInitializedLoc) ||
1370 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1379 if (parseGlobalValue(Ty, Init))
1384 return error(TyLoc,
"invalid type for global variable");
1386 GlobalValue *GVal =
nullptr;
1389 if (!
Name.empty()) {
1390 auto I = ForwardRefVals.find(Name);
1391 if (
I != ForwardRefVals.end()) {
1392 GVal =
I->second.first;
1393 ForwardRefVals.erase(
I);
1394 }
else if (M->getNamedValue(Name)) {
1395 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1400 if (NameID == (
unsigned)-1)
1401 NameID = NumberedVals.getNext();
1403 auto I = ForwardRefValIDs.find(NameID);
1404 if (
I != ForwardRefValIDs.end()) {
1405 GVal =
I->second.first;
1406 ForwardRefValIDs.erase(
I);
1410 GlobalVariable *GV =
new GlobalVariable(
1415 NumberedVals.add(NameID, GV);
1433 "forward reference and definition of global have different types");
1453 }
else if (Lex.getKind() == lltok::kw_align) {
1454 MaybeAlign Alignment;
1455 if (parseOptionalAlignment(Alignment))
1461 if (parseOptionalCodeModel(CodeModel))
1465 if (parseGlobalObjectMetadataAttachment(*GV))
1468 if (parseSanitizer(GV))
1472 if (parseOptionalComdat(Name,
C))
1477 return tokError(
"unknown global variable property!");
1481 AttrBuilder
Attrs(M->getContext());
1483 std::vector<unsigned> FwdRefAttrGrps;
1484 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1486 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1488 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1496bool LLParser::parseUnnamedAttrGrp() {
1498 LocTy AttrGrpLoc = Lex.getLoc();
1502 return tokError(
"expected attribute group id");
1504 unsigned VarID = Lex.getUIntVal();
1505 std::vector<unsigned> unused;
1513 auto R = NumberedAttrBuilders.find(
VarID);
1514 if (R == NumberedAttrBuilders.end())
1515 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1517 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1518 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1521 if (!
R->second.hasAttributes())
1522 return error(AttrGrpLoc,
"attribute group has no attributes");
1529#define GET_ATTR_NAMES
1530#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1531 case lltok::kw_##DISPLAY_NAME: \
1532 return Attribute::ENUM_NAME;
1533#include "llvm/IR/Attributes.inc"
1542 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1545 case Attribute::Alignment: {
1546 MaybeAlign Alignment;
1554 if (parseOptionalAlignment(Alignment,
true))
1557 B.addAlignmentAttr(Alignment);
1560 case Attribute::StackAlignment: {
1565 parseUInt32(Alignment))
1568 if (parseOptionalStackAlignment(Alignment))
1571 B.addStackAlignmentAttr(Alignment);
1574 case Attribute::AllocSize: {
1575 unsigned ElemSizeArg;
1576 std::optional<unsigned> NumElemsArg;
1577 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1579 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1582 case Attribute::VScaleRange: {
1583 unsigned MinValue, MaxValue;
1584 if (parseVScaleRangeArguments(MinValue, MaxValue))
1586 B.addVScaleRangeAttr(MinValue,
1587 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1590 case Attribute::Dereferenceable: {
1592 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1594 B.addDereferenceableAttr(Bytes);
1597 case Attribute::DereferenceableOrNull: {
1599 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1601 B.addDereferenceableOrNullAttr(Bytes);
1604 case Attribute::UWTable: {
1606 if (parseOptionalUWTableKind(Kind))
1608 B.addUWTableAttr(Kind);
1611 case Attribute::AllocKind: {
1613 if (parseAllocKind(Kind))
1615 B.addAllocKindAttr(Kind);
1618 case Attribute::Memory: {
1619 std::optional<MemoryEffects> ME = parseMemoryAttr();
1622 B.addMemoryAttr(*ME);
1625 case Attribute::NoFPClass: {
1628 B.addNoFPClassAttr(NoFPClass);
1634 case Attribute::Range:
1635 return parseRangeAttr(
B);
1636 case Attribute::Initializes:
1637 return parseInitializesAttr(
B);
1638 case Attribute::Captures:
1639 return parseCapturesAttr(
B);
1641 B.addAttribute(Attr);
1649 case lltok::kw_readnone:
1652 case lltok::kw_readonly:
1655 case lltok::kw_writeonly:
1674bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1675 std::vector<unsigned> &FwdRefAttrGrps,
1676 bool InAttrGrp, LocTy &BuiltinLoc) {
1677 bool HaveError =
false;
1688 if (parseStringAttribute(
B))
1700 "cannot have an attribute group reference in an attribute group");
1703 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1709 SMLoc Loc = Lex.getLoc();
1710 if (Token == lltok::kw_builtin)
1722 return error(Lex.getLoc(),
"unterminated attribute group");
1725 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1732 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1736 B.addMemoryAttr(ME);
1750 PTy->getAddressSpace());
1759 error(Loc,
"'" + Name +
"' is not a basic block");
1761 error(Loc,
"'" + Name +
"' defined with type '" +
1774 error(Loc,
"global variable reference must have pointer type");
1785 auto I = ForwardRefVals.find(Name);
1786 if (
I != ForwardRefVals.end())
1787 Val =
I->second.first;
1793 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1797 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1804 error(Loc,
"global variable reference must have pointer type");
1808 GlobalValue *Val = NumberedVals.get(
ID);
1813 auto I = ForwardRefValIDs.find(
ID);
1814 if (
I != ForwardRefValIDs.end())
1815 Val =
I->second.first;
1821 checkValidVariableType(Loc,
"@" + Twine(
ID), Ty, Val));
1825 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1833Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
1837 if (
I != ComdatSymTab.
end())
1841 Comdat *
C = M->getOrInsertComdat(Name);
1842 ForwardRefComdats[
Name] = Loc;
1852bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1853 if (Lex.getKind() !=
T)
1854 return tokError(ErrMsg);
1861bool LLParser::parseStringConstant(std::string &Result) {
1863 return tokError(
"expected string constant");
1864 Result = Lex.getStrVal();
1871bool LLParser::parseUInt32(uint32_t &Val) {
1872 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1873 return tokError(
"expected integer");
1874 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1875 if (Val64 !=
unsigned(Val64))
1876 return tokError(
"expected 32-bit integer (too large)");
1884bool LLParser::parseUInt64(uint64_t &Val) {
1885 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1886 return tokError(
"expected integer");
1887 Val = Lex.getAPSIntVal().getLimitedValue();
1897 switch (Lex.getKind()) {
1899 return tokError(
"expected localdynamic, initialexec or localexec");
1927 return parseTLSModel(TLM) ||
1928 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1936bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1937 AddrSpace = DefaultAS;
1941 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1943 auto AddrSpaceStr = Lex.getStrVal();
1944 if (AddrSpaceStr ==
"A") {
1945 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1946 }
else if (AddrSpaceStr ==
"G") {
1947 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1948 }
else if (AddrSpaceStr ==
"P") {
1949 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1951 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1957 return tokError(
"expected integer or string constant");
1958 SMLoc Loc = Lex.getLoc();
1959 if (parseUInt32(AddrSpace))
1962 return error(Loc,
"invalid address space, must be a 24-bit integer");
1966 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1967 ParseAddrspaceValue(AddrSpace) ||
1974bool LLParser::parseStringAttribute(AttrBuilder &
B) {
1975 std::string Attr = Lex.getStrVal();
1978 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1980 B.addAttribute(Attr, Val);
1985bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
1986 bool HaveError =
false;
1993 if (parseStringAttribute(
B))
2004 SMLoc Loc = Lex.getLoc();
2009 if (parseEnumAttribute(Attr,
B,
false))
2013 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2015 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2063bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2064 unsigned &Visibility,
2065 unsigned &DLLStorageClass,
bool &DSOLocal) {
2069 parseOptionalDSOLocal(DSOLocal);
2070 parseOptionalVisibility(Visibility);
2071 parseOptionalDLLStorageClass(DLLStorageClass);
2074 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2080void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2081 switch (Lex.getKind()) {
2102void LLParser::parseOptionalVisibility(
unsigned &Res) {
2103 switch (Lex.getKind()) {
2120bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2124 return tokError(
"unknown import kind. Expect definition or declaration.");
2139void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2140 switch (Lex.getKind()) {
2210bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2211 switch (Lex.getKind()) {
2298 return tokError(
"unknown RISC-V ABI VLEN");
2299#define CC_VLS_CASE(ABIVlen) \
2301 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2320 return parseUInt32(CC);
2330bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2333 std::string
Name = Lex.getStrVal();
2334 Kind = M->getMDKindID(Name);
2337 return parseMDNode(MD);
2342bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2345 return tokError(
"expected metadata after comma");
2349 if (parseMetadataAttachment(MDK,
N))
2352 if (MDK == LLVMContext::MD_DIAssignID)
2353 TempDIAssignIDAttachments[
N].push_back(&Inst);
2357 if (MDK == LLVMContext::MD_tbaa)
2358 InstsWithTBAATag.push_back(&Inst);
2367bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2370 if (parseMetadataAttachment(MDK,
N))
2379bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2381 if (parseGlobalObjectMetadataAttachment(
F))
2389bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2390 Alignment = std::nullopt;
2391 if (!EatIfPresent(lltok::kw_align))
2393 LocTy AlignLoc = Lex.getLoc();
2396 LocTy ParenLoc = Lex.getLoc();
2397 bool HaveParens =
false;
2403 if (parseUInt64(
Value))
2407 return error(ParenLoc,
"expected ')'");
2410 return error(AlignLoc,
"alignment is not a power of two");
2412 return error(AlignLoc,
"huge alignments are not supported yet");
2422 auto StrVal = Lex.getStrVal();
2423 auto ErrMsg =
"expected global code model string";
2424 if (StrVal ==
"tiny")
2426 else if (StrVal ==
"small")
2428 else if (StrVal ==
"kernel")
2430 else if (StrVal ==
"medium")
2432 else if (StrVal ==
"large")
2435 return tokError(ErrMsg);
2446bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2448 assert((AttrKind == lltok::kw_dereferenceable ||
2449 AttrKind == lltok::kw_dereferenceable_or_null) &&
2453 if (!EatIfPresent(AttrKind))
2455 LocTy ParenLoc = Lex.getLoc();
2457 return error(ParenLoc,
"expected '('");
2458 LocTy DerefLoc = Lex.getLoc();
2459 if (parseUInt64(Bytes))
2461 ParenLoc = Lex.getLoc();
2463 return error(ParenLoc,
"expected ')'");
2465 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2469bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2474 LocTy KindLoc = Lex.getLoc();
2480 return error(KindLoc,
"expected unwind table kind");
2487 LocTy ParenLoc = Lex.getLoc();
2489 return error(ParenLoc,
"expected '('");
2490 LocTy KindLoc = Lex.getLoc();
2492 if (parseStringConstant(Arg))
2493 return error(KindLoc,
"expected allockind value");
2497 }
else if (
A ==
"realloc") {
2499 }
else if (
A ==
"free") {
2501 }
else if (
A ==
"uninitialized") {
2503 }
else if (
A ==
"zeroed") {
2505 }
else if (
A ==
"aligned") {
2508 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2511 ParenLoc = Lex.getLoc();
2513 return error(ParenLoc,
"expected ')'");
2515 return error(KindLoc,
"expected allockind value");
2528 return std::nullopt;
2543 return std::nullopt;
2547std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2552 Lex.setIgnoreColonInIdentifiers(
true);
2557 tokError(
"expected '('");
2558 return std::nullopt;
2561 bool SeenLoc =
false;
2563 std::optional<IRMemLocation> Loc =
keywordToLoc(Lex.getKind());
2567 tokError(
"expected ':' after location");
2568 return std::nullopt;
2575 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2576 "or access kind (none, read, write, readwrite)");
2578 tokError(
"expected access kind (none, read, write, readwrite)");
2579 return std::nullopt;
2588 tokError(
"default access kind must be specified first");
2589 return std::nullopt;
2598 tokError(
"unterminated memory attribute");
2599 return std::nullopt;
2641unsigned LLParser::parseNoFPClassAttr() {
2646 tokError(
"expected '('");
2653 if (TestMask != 0) {
2657 !parseUInt64(
Value)) {
2659 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
2664 error(Lex.getLoc(),
"expected ')'");
2670 error(Lex.getLoc(),
"expected nofpclass test mask");
2688bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2689 bool &AteExtraComma) {
2690 AteExtraComma =
false;
2694 AteExtraComma =
true;
2698 if (Lex.getKind() != lltok::kw_align)
2699 return error(Lex.getLoc(),
"expected metadata or 'align'");
2701 if (parseOptionalAlignment(Alignment))
2714bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
2715 bool &AteExtraComma) {
2716 AteExtraComma =
false;
2720 AteExtraComma =
true;
2726 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
2728 if (parseOptionalAddrSpace(AddrSpace))
2735bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2736 std::optional<unsigned> &HowManyArg) {
2739 auto StartParen = Lex.getLoc();
2741 return error(StartParen,
"expected '('");
2743 if (parseUInt32(BaseSizeArg))
2747 auto HowManyAt = Lex.getLoc();
2749 if (parseUInt32(HowMany))
2751 if (HowMany == BaseSizeArg)
2752 return error(HowManyAt,
2753 "'allocsize' indices can't refer to the same parameter");
2754 HowManyArg = HowMany;
2756 HowManyArg = std::nullopt;
2758 auto EndParen = Lex.getLoc();
2760 return error(EndParen,
"expected ')'");
2764bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2765 unsigned &MaxValue) {
2768 auto StartParen = Lex.getLoc();
2770 return error(StartParen,
"expected '('");
2772 if (parseUInt32(MinValue))
2776 if (parseUInt32(MaxValue))
2779 MaxValue = MinValue;
2781 auto EndParen = Lex.getLoc();
2783 return error(EndParen,
"expected ')'");
2792bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2797 return parseScope(SSID) || parseOrdering(Ordering);
2807 auto StartParenAt = Lex.getLoc();
2809 return error(StartParenAt,
"Expected '(' in syncscope");
2812 auto SSNAt = Lex.getLoc();
2813 if (parseStringConstant(SSN))
2814 return error(SSNAt,
"Expected synchronization scope name");
2816 auto EndParenAt = Lex.getLoc();
2818 return error(EndParenAt,
"Expected ')' in syncscope");
2820 SSID = Context.getOrInsertSyncScopeID(SSN);
2831 switch (Lex.getKind()) {
2833 return tokError(
"Expected ordering on atomic instruction");
2852bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2854 if (!EatIfPresent(lltok::kw_alignstack))
2856 LocTy ParenLoc = Lex.getLoc();
2858 return error(ParenLoc,
"expected '('");
2859 LocTy AlignLoc = Lex.getLoc();
2860 if (parseUInt32(Alignment))
2862 ParenLoc = Lex.getLoc();
2864 return error(ParenLoc,
"expected ')'");
2866 return error(AlignLoc,
"stack alignment is not a power of two");
2880 bool &AteExtraComma) {
2881 AteExtraComma =
false;
2884 return tokError(
"expected ',' as start of index list");
2888 if (Indices.
empty())
2889 return tokError(
"expected index");
2890 AteExtraComma =
true;
2894 if (parseUInt32(Idx))
2907bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2908 SMLoc TypeLoc = Lex.getLoc();
2909 switch (Lex.getKind()) {
2911 return tokError(Msg);
2920 if (
Result->isPointerTy()) {
2922 if (parseOptionalAddrSpace(AddrSpace))
2928 return tokError(
"ptr* is invalid - use ptr instead");
2939 if (parseTargetExtType(Result))
2945 if (parseAnonStructType(Result,
false))
2951 if (parseArrayVectorType(Result,
false))
2958 if (parseAnonStructType(Result,
true) ||
2959 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2961 }
else if (parseArrayVectorType(Result,
true))
2966 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
2972 Entry.second = Lex.getLoc();
2981 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
2987 Entry.second = Lex.getLoc();
2997 switch (Lex.getKind()) {
3000 if (!AllowVoid &&
Result->isVoidTy())
3001 return error(TypeLoc,
"void type only allowed for function results");
3007 return tokError(
"basic block pointers are invalid");
3009 return tokError(
"pointers to void are invalid - use i8* instead");
3011 return tokError(
"pointer to this type is invalid");
3019 return tokError(
"basic block pointers are invalid");
3021 return tokError(
"pointers to void are invalid; use i8* instead");
3023 return tokError(
"pointer to this type is invalid");
3025 if (parseOptionalAddrSpace(AddrSpace) ||
3026 parseToken(
lltok::star,
"expected '*' in address space"))
3035 if (parseFunctionType(Result))
3048 PerFunctionState &PFS,
bool IsMustTailCall,
3049 bool InVarArgsFunc) {
3055 if (!ArgList.
empty() &&
3056 parseToken(
lltok::comma,
"expected ',' in argument list"))
3061 const char *Msg =
"unexpected ellipsis in argument list for ";
3062 if (!IsMustTailCall)
3063 return tokError(Twine(Msg) +
"non-musttail call");
3065 return tokError(Twine(Msg) +
"musttail call in non-varargs function");
3067 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3072 Type *ArgTy =
nullptr;
3074 if (parseType(ArgTy, ArgLoc))
3077 return error(ArgLoc,
"invalid type for function argument");
3079 AttrBuilder ArgAttrs(M->getContext());
3082 if (parseMetadataAsValue(V, PFS))
3086 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3093 if (IsMustTailCall && InVarArgsFunc)
3094 return tokError(
"expected '...' at end of argument list for musttail call "
3095 "in varargs function");
3103bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3106 if (!EatIfPresent(AttrToken))
3109 return error(Lex.getLoc(),
"expected '('");
3113 return error(Lex.getLoc(),
"expected ')'");
3115 B.addTypeAttr(AttrKind, Ty);
3121bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3129 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3131 return tokError(
"expected integer");
3132 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3134 "integer is too large for the bit width of specified type");
3135 Val = Lex.getAPSIntVal().extend(
BitWidth);
3140 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3143 return error(TyLoc,
"the range must have integer type!");
3151 return tokError(
"the range represent the empty set but limits aren't 0!");
3162bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3165 auto ParseAPSInt = [&](APInt &Val) {
3167 return tokError(
"expected integer");
3168 Val = Lex.getAPSIntVal().extend(64);
3188 return tokError(
"the range should not represent the full or empty set!");
3200 if (!CRLOrNull.has_value())
3201 return tokError(
"Invalid (unordered or overlapping) range list");
3202 B.addInitializesAttr(*CRLOrNull);
3206bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3208 std::optional<CaptureComponents>
Ret;
3212 Lex.setIgnoreColonInIdentifiers(
true);
3220 bool SeenComponent =
false;
3226 return tokError(
"duplicate 'ret' location");
3229 SeenComponent =
false;
3234 return tokError(
"cannot use 'none' with other component");
3238 return tokError(
"cannot use 'none' with other component");
3249 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3250 "'provenance' or 'read_provenance'");
3253 SeenComponent =
true;
3274bool LLParser::parseOptionalOperandBundles(
3276 LocTy BeginLoc = Lex.getLoc();
3282 if (!BundleList.
empty() &&
3283 parseToken(
lltok::comma,
"expected ',' in input list"))
3287 if (parseStringConstant(
Tag))
3290 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3293 std::vector<Value *> Inputs;
3296 if (!Inputs.empty() &&
3297 parseToken(
lltok::comma,
"expected ',' in input list"))
3301 Value *Input =
nullptr;
3305 if (parseMetadataAsValue(Input, PFS))
3307 }
else if (parseValue(Ty, Input, PFS)) {
3310 Inputs.push_back(Input);
3318 if (BundleList.
empty())
3319 return error(BeginLoc,
"operand bundle set must not be empty");
3326 unsigned NextID,
unsigned ID) {
3328 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3329 Twine(NextID) +
"' or greater");
3346 unsigned CurValID = 0;
3360 LocTy TypeLoc = Lex.getLoc();
3361 Type *ArgTy =
nullptr;
3362 AttrBuilder
Attrs(M->getContext());
3363 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3367 return error(TypeLoc,
"argument can not have void type");
3371 Name = Lex.getStrVal();
3376 ArgID = Lex.getUIntVal();
3377 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3384 CurValID = ArgID + 1;
3388 return error(TypeLoc,
"invalid type for function argument");
3396 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3401bool LLParser::parseFunctionType(
Type *&Result) {
3405 return tokError(
"invalid function return type");
3409 SmallVector<unsigned> UnnamedArgNums;
3410 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3414 for (
const ArgInfo &Arg : ArgList) {
3415 if (!Arg.Name.empty())
3416 return error(Arg.Loc,
"argument name invalid in function type");
3417 if (Arg.Attrs.hasAttributes())
3418 return error(Arg.Loc,
"argument attributes invalid in function type");
3422 for (
const ArgInfo &Arg : ArgList)
3431bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3433 if (parseStructBody(Elts))
3441bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3442 std::pair<Type *, LocTy> &Entry,
3446 return error(TypeLoc,
"redefinition of type");
3452 Entry.second = SMLoc();
3457 ResultTy =
Entry.first;
3469 return error(TypeLoc,
"forward references to non-struct type");
3473 return parseArrayVectorType(ResultTy,
true);
3474 return parseType(ResultTy);
3478 Entry.second = SMLoc();
3487 if (parseStructBody(Body) ||
3488 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3492 return tokError(
toString(std::move(
E)));
3512 LocTy EltTyLoc = Lex.getLoc();
3519 return error(EltTyLoc,
"invalid element type for struct");
3522 EltTyLoc = Lex.getLoc();
3527 return error(EltTyLoc,
"invalid element type for struct");
3532 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3541bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3542 bool Scalable =
false;
3546 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3552 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3553 Lex.getAPSIntVal().getBitWidth() > 64)
3554 return tokError(
"expected number in address space");
3556 LocTy SizeLoc = Lex.getLoc();
3557 uint64_t
Size = Lex.getAPSIntVal().getZExtValue();
3560 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3563 LocTy TypeLoc = Lex.getLoc();
3564 Type *EltTy =
nullptr;
3565 if (parseType(EltTy))
3569 "expected end of sequential type"))
3574 return error(SizeLoc,
"zero element vector is illegal");
3576 return error(SizeLoc,
"size too large for vector");
3578 return error(TypeLoc,
"invalid vector element type");
3582 return error(TypeLoc,
"invalid array element type");
3599bool LLParser::parseTargetExtType(
Type *&Result) {
3604 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3605 parseStringConstant(TypeName))
3612 SmallVector<unsigned> IntParams;
3613 bool SeenInt =
false;
3620 if (parseUInt32(IntVal))
3623 }
else if (SeenInt) {
3626 return tokError(
"expected uint32 param");
3629 if (parseType(TypeParam,
true))
3635 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3640 if (
auto E = TTy.takeError())
3641 return tokError(
toString(std::move(
E)));
3654 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3657 auto It = UnnamedArgNums.
begin();
3660 unsigned ArgNum = *It++;
3661 NumberedVals.add(ArgNum, &A);
3666LLParser::PerFunctionState::~PerFunctionState() {
3669 for (
const auto &P : ForwardRefVals) {
3672 P.second.first->replaceAllUsesWith(
3674 P.second.first->deleteValue();
3677 for (
const auto &P : ForwardRefValIDs) {
3680 P.second.first->replaceAllUsesWith(
3682 P.second.first->deleteValue();
3686bool LLParser::PerFunctionState::finishFunction() {
3687 if (!ForwardRefVals.empty())
3688 return P.error(ForwardRefVals.begin()->second.second,
3689 "use of undefined value '%" + ForwardRefVals.begin()->first +
3691 if (!ForwardRefValIDs.empty())
3692 return P.error(ForwardRefValIDs.begin()->second.second,
3693 "use of undefined value '%" +
3694 Twine(ForwardRefValIDs.begin()->first) +
"'");
3701Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
3704 Value *Val =
F.getValueSymbolTable()->lookup(Name);
3709 auto I = ForwardRefVals.find(Name);
3710 if (
I != ForwardRefVals.end())
3711 Val =
I->second.first;
3716 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
3720 P.error(Loc,
"invalid use of a non-first-class type");
3731 if (FwdVal->
getName() != Name) {
3732 P.error(Loc,
"name is too long which can result in name collisions, "
3733 "consider making the name shorter or "
3734 "increasing -non-global-value-max-name-size");
3738 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3742Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
3744 Value *Val = NumberedVals.get(
ID);
3749 auto I = ForwardRefValIDs.find(
ID);
3750 if (
I != ForwardRefValIDs.end())
3751 Val =
I->second.first;
3756 return P.checkValidVariableType(Loc,
"%" + Twine(
ID), Ty, Val);
3759 P.error(Loc,
"invalid use of a non-first-class type");
3771 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3777bool LLParser::PerFunctionState::setInstName(
int NameID,
3778 const std::string &NameStr,
3779 LocTy NameLoc, Instruction *Inst) {
3782 if (NameID != -1 || !NameStr.empty())
3783 return P.error(NameLoc,
"instructions returning void cannot have a name");
3789 if (NameStr.empty()) {
3792 NameID = NumberedVals.getNext();
3794 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3798 auto FI = ForwardRefValIDs.find(NameID);
3799 if (FI != ForwardRefValIDs.end()) {
3802 return P.error(NameLoc,
"instruction forward referenced with type '" +
3806 Sentinel->replaceAllUsesWith(Inst);
3808 ForwardRefValIDs.erase(FI);
3811 NumberedVals.add(NameID, Inst);
3816 auto FI = ForwardRefVals.find(NameStr);
3817 if (FI != ForwardRefVals.end()) {
3820 return P.error(NameLoc,
"instruction forward referenced with type '" +
3824 Sentinel->replaceAllUsesWith(Inst);
3826 ForwardRefVals.erase(FI);
3832 if (Inst->
getName() != NameStr)
3833 return P.error(NameLoc,
"multiple definition of local value named '" +
3840BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
3854BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
3855 int NameID,
LocTy Loc) {
3859 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3862 NameID = NumberedVals.getNext();
3864 BB = getBB(NameID, Loc);
3866 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
3870 BB = getBB(Name, Loc);
3872 P.error(Loc,
"unable to create block named '" + Name +
"'");
3883 ForwardRefValIDs.erase(NameID);
3884 NumberedVals.add(NameID, BB);
3887 ForwardRefVals.erase(Name);
3904bool LLParser::parseValID(ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3905 ID.Loc = Lex.getLoc();
3906 switch (Lex.getKind()) {
3908 return tokError(
"expected value token");
3910 ID.UIntVal = Lex.getUIntVal();
3914 ID.StrVal = Lex.getStrVal();
3918 ID.UIntVal = Lex.getUIntVal();
3922 ID.StrVal = Lex.getStrVal();
3926 ID.APSIntVal = Lex.getAPSIntVal();
3930 ID.APFloatVal = Lex.getAPFloatVal();
3951 if (parseGlobalValueVector(Elts) ||
3952 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3955 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3956 ID.UIntVal = Elts.
size();
3957 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3958 Elts.
size() *
sizeof(Elts[0]));
3969 LocTy FirstEltLoc = Lex.getLoc();
3970 if (parseGlobalValueVector(Elts) ||
3972 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3976 if (isPackedStruct) {
3977 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3978 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3979 Elts.
size() *
sizeof(Elts[0]));
3980 ID.UIntVal = Elts.
size();
3986 return error(
ID.Loc,
"constant vector must not be empty");
3988 if (!Elts[0]->
getType()->isIntegerTy() &&
3989 !Elts[0]->
getType()->isFloatingPointTy() &&
3993 "vector elements must have integer, pointer or floating point type");
3996 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3998 return error(FirstEltLoc,
"vector element #" + Twine(i) +
3999 " is not of type '" +
4009 LocTy FirstEltLoc = Lex.getLoc();
4010 if (parseGlobalValueVector(Elts) ||
4022 if (!Elts[0]->
getType()->isFirstClassType())
4023 return error(FirstEltLoc,
"invalid array element type: " +
4029 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4031 return error(FirstEltLoc,
"array element #" + Twine(i) +
4032 " is not of type '" +
4052 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4055 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4058 parseStringConstant(
ID.StrVal) ||
4059 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4062 ID.StrVal2 = Lex.getStrVal();
4063 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4064 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4075 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4076 parseValID(Fn, PFS) ||
4078 "expected comma in block address expression") ||
4079 parseValID(Label, PFS) ||
4080 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4084 return error(Fn.
Loc,
"expected function name in blockaddress");
4086 return error(
Label.Loc,
"expected basic block name in blockaddress");
4089 GlobalValue *GV =
nullptr;
4091 GV = NumberedVals.get(Fn.
UIntVal);
4092 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4093 GV = M->getNamedValue(Fn.
StrVal);
4099 return error(Fn.
Loc,
"expected function name in blockaddress");
4101 if (
F->isDeclaration())
4102 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4107 GlobalValue *&FwdRef =
4108 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4116 "type of blockaddress must be a pointer and not '" +
4121 FwdDeclAS = PFS->getFunction().getAddressSpace();
4125 FwdRef =
new GlobalVariable(
4130 ID.ConstantVal = FwdRef;
4138 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4140 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4142 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4144 return error(
Label.Loc,
"referenced value is not a basic block");
4147 return error(
Label.Loc,
"cannot take address of numeric label after "
4148 "the function is defined");
4150 F->getValueSymbolTable()->lookup(
Label.StrVal));
4152 return error(
Label.Loc,
"referenced value is not a basic block");
4166 if (parseValID(Fn, PFS))
4171 "expected global value name in dso_local_equivalent");
4174 GlobalValue *GV =
nullptr;
4176 GV = NumberedVals.get(Fn.
UIntVal);
4177 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4178 GV = M->getNamedValue(Fn.
StrVal);
4184 ? ForwardRefDSOLocalEquivalentIDs
4185 : ForwardRefDSOLocalEquivalentNames;
4186 GlobalValue *&FwdRef = FwdRefMap[Fn];
4193 ID.ConstantVal = FwdRef;
4199 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4200 "in dso_local_equivalent");
4211 if (parseValID(
ID, PFS))
4215 return error(
ID.Loc,
"expected global value name in no_cfi");
4226 Constant *Disc =
nullptr, *AddrDisc =
nullptr;
4229 "expected '(' in constant ptrauth expression") ||
4230 parseGlobalTypeAndValue(
Ptr) ||
4232 "expected comma in constant ptrauth expression") ||
4233 parseGlobalTypeAndValue(
Key))
4237 if (parseGlobalTypeAndValue(Disc) ||
4238 (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4241 "expected ')' in constant ptrauth expression"))
4244 if (!
Ptr->getType()->isPointerTy())
4245 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4248 if (!KeyC || KeyC->getBitWidth() != 32)
4249 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4251 ConstantInt *DiscC =
nullptr;
4257 "constant ptrauth integer discriminator must be i64 constant");
4263 if (!AddrDisc->getType()->isPointerTy())
4265 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4281 unsigned Opc = Lex.getUIntVal();
4282 Type *DestTy =
nullptr;
4285 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4286 parseGlobalTypeAndValue(SrcVal) ||
4287 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4288 parseType(DestTy) ||
4289 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4292 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4301 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4303 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4305 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4307 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4309 return error(
ID.Loc,
"urem constexprs are no longer supported");
4311 return error(
ID.Loc,
"srem constexprs are no longer supported");
4313 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4315 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4317 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4319 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4321 return error(
ID.Loc,
"frem constexprs are no longer supported");
4323 return error(
ID.Loc,
"and constexprs are no longer supported");
4325 return error(
ID.Loc,
"or constexprs are no longer supported");
4327 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4329 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4331 return error(
ID.Loc,
"shl constexprs are no longer supported");
4333 return error(
ID.Loc,
"mul constexprs are no longer supported");
4335 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4337 return error(
ID.Loc,
"select constexprs are no longer supported");
4339 return error(
ID.Loc,
"zext constexprs are no longer supported");
4341 return error(
ID.Loc,
"sext constexprs are no longer supported");
4343 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4345 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4347 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4349 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4351 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4353 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4355 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4357 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4365 unsigned Opc = Lex.getUIntVal();
4368 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4369 Opc == Instruction::Mul) {
4378 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4379 parseGlobalTypeAndValue(Val0) ||
4380 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4381 parseGlobalTypeAndValue(Val1) ||
4382 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4385 return error(
ID.Loc,
"operands of constexpr must have same type");
4389 "constexpr requires integer or integer vector operands");
4400 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4403 if (parseGlobalTypeAndValue(
C))
4405 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4417 unsigned Opc = Lex.getUIntVal();
4420 bool HasInRange =
false;
4426 if (
Opc == Instruction::GetElementPtr) {
4442 return tokError(
"expected integer");
4443 InRangeStart = Lex.getAPSIntVal();
4448 return tokError(
"expected integer");
4449 InRangeEnd = Lex.getAPSIntVal();
4457 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4460 if (
Opc == Instruction::GetElementPtr) {
4461 if (parseType(Ty) ||
4462 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4466 if (parseGlobalValueVector(Elts) ||
4470 if (
Opc == Instruction::GetElementPtr) {
4471 if (Elts.
size() == 0 ||
4472 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4473 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4476 std::optional<ConstantRange>
InRange;
4478 unsigned IndexWidth =
4479 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4480 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4481 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4482 if (InRangeStart.
sge(InRangeEnd))
4483 return error(
ID.Loc,
"expected end to be larger than start");
4493 for (Constant *Val : Indices) {
4496 return error(
ID.Loc,
"getelementptr index must be an integer");
4499 if (GEPWidth && (ValNumEl != GEPWidth))
4502 "getelementptr vector index has a wrong number of elements");
4505 GEPWidth = ValNumEl;
4509 SmallPtrSet<Type*, 4> Visited;
4510 if (!Indices.empty() && !Ty->
isSized(&Visited))
4511 return error(
ID.Loc,
"base element of getelementptr must be sized");
4514 return error(
ID.Loc,
"invalid getelementptr indices");
4518 }
else if (
Opc == Instruction::ShuffleVector) {
4519 if (Elts.
size() != 3)
4520 return error(
ID.Loc,
"expected three operands to shufflevector");
4522 return error(
ID.Loc,
"invalid operands to shufflevector");
4523 SmallVector<int, 16>
Mask;
4526 }
else if (
Opc == Instruction::ExtractElement) {
4527 if (Elts.
size() != 2)
4528 return error(
ID.Loc,
"expected two operands to extractelement");
4530 return error(
ID.Loc,
"invalid extractelement operands");
4533 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4534 if (Elts.
size() != 3)
4535 return error(
ID.Loc,
"expected three operands to insertelement");
4537 return error(
ID.Loc,
"invalid insertelement operands");
4552bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4556 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4557 convertValIDToValue(Ty,
ID, V,
nullptr);
4559 return error(
ID.Loc,
"global values must be constants");
4563bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4565 return parseType(Ty) || parseGlobalValue(Ty, V);
4568bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4571 LocTy KwLoc = Lex.getLoc();
4577 return tokError(
"expected comdat variable");
4578 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4580 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4583 if (GlobalName.
empty())
4584 return tokError(
"comdat cannot be unnamed");
4585 C = getComdat(std::string(GlobalName), KwLoc);
4594bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4608 if (parseGlobalTypeAndValue(
C))
4616bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
4618 if (parseMDNodeVector(Elts))
4629bool LLParser::parseMDNode(MDNode *&
N) {
4631 return parseSpecializedMDNode(
N);
4633 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4636bool LLParser::parseMDNodeTail(MDNode *&
N) {
4639 return parseMDTuple(
N);
4642 return parseMDNodeID(
N);
4648template <
class FieldTy>
struct MDFieldImpl {
4649 typedef MDFieldImpl ImplTy;
4653 void assign(FieldTy Val) {
4655 this->Val = std::move(Val);
4658 explicit MDFieldImpl(FieldTy
Default)
4666template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4667 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4678 void assign(FieldTypeA
A) {
4680 this->
A = std::move(
A);
4684 void assign(FieldTypeB
B) {
4686 this->
B = std::move(
B);
4690 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4692 WhatIs(IsInvalid) {}
4695struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4702struct LineField :
public MDUnsignedField {
4703 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4706struct ColumnField :
public MDUnsignedField {
4707 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4710struct DwarfTagField :
public MDUnsignedField {
4716struct DwarfMacinfoTypeField :
public MDUnsignedField {
4722struct DwarfAttEncodingField :
public MDUnsignedField {
4723 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4726struct DwarfVirtualityField :
public MDUnsignedField {
4730struct DwarfLangField :
public MDUnsignedField {
4734struct DwarfCCField :
public MDUnsignedField {
4735 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4738struct DwarfEnumKindField :
public MDUnsignedField {
4739 DwarfEnumKindField()
4744struct EmissionKindField :
public MDUnsignedField {
4745 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4748struct FixedPointKindField :
public MDUnsignedField {
4749 FixedPointKindField()
4750 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4753struct NameTableKindField :
public MDUnsignedField {
4754 NameTableKindField()
4757 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4760struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4761 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4764struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4765 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4768struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4769 MDAPSIntField() : ImplTy(
APSInt()) {}
4772struct MDSignedField :
public MDFieldImpl<int64_t> {
4776 MDSignedField(int64_t
Default = 0)
4778 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4782struct MDBoolField :
public MDFieldImpl<bool> {
4786struct MDField :
public MDFieldImpl<Metadata *> {
4789 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4792struct MDStringField :
public MDFieldImpl<MDString *> {
4793 enum class EmptyIs {
4798 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
4799 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4802struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4806struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4810struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4811 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4812 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4814 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4815 bool AllowNull =
true)
4816 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4818 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4819 bool isMDField()
const {
return WhatIs == IsTypeB; }
4820 int64_t getMDSignedValue()
const {
4821 assert(isMDSignedField() &&
"Wrong field type");
4824 Metadata *getMDFieldValue()
const {
4825 assert(isMDField() &&
"Wrong field type");
4830struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4831 MDUnsignedOrMDField(uint64_t
Default = 0,
bool AllowNull =
true)
4832 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
4834 MDUnsignedOrMDField(uint64_t
Default, uint64_t Max,
bool AllowNull =
true)
4835 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
4837 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
4838 bool isMDField()
const {
return WhatIs == IsTypeB; }
4839 uint64_t getMDUnsignedValue()
const {
4840 assert(isMDUnsignedField() &&
"Wrong field type");
4843 Metadata *getMDFieldValue()
const {
4844 assert(isMDField() &&
"Wrong field type");
4849 if (isMDUnsignedField())
4851 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
4853 return getMDFieldValue();
4865 return tokError(
"expected integer");
4867 Result.assign(Lex.getAPSIntVal());
4874 MDUnsignedField &Result) {
4875 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
4876 return tokError(
"expected unsigned integer");
4878 auto &U = Lex.getAPSIntVal();
4879 if (U.ugt(Result.Max))
4880 return tokError(
"value for '" + Name +
"' too large, limit is " +
4882 Result.assign(U.getZExtValue());
4883 assert(Result.Val <= Result.Max &&
"Expected value in range");
4890 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4894 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4900 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4903 return tokError(
"expected DWARF tag");
4907 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
4908 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4917 DwarfMacinfoTypeField &Result) {
4919 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4922 return tokError(
"expected DWARF macinfo type");
4926 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4927 Lex.getStrVal() +
"'");
4928 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4930 Result.assign(Macinfo);
4937 DwarfVirtualityField &Result) {
4939 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4942 return tokError(
"expected DWARF virtuality code");
4946 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4947 Lex.getStrVal() +
"'");
4948 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4949 Result.assign(Virtuality);
4956 DwarfEnumKindField &Result) {
4958 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4961 return tokError(
"expected DWARF enum kind code");
4965 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
4966 Lex.getStrVal() +
"'");
4967 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
4968 Result.assign(EnumKind);
4976 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4979 return tokError(
"expected DWARF language");
4983 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
4985 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4986 Result.assign(Lang);
4994 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
4997 return tokError(
"expected DWARF calling convention");
5001 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5002 Lex.getStrVal() +
"'");
5003 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5011 EmissionKindField &Result) {
5013 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5016 return tokError(
"expected emission kind");
5020 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5022 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5023 Result.assign(*Kind);
5030 FixedPointKindField &Result) {
5032 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5035 return tokError(
"expected fixed-point kind");
5039 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5041 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5042 Result.assign(*Kind);
5049 NameTableKindField &Result) {
5051 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5054 return tokError(
"expected nameTable kind");
5058 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5060 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5061 Result.assign((
unsigned)*Kind);
5068 DwarfAttEncodingField &Result) {
5070 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5073 return tokError(
"expected DWARF type attribute encoding");
5077 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5078 Lex.getStrVal() +
"'");
5079 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5080 Result.assign(Encoding);
5094 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5096 bool Res = parseUInt32(TempVal);
5102 return tokError(
"expected debug info flag");
5106 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5121 Result.assign(Combined);
5134 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5136 bool Res = parseUInt32(TempVal);
5142 return tokError(
"expected debug info flag");
5146 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5147 Lex.getStrVal() +
"'");
5161 Result.assign(Combined);
5168 return tokError(
"expected signed integer");
5170 auto &S = Lex.getAPSIntVal();
5172 return tokError(
"value for '" + Name +
"' too small, limit is " +
5175 return tokError(
"value for '" + Name +
"' too large, limit is " +
5177 Result.assign(S.getExtValue());
5178 assert(Result.Val >= Result.Min &&
"Expected value in range");
5179 assert(Result.Val <= Result.Max &&
"Expected value in range");
5186 switch (Lex.getKind()) {
5188 return tokError(
"expected 'true' or 'false'");
5190 Result.assign(
true);
5193 Result.assign(
false);
5203 if (!Result.AllowNull)
5204 return tokError(
"'" + Name +
"' cannot be null");
5206 Result.assign(
nullptr);
5211 if (parseMetadata(MD,
nullptr))
5220 MDSignedOrMDField &Result) {
5223 MDSignedField Res = Result.A;
5224 if (!parseMDField(
Loc, Name, Res)) {
5232 MDField Res = Result.B;
5233 if (!parseMDField(
Loc, Name, Res)) {
5243 MDUnsignedOrMDField &Result) {
5246 MDUnsignedField Res = Result.A;
5247 if (!parseMDField(
Loc, Name, Res)) {
5255 MDField Res = Result.B;
5256 if (!parseMDField(
Loc, Name, Res)) {
5266 LocTy ValueLoc = Lex.getLoc();
5268 if (parseStringConstant(S))
5272 switch (Result.EmptyIs) {
5273 case MDStringField::EmptyIs::Null:
5274 Result.assign(
nullptr);
5276 case MDStringField::EmptyIs::Empty:
5278 case MDStringField::EmptyIs::Error:
5279 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5290 if (parseMDNodeVector(MDs))
5293 Result.assign(std::move(MDs));
5299 ChecksumKindField &Result) {
5300 std::optional<DIFile::ChecksumKind> CSKind =
5304 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5307 Result.assign(*CSKind);
5314template <
class ParserTy>
5315bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5318 return tokError(
"expected field label here");
5327template <
class ParserTy>
5328bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5335 if (parseMDFieldsImplBody(ParseField))
5338 ClosingLoc = Lex.getLoc();
5342template <
class FieldTy>
5343bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5345 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5347 LocTy Loc = Lex.getLoc();
5349 return parseMDField(Loc, Name, Result);
5352bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5355#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5356 if (Lex.getStrVal() == #CLASS) \
5357 return parse##CLASS(N, IsDistinct);
5358#include "llvm/IR/Metadata.def"
5360 return tokError(
"expected metadata type");
5363#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5364#define NOP_FIELD(NAME, TYPE, INIT)
5365#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5367 return error(ClosingLoc, "missing required field '" #NAME "'");
5368#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5369 if (Lex.getStrVal() == #NAME) \
5370 return parseMDField(#NAME, NAME);
5371#define PARSE_MD_FIELDS() \
5372 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5375 if (parseMDFieldsImpl( \
5377 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5378 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5383 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5385#define GET_OR_DISTINCT(CLASS, ARGS) \
5386 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5391bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5392#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5393 OPTIONAL(line, LineField, ); \
5394 OPTIONAL(column, ColumnField, ); \
5395 REQUIRED(scope, MDField, ( false)); \
5396 OPTIONAL(inlinedAt, MDField, ); \
5397 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5398 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5399 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5401#undef VISIT_MD_FIELDS
5404 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5405 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5411bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5413 return tokError(
"missing 'distinct', required for !DIAssignID()");
5429bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5430#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5431 REQUIRED(tag, DwarfTagField, ); \
5432 OPTIONAL(header, MDStringField, ); \
5433 OPTIONAL(operands, MDFieldList, );
5435#undef VISIT_MD_FIELDS
5438 (Context, tag.Val, header.Val, operands.Val));
5447bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5448#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5449 OPTIONAL(name, MDStringField, ); \
5450 OPTIONAL(file, MDField, ); \
5451 OPTIONAL(line, LineField, ); \
5452 OPTIONAL(scope, MDField, ); \
5453 OPTIONAL(baseType, MDField, ); \
5454 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5455 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5456 OPTIONAL(flags, DIFlagField, ); \
5457 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5458 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5459 OPTIONAL(stride, MDSignedOrMDField, ); \
5460 OPTIONAL(bias, MDSignedOrMDField, );
5462#undef VISIT_MD_FIELDS
5464 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5465 if (Bound.isMDSignedField())
5468 if (Bound.isMDField())
5469 return Bound.getMDFieldValue();
5473 Metadata *LowerBound = convToMetadata(lowerBound);
5475 Metadata *Stride = convToMetadata(stride);
5476 Metadata *Bias = convToMetadata(bias);
5479 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5480 size.getValueAsMetadata(Context), align.Val, flags.Val,
5481 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5490bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5491#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5492 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5493 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5494 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5495 OPTIONAL(stride, MDSignedOrMDField, );
5497#undef VISIT_MD_FIELDS
5504 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5505 if (Bound.isMDSignedField())
5508 if (Bound.isMDField())
5509 return Bound.getMDFieldValue();
5514 LowerBound = convToMetadata(lowerBound);
5516 Stride = convToMetadata(stride);
5519 (Context,
Count, LowerBound, UpperBound, Stride));
5527bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5528#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5529 OPTIONAL(count, MDSignedOrMDField, ); \
5530 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5531 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5532 OPTIONAL(stride, MDSignedOrMDField, );
5534#undef VISIT_MD_FIELDS
5536 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5537 if (Bound.isMDSignedField())
5539 Context, {dwarf::DW_OP_consts,
5540 static_cast<uint64_t
>(Bound.getMDSignedValue())});
5541 if (Bound.isMDField())
5542 return Bound.getMDFieldValue();
5547 Metadata *LowerBound = ConvToMetadata(lowerBound);
5549 Metadata *Stride = ConvToMetadata(stride);
5552 (Context,
Count, LowerBound, UpperBound, Stride));
5559bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5560#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5561 REQUIRED(name, MDStringField, ); \
5562 REQUIRED(value, MDAPSIntField, ); \
5563 OPTIONAL(isUnsigned, MDBoolField, (false));
5565#undef VISIT_MD_FIELDS
5567 if (isUnsigned.Val && value.Val.isNegative())
5568 return tokError(
"unsigned enumerator with negative value");
5573 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5585bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5586#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5587 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5588 OPTIONAL(name, MDStringField, ); \
5589 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5590 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5591 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5592 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5593 OPTIONAL(flags, DIFlagField, );
5595#undef VISIT_MD_FIELDS
5598 size.getValueAsMetadata(Context),
5599 align.Val, encoding.Val,
5600 num_extra_inhabitants.Val, flags.Val));
5609bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
5610#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5611 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5612 OPTIONAL(name, MDStringField, ); \
5613 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5614 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5615 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5616 OPTIONAL(flags, DIFlagField, ); \
5617 OPTIONAL(kind, FixedPointKindField, ); \
5618 OPTIONAL(factor, MDSignedField, ); \
5619 OPTIONAL(numerator, MDAPSIntField, ); \
5620 OPTIONAL(denominator, MDAPSIntField, );
5622#undef VISIT_MD_FIELDS
5625 (Context, tag.Val,
name.Val,
5626 size.getValueAsMetadata(Context), align.Val,
5627 encoding.Val, flags.Val, kind.Val, factor.Val,
5628 numerator.Val, denominator.Val));
5634bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5635#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5636 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5637 OPTIONAL(name, MDStringField, ); \
5638 OPTIONAL(stringLength, MDField, ); \
5639 OPTIONAL(stringLengthExpression, MDField, ); \
5640 OPTIONAL(stringLocationExpression, MDField, ); \
5641 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5642 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5643 OPTIONAL(encoding, DwarfAttEncodingField, );
5645#undef VISIT_MD_FIELDS
5649 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5650 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
5651 align.Val, encoding.Val));
5664bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5665#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5666 REQUIRED(tag, DwarfTagField, ); \
5667 OPTIONAL(name, MDStringField, ); \
5668 OPTIONAL(file, MDField, ); \
5669 OPTIONAL(line, LineField, ); \
5670 OPTIONAL(scope, MDField, ); \
5671 REQUIRED(baseType, MDField, ); \
5672 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5673 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5674 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5675 OPTIONAL(flags, DIFlagField, ); \
5676 OPTIONAL(extraData, MDField, ); \
5677 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5678 OPTIONAL(annotations, MDField, ); \
5679 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5680 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5681 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5682 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5683 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5685#undef VISIT_MD_FIELDS
5687 std::optional<unsigned> DWARFAddressSpace;
5688 if (dwarfAddressSpace.Val != UINT32_MAX)
5689 DWARFAddressSpace = dwarfAddressSpace.Val;
5690 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5692 PtrAuthData.emplace(
5693 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5694 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5695 ptrAuthAuthenticatesNullValues.Val);
5698 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
5699 baseType.Val,
size.getValueAsMetadata(Context), align.Val,
5700 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5701 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5705bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5706#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5707 REQUIRED(tag, DwarfTagField, ); \
5708 OPTIONAL(name, MDStringField, ); \
5709 OPTIONAL(file, MDField, ); \
5710 OPTIONAL(line, LineField, ); \
5711 OPTIONAL(scope, MDField, ); \
5712 OPTIONAL(baseType, MDField, ); \
5713 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5714 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5715 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5716 OPTIONAL(flags, DIFlagField, ); \
5717 OPTIONAL(elements, MDField, ); \
5718 OPTIONAL(runtimeLang, DwarfLangField, ); \
5719 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5720 OPTIONAL(vtableHolder, MDField, ); \
5721 OPTIONAL(templateParams, MDField, ); \
5722 OPTIONAL(identifier, MDStringField, ); \
5723 OPTIONAL(discriminator, MDField, ); \
5724 OPTIONAL(dataLocation, MDField, ); \
5725 OPTIONAL(associated, MDField, ); \
5726 OPTIONAL(allocated, MDField, ); \
5727 OPTIONAL(rank, MDSignedOrMDField, ); \
5728 OPTIONAL(annotations, MDField, ); \
5729 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5730 OPTIONAL(specification, MDField, ); \
5731 OPTIONAL(bitStride, MDField, );
5733#undef VISIT_MD_FIELDS
5736 if (rank.isMDSignedField())
5739 else if (rank.isMDField())
5740 Rank = rank.getMDFieldValue();
5742 std::optional<unsigned> EnumKind;
5744 EnumKind = enumKind.Val;
5749 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5750 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
5751 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5752 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5753 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5754 dataLocation.Val, associated.Val, allocated.Val, Rank,
5755 annotations.Val, bitStride.Val)) {
5764 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5765 size.getValueAsMetadata(Context), align.Val,
5766 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5767 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5768 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5769 allocated.Val, Rank, annotations.Val, specification.Val,
5770 num_extra_inhabitants.Val, bitStride.Val));
5774bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5775#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5776 OPTIONAL(flags, DIFlagField, ); \
5777 OPTIONAL(cc, DwarfCCField, ); \
5778 REQUIRED(types, MDField, );
5780#undef VISIT_MD_FIELDS
5783 (Context, flags.Val, cc.Val, types.Val));
5792bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5796#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5797 REQUIRED(filename, MDStringField, ); \
5798 REQUIRED(directory, MDStringField, ); \
5799 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5800 OPTIONAL(checksum, MDStringField, ); \
5801 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5803#undef VISIT_MD_FIELDS
5805 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5806 if (checksumkind.Seen && checksum.Seen)
5807 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5808 else if (checksumkind.Seen || checksum.Seen)
5809 return tokError(
"'checksumkind' and 'checksum' must be provided together");
5811 MDString *
Source =
nullptr;
5815 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5826bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5828 return tokError(
"missing 'distinct', required for !DICompileUnit");
5830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5831 REQUIRED(language, DwarfLangField, ); \
5832 REQUIRED(file, MDField, ( false)); \
5833 OPTIONAL(producer, MDStringField, ); \
5834 OPTIONAL(isOptimized, MDBoolField, ); \
5835 OPTIONAL(flags, MDStringField, ); \
5836 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5837 OPTIONAL(splitDebugFilename, MDStringField, ); \
5838 OPTIONAL(emissionKind, EmissionKindField, ); \
5839 OPTIONAL(enums, MDField, ); \
5840 OPTIONAL(retainedTypes, MDField, ); \
5841 OPTIONAL(globals, MDField, ); \
5842 OPTIONAL(imports, MDField, ); \
5843 OPTIONAL(macros, MDField, ); \
5844 OPTIONAL(dwoId, MDUnsignedField, ); \
5845 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5846 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5847 OPTIONAL(nameTableKind, NameTableKindField, ); \
5848 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5849 OPTIONAL(sysroot, MDStringField, ); \
5850 OPTIONAL(sdk, MDStringField, );
5852#undef VISIT_MD_FIELDS
5855 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5856 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5857 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5858 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5859 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5872bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5873 auto Loc = Lex.getLoc();
5874#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5875 OPTIONAL(scope, MDField, ); \
5876 OPTIONAL(name, MDStringField, ); \
5877 OPTIONAL(linkageName, MDStringField, ); \
5878 OPTIONAL(file, MDField, ); \
5879 OPTIONAL(line, LineField, ); \
5880 OPTIONAL(type, MDField, ); \
5881 OPTIONAL(isLocal, MDBoolField, ); \
5882 OPTIONAL(isDefinition, MDBoolField, (true)); \
5883 OPTIONAL(scopeLine, LineField, ); \
5884 OPTIONAL(containingType, MDField, ); \
5885 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5886 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5887 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5888 OPTIONAL(flags, DIFlagField, ); \
5889 OPTIONAL(spFlags, DISPFlagField, ); \
5890 OPTIONAL(isOptimized, MDBoolField, ); \
5891 OPTIONAL(unit, MDField, ); \
5892 OPTIONAL(templateParams, MDField, ); \
5893 OPTIONAL(declaration, MDField, ); \
5894 OPTIONAL(retainedNodes, MDField, ); \
5895 OPTIONAL(thrownTypes, MDField, ); \
5896 OPTIONAL(annotations, MDField, ); \
5897 OPTIONAL(targetFuncName, MDStringField, ); \
5898 OPTIONAL(keyInstructions, MDBoolField, );
5900#undef VISIT_MD_FIELDS
5905 spFlags.Seen ? spFlags.Val
5907 isOptimized.Val, virtuality.Val);
5908 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5911 "missing 'distinct', required for !DISubprogram that is a Definition");
5914 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5915 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5916 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5917 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5918 targetFuncName.Val, keyInstructions.Val));
5924bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5925#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5926 REQUIRED(scope, MDField, ( false)); \
5927 OPTIONAL(file, MDField, ); \
5928 OPTIONAL(line, LineField, ); \
5929 OPTIONAL(column, ColumnField, );
5931#undef VISIT_MD_FIELDS
5934 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
5940bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 REQUIRED(scope, MDField, ( false)); \
5943 OPTIONAL(file, MDField, ); \
5944 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5946#undef VISIT_MD_FIELDS
5949 (Context, scope.Val,
file.Val, discriminator.Val));
5955bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5956#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5957 REQUIRED(scope, MDField, ); \
5958 OPTIONAL(declaration, MDField, ); \
5959 OPTIONAL(name, MDStringField, ); \
5960 OPTIONAL(file, MDField, ); \
5961 OPTIONAL(line, LineField, );
5963#undef VISIT_MD_FIELDS
5966 (Context, scope.Val, declaration.Val,
name.Val,
5967 file.Val, line.Val));
5973bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5974#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5975 REQUIRED(scope, MDField, ); \
5976 OPTIONAL(name, MDStringField, ); \
5977 OPTIONAL(exportSymbols, MDBoolField, );
5979#undef VISIT_MD_FIELDS
5982 (Context, scope.Val,
name.Val, exportSymbols.Val));
5989bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5990#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5991 REQUIRED(type, DwarfMacinfoTypeField, ); \
5992 OPTIONAL(line, LineField, ); \
5993 REQUIRED(name, MDStringField, ); \
5994 OPTIONAL(value, MDStringField, );
5996#undef VISIT_MD_FIELDS
5999 (Context, type.Val, line.Val,
name.Val, value.Val));
6005bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6006#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6007 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6008 OPTIONAL(line, LineField, ); \
6009 REQUIRED(file, MDField, ); \
6010 OPTIONAL(nodes, MDField, );
6012#undef VISIT_MD_FIELDS
6015 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6023bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6024#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6025 REQUIRED(scope, MDField, ); \
6026 REQUIRED(name, MDStringField, ); \
6027 OPTIONAL(configMacros, MDStringField, ); \
6028 OPTIONAL(includePath, MDStringField, ); \
6029 OPTIONAL(apinotes, MDStringField, ); \
6030 OPTIONAL(file, MDField, ); \
6031 OPTIONAL(line, LineField, ); \
6032 OPTIONAL(isDecl, MDBoolField, );
6034#undef VISIT_MD_FIELDS
6037 configMacros.Val, includePath.Val,
6038 apinotes.Val, line.Val, isDecl.Val));
6044bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6045#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6046 OPTIONAL(name, MDStringField, ); \
6047 REQUIRED(type, MDField, ); \
6048 OPTIONAL(defaulted, MDBoolField, );
6050#undef VISIT_MD_FIELDS
6053 (Context,
name.Val, type.Val, defaulted.Val));
6061bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6062#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6063 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6064 OPTIONAL(name, MDStringField, ); \
6065 OPTIONAL(type, MDField, ); \
6066 OPTIONAL(defaulted, MDBoolField, ); \
6067 REQUIRED(value, MDField, );
6070#undef VISIT_MD_FIELDS
6073 DITemplateValueParameter,
6074 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6083bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6084#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6085 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6086 OPTIONAL(scope, MDField, ); \
6087 OPTIONAL(linkageName, MDStringField, ); \
6088 OPTIONAL(file, MDField, ); \
6089 OPTIONAL(line, LineField, ); \
6090 OPTIONAL(type, MDField, ); \
6091 OPTIONAL(isLocal, MDBoolField, ); \
6092 OPTIONAL(isDefinition, MDBoolField, (true)); \
6093 OPTIONAL(templateParams, MDField, ); \
6094 OPTIONAL(declaration, MDField, ); \
6095 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6096 OPTIONAL(annotations, MDField, );
6098#undef VISIT_MD_FIELDS
6102 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6103 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6104 declaration.Val, templateParams.Val, align.Val,
6116bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6117#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6118 REQUIRED(scope, MDField, ( false)); \
6119 OPTIONAL(name, MDStringField, ); \
6120 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6121 OPTIONAL(file, MDField, ); \
6122 OPTIONAL(line, LineField, ); \
6123 OPTIONAL(type, MDField, ); \
6124 OPTIONAL(flags, DIFlagField, ); \
6125 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6126 OPTIONAL(annotations, MDField, );
6128#undef VISIT_MD_FIELDS
6131 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6132 type.Val, arg.Val, flags.Val, align.Val,
6139bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6140#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6141 REQUIRED(scope, MDField, ( false)); \
6142 REQUIRED(name, MDStringField, ); \
6143 REQUIRED(file, MDField, ); \
6144 REQUIRED(line, LineField, ); \
6145 OPTIONAL(column, ColumnField, ); \
6146 OPTIONAL(isArtificial, MDBoolField, ); \
6147 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6149#undef VISIT_MD_FIELDS
6151 std::optional<unsigned> CoroSuspendIdx =
6152 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6156 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6157 column.Val, isArtificial.Val, CoroSuspendIdx));
6163bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6176 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6185 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6186 Lex.getStrVal() +
"'");
6189 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6190 return tokError(
"expected unsigned integer");
6192 auto &
U = Lex.getAPSIntVal();
6194 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6208bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6210 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6213 return parseDIExpressionBody(Result, IsDistinct);
6218bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6219 assert(PFS &&
"Expected valid function state");
6230 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6244bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6246#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6247 REQUIRED(var, MDField, ); \
6248 REQUIRED(expr, MDField, );
6250#undef VISIT_MD_FIELDS
6253 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6260bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6261#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6262 OPTIONAL(name, MDStringField, ); \
6263 OPTIONAL(file, MDField, ); \
6264 OPTIONAL(line, LineField, ); \
6265 OPTIONAL(setter, MDStringField, ); \
6266 OPTIONAL(getter, MDStringField, ); \
6267 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6268 OPTIONAL(type, MDField, );
6270#undef VISIT_MD_FIELDS
6273 (Context,
name.Val,
file.Val, line.Val, setter.Val,
6274 getter.Val, attributes.Val, type.Val));
6281bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6282#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6283 REQUIRED(tag, DwarfTagField, ); \
6284 REQUIRED(scope, MDField, ); \
6285 OPTIONAL(entity, MDField, ); \
6286 OPTIONAL(file, MDField, ); \
6287 OPTIONAL(line, LineField, ); \
6288 OPTIONAL(name, MDStringField, ); \
6289 OPTIONAL(elements, MDField, );
6291#undef VISIT_MD_FIELDS
6294 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6295 line.Val,
name.Val, elements.Val));
6299#undef PARSE_MD_FIELD
6311bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6314 if (parseMetadata(MD, &PFS))
6325bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6326 PerFunctionState *PFS) {
6329 if (parseType(Ty, TypeMsg, Loc))
6332 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6335 if (parseValue(Ty, V, PFS))
6350bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6354 if (Lex.getStrVal() ==
"DIArgList") {
6356 if (parseDIArgList(AL, PFS))
6362 if (parseSpecializedMDNode(
N)) {
6372 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6382 if (parseMDString(S))
6392 if (parseMDNodeTail(
N))
6403 PerFunctionState *PFS) {
6405 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6410 return error(
ID.Loc,
"invalid use of function-local name");
6411 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6412 return V ==
nullptr;
6415 return error(
ID.Loc,
"invalid use of function-local name");
6416 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6417 return V ==
nullptr;
6420 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6424 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6429 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6432 return V ==
nullptr;
6434 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6437 return V ==
nullptr;
6440 return error(
ID.Loc,
"integer constant must have integer type");
6442 V = ConstantInt::get(Context,
ID.APSIntVal);
6447 return error(
ID.Loc,
"floating point constant invalid for type");
6453 bool IsSNAN =
ID.APFloatVal.isSignaling();
6468 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6470 ID.APFloatVal.isNegative(), &Payload);
6473 V = ConstantFP::get(Context,
ID.APFloatVal);
6475 if (
V->getType() != Ty)
6476 return error(
ID.Loc,
"floating point constant does not have type '" +
6482 return error(
ID.Loc,
"null must be a pointer type");
6488 return error(
ID.Loc,
"invalid type for undef constant");
6493 return error(
ID.Loc,
"invalid empty array initializer");
6499 return error(
ID.Loc,
"invalid type for null constant");
6502 return error(
ID.Loc,
"invalid type for null constant");
6507 return error(
ID.Loc,
"invalid type for none constant");
6513 return error(
ID.Loc,
"invalid type for poison constant");
6517 if (
ID.ConstantVal->getType() != Ty)
6518 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6525 return error(
ID.Loc,
"vector constant must have vector type");
6527 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6529 "' but expected '" +
6537 if (
ST->getNumElements() !=
ID.UIntVal)
6539 "initializer with struct type has wrong # elements");
6541 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6544 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6545 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6548 "element " + Twine(i) +
6549 " of struct initializer doesn't match struct element type");
6552 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6554 return error(
ID.Loc,
"constant expression type mismatch");
6563 auto Loc = Lex.getLoc();
6564 if (parseValID(
ID,
nullptr))
6577 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6587 return error(Loc,
"expected a constant value");
6591bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6594 return parseValID(
ID, PFS, Ty) ||
6595 convertValIDToValue(Ty,
ID, V, PFS);
6598bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6600 return parseType(Ty) || parseValue(Ty, V, PFS);
6603bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
6604 PerFunctionState &PFS) {
6607 if (parseTypeAndValue(V, PFS))
6610 return error(Loc,
"expected a basic block");
6619 if (!Name.starts_with(
"llvm.dbg."))
6622 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6623 FnID == Intrinsic::dbg_assign;
6631bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6632 unsigned &FunctionNumber,
6635 LocTy LinkageLoc = Lex.getLoc();
6637 unsigned Visibility;
6638 unsigned DLLStorageClass;
6640 AttrBuilder RetAttrs(M->getContext());
6643 Type *RetType =
nullptr;
6644 LocTy RetTypeLoc = Lex.getLoc();
6645 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
6647 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6648 parseType(RetType, RetTypeLoc,
true ))
6657 return error(LinkageLoc,
"invalid linkage for function definition");
6667 return error(LinkageLoc,
"invalid linkage for function declaration");
6671 return error(LinkageLoc,
"invalid function linkage type");
6675 return error(LinkageLoc,
6676 "symbol with local linkage must have default visibility");
6679 return error(LinkageLoc,
6680 "symbol with local linkage cannot have a DLL storage class");
6683 return error(RetTypeLoc,
"invalid function return type");
6685 LocTy NameLoc = Lex.getLoc();
6687 std::string FunctionName;
6689 FunctionName = Lex.getStrVal();
6691 FunctionNumber = Lex.getUIntVal();
6692 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6696 return tokError(
"expected function name");
6702 return tokError(
"expected '(' in function argument list");
6706 AttrBuilder FuncAttrs(M->getContext());
6707 std::vector<unsigned> FwdRefAttrGrps;
6710 std::string Partition;
6711 MaybeAlign Alignment;
6714 unsigned AddrSpace = 0;
6720 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6721 parseOptionalUnnamedAddr(UnnamedAddr) ||
6722 parseOptionalProgramAddrSpace(AddrSpace) ||
6723 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6727 parseOptionalComdat(FunctionName,
C) ||
6728 parseOptionalAlignment(Alignment) ||
6729 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6733 parseGlobalTypeAndValue(PersonalityFn)))
6736 if (FuncAttrs.contains(Attribute::Builtin))
6737 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6740 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
6742 FuncAttrs.removeAttribute(Attribute::Alignment);
6747 std::vector<Type*> ParamTypeList;
6750 for (
const ArgInfo &Arg : ArgList) {
6751 ParamTypeList.push_back(Arg.Ty);
6752 Attrs.push_back(Arg.Attrs);
6759 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
6760 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6766 GlobalValue *FwdFn =
nullptr;
6767 if (!FunctionName.empty()) {
6770 auto FRVI = ForwardRefVals.find(FunctionName);
6771 if (FRVI != ForwardRefVals.end()) {
6772 FwdFn = FRVI->second.first;
6774 return error(FRVI->second.second,
6775 "invalid forward reference to "
6778 "' with wrong type: "
6782 ForwardRefVals.erase(FRVI);
6783 }
else if ((Fn = M->getFunction(FunctionName))) {
6785 return error(NameLoc,
6786 "invalid redefinition of function '" + FunctionName +
"'");
6787 }
else if (M->getNamedValue(FunctionName)) {
6788 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6794 if (FunctionNumber == (
unsigned)-1)
6795 FunctionNumber = NumberedVals.getNext();
6799 auto I = ForwardRefValIDs.find(FunctionNumber);
6800 if (
I != ForwardRefValIDs.end()) {
6801 FwdFn =
I->second.first;
6803 return error(NameLoc,
"type of definition and forward reference of '@" +
6804 Twine(FunctionNumber) +
6809 ForwardRefValIDs.erase(
I);
6818 if (FunctionName.empty())
6819 NumberedVals.add(FunctionNumber, Fn);
6834 if (!
GC.empty()) Fn->
setGC(GC);
6837 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6841 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6843 if (ArgList[i].
Name.empty())
continue;
6846 ArgIt->
setName(ArgList[i].Name);
6848 if (ArgIt->
getName() != ArgList[i].Name)
6849 return error(ArgList[i].Loc,
6850 "redefinition of argument '%" + ArgList[i].Name +
"'");
6863 if (FunctionName.empty()) {
6865 ID.UIntVal = FunctionNumber;
6868 ID.StrVal = FunctionName;
6870 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6871 if (Blocks != ForwardRefBlockAddresses.end())
6872 return error(Blocks->first.Loc,
6873 "cannot take blockaddress inside a declaration");
6877bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6879 if (FunctionNumber == -1) {
6881 ID.StrVal = std::string(F.getName());
6884 ID.UIntVal = FunctionNumber;
6887 auto Blocks = P.ForwardRefBlockAddresses.find(
ID);
6888 if (Blocks == P.ForwardRefBlockAddresses.end())
6891 for (
const auto &
I : Blocks->second) {
6892 const ValID &BBID =
I.first;
6893 GlobalValue *GV =
I.second;
6896 "Expected local id or name");
6903 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6906 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
6914 P.ForwardRefBlockAddresses.erase(Blocks);
6920bool LLParser::parseFunctionBody(Function &Fn,
unsigned FunctionNumber,
6921 ArrayRef<unsigned> UnnamedArgNums) {
6923 return tokError(
"expected '{' in function body");
6926 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6930 if (PFS.resolveForwardRefBlockAddresses())
6936 return tokError(
"function body requires at least one basic block");
6940 if (parseBasicBlock(PFS))
6944 if (parseUseListOrder(&PFS))
6951 return PFS.finishFunction();
6956bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6960 LocTy NameLoc = Lex.getLoc();
6962 Name = Lex.getStrVal();
6965 NameID = Lex.getUIntVal();
6969 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6973 std::string NameStr;
6978 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
6979 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
6986 if (SeenOldDbgInfoFormat)
6987 return error(Lex.getLoc(),
"debug record should not appear in a module "
6988 "containing debug info intrinsics");
6989 SeenNewDbgInfoFormat =
true;
6993 if (parseDebugRecord(DR, PFS))
6995 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7000 LocTy NameLoc = Lex.getLoc();
7005 NameID = Lex.getUIntVal();
7007 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7010 NameStr = Lex.getStrVal();
7012 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7016 switch (parseInstruction(Inst, BB, PFS)) {
7019 case InstError:
return true;
7026 if (parseInstructionMetadata(*Inst))
7029 case InstExtraComma:
7034 if (parseInstructionMetadata(*Inst))
7040 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7044 for (DbgRecordPtr &DR : TrailingDbgRecord)
7046 TrailingDbgRecord.clear();
7049 assert(TrailingDbgRecord.empty() &&
7050 "All debug values should have been attached to an instruction.");
7059bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7062 LocTy DVRLoc = Lex.getLoc();
7064 return error(DVRLoc,
"expected debug record type here");
7065 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7066 .Case(
"declare", RecordKind::ValueKind)
7067 .Case(
"value", RecordKind::ValueKind)
7068 .Case(
"assign", RecordKind::ValueKind)
7069 .Case(
"label", RecordKind::LabelKind);
7078 if (parseMDNode(Label))
7083 if (parseMDNode(DbgLoc))
7091 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7092 .Case(
"declare", LocType::Declare)
7093 .Case(
"value", LocType::Value)
7094 .Case(
"assign", LocType::Assign);
7102 if (parseMetadata(ValLocMD, &PFS))
7109 if (parseMDNode(Variable))
7116 if (parseMDNode(Expression))
7122 MDNode *AssignID =
nullptr;
7123 Metadata *AddressLocation =
nullptr;
7124 MDNode *AddressExpression =
nullptr;
7127 if (parseMDNode(AssignID))
7133 if (parseMetadata(AddressLocation, &PFS))
7139 if (parseMDNode(AddressExpression))
7153 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7163int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7164 PerFunctionState &PFS) {
7167 return tokError(
"found end of file when expecting more instructions");
7168 LocTy Loc = Lex.getLoc();
7169 unsigned KeywordVal = Lex.getUIntVal();
7174 return error(Loc,
"expected instruction opcode");
7178 return parseRet(Inst, BB, PFS);
7180 return parseBr(Inst, PFS);
7182 return parseSwitch(Inst, PFS);
7184 return parseIndirectBr(Inst, PFS);
7186 return parseInvoke(Inst, PFS);
7188 return parseResume(Inst, PFS);
7190 return parseCleanupRet(Inst, PFS);
7192 return parseCatchRet(Inst, PFS);
7194 return parseCatchSwitch(Inst, PFS);
7196 return parseCatchPad(Inst, PFS);
7198 return parseCleanupPad(Inst, PFS);
7200 return parseCallBr(Inst, PFS);
7203 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7204 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7220 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7232 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7233 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7247 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7255 return parseArithmetic(Inst, PFS, KeywordVal,
7259 if (parseLogical(Inst, PFS, KeywordVal))
7267 return parseLogical(Inst, PFS, KeywordVal);
7270 if (parseCompare(Inst, PFS, KeywordVal))
7277 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7278 int Res = parseCompare(Inst, PFS, KeywordVal);
7290 bool Res = parseCast(Inst, PFS, KeywordVal);
7302 if (parseCast(Inst, PFS, KeywordVal))
7319 return parseCast(Inst, PFS, KeywordVal);
7322 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7323 if (parseCast(Inst, PFS, KeywordVal))
7332 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7333 int Res = parseSelect(Inst, PFS);
7338 return error(Loc,
"fast-math-flags specified for select without "
7339 "floating-point scalar or vector return type");
7345 return parseVAArg(Inst, PFS);
7347 return parseExtractElement(Inst, PFS);
7349 return parseInsertElement(Inst, PFS);
7351 return parseShuffleVector(Inst, PFS);
7353 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7354 int Res = parsePHI(Inst, PFS);
7359 return error(Loc,
"fast-math-flags specified for phi without "
7360 "floating-point scalar or vector return type");
7366 return parseLandingPad(Inst, PFS);
7368 return parseFreeze(Inst, PFS);
7380 return parseAlloc(Inst, PFS);
7382 return parseLoad(Inst, PFS);
7384 return parseStore(Inst, PFS);
7386 return parseCmpXchg(Inst, PFS);
7388 return parseAtomicRMW(Inst, PFS);
7390 return parseFence(Inst, PFS);
7392 return parseGetElementPtr(Inst, PFS);
7394 return parseExtractValue(Inst, PFS);
7396 return parseInsertValue(Inst, PFS);
7401bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7402 if (
Opc == Instruction::FCmp) {
7403 switch (Lex.getKind()) {
7405 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7424 switch (Lex.getKind()) {
7426 return tokError(
"expected icmp predicate (e.g. 'eq')");
7450bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7451 PerFunctionState &PFS) {
7452 SMLoc TypeLoc = Lex.getLoc();
7454 if (parseType(Ty,
true ))
7457 Type *ResType = PFS.getFunction().getReturnType();
7461 return error(TypeLoc,
"value doesn't match function result type '" +
7469 if (parseValue(Ty, RV, PFS))
7473 return error(TypeLoc,
"value doesn't match function result type '" +
7483bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7487 if (parseTypeAndValue(Op0, Loc, PFS))
7496 return error(Loc,
"branch condition must have 'i1' type");
7498 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7499 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7500 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7501 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7513bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7514 LocTy CondLoc, BBLoc;
7517 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7518 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7519 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7523 if (!
Cond->getType()->isIntegerTy())
7524 return error(CondLoc,
"switch condition must have integer type");
7527 SmallPtrSet<Value*, 32> SeenCases;
7533 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7534 parseToken(
lltok::comma,
"expected ',' after case value") ||
7535 parseTypeAndBasicBlock(DestBB, PFS))
7538 if (!SeenCases.
insert(Constant).second)
7539 return error(CondLoc,
"duplicate case value in switch");
7541 return error(CondLoc,
"case value is not a constant integer");
7549 for (
const auto &[OnVal, Dest] : Table)
7550 SI->addCase(OnVal, Dest);
7558bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7561 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7562 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7566 if (!
Address->getType()->isPointerTy())
7567 return error(AddrLoc,
"indirectbr address must have pointer type");
7570 SmallVector<BasicBlock*, 16> DestList;
7574 if (parseTypeAndBasicBlock(DestBB, PFS))
7579 if (parseTypeAndBasicBlock(DestBB, PFS))
7585 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7589 for (BasicBlock *Dest : DestList)
7599 FunctionType *&FuncTy) {
7605 for (
const ParamInfo &Arg : ArgList)
7619bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7620 LocTy CallLoc = Lex.getLoc();
7621 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7622 std::vector<unsigned> FwdRefAttrGrps;
7625 unsigned InvokeAddrSpace;
7626 Type *RetType =
nullptr;
7633 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7634 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7635 parseType(RetType, RetTypeLoc,
true ) ||
7636 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7637 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7639 parseOptionalOperandBundles(BundleList, PFS) ||
7641 parseTypeAndBasicBlock(NormalBB, PFS) ||
7643 parseTypeAndBasicBlock(UnwindBB, PFS))
7650 if (resolveFunctionType(RetType, ArgList, Ty))
7651 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7657 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
7662 SmallVector<Value *, 8>
Args;
7669 for (
const ParamInfo &Arg : ArgList) {
7670 Type *ExpectedTy =
nullptr;
7673 }
else if (!Ty->isVarArg()) {
7674 return error(Arg.Loc,
"too many arguments specified");
7677 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7678 return error(Arg.Loc,
"argument is not of expected type '" +
7680 Args.push_back(Arg.V);
7685 return error(CallLoc,
"not enough parameters specified for call");
7694 II->setCallingConv(CC);
7695 II->setAttributes(PAL);
7696 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
7703bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7705 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7713bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7714 PerFunctionState &PFS) {
7715 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7720 if (!
Args.empty() &&
7721 parseToken(
lltok::comma,
"expected ',' in argument list"))
7726 Type *ArgTy =
nullptr;
7727 if (parseType(ArgTy, ArgLoc))
7732 if (parseMetadataAsValue(V, PFS))
7735 if (parseValue(ArgTy, V, PFS))
7747bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7748 Value *CleanupPad =
nullptr;
7750 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7765 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7776bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7777 Value *CatchPad =
nullptr;
7779 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7786 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7787 parseTypeAndBasicBlock(BB, PFS))
7796bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7804 return tokError(
"expected scope value for catchswitch");
7809 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7815 if (parseTypeAndBasicBlock(DestBB, PFS))
7820 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7823 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7831 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7837 for (BasicBlock *DestBB : Table)
7838 CatchSwitch->addHandler(DestBB);
7845bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7846 Value *CatchSwitch =
nullptr;
7852 return tokError(
"expected scope value for catchpad");
7857 SmallVector<Value *, 8>
Args;
7858 if (parseExceptionArgs(Args, PFS))
7867bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7868 Value *ParentPad =
nullptr;
7875 return tokError(
"expected scope value for cleanuppad");
7880 SmallVector<Value *, 8>
Args;
7881 if (parseExceptionArgs(Args, PFS))
7897bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7898 unsigned Opc,
bool IsFP) {
7900 if (parseTypeAndValue(
LHS, Loc, PFS))
7907 return error(Loc,
"invalid operand type for instruction");
7917bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7918 LocTy CallLoc = Lex.getLoc();
7919 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7920 std::vector<unsigned> FwdRefAttrGrps;
7923 Type *RetType =
nullptr;
7930 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7931 parseType(RetType, RetTypeLoc,
true ) ||
7932 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7933 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7935 parseOptionalOperandBundles(BundleList, PFS) ||
7937 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7942 SmallVector<BasicBlock *, 16> IndirectDests;
7946 if (parseTypeAndBasicBlock(DestBB, PFS))
7951 if (parseTypeAndBasicBlock(DestBB, PFS))
7957 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7964 if (resolveFunctionType(RetType, ArgList, Ty))
7965 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7976 SmallVector<Value *, 8>
Args;
7983 for (
const ParamInfo &Arg : ArgList) {
7984 Type *ExpectedTy =
nullptr;
7987 }
else if (!Ty->isVarArg()) {
7988 return error(Arg.Loc,
"too many arguments specified");
7991 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7992 return error(Arg.Loc,
"argument is not of expected type '" +
7994 Args.push_back(Arg.V);
7999 return error(CallLoc,
"not enough parameters specified for call");
8011 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8025bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8026 unsigned Opc,
bool IsFP) {
8028 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8029 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8037 return error(Loc,
"invalid operand type for instruction");
8045bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8048 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8049 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8055 "instruction requires integer or integer vector operands");
8064bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8070 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8071 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8075 if (
Opc == Instruction::FCmp) {
8077 return error(Loc,
"fcmp requires floating point operands");
8080 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8083 return error(Loc,
"icmp requires integer operands");
8095bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8099 Type *DestTy =
nullptr;
8100 if (parseTypeAndValue(
Op, Loc, PFS) ||
8101 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8106 return error(Loc,
"invalid cast opcode for cast from '" +
8115bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8117 Value *Op0, *Op1, *Op2;
8118 if (parseTypeAndValue(Op0, Loc, PFS) ||
8119 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8120 parseTypeAndValue(Op1, PFS) ||
8121 parseToken(
lltok::comma,
"expected ',' after select value") ||
8122 parseTypeAndValue(Op2, PFS))
8126 return error(Loc, Reason);
8134bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8136 Type *EltTy =
nullptr;
8138 if (parseTypeAndValue(
Op, PFS) ||
8139 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8140 parseType(EltTy, TypeLoc))
8144 return error(TypeLoc,
"va_arg requires operand with first class type");
8146 Inst =
new VAArgInst(
Op, EltTy);
8152bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8155 if (parseTypeAndValue(Op0, Loc, PFS) ||
8156 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8157 parseTypeAndValue(Op1, PFS))
8161 return error(Loc,
"invalid extractelement operands");
8169bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8171 Value *Op0, *Op1, *Op2;
8172 if (parseTypeAndValue(Op0, Loc, PFS) ||
8173 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8174 parseTypeAndValue(Op1, PFS) ||
8175 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8176 parseTypeAndValue(Op2, PFS))
8180 return error(Loc,
"invalid insertelement operands");
8188bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8190 Value *Op0, *Op1, *Op2;
8191 if (parseTypeAndValue(Op0, Loc, PFS) ||
8192 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8193 parseTypeAndValue(Op1, PFS) ||
8194 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8195 parseTypeAndValue(Op2, PFS))
8199 return error(Loc,
"invalid shufflevector operands");
8201 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8207int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8211 if (parseType(Ty, TypeLoc))
8215 return error(TypeLoc,
"phi node must have first class type");
8218 bool AteExtraComma =
false;
8230 AteExtraComma =
true;
8234 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8235 parseValue(Ty, Op0, PFS) ||
8236 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8245 for (
const auto &[Val, BB] : PHIVals)
8248 return AteExtraComma ? InstExtraComma : InstNormal;
8257bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8260 if (parseType(Ty, TyLoc))
8273 return tokError(
"expected 'catch' or 'filter' clause type");
8277 if (parseTypeAndValue(V, VLoc, PFS))
8284 return error(VLoc,
"'catch' clause has an invalid type");
8287 return error(VLoc,
"'filter' clause has an invalid type");
8292 return error(VLoc,
"clause argument must be a constant");
8296 Inst = LP.release();
8302bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8305 if (parseTypeAndValue(
Op, Loc, PFS))
8308 Inst =
new FreezeInst(
Op);
8321bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8323 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8324 std::vector<unsigned> FwdRefAttrGrps;
8326 unsigned CallAddrSpace;
8328 Type *RetType =
nullptr;
8333 LocTy CallLoc = Lex.getLoc();
8337 "expected 'tail call', 'musttail call', or 'notail call'"))
8340 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8342 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8343 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8344 parseType(RetType, RetTypeLoc,
true ) ||
8345 parseValID(CalleeID, &PFS) ||
8347 PFS.getFunction().isVarArg()) ||
8348 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8349 parseOptionalOperandBundles(BundleList, PFS))
8356 if (resolveFunctionType(RetType, ArgList, Ty))
8357 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8363 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8370 SmallVector<Value*, 8>
Args;
8376 for (
const ParamInfo &Arg : ArgList) {
8377 Type *ExpectedTy =
nullptr;
8380 }
else if (!Ty->isVarArg()) {
8381 return error(Arg.Loc,
"too many arguments specified");
8384 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8385 return error(Arg.Loc,
"argument is not of expected type '" +
8387 Args.push_back(Arg.V);
8388 Attrs.push_back(Arg.Attrs);
8392 return error(CallLoc,
"not enough parameters specified for call");
8405 return error(CallLoc,
"fast-math-flags specified for call without "
8406 "floating-point scalar or vector return type");
8413 if (SeenNewDbgInfoFormat) {
8415 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8416 "using non-intrinsic debug info");
8418 SeenOldDbgInfoFormat =
true;
8421 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8433int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8435 LocTy SizeLoc, TyLoc, ASLoc;
8436 MaybeAlign Alignment;
8437 unsigned AddrSpace = 0;
8440 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8441 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8443 if (parseType(Ty, TyLoc))
8447 return error(TyLoc,
"invalid type for alloca");
8449 bool AteExtraComma =
false;
8451 if (Lex.getKind() == lltok::kw_align) {
8452 if (parseOptionalAlignment(Alignment))
8454 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8457 ASLoc = Lex.getLoc();
8458 if (parseOptionalAddrSpace(AddrSpace))
8461 AteExtraComma =
true;
8463 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8466 if (Lex.getKind() == lltok::kw_align) {
8467 if (parseOptionalAlignment(Alignment))
8469 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8472 ASLoc = Lex.getLoc();
8473 if (parseOptionalAddrSpace(AddrSpace))
8476 AteExtraComma =
true;
8482 if (
Size && !
Size->getType()->isIntegerTy())
8483 return error(SizeLoc,
"element count must have integer type");
8485 SmallPtrSet<Type *, 4> Visited;
8486 if (!Alignment && !Ty->
isSized(&Visited))
8487 return error(TyLoc,
"Cannot allocate unsized type");
8489 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8490 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
8494 return AteExtraComma ? InstExtraComma : InstNormal;
8501int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8503 MaybeAlign Alignment;
8504 bool AteExtraComma =
false;
8505 bool isAtomic =
false;
8514 bool isVolatile =
false;
8521 LocTy ExplicitTypeLoc = Lex.getLoc();
8522 if (parseType(Ty) ||
8523 parseToken(
lltok::comma,
"expected comma after load's type") ||
8524 parseTypeAndValue(Val, Loc, PFS) ||
8525 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8526 parseOptionalCommaAlign(Alignment, AteExtraComma))
8530 return error(Loc,
"load operand must be a pointer to a first class type");
8531 if (isAtomic && !Alignment)
8532 return error(Loc,
"atomic load must have explicit non-zero alignment");
8535 return error(Loc,
"atomic load cannot use Release ordering");
8537 SmallPtrSet<Type *, 4> Visited;
8538 if (!Alignment && !Ty->
isSized(&Visited))
8539 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8541 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8542 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8543 return AteExtraComma ? InstExtraComma : InstNormal;
8551int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8553 MaybeAlign Alignment;
8554 bool AteExtraComma =
false;
8555 bool isAtomic =
false;
8564 bool isVolatile =
false;
8570 if (parseTypeAndValue(Val, Loc, PFS) ||
8571 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8572 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8573 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8574 parseOptionalCommaAlign(Alignment, AteExtraComma))
8577 if (!
Ptr->getType()->isPointerTy())
8578 return error(PtrLoc,
"store operand must be a pointer");
8580 return error(Loc,
"store operand must be a first class value");
8581 if (isAtomic && !Alignment)
8582 return error(Loc,
"atomic store must have explicit non-zero alignment");
8585 return error(Loc,
"atomic store cannot use Acquire ordering");
8586 SmallPtrSet<Type *, 4> Visited;
8588 return error(Loc,
"storing unsized types is not allowed");
8590 Alignment = M->getDataLayout().getABITypeAlign(Val->
getType());
8592 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8593 return AteExtraComma ? InstExtraComma : InstNormal;
8600int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8602 bool AteExtraComma =
false;
8606 bool isVolatile =
false;
8607 bool isWeak =
false;
8608 MaybeAlign Alignment;
8616 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8617 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8618 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8619 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8620 parseTypeAndValue(New, NewLoc, PFS) ||
8621 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8622 parseOrdering(FailureOrdering) ||
8623 parseOptionalCommaAlign(Alignment, AteExtraComma))
8627 return tokError(
"invalid cmpxchg success ordering");
8629 return tokError(
"invalid cmpxchg failure ordering");
8630 if (!
Ptr->getType()->isPointerTy())
8631 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8632 if (
Cmp->getType() !=
New->getType())
8633 return error(NewLoc,
"compare value and new value type do not match");
8634 if (!
New->getType()->isFirstClassType())
8635 return error(NewLoc,
"cmpxchg operand must be a first class value");
8637 const Align DefaultAlignment(
8638 PFS.getFunction().getDataLayout().getTypeStoreSize(
8641 AtomicCmpXchgInst *CXI =
8642 new AtomicCmpXchgInst(
Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8643 SuccessOrdering, FailureOrdering, SSID);
8648 return AteExtraComma ? InstExtraComma : InstNormal;
8654int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8656 bool AteExtraComma =
false;
8659 bool isVolatile =
false;
8662 MaybeAlign Alignment;
8667 switch (Lex.getKind()) {
8669 return tokError(
"expected binary operation in atomicrmw");
8720 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8721 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8722 parseTypeAndValue(Val, ValLoc, PFS) ||
8723 parseScopeAndOrdering(
true , SSID, Ordering) ||
8724 parseOptionalCommaAlign(Alignment, AteExtraComma))
8728 return tokError(
"atomicrmw cannot be unordered");
8729 if (!
Ptr->getType()->isPointerTy())
8730 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8732 return error(ValLoc,
"atomicrmw operand may not be scalable");
8741 " operand must be an integer, floating point, or pointer type");
8745 return error(ValLoc,
"atomicrmw " +
8747 " operand must be a floating point type");
8751 return error(ValLoc,
"atomicrmw " +
8753 " operand must be an integer");
8758 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8761 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8763 const Align DefaultAlignment(
8764 PFS.getFunction().getDataLayout().getTypeStoreSize(
8766 AtomicRMWInst *RMWI =
8768 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8771 return AteExtraComma ? InstExtraComma : InstNormal;
8776int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8779 if (parseScopeAndOrdering(
true , SSID, Ordering))
8783 return tokError(
"fence cannot be unordered");
8785 return tokError(
"fence cannot be monotonic");
8787 Inst =
new FenceInst(Context, Ordering, SSID);
8793int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8795 Value *Val =
nullptr;
8811 if (parseType(Ty) ||
8812 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8813 parseTypeAndValue(
Ptr, Loc, PFS))
8818 if (!BasePointerType)
8819 return error(Loc,
"base of getelementptr must be a pointer");
8821 SmallVector<Value*, 16> Indices;
8822 bool AteExtraComma =
false;
8825 ElementCount GEPWidth =
BaseType->isVectorTy()
8831 AteExtraComma =
true;
8834 if (parseTypeAndValue(Val, EltLoc, PFS))
8837 return error(EltLoc,
"getelementptr index must be an integer");
8840 ElementCount ValNumEl = ValVTy->getElementCount();
8844 "getelementptr vector index has a wrong number of elements");
8845 GEPWidth = ValNumEl;
8850 SmallPtrSet<Type*, 4> Visited;
8852 return error(Loc,
"base element of getelementptr must be sized");
8856 return error(Loc,
"getelementptr cannot target structure that contains "
8857 "scalable vector type");
8860 return error(Loc,
"invalid getelementptr indices");
8863 GEP->setNoWrapFlags(NW);
8864 return AteExtraComma ? InstExtraComma : InstNormal;
8869int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8871 SmallVector<unsigned, 4> Indices;
8873 if (parseTypeAndValue(Val, Loc, PFS) ||
8874 parseIndexList(Indices, AteExtraComma))
8878 return error(Loc,
"extractvalue operand must be aggregate type");
8881 return error(Loc,
"invalid indices for extractvalue");
8883 return AteExtraComma ? InstExtraComma : InstNormal;
8888int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8890 SmallVector<unsigned, 4> Indices;
8892 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8893 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8894 parseTypeAndValue(Val1, Loc1, PFS) ||
8895 parseIndexList(Indices, AteExtraComma))
8899 return error(Loc0,
"insertvalue operand must be aggregate type");
8903 return error(Loc0,
"invalid indices for insertvalue");
8904 if (IndexedType != Val1->
getType())
8905 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8909 return AteExtraComma ? InstExtraComma : InstNormal;
8920bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8935 if (parseMetadata(MD,
nullptr))
8940 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8946bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
8948 if (!
V->hasUseList())
8951 return error(Loc,
"value has no uses");
8953 unsigned NumUses = 0;
8954 SmallDenseMap<const Use *, unsigned, 16> Order;
8955 for (
const Use &U :
V->uses()) {
8956 if (++NumUses > Indexes.
size())
8958 Order[&
U] = Indexes[NumUses - 1];
8961 return error(Loc,
"value only has one use");
8962 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8964 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
8966 V->sortUseList([&](
const Use &L,
const Use &R) {
8974bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8975 SMLoc Loc = Lex.getLoc();
8979 return tokError(
"expected non-empty list of uselistorder indexes");
8986 bool IsOrdered =
true;
8987 assert(Indexes.
empty() &&
"Expected empty order vector");
8990 if (parseUInt32(Index))
8995 Max = std::max(Max, Index);
8996 IsOrdered &= Index == Indexes.
size();
9004 if (Indexes.
size() < 2)
9005 return error(Loc,
"expected >= 2 uselistorder indexes");
9008 "expected distinct uselistorder indexes in range [0, size)");
9010 return error(Loc,
"expected uselistorder indexes to change the order");
9017bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9018 SMLoc Loc = Lex.getLoc();
9023 SmallVector<unsigned, 16> Indexes;
9024 if (parseTypeAndValue(V, PFS) ||
9025 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9026 parseUseListOrderIndexes(Indexes))
9029 return sortUseListOrder(V, Indexes, Loc);
9034bool LLParser::parseUseListOrderBB() {
9036 SMLoc Loc = Lex.getLoc();
9040 SmallVector<unsigned, 16> Indexes;
9041 if (parseValID(Fn,
nullptr) ||
9042 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9043 parseValID(Label,
nullptr) ||
9044 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9045 parseUseListOrderIndexes(Indexes))
9051 GV = M->getNamedValue(Fn.
StrVal);
9053 GV = NumberedVals.get(Fn.
UIntVal);
9055 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9058 "invalid function forward reference in uselistorder_bb");
9061 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9062 if (
F->isDeclaration())
9063 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
9067 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
9069 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
9070 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
9072 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
9074 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
9076 return sortUseListOrder(V, Indexes, Loc);
9082bool LLParser::parseModuleEntry(
unsigned ID) {
9091 parseStringConstant(Path) ||
9099 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9100 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9101 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9102 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9103 parseUInt32(Hash[4]))
9110 auto ModuleEntry = Index->addModule(Path, Hash);
9111 ModuleIdMap[
ID] = ModuleEntry->first();
9118bool LLParser::parseTypeIdEntry(
unsigned ID) {
9127 parseStringConstant(Name))
9130 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9132 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9137 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9138 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9139 for (
auto TIDRef : FwdRefTIDs->second) {
9141 "Forward referenced type id GUID expected to be 0");
9144 ForwardRefTypeIds.erase(FwdRefTIDs);
9152bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9156 parseTypeTestResolution(TIS.
TTRes))
9161 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9172 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
9178bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9187 parseStringConstant(Name))
9191 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9198 IdToIndexMapType IdToIndexMap;
9211 if (parseGVReference(VI, GVId))
9218 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9219 TI.push_back({
Offset, VI});
9227 for (
auto I : IdToIndexMap) {
9228 auto &Infos = ForwardRefValueInfos[
I.first];
9229 for (
auto P :
I.second) {
9231 "Forward referenced ValueInfo expected to be empty");
9232 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9242 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9243 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9244 for (
auto TIDRef : FwdRefTIDs->second) {
9246 "Forward referenced type id GUID expected to be 0");
9249 ForwardRefTypeIds.erase(FwdRefTIDs);
9261bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9269 switch (Lex.getKind()) {
9289 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9301 switch (Lex.getKind()) {
9316 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9329 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9342bool LLParser::parseOptionalWpdResolutions(
9343 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9351 WholeProgramDevirtResolution WPDRes;
9355 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9358 WPDResMap[
Offset] = WPDRes;
9375bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9383 switch (Lex.getKind()) {
9394 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9400 switch (Lex.getKind()) {
9408 if (parseOptionalResByArg(WPDRes.
ResByArg))
9412 return error(Lex.getLoc(),
9413 "expected optional WholeProgramDevirtResolution field");
9430bool LLParser::parseOptionalResByArg(
9431 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9439 std::vector<uint64_t>
Args;
9440 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9448 WholeProgramDevirtResolution::ByArg ByArg;
9449 switch (Lex.getKind()) {
9463 return error(Lex.getLoc(),
9464 "unexpected WholeProgramDevirtResolution::ByArg kind");
9470 switch (Lex.getKind()) {
9474 parseUInt64(ByArg.
Info))
9480 parseUInt32(ByArg.
Byte))
9486 parseUInt32(ByArg.
Bit))
9490 return error(Lex.getLoc(),
9491 "expected optional whole program devirt field");
9498 ResByArg[
Args] = ByArg;
9509bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9517 if (parseUInt64(Val))
9519 Args.push_back(Val);
9528static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9533 assert(!(ReadOnly && WriteOnly));
9543bool LLParser::addGlobalValueToIndex(
9545 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
9550 VI = Index->getOrInsertValueInfo(GUID);
9554 auto *GV = M->getNamedValue(Name);
9556 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
9558 VI = Index->getOrInsertValueInfo(GV);
9562 "Need a source_filename to compute GUID for local");
9565 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9570 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9571 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9572 for (
auto VIRef : FwdRefVIs->second) {
9574 "Forward referenced ValueInfo expected to be empty");
9577 ForwardRefValueInfos.erase(FwdRefVIs);
9581 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9582 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9583 for (
auto AliaseeRef : FwdRefAliasees->second) {
9584 assert(!AliaseeRef.first->hasAliasee() &&
9585 "Forward referencing alias already has aliasee");
9586 assert(Summary &&
"Aliasee must be a definition");
9587 AliaseeRef.first->setAliasee(VI,
Summary.get());
9589 ForwardRefAliasees.erase(FwdRefAliasees);
9594 Index->addGlobalValueSummary(VI, std::move(Summary));
9597 if (
ID == NumberedValueInfos.size())
9598 NumberedValueInfos.push_back(VI);
9601 if (
ID > NumberedValueInfos.size())
9602 NumberedValueInfos.resize(
ID + 1);
9603 NumberedValueInfos[
ID] =
VI;
9611bool LLParser::parseSummaryIndexFlags() {
9618 if (parseUInt64(Flags))
9621 Index->setFlags(Flags);
9627bool LLParser::parseBlockCount() {
9633 uint64_t BlockCount;
9634 if (parseUInt64(BlockCount))
9637 Index->setBlockCount(BlockCount);
9645bool LLParser::parseGVEntry(
unsigned ID) {
9653 LocTy Loc = Lex.getLoc();
9656 switch (Lex.getKind()) {
9660 parseStringConstant(Name))
9666 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9670 return error(Lex.getLoc(),
"expected name or guid tag");
9693 switch (Lex.getKind()) {
9695 if (parseFunctionSummary(Name, GUID,
ID))
9699 if (parseVariableSummary(Name, GUID,
ID))
9703 if (parseAliasSummary(Name, GUID,
ID))
9707 return error(Lex.getLoc(),
"expected summary type");
9725 LocTy Loc = Lex.getLoc();
9729 StringRef ModulePath;
9730 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9733 false,
false,
false,
9737 FunctionSummary::TypeIdInfo TypeIdInfo;
9738 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9740 std::vector<CallsiteInfo> Callsites;
9741 std::vector<AllocInfo> Allocs;
9743 FunctionSummary::FFlags FFlags = {};
9746 parseModuleReference(ModulePath) ||
9747 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9750 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9755 switch (Lex.getKind()) {
9757 if (parseOptionalFFlags(FFlags))
9761 if (parseOptionalCalls(Calls))
9765 if (parseOptionalTypeIdInfo(TypeIdInfo))
9769 if (parseOptionalRefs(Refs))
9773 if (parseOptionalParamAccesses(ParamAccesses))
9777 if (parseOptionalAllocs(Allocs))
9781 if (parseOptionalCallsites(Callsites))
9785 return error(Lex.getLoc(),
"expected optional function summary field");
9792 auto FS = std::make_unique<FunctionSummary>(
9793 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9799 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9801 FS->setModulePath(ModulePath);
9803 return addGlobalValueToIndex(Name, GUID,
9805 std::move(FS), Loc);
9813 LocTy Loc = Lex.getLoc();
9817 StringRef ModulePath;
9818 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9821 false,
false,
false,
9823 GlobalVarSummary::GVarFlags GVarFlags(
false,
9831 parseModuleReference(ModulePath) ||
9832 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9834 parseGVarFlags(GVarFlags))
9839 switch (Lex.getKind()) {
9841 if (parseOptionalVTableFuncs(VTableFuncs))
9845 if (parseOptionalRefs(Refs))
9849 return error(Lex.getLoc(),
"expected optional variable summary field");
9857 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9859 GS->setModulePath(ModulePath);
9860 GS->setVTableFuncs(std::move(VTableFuncs));
9862 return addGlobalValueToIndex(Name, GUID,
9864 std::move(GS), Loc);
9873 LocTy Loc = Lex.getLoc();
9876 StringRef ModulePath;
9877 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9880 false,
false,
false,
9884 parseModuleReference(ModulePath) ||
9885 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9891 ValueInfo AliaseeVI;
9893 if (parseGVReference(AliaseeVI, GVId))
9899 auto AS = std::make_unique<AliasSummary>(GVFlags);
9901 AS->setModulePath(ModulePath);
9905 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9907 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9908 assert(Summary &&
"Aliasee must be a definition");
9909 AS->setAliasee(AliaseeVI, Summary);
9912 return addGlobalValueToIndex(Name, GUID,
9914 std::move(AS), Loc);
9919bool LLParser::parseFlag(
unsigned &Val) {
9920 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
9921 return tokError(
"expected integer");
9922 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9938bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9942 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9948 switch (Lex.getKind()) {
9951 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9957 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9963 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9969 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9975 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9981 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9987 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9993 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9999 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10005 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10010 return error(Lex.getLoc(),
"expected function flag type");
10014 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10025bool LLParser::parseOptionalCalls(
10026 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10030 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10034 IdToIndexMapType IdToIndexMap;
10043 LocTy Loc = Lex.getLoc();
10045 if (parseGVReference(VI, GVId))
10049 unsigned RelBF = 0;
10050 unsigned HasTailCall =
false;
10054 switch (Lex.getKind()) {
10057 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10062 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10067 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10071 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10075 return tokError(
"Expected only one of hotness or relbf");
10080 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10090 for (
auto I : IdToIndexMap) {
10091 auto &Infos = ForwardRefValueInfos[
I.first];
10092 for (
auto P :
I.second) {
10094 "Forward referenced ValueInfo expected to be empty");
10095 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10108 switch (Lex.getKind()) {
10112 case lltok::kw_cold:
10118 case lltok::kw_hot:
10125 return error(Lex.getLoc(),
"invalid call edge hotness");
10134bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10138 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10142 IdToIndexMapType IdToIndexMap;
10146 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10151 LocTy Loc = Lex.getLoc();
10153 if (parseGVReference(VI, GVId))
10166 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10167 VTableFuncs.push_back({
VI,
Offset});
10169 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10175 for (
auto I : IdToIndexMap) {
10176 auto &Infos = ForwardRefValueInfos[
I.first];
10177 for (
auto P :
I.second) {
10179 "Forward referenced ValueInfo expected to be empty");
10180 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10184 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10191bool LLParser::parseParamNo(uint64_t &ParamNo) {
10193 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10199bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10202 auto ParseAPSInt = [&](
APSInt &Val) {
10204 return tokError(
"expected integer");
10205 Val = Lex.getAPSIntVal();
10207 Val.setIsSigned(
true);
10229bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10230 IdLocListType &IdLocList) {
10238 LocTy Loc = Lex.getLoc();
10239 if (parseGVReference(VI, GVId))
10243 IdLocList.emplace_back(GVId, Loc);
10246 parseParamNo(
Call.ParamNo) ||
10248 parseParamAccessOffset(
Call.Offsets))
10260bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10261 IdLocListType &IdLocList) {
10263 parseParamNo(
Param.ParamNo) ||
10265 parseParamAccessOffset(
Param.Use))
10274 FunctionSummary::ParamAccess::Call
Call;
10275 if (parseParamAccessCall(
Call, IdLocList))
10292bool LLParser::parseOptionalParamAccesses(
10293 std::vector<FunctionSummary::ParamAccess> &Params) {
10301 IdLocListType VContexts;
10302 size_t CallsNum = 0;
10304 FunctionSummary::ParamAccess ParamAccess;
10305 if (parseParamAccess(ParamAccess, VContexts))
10307 CallsNum += ParamAccess.
Calls.size();
10308 assert(VContexts.size() == CallsNum);
10310 Params.emplace_back(std::move(ParamAccess));
10318 IdLocListType::const_iterator ItContext = VContexts.begin();
10319 for (
auto &PA : Params) {
10320 for (
auto &
C : PA.Calls) {
10322 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10323 ItContext->second);
10327 assert(ItContext == VContexts.end());
10334bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10338 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10342 struct ValueContext {
10347 std::vector<ValueContext> VContexts;
10351 VC.Loc = Lex.getLoc();
10352 if (parseGVReference(
VC.VI,
VC.GVId))
10354 VContexts.push_back(VC);
10360 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10361 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10364 IdToIndexMapType IdToIndexMap;
10365 for (
auto &VC : VContexts) {
10370 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10376 for (
auto I : IdToIndexMap) {
10377 auto &Infos = ForwardRefValueInfos[
I.first];
10378 for (
auto P :
I.second) {
10380 "Forward referenced ValueInfo expected to be empty");
10381 Infos.emplace_back(&Refs[
P.first],
P.second);
10395bool LLParser::parseOptionalTypeIdInfo(
10396 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10405 switch (Lex.getKind()) {
10407 if (parseTypeTests(TypeIdInfo.
TypeTests))
10431 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
10435 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10444bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10452 IdToIndexMapType IdToIndexMap;
10456 unsigned ID = Lex.getUIntVal();
10457 LocTy Loc = Lex.getLoc();
10461 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10463 }
else if (parseUInt64(GUID))
10465 TypeTests.push_back(GUID);
10470 for (
auto I : IdToIndexMap) {
10471 auto &Ids = ForwardRefTypeIds[
I.first];
10472 for (
auto P :
I.second) {
10473 assert(TypeTests[
P.first] == 0 &&
10474 "Forward referenced type id GUID expected to be 0");
10475 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10479 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10487bool LLParser::parseVFuncIdList(
10488 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10489 assert(Lex.getKind() == Kind);
10496 IdToIndexMapType IdToIndexMap;
10498 FunctionSummary::VFuncId VFuncId;
10499 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10501 VFuncIdList.push_back(VFuncId);
10509 for (
auto I : IdToIndexMap) {
10510 auto &Ids = ForwardRefTypeIds[
I.first];
10511 for (
auto P :
I.second) {
10512 assert(VFuncIdList[
P.first].GUID == 0 &&
10513 "Forward referenced type id GUID expected to be 0");
10514 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10523bool LLParser::parseConstVCallList(
10525 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10526 assert(Lex.getKind() == Kind);
10533 IdToIndexMapType IdToIndexMap;
10535 FunctionSummary::ConstVCall ConstVCall;
10536 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10538 ConstVCallList.push_back(ConstVCall);
10546 for (
auto I : IdToIndexMap) {
10547 auto &Ids = ForwardRefTypeIds[
I.first];
10548 for (
auto P :
I.second) {
10549 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10550 "Forward referenced type id GUID expected to be 0");
10551 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10560bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10561 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10563 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10567 if (parseArgs(ConstVCall.
Args))
10579bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10580 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10590 unsigned ID = Lex.getUIntVal();
10591 LocTy Loc = Lex.getLoc();
10595 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
10597 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10599 parseUInt64(VFuncId.
GUID))
10605 parseUInt64(VFuncId.
Offset) ||
10617bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10627 switch (Lex.getKind()) {
10634 assert(HasLinkage &&
"Linkage not optional in summary entry");
10641 parseOptionalVisibility(Flag);
10646 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10652 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10658 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10664 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10673 if (parseOptionalImportType(Lex.getKind(), IK))
10675 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10679 return error(Lex.getLoc(),
"expected gv flag type");
10693bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10701 auto ParseRest = [
this](
unsigned int &Val) {
10705 return parseFlag(Val);
10710 switch (Lex.getKind()) {
10711 case lltok::kw_readonly:
10712 if (ParseRest(Flag))
10716 case lltok::kw_writeonly:
10717 if (ParseRest(Flag))
10722 if (ParseRest(Flag))
10727 if (ParseRest(Flag))
10732 return error(Lex.getLoc(),
"expected gvar flag type");
10740bool LLParser::parseModuleReference(StringRef &ModulePath) {
10747 unsigned ModuleID = Lex.getUIntVal();
10748 auto I = ModuleIdMap.find(ModuleID);
10750 assert(
I != ModuleIdMap.end());
10751 ModulePath =
I->second;
10757bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
10760 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10764 GVId = Lex.getUIntVal();
10766 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10768 VI = NumberedValueInfos[GVId];
10785bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10789 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10801 SmallVector<uint8_t> Versions;
10804 if (parseAllocType(V))
10809 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10813 std::vector<MIBInfo> MIBs;
10814 if (parseMemProfs(MIBs))
10817 Allocs.push_back({Versions, MIBs});
10834bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10838 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10844 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10853 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10859 SmallVector<unsigned> StackIdIndices;
10863 uint64_t StackId = 0;
10864 if (parseUInt64(StackId))
10866 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
10887bool LLParser::parseAllocType(uint8_t &
AllocType) {
10888 switch (Lex.getKind()) {
10895 case lltok::kw_cold:
10898 case lltok::kw_hot:
10902 return error(Lex.getLoc(),
"invalid alloc type");
10915bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10919 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10923 IdToIndexMapType IdToIndexMap;
10926 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10933 LocTy Loc = Lex.getLoc();
10935 if (parseGVReference(VI, GVId))
10939 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10945 SmallVector<unsigned> Clones;
10948 if (parseUInt32(V))
10954 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10960 SmallVector<unsigned> StackIdIndices;
10964 uint64_t StackId = 0;
10965 if (parseUInt64(StackId))
10967 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
10978 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
10979 Callsites.push_back({
VI, Clones, StackIdIndices});
10987 for (
auto I : IdToIndexMap) {
10988 auto &Infos = ForwardRefValueInfos[
I.first];
10989 for (
auto P :
I.second) {
10991 "Forward referenced ValueInfo expected to be empty");
10992 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10996 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
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)"
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
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.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
static SymbolRef::Type getType(const Symbol *Sym)
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
APSInt extOrTrunc(uint32_t width) const
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 LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ 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 LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static LLVM_ABI 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 LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
LLVM_ABI 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 LLVM_ABI 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 LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI 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 LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI 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 LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI 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)
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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 LLVM_ABI 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 LLVM_ABI 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...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
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
void setDSOLocal(bool Local)
LLVM_ABI 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)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
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
LLVM_ABI void setPartition(StringRef Part)
LLVM_ABI 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)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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 LLVM_ABI 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 LLVM_ABI 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)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI 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)
lltok::Kind getKind() 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*.
static LLVM_ABI 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...
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI 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()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
A Module instance is used to store all the information related to an LLVM module.
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI 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 LLVM_ABI 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 LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
constexpr const char * getPointer() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
static LLVM_ABI 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.
ArrayRef< int > getShuffleMask() const
static LLVM_ABI 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.
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.
iterator find(StringRef Key)
StringMapIterBase< Comdat, false > iterator
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
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.
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.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
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 LLVM_ABI IntegerType * getInt1Ty(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 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.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
LLVM_ABI unsigned getTag(StringRef TagString)
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
LLVM_ABI 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 Align[]
Key for Kernel::Arg::Metadata::mAlign.
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.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
initializer< Ty > init(const Ty &Val)
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_amdgpu_gfx_whole_wave
@ 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
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
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)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
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...
auto cast_or_null(const Y &Val)
LLVM_ABI 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.)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
auto dyn_cast_or_null(const Y &Val)
@ 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.
bool isPointerTy(const Type *T)
FunctionAddr VTableAddr Count
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
CaptureComponents
Components of the pointer that may be captured.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
static LLVM_ABI const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static LLVM_ABI const fltSemantics & IEEEdouble() LLVM_READNONE
static LLVM_ABI const fltSemantics & IEEEhalf() LLVM_READNONE
static LLVM_ABI const fltSemantics & BFloat() LLVM_READNONE
std::vector< uint64_t > Args
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
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
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....
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.
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::@273232264270353276247031231016211363171152164072 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.