65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
81 const char *Boundary = BoundaryLoc.
getPointer();
82 const char *BlockCommentStart =
nullptr;
83 bool InLineComment =
false;
85 for (
const char *Ptr = Begin; Ptr <
End;) {
86 if (BlockCommentStart) {
87 if (Ptr + 1 <
End && Ptr[0] ==
'*' && Ptr[1] ==
'/') {
89 if (BlockCommentStart < Boundary && Ptr > Boundary)
91 BlockCommentStart =
nullptr;
99 if (*Ptr ==
'\n' || *Ptr ==
'\r')
100 InLineComment =
false;
106 InLineComment =
true;
110 if (Ptr + 1 <
End && Ptr[0] ==
'/' && Ptr[1] ==
'*') {
111 BlockCommentStart = Ptr;
118 return BlockCommentStart && BlockCommentStart < Boundary && End > Boundary;
127 if (Context.shouldDiscardValueNames())
130 "Can't read textual IR with a Context that discards named Values");
133 if (parseTargetDefinitions(DataLayoutCallback))
138 validateEndOfIndex();
143 restoreParsingState(Slots);
147 if (parseType(Ty) || parseConstantValue(Ty,
C))
150 return error(Lex.getLoc(),
"expected end of string");
156 restoreParsingState(Slots);
160 SMLoc Start = Lex.getLoc();
165 Read =
End.getPointer() - Start.getPointer();
172 restoreParsingState(Slots);
176 SMLoc Start = Lex.getLoc();
178 bool Status = parseDIExpressionBody(Result,
false);
180 Read =
End.getPointer() - Start.getPointer();
187 restoreParsingState(&Slots);
191 if (Lex.getLoc().getPointer() >=
End.getPointer())
192 return error(
End,
"expected end of metadata definition");
194 return tokError(
"expected a metadata definition");
195 if (parseStandaloneMetadata())
197 if (Lex.getPrevTokEndLoc().getPointer() >
End.getPointer() ||
199 Lex.getLoc().getPointer() <
End.getPointer()) ||
201 return error(
End,
"expected end of metadata definition");
205 return tokError(
"expected end of metadata definitions");
207 if (!ForwardRefMDNodes.empty())
208 return error(ForwardRefMDNodes.begin()->second.second,
209 "use of undefined metadata '!" +
210 Twine(ForwardRefMDNodes.begin()->first) +
"'");
212 for (
auto &[
_, MD] : NumberedMetadata)
213 if (MD && !MD->isResolved())
216 NewDistinctSPs.clear();
218 Slots.MetadataNodes = std::move(NumberedMetadata);
222void LLParser::restoreParsingState(
const SlotMapping *Slots) {
229 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
230 for (
const auto &
I : Slots->
Types)
231 NumberedTypes.insert(
232 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
238 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
245 if (MD->isTemporary())
249 assert(
II->use_empty() &&
"Cannot have uses");
250 II->eraseFromParent();
259void LLParser::dropUnknownMetadataReferences() {
260 auto Pred = [](
unsigned MDKind, MDNode *
Node) {
return Node->isTemporary(); };
262 F.eraseMetadataIf(
Pred);
264 I.eraseMetadataIf(
Pred);
271 for (GlobalVariable &GV : M->globals())
272 GV.eraseMetadataIf(
Pred);
275 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
277 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
282 if (
Info.first->getNumTemporaryUses() == 1) {
283 NumberedMetadata.erase(ID);
284 ForwardRefMDNodes.erase(ID);
297 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
298 "Mixed debug intrinsics/records seen without a parsing error?");
301 for (
const auto &RAG : ForwardRefAttrGroups) {
303 const std::vector<unsigned> &
Attrs = RAG.second;
304 AttrBuilder
B(Context);
306 for (
const auto &Attr : Attrs) {
307 auto R = NumberedAttrBuilders.find(Attr);
308 if (R != NumberedAttrBuilders.end())
313 AttributeList AS = Fn->getAttributes();
314 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
315 AS = AS.removeFnAttributes(Context);
321 if (MaybeAlign
A = FnAttrs.getAlignment()) {
322 Fn->setAlignment(*
A);
323 FnAttrs.removeAttribute(Attribute::Alignment);
326 AS = AS.addFnAttributes(Context, FnAttrs);
327 Fn->setAttributes(AS);
329 AttributeList AS = CI->getAttributes();
330 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
331 AS = AS.removeFnAttributes(Context);
333 AS = AS.addFnAttributes(Context, FnAttrs);
334 CI->setAttributes(AS);
336 AttributeList AS =
II->getAttributes();
337 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
338 AS = AS.removeFnAttributes(Context);
340 AS = AS.addFnAttributes(Context, FnAttrs);
341 II->setAttributes(AS);
343 AttributeList AS = CBI->getAttributes();
344 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
345 AS = AS.removeFnAttributes(Context);
347 AS = AS.addFnAttributes(Context, FnAttrs);
348 CBI->setAttributes(AS);
350 AttrBuilder
Attrs(M->getContext(), GV->getAttributes());
360 if (!ForwardRefBlockAddresses.empty())
361 return error(ForwardRefBlockAddresses.begin()->first.Loc,
362 "expected function name in blockaddress");
364 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
365 GlobalValue *FwdRef) {
366 GlobalValue *GV =
nullptr;
368 GV = M->getNamedValue(GVRef.
StrVal);
370 GV = NumberedVals.get(GVRef.
UIntVal);
375 "' referenced by dso_local_equivalent");
379 "expected a function, alias to function, or ifunc "
380 "in dso_local_equivalent");
383 FwdRef->replaceAllUsesWith(Equiv);
384 FwdRef->eraseFromParent();
391 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
392 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
395 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
396 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
399 ForwardRefDSOLocalEquivalentIDs.clear();
400 ForwardRefDSOLocalEquivalentNames.clear();
402 for (
const auto &NT : NumberedTypes)
403 if (
NT.second.second.isValid())
405 "use of undefined type '%" + Twine(
NT.first) +
"'");
407 for (
const auto &[Name, TypeInfo] : NamedTypes)
408 if (TypeInfo.second.isValid())
409 return error(TypeInfo.second,
410 "use of undefined type named '" + Name +
"'");
412 if (!ForwardRefComdats.empty())
413 return error(ForwardRefComdats.begin()->second,
414 "use of undefined comdat '$" +
415 ForwardRefComdats.begin()->first +
"'");
418 dropUnknownMetadataReferences();
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) +
"'");
426 for (
auto [Loc, DR, MD] : PendingDbgRecords) {
430 return error(Loc,
"invalid debug location");
432 PendingDbgRecords.clear();
433 for (
auto [Loc,
I, MD] : PendingDbgInsts) {
437 return error(Loc,
"invalid !dbg metadata");
439 PendingDbgInsts.clear();
453 if (!CB || !CB->isCallee(&U))
454 return error(
Info.second,
"intrinsic can only be used as callee");
456 std::string ErrorMsg;
457 raw_string_ostream ErrorOS(ErrorMsg);
471 return error(
Info.second,
"unknown intrinsic '" + Name +
"'");
482 Info.first->eraseFromParent();
483 ForwardRefVals.erase(Name);
492 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
493 FunctionType *FTy =
nullptr;
494 for (Use &U :
V->uses()) {
496 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
498 FTy = CB->getFunctionType();
506 Type *Ty = GetCommonFunctionType(
Info.first);
514 GV =
new GlobalVariable(*M, Ty,
false,
517 Info.first->replaceAllUsesWith(GV);
518 Info.first->eraseFromParent();
519 ForwardRefVals.erase(Name);
522 if (!ForwardRefVals.empty())
523 return error(ForwardRefVals.begin()->second.second,
524 "use of undefined value '@" + ForwardRefVals.begin()->first +
527 if (!ForwardRefValIDs.empty())
528 return error(ForwardRefValIDs.begin()->second.second,
529 "use of undefined value '@" +
530 Twine(ForwardRefValIDs.begin()->first) +
"'");
533 for (
auto &
N : NumberedMetadata) {
534 if (
N.second && !
N.second->isResolved())
535 N.second->resolveCycles();
539 NewDistinctSPs.clear();
561 Slots->GlobalValues = std::move(NumberedVals);
562 Slots->MetadataNodes = std::move(NumberedMetadata);
563 for (
const auto &
I : NamedTypes)
564 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
565 for (
const auto &
I : NumberedTypes)
566 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
572bool LLParser::validateEndOfIndex() {
576 if (!ForwardRefValueInfos.empty())
577 return error(ForwardRefValueInfos.begin()->second.front().second,
578 "use of undefined summary '^" +
579 Twine(ForwardRefValueInfos.begin()->first) +
"'");
581 if (!ForwardRefAliasees.empty())
582 return error(ForwardRefAliasees.begin()->second.front().second,
583 "use of undefined summary '^" +
584 Twine(ForwardRefAliasees.begin()->first) +
"'");
586 if (!ForwardRefTypeIds.empty())
587 return error(ForwardRefTypeIds.begin()->second.front().second,
588 "use of undefined type id summary '^" +
589 Twine(ForwardRefTypeIds.begin()->first) +
"'");
603 std::string TentativeDLStr = M->getDataLayoutStr();
608 switch (Lex.getKind()) {
610 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
614 if (parseSourceFileName())
623 if (
auto LayoutOverride =
624 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
625 TentativeDLStr = *LayoutOverride;
631 M->setDataLayout(MaybeDL.
get());
635bool LLParser::parseTopLevelEntities() {
639 switch (Lex.getKind()) {
643 if (parseSummaryEntry())
647 if (parseSourceFileName())
657 switch (Lex.getKind()) {
659 return tokError(
"expected top-level entity");
670 if (parseModuleAsm())
674 if (parseUnnamedType())
678 if (parseNamedType())
682 if (parseUnnamedGlobal())
686 if (parseNamedGlobal())
691 if (parseStandaloneMetadata())
695 if (parseSummaryEntry())
699 if (parseNamedMetadata())
703 if (parseUnnamedAttrGrp())
707 if (parseUseListOrder())
719bool LLParser::parseModuleAsm() {
727 Module::GlobalAsmProperties Props;
731 SMLoc Loc = Lex.getLoc();
733 return error(Loc,
"expected property name followed by ':'");
735 Key = Lex.getStrVal();
738 if (parseStringConstant(
Value))
742 return error(Loc,
"unknown property name");
752 std::string AsmStrPart;
753 if (parseStringConstant(AsmStrPart))
755 AsmStr += AsmStrPart +
"\n";
758 M->appendModuleInlineAsm({AsmStr, Props});
765bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
771 return tokError(
"unknown target property");
774 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
775 parseStringConstant(Str))
777 M->setTargetTriple(Triple(std::move(Str)));
781 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
783 DLStrLoc = Lex.getLoc();
784 if (parseStringConstant(TentativeDLStr))
792bool LLParser::parseSourceFileName() {
795 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
796 parseStringConstant(SourceFileName))
799 M->setSourceFileName(SourceFileName);
805bool LLParser::parseUnnamedType() {
806 LocTy TypeLoc = Lex.getLoc();
807 unsigned TypeID = Lex.getUIntVal();
810 if (parseToken(
lltok::equal,
"expected '=' after name") ||
815 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
819 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
821 return error(TypeLoc,
"non-struct types may not be recursive");
823 Entry.second = SMLoc();
831bool LLParser::parseNamedType() {
832 std::string
Name = Lex.getStrVal();
833 LocTy NameLoc = Lex.getLoc();
836 if (parseToken(
lltok::equal,
"expected '=' after name") ||
841 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
845 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
847 return error(NameLoc,
"non-struct types may not be recursive");
849 Entry.second = SMLoc();
857bool LLParser::parseDeclare() {
861 std::vector<std::pair<unsigned, MDNode *>> MDs;
865 if (parseMetadataAttachment(MDK,
N))
867 MDs.push_back({MDK,
N});
871 unsigned FunctionNumber = -1;
872 SmallVector<unsigned> UnnamedArgNums;
873 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
876 F->addMetadata(MD.first, *MD.second);
882bool LLParser::parseDefine() {
885 FileLoc FunctionStart = getTokLineColumnPos();
889 unsigned FunctionNumber = -1;
890 SmallVector<unsigned> UnnamedArgNums;
892 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
893 parseOptionalFunctionMetadata(*
F) ||
894 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
896 ParserContext->addFunctionLocation(
897 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
905bool LLParser::parseGlobalType(
bool &IsConstant) {
912 return tokError(
"expected 'global' or 'constant'");
918bool LLParser::parseOptionalUnnamedAddr(
939bool LLParser::parseUnnamedGlobal() {
942 LocTy NameLoc = Lex.getLoc();
946 VarID = Lex.getUIntVal();
947 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
951 if (parseToken(
lltok::equal,
"expected '=' after name"))
954 VarID = NumberedVals.getNext();
958 unsigned Linkage, Visibility, DLLStorageClass;
962 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
964 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
967 switch (Lex.getKind()) {
969 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
970 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
973 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
974 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
983bool LLParser::parseNamedGlobal() {
985 LocTy NameLoc = Lex.getLoc();
986 std::string
Name = Lex.getStrVal();
990 unsigned Linkage, Visibility, DLLStorageClass;
994 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
995 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
997 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
1000 switch (Lex.getKind()) {
1002 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
1003 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1006 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
1007 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1011bool LLParser::parseComdat() {
1013 std::string
Name = Lex.getStrVal();
1014 LocTy NameLoc = Lex.getLoc();
1021 return tokError(
"expected comdat type");
1024 switch (Lex.getKind()) {
1026 return tokError(
"unknown selection kind");
1048 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
1049 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
1052 if (
I != ComdatSymTab.
end())
1055 C = M->getOrInsertComdat(Name);
1056 C->setSelectionKind(SK);
1063bool LLParser::parseMDString(
MDString *&Result) {
1065 if (parseStringConstant(Str))
1073bool LLParser::parseMDNodeID(
MDNode *&Result) {
1075 LocTy IDLoc = Lex.getLoc();
1077 if (parseUInt32(MID))
1081 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
1088 auto &FwdRef = ForwardRefMDNodes[MID];
1091 Result = FwdRef.first.get();
1092 It->second.reset(Result);
1098bool LLParser::parseNamedMetadata() {
1100 std::string
Name = Lex.getStrVal();
1108 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1111 MDNode *
N =
nullptr;
1116 Lex.getStrVal() ==
"DIExpression") {
1117 if (parseDIExpression(
N,
false))
1122 Lex.getStrVal() ==
"DIArgList") {
1123 return tokError(
"found DIArgList outside of function");
1131 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1136bool LLParser::parseStandaloneMetadata() {
1139 unsigned MetadataID = 0;
1142 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1147 return tokError(
"unexpected type in metadata definition");
1151 if (parseSpecializedMDNode(Init, IsDistinct))
1154 parseMDTuple(Init, IsDistinct))
1158 auto FI = ForwardRefMDNodes.find(MetadataID);
1159 if (FI != ForwardRefMDNodes.end()) {
1160 auto *ToReplace = FI->second.first.get();
1164 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1165 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1166 "Inst unexpectedly already has DIAssignID attachment");
1167 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1171 ToReplace->replaceAllUsesWith(Init);
1172 ForwardRefMDNodes.erase(FI);
1174 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1176 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1178 return tokError(
"Metadata id is already used");
1179 It->second.reset(Init);
1186bool LLParser::skipModuleSummaryEntry() {
1199 return tokError(
"Expected 'gv', 'module', 'typeid', "
1200 "'typeidCompatibleVTable', 'flags', 'blockcount', "
1201 "'cfiFunctionDefs' or 'cfiFunctionDecls' at the start of "
1204 return parseSummaryIndexFlags();
1206 return parseBlockCount();
1208 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1209 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1213 unsigned NumOpenParen = 1;
1215 switch (Lex.getKind()) {
1223 return tokError(
"found end of file while parsing summary entry");
1229 }
while (NumOpenParen > 0);
1235bool LLParser::parseSummaryEntry() {
1241 Lex.setIgnoreColonInIdentifiers(
true);
1249 return skipModuleSummaryEntry();
1251 bool result =
false;
1252 switch (Lex.getKind()) {
1254 result = parseGVEntry(SummaryID);
1257 result = parseModuleEntry(SummaryID);
1260 result = parseTypeIdEntry(SummaryID);
1263 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1266 result = parseSummaryIndexFlags();
1269 result = parseBlockCount();
1273 result = parseCfiFunctions();
1276 result =
error(Lex.getLoc(),
"unexpected summary kind");
1279 Lex.setIgnoreColonInIdentifiers(
false);
1313bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1314 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1315 unsigned DLLStorageClass,
bool DSOLocal,
1330 return error(NameLoc,
"invalid linkage type for alias");
1333 return error(NameLoc,
1334 "symbol with local linkage must have default visibility");
1337 return error(NameLoc,
1338 "symbol with local linkage cannot have a DLL storage class");
1341 LocTy ExplicitTypeLoc = Lex.getLoc();
1342 if (parseType(Ty) ||
1343 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1347 LocTy AliaseeLoc = Lex.getLoc();
1352 if (parseGlobalTypeAndValue(Aliasee))
1357 if (parseValID(ID,
nullptr))
1360 return error(AliaseeLoc,
"invalid aliasee");
1361 Aliasee =
ID.ConstantVal;
1367 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1368 unsigned AddrSpace = PTy->getAddressSpace();
1370 GlobalValue *GVal =
nullptr;
1374 if (!
Name.empty()) {
1375 auto I = ForwardRefVals.find(Name);
1376 if (
I != ForwardRefVals.end()) {
1377 GVal =
I->second.first;
1378 ForwardRefVals.erase(Name);
1379 }
else if (M->getNamedValue(Name)) {
1380 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1383 auto I = ForwardRefValIDs.find(NameID);
1384 if (
I != ForwardRefValIDs.end()) {
1385 GVal =
I->second.first;
1386 ForwardRefValIDs.erase(
I);
1391 std::unique_ptr<GlobalAlias> GA;
1392 std::unique_ptr<GlobalIFunc> GI;
1420 if (parseGlobalObjectMetadataAttachment(*GI))
1423 return tokError(
"unknown alias or ifunc property!");
1428 NumberedVals.add(NameID, GV);
1435 "forward reference and definition of alias have different types");
1445 M->insertAlias(GA.release());
1447 M->insertIFunc(GI.release());
1448 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1457 case lltok::kw_sanitize_memtag:
1471 switch (Lex.getKind()) {
1473 Meta.NoAddress =
true;
1476 Meta.NoHWAddress =
true;
1478 case lltok::kw_sanitize_memtag:
1482 Meta.IsDynInit =
true;
1485 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1505bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1506 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1507 unsigned Visibility,
unsigned DLLStorageClass,
1511 return error(NameLoc,
1512 "symbol with local linkage must have default visibility");
1515 return error(NameLoc,
1516 "symbol with local linkage cannot have a DLL storage class");
1520 LocTy IsExternallyInitializedLoc;
1524 if (parseOptionalAddrSpace(AddrSpace) ||
1526 IsExternallyInitialized,
1527 &IsExternallyInitializedLoc) ||
1528 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1537 if (parseGlobalValue(Ty, Init))
1542 return error(TyLoc,
"invalid type for global variable");
1544 GlobalValue *GVal =
nullptr;
1547 if (!
Name.empty()) {
1548 auto I = ForwardRefVals.find(Name);
1549 if (
I != ForwardRefVals.end()) {
1550 GVal =
I->second.first;
1551 ForwardRefVals.erase(
I);
1552 }
else if (M->getNamedValue(Name)) {
1553 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1558 if (NameID == (
unsigned)-1)
1559 NameID = NumberedVals.getNext();
1561 auto I = ForwardRefValIDs.find(NameID);
1562 if (
I != ForwardRefValIDs.end()) {
1563 GVal =
I->second.first;
1564 ForwardRefValIDs.erase(
I);
1568 GlobalVariable *GV =
new GlobalVariable(
1573 NumberedVals.add(NameID, GV);
1591 "forward reference and definition of global have different types");
1611 }
else if (Lex.getKind() == lltok::kw_align) {
1613 if (parseOptionalAlignment(Alignment))
1619 if (parseOptionalCodeModel(CodeModel))
1623 if (parseGlobalObjectMetadataAttachment(*GV))
1626 if (parseSanitizer(GV))
1630 if (parseOptionalComdat(Name,
C))
1635 return tokError(
"unknown global variable property!");
1639 AttrBuilder
Attrs(M->getContext());
1641 std::vector<unsigned> FwdRefAttrGrps;
1642 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1644 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1646 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1654bool LLParser::parseUnnamedAttrGrp() {
1656 LocTy AttrGrpLoc = Lex.getLoc();
1660 return tokError(
"expected attribute group id");
1662 unsigned VarID = Lex.getUIntVal();
1663 std::vector<unsigned> unused;
1671 auto R = NumberedAttrBuilders.find(
VarID);
1672 if (R == NumberedAttrBuilders.end())
1673 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1675 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1676 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1679 if (!
R->second.hasAttributes())
1680 return error(AttrGrpLoc,
"attribute group has no attributes");
1687#define GET_ATTR_NAMES
1688#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1689 case lltok::kw_##DISPLAY_NAME: \
1690 return Attribute::ENUM_NAME;
1691#include "llvm/IR/Attributes.inc"
1700 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1703 case Attribute::Alignment: {
1712 if (parseOptionalAlignment(Alignment,
true))
1715 B.addAlignmentAttr(Alignment);
1718 case Attribute::StackAlignment: {
1723 parseUInt32(Alignment))
1726 if (parseOptionalStackAlignment(Alignment))
1729 B.addStackAlignmentAttr(Alignment);
1732 case Attribute::AllocSize: {
1733 unsigned ElemSizeArg;
1734 std::optional<unsigned> NumElemsArg;
1735 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1737 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1740 case Attribute::VScaleRange: {
1741 unsigned MinValue, MaxValue;
1742 if (parseVScaleRangeArguments(MinValue, MaxValue))
1744 B.addVScaleRangeAttr(MinValue,
1745 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1748 case Attribute::Dereferenceable: {
1749 std::optional<uint64_t> Bytes;
1750 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1752 assert(Bytes.has_value());
1753 B.addDereferenceableAttr(Bytes.value());
1756 case Attribute::DeadOnReturn: {
1757 std::optional<uint64_t> Bytes;
1758 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1761 if (Bytes.has_value()) {
1762 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1764 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1768 case Attribute::DereferenceableOrNull: {
1769 std::optional<uint64_t> Bytes;
1770 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1772 assert(Bytes.has_value());
1773 B.addDereferenceableOrNullAttr(Bytes.value());
1776 case Attribute::UWTable: {
1778 if (parseOptionalUWTableKind(Kind))
1780 B.addUWTableAttr(Kind);
1783 case Attribute::AllocKind: {
1785 if (parseAllocKind(Kind))
1787 B.addAllocKindAttr(Kind);
1790 case Attribute::Memory: {
1791 std::optional<MemoryEffects> ME = parseMemoryAttr();
1794 B.addMemoryAttr(*ME);
1797 case Attribute::DenormalFPEnv: {
1798 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1802 B.addDenormalFPEnvAttr(*
Mode);
1805 case Attribute::NoFPClass: {
1808 B.addNoFPClassAttr(NoFPClass);
1814 case Attribute::Range:
1815 return parseRangeAttr(
B);
1816 case Attribute::Initializes:
1817 return parseInitializesAttr(
B);
1818 case Attribute::Captures:
1819 return parseCapturesAttr(
B);
1821 B.addAttribute(Attr);
1829 case lltok::kw_readnone:
1832 case lltok::kw_readonly:
1835 case lltok::kw_writeonly:
1854bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1855 std::vector<unsigned> &FwdRefAttrGrps,
1856 bool InAttrGrp, LocTy &BuiltinLoc) {
1857 bool HaveError =
false;
1868 if (parseStringAttribute(
B))
1880 "cannot have an attribute group reference in an attribute group");
1883 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1889 SMLoc Loc = Lex.getLoc();
1890 if (Token == lltok::kw_builtin)
1902 return error(Lex.getLoc(),
"unterminated attribute group");
1905 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1912 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1916 B.addMemoryAttr(ME);
1930 PTy->getAddressSpace());
1939 error(Loc,
"'" + Name +
"' is not a basic block");
1941 error(Loc,
"'" + Name +
"' defined with type '" +
1954 error(Loc,
"global variable reference must have pointer type");
1965 auto I = ForwardRefVals.find(Name);
1966 if (
I != ForwardRefVals.end())
1967 Val =
I->second.first;
1973 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1977 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1984 error(Loc,
"global variable reference must have pointer type");
1988 GlobalValue *Val = NumberedVals.get(ID);
1993 auto I = ForwardRefValIDs.find(ID);
1994 if (
I != ForwardRefValIDs.end())
1995 Val =
I->second.first;
2001 checkValidVariableType(Loc,
"@" + Twine(ID), Ty, Val));
2005 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
2013Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
2017 if (
I != ComdatSymTab.
end())
2021 Comdat *
C = M->getOrInsertComdat(Name);
2022 ForwardRefComdats[
Name] = Loc;
2032bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
2033 if (Lex.getKind() !=
T)
2034 return tokError(ErrMsg);
2041bool LLParser::parseStringConstant(std::string &Result) {
2043 return tokError(
"expected string constant");
2044 Result = Lex.getStrVal();
2051bool LLParser::parseUInt32(uint32_t &Val) {
2052 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2053 return tokError(
"expected integer");
2054 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2055 if (Val64 !=
unsigned(Val64))
2056 return tokError(
"expected 32-bit integer (too large)");
2064bool LLParser::parseUInt64(
uint64_t &Val) {
2065 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2066 return tokError(
"expected integer");
2067 Val = Lex.getAPSIntVal().getLimitedValue();
2077 switch (Lex.getKind()) {
2079 return tokError(
"expected localdynamic, initialexec or localexec");
2107 return parseTLSModel(TLM) ||
2108 parseToken(
lltok::rparen,
"expected ')' after thread local model");
2116bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
2117 AddrSpace = DefaultAS;
2121 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
2123 const std::string &AddrSpaceStr = Lex.getStrVal();
2124 if (AddrSpaceStr ==
"A") {
2125 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2126 }
else if (AddrSpaceStr ==
"G") {
2127 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2128 }
else if (AddrSpaceStr ==
"P") {
2129 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2130 }
else if (std::optional<unsigned> AS =
2131 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2134 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2140 return tokError(
"expected integer or string constant");
2141 SMLoc Loc = Lex.getLoc();
2142 if (parseUInt32(AddrSpace))
2145 return error(Loc,
"invalid address space, must be a 24-bit integer");
2149 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2150 ParseAddrspaceValue(AddrSpace) ||
2157bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2158 std::string Attr = Lex.getStrVal();
2161 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2163 B.addAttribute(Attr, Val);
2168bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2169 bool HaveError =
false;
2176 if (parseStringAttribute(
B))
2187 SMLoc Loc = Lex.getLoc();
2192 if (parseEnumAttribute(Attr,
B,
false))
2196 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2198 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2246bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2247 unsigned &Visibility,
2248 unsigned &DLLStorageClass,
bool &DSOLocal) {
2252 parseOptionalDSOLocal(DSOLocal);
2253 parseOptionalVisibility(Visibility);
2254 parseOptionalDLLStorageClass(DLLStorageClass);
2257 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2263void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2264 switch (Lex.getKind()) {
2285void LLParser::parseOptionalVisibility(
unsigned &Res) {
2286 switch (Lex.getKind()) {
2303bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2307 return tokError(
"unknown import kind. Expect definition or declaration.");
2322void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2323 switch (Lex.getKind()) {
2394bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2395 switch (Lex.getKind()) {
2485 return tokError(
"unknown RISC-V ABI VLEN");
2486#define CC_VLS_CASE(ABIVlen) \
2488 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2516 return parseUInt32(
CC);
2526bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2529 std::string
Name = Lex.getStrVal();
2530 Kind = M->getMDKindID(Name);
2533 return parseMDNode(MD);
2538bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2541 return tokError(
"expected metadata after comma");
2545 auto Loc = Lex.getLoc();
2546 if (parseMetadataAttachment(MDK,
N))
2549 if (MDK == LLVMContext::MD_DIAssignID)
2550 TempDIAssignIDAttachments[
N].push_back(&Inst);
2551 else if (MDK == LLVMContext::MD_dbg)
2552 PendingDbgInsts.emplace_back(Loc, &Inst,
N);
2563bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2566 if (parseMetadataAttachment(MDK,
N))
2575bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2577 if (parseGlobalObjectMetadataAttachment(
F))
2585bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2587 if (!EatIfPresent(lltok::kw_align))
2589 LocTy AlignLoc = Lex.getLoc();
2592 LocTy ParenLoc = Lex.getLoc();
2593 bool HaveParens =
false;
2599 if (parseUInt64(
Value))
2603 return error(ParenLoc,
"expected ')'");
2606 return error(AlignLoc,
"alignment is not a power of two");
2608 return error(AlignLoc,
"huge alignments are not supported yet");
2616bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2620 LocTy AlignLoc = Lex.getLoc();
2623 LocTy ParenLoc = Lex.getLoc();
2625 return error(ParenLoc,
"expected '('");
2627 if (parseUInt64(
Value))
2630 ParenLoc = Lex.getLoc();
2632 return error(ParenLoc,
"expected ')'");
2635 return error(AlignLoc,
"alignment is not a power of two");
2637 return error(AlignLoc,
"huge alignments are not supported yet");
2647 auto StrVal = Lex.getStrVal();
2648 auto ErrMsg =
"expected global code model string";
2649 if (StrVal ==
"tiny")
2651 else if (StrVal ==
"small")
2653 else if (StrVal ==
"kernel")
2655 else if (StrVal ==
"medium")
2657 else if (StrVal ==
"large")
2660 return tokError(ErrMsg);
2672bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2673 std::optional<uint64_t> &Bytes,
2674 bool ErrorNoBytes) {
2675 assert((AttrKind == lltok::kw_dereferenceable ||
2676 AttrKind == lltok::kw_dereferenceable_or_null ||
2677 AttrKind == lltok::kw_dead_on_return) &&
2681 if (!EatIfPresent(AttrKind))
2683 LocTy ParenLoc = Lex.getLoc();
2686 return error(ParenLoc,
"expected '('");
2687 Bytes = std::nullopt;
2690 LocTy DerefLoc = Lex.getLoc();
2691 if (parseUInt64(Bytes.value()))
2693 ParenLoc = Lex.getLoc();
2695 return error(ParenLoc,
"expected ')'");
2697 return error(DerefLoc,
"byte count specified must be non-zero");
2701bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2706 LocTy KindLoc = Lex.getLoc();
2712 return error(KindLoc,
"expected unwind table kind");
2719 LocTy ParenLoc = Lex.getLoc();
2721 return error(ParenLoc,
"expected '('");
2722 LocTy KindLoc = Lex.getLoc();
2724 if (parseStringConstant(Arg))
2725 return error(KindLoc,
"expected allockind value");
2729 }
else if (
A ==
"realloc") {
2731 }
else if (
A ==
"free") {
2733 }
else if (
A ==
"uninitialized") {
2735 }
else if (
A ==
"zeroed") {
2737 }
else if (
A ==
"aligned") {
2740 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2743 ParenLoc = Lex.getLoc();
2745 return error(ParenLoc,
"expected ')'");
2747 return error(KindLoc,
"expected allockind value");
2756 return {Loc::ArgMem};
2758 return {Loc::InaccessibleMem};
2760 return {Loc::ErrnoMem};
2762 return {Loc::TargetMem0};
2764 return {Loc::TargetMem1};
2787 return std::nullopt;
2791static std::optional<DenormalMode::DenormalModeKind>
2803 return std::nullopt;
2807std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2812 Lex.setIgnoreColonInIdentifiers(
true);
2817 tokError(
"expected '('");
2818 return std::nullopt;
2821 bool SeenLoc =
false;
2822 bool SeenTargetLoc =
false;
2825 if (!Locs.
empty()) {
2828 tokError(
"expected ':' after location");
2829 return std::nullopt;
2836 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2837 "or access kind (none, read, write, readwrite)");
2839 tokError(
"expected access kind (none, read, write, readwrite)");
2840 return std::nullopt;
2844 if (!Locs.
empty()) {
2849 SeenTargetLoc =
true;
2851 if (Locs.size() > 1 && SeenTargetLoc) {
2852 tokError(
"target memory default access kind must be specified first");
2853 return std::nullopt;
2858 tokError(
"default access kind must be specified first");
2859 return std::nullopt;
2868 tokError(
"unterminated memory attribute");
2869 return std::nullopt;
2872std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2873 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2876 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2877 "positivezero, dynamic)");
2883 std::optional<DenormalMode::DenormalModeKind> InputMode;
2887 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2888 "positivezero, dynamic)");
2895 InputMode = OutputMode;
2898 return DenormalMode(*OutputMode, *InputMode);
2901std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2904 Lex.setIgnoreColonInIdentifiers(
true);
2915 bool HasDefaultSection =
false;
2917 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2918 if (!ParsedDefaultMode)
2920 DefaultMode = *ParsedDefaultMode;
2921 HasDefaultSection =
true;
2926 if (HasDefaultSection && !HasComma) {
2927 tokError(
"expected ',' before float:");
2932 if (parseType(Ty) || !Ty->
isFloatTy()) {
2933 tokError(
"expected float:");
2937 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2940 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2944 F32Mode = *ParsedF32Mode;
2947 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2950 return DenormalFPEnv(DefaultMode, F32Mode);
2992unsigned LLParser::parseNoFPClassAttr() {
2997 tokError(
"expected '('");
3004 if (TestMask != 0) {
3008 !parseUInt64(
Value)) {
3010 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
3015 error(Lex.getLoc(),
"expected ')'");
3021 error(Lex.getLoc(),
"expected nofpclass test mask");
3039bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
3040 bool &AteExtraComma) {
3041 AteExtraComma =
false;
3045 AteExtraComma =
true;
3049 if (Lex.getKind() != lltok::kw_align)
3050 return error(Lex.getLoc(),
"expected metadata or 'align'");
3052 if (parseOptionalAlignment(Alignment))
3065bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
3066 bool &AteExtraComma) {
3067 AteExtraComma =
false;
3071 AteExtraComma =
true;
3077 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
3079 if (parseOptionalAddrSpace(AddrSpace))
3086bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
3087 std::optional<unsigned> &HowManyArg) {
3090 auto StartParen = Lex.getLoc();
3092 return error(StartParen,
"expected '('");
3094 if (parseUInt32(BaseSizeArg))
3098 auto HowManyAt = Lex.getLoc();
3100 if (parseUInt32(HowMany))
3102 if (HowMany == BaseSizeArg)
3103 return error(HowManyAt,
3104 "'allocsize' indices can't refer to the same parameter");
3105 HowManyArg = HowMany;
3107 HowManyArg = std::nullopt;
3109 auto EndParen = Lex.getLoc();
3111 return error(EndParen,
"expected ')'");
3115bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3116 unsigned &MaxValue) {
3119 auto StartParen = Lex.getLoc();
3121 return error(StartParen,
"expected '('");
3123 if (parseUInt32(MinValue))
3127 if (parseUInt32(MaxValue))
3130 MaxValue = MinValue;
3132 auto EndParen = Lex.getLoc();
3134 return error(EndParen,
"expected ')'");
3143bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3148 return parseScope(SSID) || parseOrdering(Ordering);
3158 auto StartParenAt = Lex.getLoc();
3160 return error(StartParenAt,
"Expected '(' in syncscope");
3163 auto SSNAt = Lex.getLoc();
3164 if (parseStringConstant(SSN))
3165 return error(SSNAt,
"Expected synchronization scope name");
3167 auto EndParenAt = Lex.getLoc();
3169 return error(EndParenAt,
"Expected ')' in syncscope");
3171 SSID = Context.getOrInsertSyncScopeID(SSN);
3182 switch (Lex.getKind()) {
3184 return tokError(
"Expected ordering on atomic instruction");
3203bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3205 if (!EatIfPresent(lltok::kw_alignstack))
3207 LocTy ParenLoc = Lex.getLoc();
3209 return error(ParenLoc,
"expected '('");
3210 LocTy AlignLoc = Lex.getLoc();
3211 if (parseUInt32(Alignment))
3213 ParenLoc = Lex.getLoc();
3215 return error(ParenLoc,
"expected ')'");
3217 return error(AlignLoc,
"stack alignment is not a power of two");
3231 bool &AteExtraComma) {
3232 AteExtraComma =
false;
3235 return tokError(
"expected ',' as start of index list");
3239 if (Indices.
empty())
3240 return tokError(
"expected index");
3241 AteExtraComma =
true;
3245 if (parseUInt32(Idx))
3258bool LLParser::parseType(
Type *&Result,
const Twine &
Msg,
bool AllowVoid) {
3259 SMLoc TypeLoc = Lex.getLoc();
3260 switch (Lex.getKind()) {
3262 return tokError(
Msg);
3271 if (
Result->isPointerTy()) {
3273 if (parseOptionalAddrSpace(AddrSpace))
3279 return tokError(
"ptr* is invalid - use ptr instead");
3290 if (parseTargetExtType(Result))
3296 if (parseAnonStructType(Result,
false))
3302 if (parseArrayVectorType(Result,
false))
3309 if (parseAnonStructType(Result,
true) ||
3310 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3312 }
else if (parseArrayVectorType(Result,
true))
3317 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3323 Entry.second = Lex.getLoc();
3332 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3338 Entry.second = Lex.getLoc();
3348 switch (Lex.getKind()) {
3351 if (!AllowVoid &&
Result->isVoidTy())
3352 return error(TypeLoc,
"void type only allowed for function results");
3358 return tokError(
"basic block pointers are invalid");
3360 return tokError(
"pointers to void are invalid - use i8* instead");
3362 return tokError(
"pointer to this type is invalid");
3370 return tokError(
"basic block pointers are invalid");
3372 return tokError(
"pointers to void are invalid; use i8* instead");
3374 return tokError(
"pointer to this type is invalid");
3376 if (parseOptionalAddrSpace(AddrSpace) ||
3377 parseToken(
lltok::star,
"expected '*' in address space"))
3386 if (parseFunctionType(Result))
3399 PerFunctionState &PFS,
bool IsMustTailCall,
3400 bool InVarArgsFunc) {
3406 if (!ArgList.
empty() &&
3407 parseToken(
lltok::comma,
"expected ',' in argument list"))
3412 const char *
Msg =
"unexpected ellipsis in argument list for ";
3413 if (!IsMustTailCall)
3414 return tokError(Twine(
Msg) +
"non-musttail call");
3416 return tokError(Twine(
Msg) +
"musttail call in non-varargs function");
3418 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3423 Type *ArgTy =
nullptr;
3425 if (parseType(ArgTy, ArgLoc))
3428 return error(ArgLoc,
"invalid type for function argument");
3430 AttrBuilder ArgAttrs(M->getContext());
3433 if (parseMetadataAsValue(
V, PFS))
3437 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy,
V, PFS))
3444 if (IsMustTailCall && InVarArgsFunc)
3445 return tokError(
"expected '...' at end of argument list for musttail call "
3446 "in varargs function");
3454bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3457 if (!EatIfPresent(AttrToken))
3460 return error(Lex.getLoc(),
"expected '('");
3464 return error(Lex.getLoc(),
"expected ')'");
3466 B.addTypeAttr(AttrKind, Ty);
3472bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3480 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3482 return tokError(
"expected integer");
3483 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3485 "integer is too large for the bit width of specified type");
3486 Val = Lex.getAPSIntVal().extend(
BitWidth);
3491 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3494 return error(TyLoc,
"the range must have integer type!");
3502 return tokError(
"the range represent the empty set but limits aren't 0!");
3513bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3516 auto ParseAPSInt = [&](APInt &Val) {
3518 return tokError(
"expected integer");
3519 Val = Lex.getAPSIntVal().extend(64);
3539 return tokError(
"the range should not represent the full or empty set!");
3551 if (!CRLOrNull.has_value())
3552 return tokError(
"Invalid (unordered or overlapping) range list");
3553 B.addInitializesAttr(*CRLOrNull);
3557bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3559 std::optional<CaptureComponents> Ret;
3563 Lex.setIgnoreColonInIdentifiers(
true);
3571 bool SeenComponent =
false;
3577 return tokError(
"duplicate 'ret' location");
3580 SeenComponent =
false;
3585 return tokError(
"cannot use 'none' with other component");
3589 return tokError(
"cannot use 'none' with other component");
3600 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3601 "'provenance' or 'read_provenance'");
3604 SeenComponent =
true;
3612 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3625bool LLParser::parseOptionalOperandBundles(
3627 LocTy BeginLoc = Lex.getLoc();
3633 if (!BundleList.
empty() &&
3634 parseToken(
lltok::comma,
"expected ',' in input list"))
3638 if (parseStringConstant(
Tag))
3641 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3644 std::vector<Value *> Inputs;
3647 if (!Inputs.empty() &&
3648 parseToken(
lltok::comma,
"expected ',' in input list"))
3656 if (parseMetadataAsValue(Input, PFS))
3658 }
else if (parseValue(Ty, Input, PFS)) {
3661 Inputs.push_back(Input);
3669 if (BundleList.
empty())
3670 return error(BeginLoc,
"operand bundle set must not be empty");
3677 unsigned NextID,
unsigned ID) {
3679 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3680 Twine(NextID) +
"' or greater");
3697 unsigned CurValID = 0;
3711 LocTy TypeLoc = Lex.getLoc();
3712 Type *ArgTy =
nullptr;
3713 AttrBuilder
Attrs(M->getContext());
3714 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3718 return error(TypeLoc,
"argument can not have void type");
3723 bool Unnamed =
false;
3725 Name = Lex.getStrVal();
3726 IdentStart = getTokLineColumnPos();
3728 IdentEnd = getPrevTokEndLineColumnPos();
3732 ArgID = Lex.getUIntVal();
3733 IdentStart = getTokLineColumnPos();
3734 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3737 IdentEnd = getPrevTokEndLineColumnPos();
3743 CurValID = ArgID + 1;
3747 return error(TypeLoc,
"invalid type for function argument");
3751 Unnamed ? std::nullopt
3752 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3757 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3762bool LLParser::parseFunctionType(
Type *&Result) {
3766 return tokError(
"invalid function return type");
3770 SmallVector<unsigned> UnnamedArgNums;
3771 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3775 for (
const ArgInfo &Arg : ArgList) {
3776 if (!Arg.Name.empty())
3777 return error(Arg.Loc,
"argument name invalid in function type");
3778 if (Arg.Attrs.hasAttributes())
3779 return error(Arg.Loc,
"argument attributes invalid in function type");
3783 for (
const ArgInfo &Arg : ArgList)
3792bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3794 if (parseStructBody(Elts))
3802bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3803 std::pair<Type *, LocTy> &Entry,
3807 return error(TypeLoc,
"redefinition of type");
3813 Entry.second = SMLoc();
3818 ResultTy =
Entry.first;
3830 return error(TypeLoc,
"forward references to non-struct type");
3834 return parseArrayVectorType(ResultTy,
true);
3835 return parseType(ResultTy);
3839 Entry.second = SMLoc();
3848 if (parseStructBody(Body) ||
3849 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3853 return tokError(
toString(std::move(
E)));
3873 LocTy EltTyLoc = Lex.getLoc();
3880 return error(EltTyLoc,
"invalid element type for struct");
3883 EltTyLoc = Lex.getLoc();
3888 return error(EltTyLoc,
"invalid element type for struct");
3893 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3902bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3903 bool Scalable =
false;
3907 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3913 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3914 Lex.getAPSIntVal().getBitWidth() > 64)
3915 return tokError(
"expected number in address space");
3917 LocTy SizeLoc = Lex.getLoc();
3921 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3924 LocTy TypeLoc = Lex.getLoc();
3925 Type *EltTy =
nullptr;
3926 if (parseType(EltTy))
3930 "expected end of sequential type"))
3935 return error(SizeLoc,
"zero element vector is illegal");
3937 return error(SizeLoc,
"size too large for vector");
3939 return error(TypeLoc,
"invalid vector element type");
3943 return error(TypeLoc,
"invalid array element type");
3960bool LLParser::parseTargetExtType(
Type *&Result) {
3965 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3966 parseStringConstant(TypeName))
3973 SmallVector<unsigned> IntParams;
3974 bool SeenInt =
false;
3981 if (parseUInt32(IntVal))
3984 }
else if (SeenInt) {
3987 return tokError(
"expected uint32 param");
3990 if (parseType(TypeParam,
true))
3996 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
4001 if (
auto E = TTy.takeError())
4002 return tokError(
toString(std::move(
E)));
4015 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
4018 auto It = UnnamedArgNums.
begin();
4021 unsigned ArgNum = *It++;
4022 NumberedVals.add(ArgNum, &A);
4027LLParser::PerFunctionState::~PerFunctionState() {
4030 for (
const auto &P : ForwardRefVals) {
4033 P.second.first->replaceAllUsesWith(
4035 P.second.first->deleteValue();
4038 for (
const auto &P : ForwardRefValIDs) {
4041 P.second.first->replaceAllUsesWith(
4043 P.second.first->deleteValue();
4047bool LLParser::PerFunctionState::finishFunction() {
4048 if (!ForwardRefVals.empty())
4049 return P.error(ForwardRefVals.begin()->second.second,
4050 "use of undefined value '%" + ForwardRefVals.begin()->first +
4052 if (!ForwardRefValIDs.empty())
4053 return P.error(ForwardRefValIDs.begin()->second.second,
4054 "use of undefined value '%" +
4055 Twine(ForwardRefValIDs.begin()->first) +
"'");
4062Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
4065 Value *Val =
F.getValueSymbolTable()->lookup(Name);
4070 auto I = ForwardRefVals.find(Name);
4071 if (
I != ForwardRefVals.end())
4072 Val =
I->second.first;
4077 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
4081 P.error(Loc,
"invalid use of a non-first-class type");
4092 if (FwdVal->
getName() != Name) {
4093 P.error(Loc,
"name is too long which can result in name collisions, "
4094 "consider making the name shorter or "
4095 "increasing -non-global-value-max-name-size");
4099 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
4103Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
4105 Value *Val = NumberedVals.get(ID);
4110 auto I = ForwardRefValIDs.find(ID);
4111 if (
I != ForwardRefValIDs.end())
4112 Val =
I->second.first;
4117 return P.checkValidVariableType(Loc,
"%" + Twine(ID), Ty, Val);
4120 P.error(Loc,
"invalid use of a non-first-class type");
4132 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4138bool LLParser::PerFunctionState::setInstName(
int NameID,
4139 const std::string &NameStr,
4140 LocTy NameLoc, Instruction *Inst) {
4143 if (NameID != -1 || !NameStr.empty())
4144 return P.error(NameLoc,
"instructions returning void cannot have a name");
4150 if (NameStr.empty()) {
4153 NameID = NumberedVals.getNext();
4155 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4159 auto FI = ForwardRefValIDs.find(NameID);
4160 if (FI != ForwardRefValIDs.end()) {
4163 return P.error(NameLoc,
"instruction forward referenced with type '" +
4167 Sentinel->replaceAllUsesWith(Inst);
4169 ForwardRefValIDs.erase(FI);
4172 NumberedVals.add(NameID, Inst);
4177 auto FI = ForwardRefVals.find(NameStr);
4178 if (FI != ForwardRefVals.end()) {
4181 return P.error(NameLoc,
"instruction forward referenced with type '" +
4185 Sentinel->replaceAllUsesWith(Inst);
4187 ForwardRefVals.erase(FI);
4193 if (Inst->
getName() != NameStr)
4194 return P.error(NameLoc,
"multiple definition of local value named '" +
4201BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4207BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID,
LocTy Loc) {
4215BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4216 int NameID,
LocTy Loc) {
4220 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4223 NameID = NumberedVals.getNext();
4225 BB = getBB(NameID, Loc);
4227 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4231 BB = getBB(Name, Loc);
4233 P.error(Loc,
"unable to create block named '" + Name +
"'");
4244 ForwardRefValIDs.erase(NameID);
4245 NumberedVals.add(NameID, BB);
4248 ForwardRefVals.erase(Name);
4265bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4266 ID.Loc = Lex.getLoc();
4267 switch (Lex.getKind()) {
4269 return tokError(
"expected value token");
4271 ID.UIntVal = Lex.getUIntVal();
4275 ID.StrVal = Lex.getStrVal();
4279 ID.UIntVal = Lex.getUIntVal();
4283 ID.StrVal = Lex.getStrVal();
4287 ID.APSIntVal = Lex.getAPSIntVal();
4291 ID.APFloatVal = Lex.getAPFloatVal();
4297 return error(
ID.Loc,
"unexpected floating-point literal");
4299 return error(
ID.Loc,
"floating-point constant invalid for type");
4304 "Invalid float strings should be caught by the lexer");
4309 return error(
ID.Loc,
"floating-point constant overflowed type");
4311 return error(
ID.Loc,
"floating-point constant underflowed type");
4317 return error(
ID.Loc,
"unexpected floating-point literal");
4319 const APInt &
Bits = Lex.getAPSIntVal();
4321 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4322 ID.APFloatVal =
APFloat(Semantics, Bits);
4344 if (parseGlobalValueVector(Elts) ||
4345 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4348 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4349 ID.UIntVal = Elts.
size();
4350 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4351 Elts.
size() *
sizeof(Elts[0]));
4362 LocTy FirstEltLoc = Lex.getLoc();
4363 if (parseGlobalValueVector(Elts) ||
4365 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4369 if (isPackedStruct) {
4370 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4371 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4372 Elts.
size() *
sizeof(Elts[0]));
4373 ID.UIntVal = Elts.
size();
4379 return error(
ID.Loc,
"constant vector must not be empty");
4381 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4382 !Elts[0]->
getType()->isFloatingPointTy() &&
4386 "vector elements must have integer, byte, pointer or floating point "
4390 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4392 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4393 " is not of type '" +
4403 LocTy FirstEltLoc = Lex.getLoc();
4404 if (parseGlobalValueVector(Elts) ||
4416 if (!Elts[0]->
getType()->isFirstClassType())
4417 return error(FirstEltLoc,
"invalid array element type: " +
4423 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4425 return error(FirstEltLoc,
"array element #" + Twine(i) +
4426 " is not of type '" +
4438 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4447 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4450 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4453 parseStringConstant(
ID.StrVal) ||
4454 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4457 ID.StrVal2 = Lex.getStrVal();
4458 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4459 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4470 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4471 parseValID(Fn, PFS) ||
4473 "expected comma in block address expression") ||
4474 parseValID(Label, PFS) ||
4475 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4479 return error(Fn.
Loc,
"expected function name in blockaddress");
4481 return error(
Label.Loc,
"expected basic block name in blockaddress");
4484 GlobalValue *GV =
nullptr;
4486 GV = NumberedVals.get(Fn.
UIntVal);
4487 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4488 GV = M->getNamedValue(Fn.
StrVal);
4494 return error(Fn.
Loc,
"expected function name in blockaddress");
4496 if (
F->isDeclaration())
4497 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4502 GlobalValue *&FwdRef =
4503 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4511 "type of blockaddress must be a pointer and not '" +
4516 FwdDeclAS = PFS->getFunction().getAddressSpace();
4520 FwdRef =
new GlobalVariable(
4525 ID.ConstantVal = FwdRef;
4533 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4535 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4537 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4539 return error(
Label.Loc,
"referenced value is not a basic block");
4542 return error(
Label.Loc,
"cannot take address of numeric label after "
4543 "the function is defined");
4545 F->getValueSymbolTable()->lookup(
Label.StrVal));
4547 return error(
Label.Loc,
"referenced value is not a basic block");
4561 if (parseValID(Fn, PFS))
4566 "expected global value name in dso_local_equivalent");
4569 GlobalValue *GV =
nullptr;
4571 GV = NumberedVals.get(Fn.
UIntVal);
4572 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4573 GV = M->getNamedValue(Fn.
StrVal);
4579 ? ForwardRefDSOLocalEquivalentIDs
4580 : ForwardRefDSOLocalEquivalentNames;
4581 GlobalValue *&FwdRef = FwdRefMap[Fn];
4588 ID.ConstantVal = FwdRef;
4594 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4595 "in dso_local_equivalent");
4606 if (parseValID(ID, PFS))
4610 return error(
ID.Loc,
"expected global value name in no_cfi");
4622 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4623 *DeactivationSymbol =
nullptr;
4626 "expected '(' in constant ptrauth expression") ||
4627 parseGlobalTypeAndValue(Ptr) ||
4629 "expected comma in constant ptrauth expression") ||
4630 parseGlobalTypeAndValue(
Key))
4633 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4635 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4638 parseGlobalTypeAndValue(DeactivationSymbol))
4641 "expected ')' in constant ptrauth expression"))
4645 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4648 if (!KeyC || KeyC->getBitWidth() != 32)
4649 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4651 ConstantInt *DiscC =
nullptr;
4657 "constant ptrauth integer discriminator must be i64 constant");
4663 if (!AddrDisc->getType()->isPointerTy())
4665 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4670 if (!DeactivationSymbol)
4671 DeactivationSymbol =
4673 if (!DeactivationSymbol->getType()->isPointerTy())
4675 "constant ptrauth deactivation symbol must be a pointer");
4689 unsigned Opc = Lex.getUIntVal();
4690 Type *DestTy =
nullptr;
4693 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4694 parseGlobalTypeAndValue(SrcVal) ||
4695 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4696 parseType(DestTy) ||
4697 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4700 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4709 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4711 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4713 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4715 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4717 return error(
ID.Loc,
"urem constexprs are no longer supported");
4719 return error(
ID.Loc,
"srem constexprs are no longer supported");
4721 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4723 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4725 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4727 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4729 return error(
ID.Loc,
"frem constexprs are no longer supported");
4731 return error(
ID.Loc,
"and constexprs are no longer supported");
4733 return error(
ID.Loc,
"or constexprs are no longer supported");
4735 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4737 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4739 return error(
ID.Loc,
"shl constexprs are no longer supported");
4741 return error(
ID.Loc,
"mul constexprs are no longer supported");
4743 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4745 return error(
ID.Loc,
"select constexprs are no longer supported");
4747 return error(
ID.Loc,
"zext constexprs are no longer supported");
4749 return error(
ID.Loc,
"sext constexprs are no longer supported");
4751 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4753 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4755 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4757 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4759 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4761 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4763 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4765 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4773 unsigned Opc = Lex.getUIntVal();
4776 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4777 Opc == Instruction::Mul) {
4786 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4787 parseGlobalTypeAndValue(Val0) ||
4788 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4789 parseGlobalTypeAndValue(Val1) ||
4790 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4793 return error(
ID.Loc,
"operands of constexpr must have same type");
4797 "constexpr requires integer or integer vector operands");
4808 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4811 if (parseGlobalTypeAndValue(
C))
4813 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4825 unsigned Opc = Lex.getUIntVal();
4828 bool HasInRange =
false;
4834 if (
Opc == Instruction::GetElementPtr) {
4850 return tokError(
"expected integer");
4851 InRangeStart = Lex.getAPSIntVal();
4856 return tokError(
"expected integer");
4857 InRangeEnd = Lex.getAPSIntVal();
4865 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4868 if (
Opc == Instruction::GetElementPtr) {
4869 if (parseType(Ty) ||
4870 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4874 if (parseGlobalValueVector(Elts) ||
4878 if (
Opc == Instruction::GetElementPtr) {
4879 if (Elts.
size() == 0 ||
4880 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4881 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4884 std::optional<ConstantRange>
InRange;
4886 unsigned IndexWidth =
4887 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4888 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4889 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4890 if (InRangeStart.
sge(InRangeEnd))
4891 return error(
ID.Loc,
"expected end to be larger than start");
4901 for (Constant *Val : Indices) {
4904 return error(
ID.Loc,
"getelementptr index must be an integer");
4907 if (GEPWidth && (ValNumEl != GEPWidth))
4910 "getelementptr vector index has a wrong number of elements");
4913 GEPWidth = ValNumEl;
4917 if (!Indices.empty() && !Ty->
isSized())
4918 return error(
ID.Loc,
"base element of getelementptr must be sized");
4921 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4924 return error(
ID.Loc,
"invalid getelementptr indices");
4930 }
else if (
Opc == Instruction::ShuffleVector) {
4931 if (Elts.
size() != 3)
4932 return error(
ID.Loc,
"expected three operands to shufflevector");
4934 return error(
ID.Loc,
"invalid operands to shufflevector");
4935 SmallVector<int, 16>
Mask;
4938 }
else if (
Opc == Instruction::ExtractElement) {
4939 if (Elts.
size() != 2)
4940 return error(
ID.Loc,
"expected two operands to extractelement");
4942 return error(
ID.Loc,
"invalid extractelement operands");
4945 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4946 if (Elts.
size() != 3)
4947 return error(
ID.Loc,
"expected three operands to insertelement");
4949 return error(
ID.Loc,
"invalid insertelement operands");
4964bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4968 bool Parsed = parseValID(ID,
nullptr, Ty) ||
4969 convertValIDToValue(Ty, ID,
V,
nullptr);
4971 return error(
ID.Loc,
"global values must be constants");
4975bool LLParser::parseGlobalTypeAndValue(Constant *&
V) {
4977 return parseType(Ty) || parseGlobalValue(Ty,
V);
4980bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4983 LocTy KwLoc = Lex.getLoc();
4989 return tokError(
"expected comdat variable");
4990 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4992 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4995 if (GlobalName.
empty())
4996 return tokError(
"comdat cannot be unnamed");
4997 C = getComdat(std::string(GlobalName), KwLoc);
5006bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5020 if (parseGlobalTypeAndValue(
C))
5028bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
5030 if (parseMDNodeVector(Elts))
5041bool LLParser::parseMDNode(MDNode *&
N) {
5043 return parseSpecializedMDNode(
N);
5045 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
5048bool LLParser::parseMDNodeTail(MDNode *&
N) {
5051 return parseMDTuple(
N);
5054 return parseMDNodeID(
N);
5060template <
class FieldTy>
struct MDFieldImpl {
5061 typedef MDFieldImpl ImplTy;
5065 void assign(FieldTy Val) {
5067 this->Val = std::move(Val);
5070 explicit MDFieldImpl(FieldTy
Default)
5078template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
5079 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5092 this->
A = std::move(
A);
5098 this->
B = std::move(
B);
5102 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5104 WhatIs(IsInvalid) {}
5107struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5114struct LineField :
public MDUnsignedField {
5115 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5118struct ColumnField :
public MDUnsignedField {
5119 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5122struct DwarfTagField :
public MDUnsignedField {
5128struct DwarfMacinfoTypeField :
public MDUnsignedField {
5134struct DwarfAttEncodingField :
public MDUnsignedField {
5135 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5138struct DwarfVirtualityField :
public MDUnsignedField {
5142struct DwarfLangField :
public MDUnsignedField {
5146struct DwarfSourceLangNameField :
public MDUnsignedField {
5147 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5150struct DwarfLangDialectField :
public MDUnsignedField {
5151 DwarfLangDialectField()
5155struct DwarfCCField :
public MDUnsignedField {
5156 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5159struct DwarfEnumKindField :
public MDUnsignedField {
5160 DwarfEnumKindField()
5165struct EmissionKindField :
public MDUnsignedField {
5166 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5169struct FixedPointKindField :
public MDUnsignedField {
5170 FixedPointKindField()
5171 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5174struct NameTableKindField :
public MDUnsignedField {
5175 NameTableKindField()
5178 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5181struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5182 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5185struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5186 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5189struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5190 MDAPSIntField() : ImplTy(
APSInt()) {}
5193struct MDSignedField :
public MDFieldImpl<int64_t> {
5197 MDSignedField(int64_t
Default = 0)
5199 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5203struct MDBoolField :
public MDFieldImpl<bool> {
5207struct MDField :
public MDFieldImpl<Metadata *> {
5210 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5213struct MDStringField :
public MDFieldImpl<MDString *> {
5214 enum class EmptyIs {
5219 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5220 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5223struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5227struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5231struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5232 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5233 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5235 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5236 bool AllowNull =
true)
5237 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5239 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5240 bool isMDField()
const {
return WhatIs == IsTypeB; }
5241 int64_t getMDSignedValue()
const {
5242 assert(isMDSignedField() &&
"Wrong field type");
5245 Metadata *getMDFieldValue()
const {
5246 assert(isMDField() &&
"Wrong field type");
5251struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5253 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5256 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5258 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5259 bool isMDField()
const {
return WhatIs == IsTypeB; }
5260 uint64_t getMDUnsignedValue()
const {
5261 assert(isMDUnsignedField() &&
"Wrong field type");
5264 Metadata *getMDFieldValue()
const {
5265 assert(isMDField() &&
"Wrong field type");
5270 if (isMDUnsignedField())
5272 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5274 return getMDFieldValue();
5286 return tokError(
"expected integer");
5288 Result.assign(Lex.getAPSIntVal());
5295 MDUnsignedField &Result) {
5296 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5297 return tokError(
"expected unsigned integer");
5299 auto &U = Lex.getAPSIntVal();
5300 if (U.ugt(Result.Max))
5301 return tokError(
"value for '" + Name +
"' too large, limit is " +
5303 Result.assign(U.getZExtValue());
5304 assert(Result.Val <= Result.Max &&
"Expected value in range");
5311 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5315 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5321 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5324 return tokError(
"expected DWARF tag");
5328 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5329 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5338 DwarfMacinfoTypeField &Result) {
5340 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5343 return tokError(
"expected DWARF macinfo type");
5347 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5348 Lex.getStrVal() +
"'");
5349 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5351 Result.assign(Macinfo);
5358 DwarfVirtualityField &Result) {
5360 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5363 return tokError(
"expected DWARF virtuality code");
5367 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5368 Lex.getStrVal() +
"'");
5369 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5370 Result.assign(Virtuality);
5377 DwarfEnumKindField &Result) {
5379 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5382 return tokError(
"expected DWARF enum kind code");
5386 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5387 Lex.getStrVal() +
"'");
5388 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5389 Result.assign(EnumKind);
5397 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5400 return tokError(
"expected DWARF language");
5404 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5406 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5407 Result.assign(Lang);
5414 DwarfSourceLangNameField &Result) {
5416 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5419 return tokError(
"expected DWARF source language name");
5423 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5424 Lex.getStrVal() +
"'");
5425 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5426 Result.assign(Lang);
5433 DwarfLangDialectField &Result) {
5438 if (Lex.getAPSIntVal() == 0)
5439 return tokError(
"value for 'dialect' must be a known DWARF language "
5440 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5441 "DW_LLVM_LANG_DIALECT_tile)");
5442 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5446 return tokError(
"expected DWARF language dialect");
5448 StringRef DialectString = Lex.getStrVal();
5453 if (Dialect > Result.Max)
5454 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5455 DialectString +
"'");
5456 Result.assign(Dialect);
5464 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5467 return tokError(
"expected DWARF calling convention");
5471 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5472 Lex.getStrVal() +
"'");
5473 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
5481 EmissionKindField &Result) {
5483 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5486 return tokError(
"expected emission kind");
5490 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5492 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5493 Result.assign(*Kind);
5500 FixedPointKindField &Result) {
5502 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5505 return tokError(
"expected fixed-point kind");
5509 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5511 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5512 Result.assign(*Kind);
5519 NameTableKindField &Result) {
5521 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5524 return tokError(
"expected nameTable kind");
5528 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5530 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5531 Result.assign((
unsigned)*Kind);
5538 DwarfAttEncodingField &Result) {
5540 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5543 return tokError(
"expected DWARF type attribute encoding");
5547 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5548 Lex.getStrVal() +
"'");
5549 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5550 Result.assign(Encoding);
5564 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5566 bool Res = parseUInt32(TempVal);
5572 return tokError(
"expected debug info flag");
5576 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5591 Result.assign(Combined);
5604 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5606 bool Res = parseUInt32(TempVal);
5612 return tokError(
"expected debug info flag");
5616 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5617 Lex.getStrVal() +
"'");
5631 Result.assign(Combined);
5638 return tokError(
"expected signed integer");
5640 auto &S = Lex.getAPSIntVal();
5642 return tokError(
"value for '" + Name +
"' too small, limit is " +
5645 return tokError(
"value for '" + Name +
"' too large, limit is " +
5647 Result.assign(S.getExtValue());
5648 assert(Result.Val >= Result.Min &&
"Expected value in range");
5649 assert(Result.Val <= Result.Max &&
"Expected value in range");
5656 switch (Lex.getKind()) {
5658 return tokError(
"expected 'true' or 'false'");
5660 Result.assign(
true);
5663 Result.assign(
false);
5673 if (!Result.AllowNull)
5674 return tokError(
"'" + Name +
"' cannot be null");
5676 Result.assign(
nullptr);
5681 if (parseMetadata(MD,
nullptr))
5690 MDSignedOrMDField &Result) {
5693 MDSignedField Res = Result.A;
5694 if (!parseMDField(
Loc, Name, Res)) {
5702 MDField Res = Result.B;
5703 if (!parseMDField(
Loc, Name, Res)) {
5713 MDUnsignedOrMDField &Result) {
5716 MDUnsignedField Res = Result.A;
5717 if (!parseMDField(
Loc, Name, Res)) {
5725 MDField Res = Result.B;
5726 if (!parseMDField(
Loc, Name, Res)) {
5736 LocTy ValueLoc = Lex.getLoc();
5738 if (parseStringConstant(S))
5742 switch (Result.EmptyIs) {
5743 case MDStringField::EmptyIs::Null:
5744 Result.assign(
nullptr);
5746 case MDStringField::EmptyIs::Empty:
5748 case MDStringField::EmptyIs::Error:
5749 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5760 if (parseMDNodeVector(MDs))
5763 Result.assign(std::move(MDs));
5769 ChecksumKindField &Result) {
5770 std::optional<DIFile::ChecksumKind> CSKind =
5774 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5777 Result.assign(*CSKind);
5784template <
class ParserTy>
5785bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5788 return tokError(
"expected field label here");
5797template <
class ParserTy>
5798bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5805 if (parseMDFieldsImplBody(ParseField))
5808 ClosingLoc = Lex.getLoc();
5812template <
class FieldTy>
5813bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5815 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5817 LocTy Loc = Lex.getLoc();
5819 return parseMDField(Loc, Name, Result);
5822bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5825#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5826 if (Lex.getStrVal() == #CLASS) \
5827 return parse##CLASS(N, IsDistinct);
5828#include "llvm/IR/Metadata.def"
5830 return tokError(
"expected metadata type");
5833#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5834#define NOP_FIELD(NAME, TYPE, INIT)
5835#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5837 return error(ClosingLoc, "missing required field '" #NAME "'");
5838#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5839 if (Lex.getStrVal() == #NAME) \
5840 return parseMDField(#NAME, NAME);
5841#define PARSE_MD_FIELDS() \
5842 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5845 if (parseMDFieldsImpl( \
5847 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5848 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5853 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5855#define GET_OR_DISTINCT(CLASS, ARGS) \
5856 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5858bool LLParser::parseMDFunctionLocalContext(
MDNode *&Result,
bool IsDistinct) {
5859 return tokError(
"!MDFunctionLocalContext parsing not yet implemented");
5865bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5866#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5867 OPTIONAL(line, LineField, ); \
5868 OPTIONAL(column, ColumnField, ); \
5869 REQUIRED(scope, MDField, ( false)); \
5870 OPTIONAL(inlinedAt, MDField, ); \
5871 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5872 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5873 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
5874 OPTIONAL(irlayers, MDField, );
5876#undef VISIT_MD_FIELDS
5879 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5880 inlinedAt.Val, isImplicitCode.Val,
5881 atomGroup.Val, atomRank.Val, irlayers.Val));
5885bool LLParser::parseDILayerLoc(
MDNode *&Result,
bool IsDistinct) {
5886#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5887 OPTIONAL(line, LineField, ); \
5888 OPTIONAL(column, ColumnField, ); \
5889 REQUIRED(file, MDField, ( false)); \
5890 REQUIRED(kind, MDStringField, );
5892#undef VISIT_MD_FIELDS
5895 (Context, kind.Val,
file.Val, line.Val, column.Val));
5899bool LLParser::parseDILayerLocList(
MDNode *&Result,
bool IsDistinct) {
5908 if (parseMetadata(MD,
nullptr))
5921bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5923 return tokError(
"missing 'distinct', required for !DIAssignID()");
5939bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5940#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5941 REQUIRED(tag, DwarfTagField, ); \
5942 OPTIONAL(header, MDStringField, ); \
5943 OPTIONAL(operands, MDFieldList, );
5945#undef VISIT_MD_FIELDS
5948 (Context, tag.Val, header.Val, operands.Val));
5957bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5958#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5959 OPTIONAL(name, MDStringField, ); \
5960 OPTIONAL(file, MDField, ); \
5961 OPTIONAL(line, LineField, ); \
5962 OPTIONAL(scope, MDField, ); \
5963 OPTIONAL(baseType, MDField, ); \
5964 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5965 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5966 OPTIONAL(flags, DIFlagField, ); \
5967 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5968 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5969 OPTIONAL(stride, MDSignedOrMDField, ); \
5970 OPTIONAL(bias, MDSignedOrMDField, );
5972#undef VISIT_MD_FIELDS
5974 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5975 if (Bound.isMDSignedField())
5978 if (Bound.isMDField())
5979 return Bound.getMDFieldValue();
5985 Metadata *Stride = convToMetadata(stride);
5986 Metadata *Bias = convToMetadata(bias);
5989 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5990 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5991 baseType.Val, LowerBound, UpperBound, Stride, Bias));
6000bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
6001#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6002 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
6003 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6004 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6005 OPTIONAL(stride, MDSignedOrMDField, );
6007#undef VISIT_MD_FIELDS
6014 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6015 if (Bound.isMDSignedField())
6018 if (Bound.isMDField())
6019 return Bound.getMDFieldValue();
6026 Stride = convToMetadata(stride);
6029 (Context,
Count, LowerBound, UpperBound, Stride));
6037bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
6038#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6039 OPTIONAL(count, MDSignedOrMDField, ); \
6040 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6041 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6042 OPTIONAL(stride, MDSignedOrMDField, );
6044#undef VISIT_MD_FIELDS
6046 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6047 if (Bound.isMDSignedField())
6049 Context, {dwarf::DW_OP_consts,
6050 static_cast<uint64_t>(Bound.getMDSignedValue())});
6051 if (Bound.isMDField())
6052 return Bound.getMDFieldValue();
6059 Metadata *Stride = ConvToMetadata(stride);
6062 (Context,
Count, LowerBound, UpperBound, Stride));
6069bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
6070#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6071 REQUIRED(name, MDStringField, ); \
6072 REQUIRED(value, MDAPSIntField, ); \
6073 OPTIONAL(isUnsigned, MDBoolField, (false));
6075#undef VISIT_MD_FIELDS
6077 if (isUnsigned.Val && value.Val.isNegative())
6078 return tokError(
"unsigned enumerator with negative value");
6083 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6095bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
6096#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6097 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6098 OPTIONAL(name, MDStringField, ); \
6099 OPTIONAL(file, MDField, ); \
6100 OPTIONAL(line, LineField, ); \
6101 OPTIONAL(scope, MDField, ); \
6102 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6103 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6104 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6105 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6106 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6107 OPTIONAL(flags, DIFlagField, );
6109#undef VISIT_MD_FIELDS
6112 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6113 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
6114 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6123bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6124#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6125 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6126 OPTIONAL(name, MDStringField, ); \
6127 OPTIONAL(file, MDField, ); \
6128 OPTIONAL(line, LineField, ); \
6129 OPTIONAL(scope, MDField, ); \
6130 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6131 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6132 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6133 OPTIONAL(flags, DIFlagField, ); \
6134 OPTIONAL(kind, FixedPointKindField, ); \
6135 OPTIONAL(factor, MDSignedField, ); \
6136 OPTIONAL(numerator, MDAPSIntField, ); \
6137 OPTIONAL(denominator, MDAPSIntField, );
6139#undef VISIT_MD_FIELDS
6142 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6143 scope.Val,
size.getValueAsMetadata(Context),
6144 align.Val, encoding.Val, flags.Val, kind.Val,
6145 factor.Val, numerator.Val, denominator.Val));
6151bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6152#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6153 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6154 OPTIONAL(name, MDStringField, ); \
6155 OPTIONAL(stringLength, MDField, ); \
6156 OPTIONAL(stringLengthExpression, MDField, ); \
6157 OPTIONAL(stringLocationExpression, MDField, ); \
6158 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6159 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6160 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6161 OPTIONAL(charType, MDField, );
6163#undef VISIT_MD_FIELDS
6167 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6168 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6169 align.Val, encoding.Val, charType.Val));
6182bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6183#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6184 REQUIRED(tag, DwarfTagField, ); \
6185 OPTIONAL(name, MDStringField, ); \
6186 OPTIONAL(file, MDField, ); \
6187 OPTIONAL(line, LineField, ); \
6188 OPTIONAL(scope, MDField, ); \
6189 REQUIRED(baseType, MDField, ); \
6190 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6191 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6192 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6193 OPTIONAL(flags, DIFlagField, ); \
6194 OPTIONAL(extraData, MDField, ); \
6195 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6196 OPTIONAL(annotations, MDField, ); \
6197 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6198 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6199 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6200 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6201 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6203#undef VISIT_MD_FIELDS
6205 std::optional<unsigned> DWARFAddressSpace;
6206 if (dwarfAddressSpace.Val != UINT32_MAX)
6207 DWARFAddressSpace = dwarfAddressSpace.Val;
6208 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6210 PtrAuthData.emplace(
6211 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6212 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6213 ptrAuthAuthenticatesNullValues.Val);
6216 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6217 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6218 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6219 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6223bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6224#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6225 REQUIRED(tag, DwarfTagField, ); \
6226 OPTIONAL(name, MDStringField, ); \
6227 OPTIONAL(file, MDField, ); \
6228 OPTIONAL(line, LineField, ); \
6229 OPTIONAL(scope, MDField, ); \
6230 OPTIONAL(baseType, MDField, ); \
6231 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6232 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6233 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6234 OPTIONAL(flags, DIFlagField, ); \
6235 OPTIONAL(elements, MDField, ); \
6236 OPTIONAL(runtimeLang, DwarfLangField, ); \
6237 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6238 OPTIONAL(vtableHolder, MDField, ); \
6239 OPTIONAL(templateParams, MDField, ); \
6240 OPTIONAL(identifier, MDStringField, ); \
6241 OPTIONAL(discriminator, MDField, ); \
6242 OPTIONAL(dataLocation, MDField, ); \
6243 OPTIONAL(associated, MDField, ); \
6244 OPTIONAL(allocated, MDField, ); \
6245 OPTIONAL(rank, MDSignedOrMDField, ); \
6246 OPTIONAL(annotations, MDField, ); \
6247 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6248 OPTIONAL(specification, MDField, ); \
6249 OPTIONAL(bitStride, MDField, );
6251#undef VISIT_MD_FIELDS
6254 if (rank.isMDSignedField())
6257 else if (rank.isMDField())
6258 Rank = rank.getMDFieldValue();
6260 std::optional<unsigned> EnumKind;
6262 EnumKind = enumKind.Val;
6267 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6268 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6269 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6270 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6271 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6272 dataLocation.Val, associated.Val, allocated.Val, Rank,
6273 annotations.Val, bitStride.Val)) {
6282 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6283 size.getValueAsMetadata(Context),
align.Val,
6284 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6285 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6286 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6287 allocated.Val, Rank, annotations.Val, specification.Val,
6288 num_extra_inhabitants.Val, bitStride.Val));
6292bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6293#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6294 OPTIONAL(flags, DIFlagField, ); \
6295 OPTIONAL(cc, DwarfCCField, ); \
6296 REQUIRED(types, MDField, );
6298#undef VISIT_MD_FIELDS
6301 (Context, flags.Val, cc.Val, types.Val));
6310bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6314#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6315 REQUIRED(filename, MDStringField, ); \
6316 REQUIRED(directory, MDStringField, ); \
6317 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6318 OPTIONAL(checksum, MDStringField, ); \
6319 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6321#undef VISIT_MD_FIELDS
6323 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6324 if (checksumkind.Seen && checksum.Seen)
6325 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6326 else if (checksumkind.Seen || checksum.Seen)
6327 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6329 MDString *
Source =
nullptr;
6333 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6345bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6347 return tokError(
"missing 'distinct', required for !DICompileUnit");
6349 LocTy Loc = Lex.getLoc();
6351#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6352 REQUIRED(file, MDField, ( false)); \
6353 OPTIONAL(language, DwarfLangField, ); \
6354 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6355 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6356 OPTIONAL(producer, MDStringField, ); \
6357 OPTIONAL(isOptimized, MDBoolField, ); \
6358 OPTIONAL(flags, MDStringField, ); \
6359 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6360 OPTIONAL(splitDebugFilename, MDStringField, ); \
6361 OPTIONAL(emissionKind, EmissionKindField, ); \
6362 OPTIONAL(enums, MDField, ); \
6363 OPTIONAL(retainedTypes, MDField, ); \
6364 OPTIONAL(globals, MDField, ); \
6365 OPTIONAL(imports, MDField, ); \
6366 OPTIONAL(macros, MDField, ); \
6367 OPTIONAL(dwoId, MDUnsignedField, ); \
6368 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6369 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6370 OPTIONAL(nameTableKind, NameTableKindField, ); \
6371 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6372 OPTIONAL(sysroot, MDStringField, ); \
6373 OPTIONAL(sdk, MDStringField, ); \
6374 OPTIONAL(dialect, DwarfLangDialectField, );
6376#undef VISIT_MD_FIELDS
6378 if (!language.Seen && !sourceLanguageName.Seen)
6379 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6380 "required for !DICompileUnit");
6382 if (language.Seen && sourceLanguageName.Seen)
6383 return error(Loc,
"can only specify one of 'language' and "
6384 "'sourceLanguageName' on !DICompileUnit");
6386 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6387 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6388 "'sourceLanguageName' on !DICompileUnit");
6390 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6393 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6394 : DISourceLanguageName(
6395 static_cast<uint16_t>(sourceLanguageName.Val),
6396 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6399 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6400 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6401 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6402 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6403 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6416bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6417 auto Loc = Lex.getLoc();
6418#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6419 OPTIONAL(scope, MDField, ); \
6420 OPTIONAL(name, MDStringField, ); \
6421 OPTIONAL(linkageName, MDStringField, ); \
6422 OPTIONAL(file, MDField, ); \
6423 OPTIONAL(line, LineField, ); \
6424 REQUIRED(type, MDField, ( false)); \
6425 OPTIONAL(isLocal, MDBoolField, ); \
6426 OPTIONAL(isDefinition, MDBoolField, (true)); \
6427 OPTIONAL(scopeLine, LineField, ); \
6428 OPTIONAL(containingType, MDField, ); \
6429 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6430 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6431 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6432 OPTIONAL(flags, DIFlagField, ); \
6433 OPTIONAL(spFlags, DISPFlagField, ); \
6434 OPTIONAL(isOptimized, MDBoolField, ); \
6435 OPTIONAL(unit, MDField, ); \
6436 OPTIONAL(templateParams, MDField, ); \
6437 OPTIONAL(declaration, MDField, ); \
6438 OPTIONAL(retainedNodes, MDField, ); \
6439 OPTIONAL(thrownTypes, MDField, ); \
6440 OPTIONAL(annotations, MDField, ); \
6441 OPTIONAL(targetFuncName, MDStringField, ); \
6442 OPTIONAL(keyInstructions, MDBoolField, );
6444#undef VISIT_MD_FIELDS
6449 spFlags.Seen ? spFlags.Val
6451 isOptimized.Val, virtuality.Val);
6452 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6455 "missing 'distinct', required for !DISubprogram that is a Definition");
6458 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6459 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6460 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6461 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6462 targetFuncName.Val, keyInstructions.Val));
6472bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6473#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6474 REQUIRED(scope, MDField, ( false)); \
6475 OPTIONAL(file, MDField, ); \
6476 OPTIONAL(line, LineField, ); \
6477 OPTIONAL(column, ColumnField, );
6479#undef VISIT_MD_FIELDS
6482 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6488bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6489#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6490 REQUIRED(scope, MDField, ( false)); \
6491 OPTIONAL(file, MDField, ); \
6492 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6494#undef VISIT_MD_FIELDS
6497 (Context, scope.Val,
file.Val, discriminator.Val));
6503bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6504#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6505 REQUIRED(scope, MDField, ); \
6506 OPTIONAL(declaration, MDField, ); \
6507 OPTIONAL(name, MDStringField, ); \
6508 OPTIONAL(file, MDField, ); \
6509 OPTIONAL(line, LineField, );
6511#undef VISIT_MD_FIELDS
6514 (Context, scope.Val, declaration.Val,
name.Val,
6515 file.Val, line.Val));
6521bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6522#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6523 REQUIRED(scope, MDField, ); \
6524 OPTIONAL(name, MDStringField, ); \
6525 OPTIONAL(exportSymbols, MDBoolField, );
6527#undef VISIT_MD_FIELDS
6530 (Context, scope.Val,
name.Val, exportSymbols.Val));
6537bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6538#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6539 REQUIRED(type, DwarfMacinfoTypeField, ); \
6540 OPTIONAL(line, LineField, ); \
6541 REQUIRED(name, MDStringField, ); \
6542 OPTIONAL(value, MDStringField, );
6544#undef VISIT_MD_FIELDS
6547 (Context, type.Val, line.Val,
name.Val, value.Val));
6553bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6554#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6555 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6556 OPTIONAL(line, LineField, ); \
6557 REQUIRED(file, MDField, ); \
6558 OPTIONAL(nodes, MDField, );
6560#undef VISIT_MD_FIELDS
6563 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6571bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6572#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6573 REQUIRED(scope, MDField, ); \
6574 REQUIRED(name, MDStringField, ); \
6575 OPTIONAL(configMacros, MDStringField, ); \
6576 OPTIONAL(includePath, MDStringField, ); \
6577 OPTIONAL(apinotes, MDStringField, ); \
6578 OPTIONAL(file, MDField, ); \
6579 OPTIONAL(line, LineField, ); \
6580 OPTIONAL(isDecl, MDBoolField, );
6582#undef VISIT_MD_FIELDS
6585 configMacros.Val, includePath.Val,
6586 apinotes.Val, line.Val, isDecl.Val));
6592bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6593#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6594 OPTIONAL(name, MDStringField, ); \
6595 REQUIRED(type, MDField, ); \
6596 OPTIONAL(defaulted, MDBoolField, );
6598#undef VISIT_MD_FIELDS
6601 (Context,
name.Val, type.Val, defaulted.Val));
6609bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6610#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6611 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6612 OPTIONAL(name, MDStringField, ); \
6613 OPTIONAL(type, MDField, ); \
6614 OPTIONAL(defaulted, MDBoolField, ); \
6615 REQUIRED(value, MDField, );
6618#undef VISIT_MD_FIELDS
6621 DITemplateValueParameter,
6622 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6631bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6632#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6633 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6634 OPTIONAL(scope, MDField, ); \
6635 OPTIONAL(linkageName, MDStringField, ); \
6636 OPTIONAL(file, MDField, ); \
6637 OPTIONAL(line, LineField, ); \
6638 OPTIONAL(type, MDField, ); \
6639 OPTIONAL(isLocal, MDBoolField, ); \
6640 OPTIONAL(isDefinition, MDBoolField, (true)); \
6641 OPTIONAL(templateParams, MDField, ); \
6642 OPTIONAL(declaration, MDField, ); \
6643 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6644 OPTIONAL(annotations, MDField, );
6646#undef VISIT_MD_FIELDS
6650 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6651 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6652 declaration.Val, templateParams.Val,
align.Val,
6664bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6665#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6666 REQUIRED(scope, MDField, ( false)); \
6667 OPTIONAL(name, MDStringField, ); \
6668 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6669 OPTIONAL(file, MDField, ); \
6670 OPTIONAL(line, LineField, ); \
6671 OPTIONAL(type, MDField, ); \
6672 OPTIONAL(flags, DIFlagField, ); \
6673 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6674 OPTIONAL(annotations, MDField, );
6676#undef VISIT_MD_FIELDS
6679 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6680 type.Val, arg.Val, flags.Val,
align.Val,
6687bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6688#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6689 REQUIRED(scope, MDField, ( false)); \
6690 REQUIRED(name, MDStringField, ); \
6691 REQUIRED(file, MDField, ); \
6692 REQUIRED(line, LineField, ); \
6693 OPTIONAL(column, ColumnField, ); \
6694 OPTIONAL(isArtificial, MDBoolField, ); \
6695 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6697#undef VISIT_MD_FIELDS
6699 std::optional<unsigned> CoroSuspendIdx =
6700 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6704 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6705 column.Val, isArtificial.Val, CoroSuspendIdx));
6711bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6724 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6733 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6734 Lex.getStrVal() +
"'");
6737 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6738 return tokError(
"expected unsigned integer");
6740 auto &
U = Lex.getAPSIntVal();
6742 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6756bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6758 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6761 return parseDIExpressionBody(Result, IsDistinct);
6766bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6767 assert(PFS &&
"Expected valid function state");
6778 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6792bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6794#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6795 REQUIRED(var, MDField, ); \
6796 REQUIRED(expr, MDField, );
6798#undef VISIT_MD_FIELDS
6801 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6808bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6809#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6810 OPTIONAL(name, MDStringField, ); \
6811 OPTIONAL(file, MDField, ); \
6812 OPTIONAL(line, LineField, ); \
6813 OPTIONAL(setter, MDStringField, ); \
6814 OPTIONAL(getter, MDStringField, ); \
6815 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6816 OPTIONAL(type, MDField, );
6818#undef VISIT_MD_FIELDS
6821 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6822 setter.Val, attributes.Val, type.Val));
6829bool LLParser::parseDIProperty(
MDNode *&Result,
bool IsDistinct) {
6830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6831 OPTIONAL(name, MDStringField, ); \
6832 OPTIONAL(file, MDField, ); \
6833 OPTIONAL(line, LineField, ); \
6834 OPTIONAL(type, MDField, ); \
6835 OPTIONAL(backing_storage, MDField, );
6837#undef VISIT_MD_FIELDS
6840 type.Val, backing_storage.Val));
6847bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6848#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6849 REQUIRED(tag, DwarfTagField, ); \
6850 REQUIRED(scope, MDField, ); \
6851 OPTIONAL(entity, MDField, ); \
6852 OPTIONAL(file, MDField, ); \
6853 OPTIONAL(line, LineField, ); \
6854 OPTIONAL(name, MDStringField, ); \
6855 OPTIONAL(elements, MDField, );
6857#undef VISIT_MD_FIELDS
6860 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6861 line.Val,
name.Val, elements.Val));
6865#undef PARSE_MD_FIELD
6877bool LLParser::parseMetadataAsValue(
Value *&
V, PerFunctionState &PFS) {
6880 if (parseMetadata(MD, &PFS))
6891bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6892 PerFunctionState *PFS) {
6895 if (parseType(Ty, TypeMsg, Loc))
6898 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6901 if (parseValue(Ty,
V, PFS))
6916bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6920 if (Lex.getStrVal() ==
"DIArgList") {
6922 if (parseDIArgList(AL, PFS))
6928 if (parseSpecializedMDNode(
N)) {
6938 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6948 if (parseMDString(S))
6958 if (parseMDNodeTail(
N))
6969 PerFunctionState *PFS) {
6971 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6976 return error(
ID.Loc,
"invalid use of function-local name");
6977 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6978 return V ==
nullptr;
6981 return error(
ID.Loc,
"invalid use of function-local name");
6982 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6983 return V ==
nullptr;
6986 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6990 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6995 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6998 return V ==
nullptr;
7000 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
7003 return V ==
nullptr;
7006 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
7009 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
7014 return error(
ID.Loc,
"floating point constant invalid for type");
7020 bool IsSNAN = ID.APFloatVal.isSignaling();
7023 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7025 else if (Ty->isBFloatTy())
7026 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7028 else if (Ty->isFloatTy())
7029 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7035 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7036 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7037 ID.APFloatVal.isNegative(), &Payload);
7040 V = ConstantFP::get(Context,
ID.APFloatVal);
7042 if (
V->getType() != Ty)
7043 return error(
ID.Loc,
"floating point constant does not have type '" +
7049 return error(
ID.Loc,
"null must be a pointer type");
7055 return error(
ID.Loc,
"invalid type for undef constant");
7060 return error(
ID.Loc,
"invalid empty array initializer");
7066 return error(
ID.Loc,
"invalid type for null constant");
7069 return error(
ID.Loc,
"invalid type for null constant");
7074 return error(
ID.Loc,
"invalid type for none constant");
7080 return error(
ID.Loc,
"invalid type for poison constant");
7084 if (
ID.ConstantVal->getType() != Ty)
7085 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7092 return error(
ID.Loc,
"vector constant must have vector type");
7094 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7096 "' but expected '" +
7104 if (
ST->getNumElements() !=
ID.UIntVal)
7106 "initializer with struct type has wrong # elements");
7108 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
7111 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
7112 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
7115 "element " + Twine(i) +
7116 " of struct initializer doesn't match struct element type");
7119 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
7121 return error(
ID.Loc,
"constant expression type mismatch");
7130 auto Loc = Lex.getLoc();
7131 if (parseValID(ID,
nullptr, Ty))
7144 if (convertValIDToValue(Ty, ID,
V,
nullptr))
7154 return error(Loc,
"expected a constant value");
7158bool LLParser::parseValue(
Type *Ty,
Value *&
V, PerFunctionState *PFS) {
7162 FileLoc
Start = getTokLineColumnPos();
7163 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID,
V, PFS);
7164 if (!Ret && ParserContext) {
7165 FileLoc
End = getPrevTokEndLineColumnPos();
7166 ParserContext->addValueReferenceAtLocation(
V, FileLocRange(Start,
End));
7171bool LLParser::parseTypeAndValue(
Value *&
V, PerFunctionState *PFS) {
7173 return parseType(Ty) || parseValue(Ty,
V, PFS);
7176bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7177 PerFunctionState &PFS) {
7180 if (parseTypeAndValue(
V, PFS))
7183 return error(Loc,
"expected a basic block");
7192 if (!Name.starts_with(
"llvm.dbg."))
7195 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7196 FnID == Intrinsic::dbg_assign;
7204bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7205 unsigned &FunctionNumber,
7208 LocTy LinkageLoc = Lex.getLoc();
7210 unsigned Visibility;
7211 unsigned DLLStorageClass;
7213 AttrBuilder RetAttrs(M->getContext());
7216 Type *RetType =
nullptr;
7217 LocTy RetTypeLoc = Lex.getLoc();
7218 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7220 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7221 parseType(RetType, RetTypeLoc,
true ))
7230 return error(LinkageLoc,
"invalid linkage for function definition");
7240 return error(LinkageLoc,
"invalid linkage for function declaration");
7244 return error(LinkageLoc,
"invalid function linkage type");
7248 return error(LinkageLoc,
7249 "symbol with local linkage must have default visibility");
7252 return error(LinkageLoc,
7253 "symbol with local linkage cannot have a DLL storage class");
7256 return error(RetTypeLoc,
"invalid function return type");
7258 LocTy NameLoc = Lex.getLoc();
7260 std::string FunctionName;
7262 FunctionName = Lex.getStrVal();
7264 FunctionNumber = Lex.getUIntVal();
7265 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7269 return tokError(
"expected function name");
7275 return tokError(
"expected '(' in function argument list");
7279 AttrBuilder FuncAttrs(M->getContext());
7280 std::vector<unsigned> FwdRefAttrGrps;
7283 std::string Partition;
7287 unsigned AddrSpace = 0;
7293 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7294 parseOptionalUnnamedAddr(UnnamedAddr) ||
7295 parseOptionalProgramAddrSpace(AddrSpace) ||
7296 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7300 parseOptionalComdat(FunctionName,
C) ||
7301 parseOptionalAlignment(Alignment) ||
7302 parseOptionalPrefAlignment(PrefAlignment) ||
7303 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7307 parseGlobalTypeAndValue(PersonalityFn)))
7310 if (FuncAttrs.contains(Attribute::Builtin))
7311 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7314 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7316 FuncAttrs.removeAttribute(Attribute::Alignment);
7321 std::vector<Type*> ParamTypeList;
7324 for (
const ArgInfo &Arg : ArgList) {
7325 ParamTypeList.push_back(Arg.Ty);
7326 Attrs.push_back(Arg.Attrs);
7333 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7334 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7340 GlobalValue *FwdFn =
nullptr;
7341 if (!FunctionName.empty()) {
7344 auto FRVI = ForwardRefVals.find(FunctionName);
7345 if (FRVI != ForwardRefVals.end()) {
7346 FwdFn = FRVI->second.first;
7348 return error(FRVI->second.second,
7349 "invalid forward reference to "
7352 "' with wrong type: "
7356 ForwardRefVals.erase(FRVI);
7357 }
else if ((Fn = M->getFunction(FunctionName))) {
7359 return error(NameLoc,
7360 "invalid redefinition of function '" + FunctionName +
"'");
7361 }
else if (M->getNamedValue(FunctionName)) {
7362 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7368 if (FunctionNumber == (
unsigned)-1)
7369 FunctionNumber = NumberedVals.getNext();
7373 auto I = ForwardRefValIDs.find(FunctionNumber);
7374 if (
I != ForwardRefValIDs.end()) {
7375 FwdFn =
I->second.first;
7377 return error(NameLoc,
"type of definition and forward reference of '@" +
7378 Twine(FunctionNumber) +
7383 ForwardRefValIDs.erase(
I);
7392 if (FunctionName.empty())
7393 NumberedVals.add(FunctionNumber, Fn);
7409 if (!
GC.empty()) Fn->
setGC(GC);
7412 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7416 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7417 if (ParserContext && ArgList[i].IdentLoc)
7418 ParserContext->addInstructionOrArgumentLocation(
7419 &*ArgIt, ArgList[i].IdentLoc.value());
7421 if (ArgList[i].
Name.empty())
continue;
7424 ArgIt->
setName(ArgList[i].Name);
7426 if (ArgIt->
getName() != ArgList[i].Name)
7427 return error(ArgList[i].Loc,
7428 "redefinition of argument '%" + ArgList[i].Name +
"'");
7441 if (FunctionName.empty()) {
7443 ID.UIntVal = FunctionNumber;
7446 ID.StrVal = FunctionName;
7448 auto Blocks = ForwardRefBlockAddresses.find(ID);
7449 if (Blocks != ForwardRefBlockAddresses.end())
7450 return error(Blocks->first.Loc,
7451 "cannot take blockaddress inside a declaration");
7455bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7457 if (FunctionNumber == -1) {
7459 ID.StrVal = std::string(F.getName());
7462 ID.UIntVal = FunctionNumber;
7465 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7466 if (Blocks == P.ForwardRefBlockAddresses.end())
7469 for (
const auto &
I : Blocks->second) {
7470 const ValID &BBID =
I.first;
7471 GlobalValue *GV =
I.second;
7474 "Expected local id or name");
7481 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7484 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7492 P.ForwardRefBlockAddresses.erase(Blocks);
7498bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
7499 ArrayRef<unsigned> UnnamedArgNums) {
7501 return tokError(
"expected '{' in function body");
7504 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7508 if (PFS.resolveForwardRefBlockAddresses())
7514 return tokError(
"function body requires at least one basic block");
7518 if (parseBasicBlock(PFS))
7522 if (parseUseListOrder(&PFS))
7529 return PFS.finishFunction();
7534bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7535 FileLoc BBStart = getTokLineColumnPos();
7540 LocTy NameLoc = Lex.getLoc();
7542 Name = Lex.getStrVal();
7545 NameID = Lex.getUIntVal();
7549 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7553 std::string NameStr;
7558 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7559 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7566 if (SeenOldDbgInfoFormat)
7567 return error(Lex.getLoc(),
"debug record should not appear in a module "
7568 "containing debug info intrinsics");
7569 SeenNewDbgInfoFormat =
true;
7573 if (parseDebugRecord(DR, PFS))
7575 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7578 FileLoc InstStart = getTokLineColumnPos();
7581 LocTy NameLoc = Lex.getLoc();
7586 NameID = Lex.getUIntVal();
7588 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7591 NameStr = Lex.getStrVal();
7593 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7597 switch (parseInstruction(Inst, BB, PFS)) {
7600 case InstError:
return true;
7607 if (parseInstructionMetadata(*Inst))
7610 case InstExtraComma:
7615 if (parseInstructionMetadata(*Inst))
7621 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7625 for (DbgRecordPtr &DR : TrailingDbgRecord)
7627 TrailingDbgRecord.clear();
7628 if (ParserContext) {
7629 ParserContext->addInstructionOrArgumentLocation(
7630 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7635 ParserContext->addBlockLocation(
7636 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7638 assert(TrailingDbgRecord.empty() &&
7639 "All debug values should have been attached to an instruction.");
7648bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7651 LocTy DVRLoc = Lex.getLoc();
7653 return error(DVRLoc,
"expected debug record type here");
7654 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7655 .Case(
"declare", RecordKind::ValueKind)
7656 .Case(
"value", RecordKind::ValueKind)
7657 .Case(
"assign", RecordKind::ValueKind)
7658 .Case(
"label", RecordKind::LabelKind)
7659 .Case(
"declare_value", RecordKind::ValueKind);
7668 if (parseMDNode(Label))
7673 if (parseMDNode(DbgLoc))
7678 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7682 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7683 .Case(
"declare", LocType::Declare)
7684 .Case(
"value", LocType::Value)
7685 .Case(
"assign", LocType::Assign)
7686 .Case(
"declare_value", LocType::DeclareValue);
7694 if (parseMetadata(ValLocMD, &PFS))
7701 if (parseMDNode(Variable))
7708 if (parseMDNode(Expression))
7714 MDNode *AssignID =
nullptr;
7715 Metadata *AddressLocation =
nullptr;
7716 MDNode *AddressExpression =
nullptr;
7719 if (parseMDNode(AssignID))
7725 if (parseMetadata(AddressLocation, &PFS))
7731 if (parseMDNode(AddressExpression))
7745 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7747 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7756int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7757 PerFunctionState &PFS) {
7760 return tokError(
"found end of file when expecting more instructions");
7761 LocTy Loc = Lex.getLoc();
7762 unsigned KeywordVal = Lex.getUIntVal();
7767 return error(Loc,
"expected instruction opcode");
7771 return parseRet(Inst, BB, PFS);
7773 return parseBr(Inst, PFS);
7775 return parseSwitch(Inst, PFS);
7777 return parseIndirectBr(Inst, PFS);
7779 return parseInvoke(Inst, PFS);
7781 return parseResume(Inst, PFS);
7783 return parseCleanupRet(Inst, PFS);
7785 return parseCatchRet(Inst, PFS);
7787 return parseCatchSwitch(Inst, PFS);
7789 return parseCatchPad(Inst, PFS);
7791 return parseCleanupPad(Inst, PFS);
7793 return parseCallBr(Inst, PFS);
7796 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7797 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7813 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7825 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7826 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7840 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7848 return parseArithmetic(Inst, PFS, KeywordVal,
7852 if (parseLogical(Inst, PFS, KeywordVal))
7860 return parseLogical(Inst, PFS, KeywordVal);
7863 if (parseCompare(Inst, PFS, KeywordVal))
7870 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7871 int Res = parseCompare(Inst, PFS, KeywordVal);
7881 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7883 bool Res = parseCast(Inst, PFS, KeywordVal);
7893 bool Res = parseCast(Inst, PFS, KeywordVal);
7905 if (parseCast(Inst, PFS, KeywordVal))
7914 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7915 if (parseCast(Inst, PFS, KeywordVal))
7928 return parseCast(Inst, PFS, KeywordVal);
7932 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7933 if (parseCast(Inst, PFS, KeywordVal))
7942 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7943 int Res = parseSelect(Inst, PFS);
7949 return error(Loc,
"fast-math-flags specified for select without "
7950 "floating-point scalar or vector return type");
7957 return parseVAArg(Inst, PFS);
7959 return parseExtractElement(Inst, PFS);
7961 return parseInsertElement(Inst, PFS);
7963 return parseShuffleVector(Inst, PFS);
7965 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7966 int Res = parsePHI(Inst, PFS);
7972 return error(Loc,
"fast-math-flags specified for phi without "
7973 "floating-point scalar or vector return type");
7980 return parseLandingPad(Inst, PFS);
7982 return parseFreeze(Inst, PFS);
7984 return parseBitInsert(Inst, PFS);
7986 return parseBitExtract(Inst, PFS);
7998 return parseAlloc(Inst, PFS);
8000 return parseLoad(Inst, PFS);
8002 return parseStore(Inst, PFS);
8004 return parseCmpXchg(Inst, PFS);
8006 return parseAtomicRMW(Inst, PFS);
8008 return parseFence(Inst, PFS);
8010 return parseGetElementPtr(Inst, PFS);
8012 return parseExtractValue(Inst, PFS);
8014 return parseInsertValue(Inst, PFS);
8019bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
8020 if (
Opc == Instruction::FCmp) {
8021 switch (Lex.getKind()) {
8023 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
8042 switch (Lex.getKind()) {
8044 return tokError(
"expected icmp predicate (e.g. 'eq')");
8068bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8069 PerFunctionState &PFS) {
8070 SMLoc TypeLoc = Lex.getLoc();
8072 if (parseType(Ty,
true ))
8075 Type *ResType = PFS.getFunction().getReturnType();
8079 return error(TypeLoc,
"value doesn't match function result type '" +
8087 if (parseValue(Ty, RV, PFS))
8091 return error(TypeLoc,
"value doesn't match function result type '" +
8101bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8105 if (parseTypeAndValue(Op0, Loc, PFS))
8114 return error(Loc,
"branch condition must have 'i1' type");
8116 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
8117 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8118 parseToken(
lltok::comma,
"expected ',' after true destination") ||
8119 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8131bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8132 LocTy CondLoc, BBLoc;
8135 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
8136 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
8137 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8141 if (!
Cond->getType()->isIntegerTy())
8142 return error(CondLoc,
"switch condition must have integer type");
8145 SmallPtrSet<Value*, 32> SeenCases;
8151 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8152 parseToken(
lltok::comma,
"expected ',' after case value") ||
8153 parseTypeAndBasicBlock(DestBB, PFS))
8156 if (!SeenCases.
insert(Constant).second)
8157 return error(CondLoc,
"duplicate case value in switch");
8159 return error(CondLoc,
"case value is not a constant integer");
8167 for (
const auto &[OnVal, Dest] :
Table)
8168 SI->addCase(OnVal, Dest);
8176bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8179 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8180 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8184 if (!
Address->getType()->isPointerTy())
8185 return error(AddrLoc,
"indirectbr address must have pointer type");
8188 SmallVector<BasicBlock*, 16> DestList;
8192 if (parseTypeAndBasicBlock(DestBB, PFS))
8197 if (parseTypeAndBasicBlock(DestBB, PFS))
8203 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8207 for (BasicBlock *Dest : DestList)
8217 FunctionType *&FuncTy) {
8223 for (
const ParamInfo &Arg : ArgList)
8237bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8238 LocTy CallLoc = Lex.getLoc();
8239 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8240 std::vector<unsigned> FwdRefAttrGrps;
8243 unsigned InvokeAddrSpace;
8244 Type *RetType =
nullptr;
8251 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8252 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8253 parseType(RetType, RetTypeLoc,
true ) ||
8254 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8255 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8257 parseOptionalOperandBundles(BundleList, PFS) ||
8259 parseTypeAndBasicBlock(NormalBB, PFS) ||
8261 parseTypeAndBasicBlock(UnwindBB, PFS))
8268 if (resolveFunctionType(RetType, ArgList, Ty))
8269 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8275 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8280 SmallVector<Value *, 8>
Args;
8287 for (
const ParamInfo &Arg : ArgList) {
8288 Type *ExpectedTy =
nullptr;
8291 }
else if (!Ty->isVarArg()) {
8292 return error(Arg.Loc,
"too many arguments specified");
8295 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8296 return error(Arg.Loc,
"argument is not of expected type '" +
8298 Args.push_back(Arg.V);
8303 return error(CallLoc,
"not enough parameters specified for call");
8312 II->setCallingConv(
CC);
8313 II->setAttributes(PAL);
8314 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8321bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8323 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8331bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8332 PerFunctionState &PFS) {
8333 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8338 if (!
Args.empty() &&
8339 parseToken(
lltok::comma,
"expected ',' in argument list"))
8344 Type *ArgTy =
nullptr;
8345 if (parseType(ArgTy, ArgLoc))
8350 if (parseMetadataAsValue(
V, PFS))
8353 if (parseValue(ArgTy,
V, PFS))
8365bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8366 Value *CleanupPad =
nullptr;
8368 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8383 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8394bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8395 Value *CatchPad =
nullptr;
8397 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8404 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8405 parseTypeAndBasicBlock(BB, PFS))
8414bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8422 return tokError(
"expected scope value for catchswitch");
8427 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8433 if (parseTypeAndBasicBlock(DestBB, PFS))
8435 Table.push_back(DestBB);
8438 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8441 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8449 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8455 for (BasicBlock *DestBB :
Table)
8456 CatchSwitch->addHandler(DestBB);
8463bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8464 Value *CatchSwitch =
nullptr;
8470 return tokError(
"expected scope value for catchpad");
8475 SmallVector<Value *, 8>
Args;
8476 if (parseExceptionArgs(Args, PFS))
8485bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8486 Value *ParentPad =
nullptr;
8493 return tokError(
"expected scope value for cleanuppad");
8498 SmallVector<Value *, 8>
Args;
8499 if (parseExceptionArgs(Args, PFS))
8515bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8516 unsigned Opc,
bool IsFP) {
8518 if (parseTypeAndValue(
LHS, Loc, PFS))
8525 return error(Loc,
"invalid operand type for instruction");
8535bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8536 LocTy CallLoc = Lex.getLoc();
8537 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8538 std::vector<unsigned> FwdRefAttrGrps;
8541 Type *RetType =
nullptr;
8548 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8549 parseType(RetType, RetTypeLoc,
true ) ||
8550 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8551 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8553 parseOptionalOperandBundles(BundleList, PFS) ||
8555 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8560 SmallVector<BasicBlock *, 16> IndirectDests;
8564 if (parseTypeAndBasicBlock(DestBB, PFS))
8569 if (parseTypeAndBasicBlock(DestBB, PFS))
8575 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8582 if (resolveFunctionType(RetType, ArgList, Ty))
8583 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8594 SmallVector<Value *, 8>
Args;
8601 for (
const ParamInfo &Arg : ArgList) {
8602 Type *ExpectedTy =
nullptr;
8605 }
else if (!Ty->isVarArg()) {
8606 return error(Arg.Loc,
"too many arguments specified");
8609 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8610 return error(Arg.Loc,
"argument is not of expected type '" +
8612 Args.push_back(Arg.V);
8617 return error(CallLoc,
"not enough parameters specified for call");
8629 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8643bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8644 unsigned Opc,
bool IsFP) {
8646 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8647 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8655 return error(Loc,
"invalid operand type for instruction");
8663bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8666 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8667 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8673 "instruction requires integer or integer vector operands");
8682bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8688 if (parseCmpPredicate(
Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8689 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8693 if (
Opc == Instruction::FCmp) {
8695 return error(Loc,
"fcmp requires floating point operands");
8698 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8701 return error(Loc,
"icmp requires integer operands");
8713bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8717 Type *DestTy =
nullptr;
8718 if (parseTypeAndValue(
Op, Loc, PFS) ||
8719 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8724 return error(Loc,
"invalid cast opcode for cast from '" +
8733bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8735 Value *Op0, *Op1, *Op2;
8736 if (parseTypeAndValue(Op0, Loc, PFS) ||
8737 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8738 parseTypeAndValue(Op1, PFS) ||
8739 parseToken(
lltok::comma,
"expected ',' after select value") ||
8740 parseTypeAndValue(Op2, PFS))
8744 return error(Loc, Reason);
8752bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8754 Type *EltTy =
nullptr;
8756 if (parseTypeAndValue(
Op, PFS) ||
8757 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8758 parseType(EltTy, TypeLoc))
8762 return error(TypeLoc,
"va_arg requires operand with first class type");
8764 Inst =
new VAArgInst(
Op, EltTy);
8770bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8773 if (parseTypeAndValue(Op0, Loc, PFS) ||
8774 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8775 parseTypeAndValue(Op1, PFS))
8779 return error(Loc,
"invalid extractelement operands");
8787bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8789 Value *Op0, *Op1, *Op2;
8790 if (parseTypeAndValue(Op0, Loc, PFS) ||
8791 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8792 parseTypeAndValue(Op1, PFS) ||
8793 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8794 parseTypeAndValue(Op2, PFS))
8798 return error(Loc,
"invalid insertelement operands");
8806bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
8810 if (parseType(Ty, Loc) ||
8811 parseToken(
lltok::comma,
"expected ',' after bitextract type") ||
8812 parseTypeAndValue(Op0, Loc, PFS) ||
8813 parseToken(
lltok::comma,
"expected ',' after bitextract source value") ||
8814 parseTypeAndValue(Op1, PFS))
8818 return error(Loc, Reason);
8826bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
8828 Value *Op0, *Op1, *Op2;
8829 if (parseTypeAndValue(Op0, Loc, PFS) ||
8830 parseToken(
lltok::comma,
"expected ',' after bitinsert source value") ||
8831 parseTypeAndValue(Op1, PFS) ||
8832 parseToken(
lltok::comma,
"expected ',' after bitinsert insert value") ||
8833 parseTypeAndValue(Op2, PFS))
8837 return error(Loc, Reason);
8845bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8847 Value *Op0, *Op1, *Op2;
8848 if (parseTypeAndValue(Op0, Loc, PFS) ||
8849 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8850 parseTypeAndValue(Op1, PFS) ||
8851 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8852 parseTypeAndValue(Op2, PFS))
8856 return error(Loc,
"invalid shufflevector operands");
8858 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8864int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8868 if (parseType(Ty, TypeLoc))
8872 return error(TypeLoc,
"phi node must have first class type");
8875 bool AteExtraComma =
false;
8887 AteExtraComma =
true;
8891 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8892 parseValue(Ty, Op0, PFS) ||
8893 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8902 for (
const auto &[Val, BB] : PHIVals)
8905 return AteExtraComma ? InstExtraComma : InstNormal;
8914bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8917 if (parseType(Ty, TyLoc))
8930 return tokError(
"expected 'catch' or 'filter' clause type");
8934 if (parseTypeAndValue(
V, VLoc, PFS))
8941 return error(VLoc,
"'catch' clause has an invalid type");
8944 return error(VLoc,
"'filter' clause has an invalid type");
8949 return error(VLoc,
"clause argument must be a constant");
8953 Inst = LP.release();
8959bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8962 if (parseTypeAndValue(
Op, Loc, PFS))
8965 Inst =
new FreezeInst(
Op);
8978bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8980 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8981 std::vector<unsigned> FwdRefAttrGrps;
8983 unsigned CallAddrSpace;
8985 Type *RetType =
nullptr;
8990 LocTy CallLoc = Lex.getLoc();
8994 "expected 'tail call', 'musttail call', or 'notail call'"))
8997 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8999 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
9000 parseOptionalProgramAddrSpace(CallAddrSpace) ||
9001 parseType(RetType, RetTypeLoc,
true ) ||
9002 parseValID(CalleeID, &PFS) ||
9004 PFS.getFunction().isVarArg()) ||
9005 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
9006 parseOptionalOperandBundles(BundleList, PFS))
9013 if (resolveFunctionType(RetType, ArgList, Ty))
9014 return error(RetTypeLoc,
"Invalid result type for LLVM function");
9020 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
9027 SmallVector<Value*, 8>
Args;
9033 for (
const ParamInfo &Arg : ArgList) {
9034 Type *ExpectedTy =
nullptr;
9037 }
else if (!Ty->isVarArg()) {
9038 return error(Arg.Loc,
"too many arguments specified");
9041 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9042 return error(Arg.Loc,
"argument is not of expected type '" +
9044 Args.push_back(Arg.V);
9045 Attrs.push_back(Arg.Attrs);
9049 return error(CallLoc,
"not enough parameters specified for call");
9062 return error(CallLoc,
"fast-math-flags specified for call without "
9063 "floating-point scalar or vector return type");
9070 if (SeenNewDbgInfoFormat) {
9072 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
9073 "using non-intrinsic debug info");
9075 SeenOldDbgInfoFormat =
true;
9078 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9090int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9092 LocTy SizeLoc, TyLoc, ASLoc;
9094 unsigned AddrSpace = 0;
9097 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9098 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9100 if (parseType(Ty, TyLoc))
9104 return error(TyLoc,
"invalid type for alloca");
9106 bool AteExtraComma =
false;
9108 if (Lex.getKind() == lltok::kw_align) {
9109 if (parseOptionalAlignment(Alignment))
9111 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9114 ASLoc = Lex.getLoc();
9115 if (parseOptionalAddrSpace(AddrSpace))
9118 AteExtraComma =
true;
9120 if (parseTypeAndValue(
Size, SizeLoc, PFS))
9123 if (Lex.getKind() == lltok::kw_align) {
9124 if (parseOptionalAlignment(Alignment))
9126 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9129 ASLoc = Lex.getLoc();
9130 if (parseOptionalAddrSpace(AddrSpace))
9133 AteExtraComma =
true;
9139 if (
Size && !
Size->getType()->isIntegerTy())
9140 return error(SizeLoc,
"element count must have integer type");
9142 if (!Alignment && !Ty->
isSized())
9143 return error(TyLoc,
"Cannot allocate unsized type");
9145 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9146 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
9150 return AteExtraComma ? InstExtraComma : InstNormal;
9157int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9160 bool AteExtraComma =
false;
9170 bool isVolatile =
false;
9176 bool IsElementwise =
false;
9178 IsElementwise =
true;
9183 LocTy ExplicitTypeLoc = Lex.getLoc();
9184 if (parseType(Ty) ||
9185 parseToken(
lltok::comma,
"expected comma after load's type") ||
9186 parseTypeAndValue(Val, Loc, PFS) ||
9187 parseScopeAndOrdering(
isAtomic, SSID, Ordering) ||
9188 parseOptionalCommaAlign(Alignment, AteExtraComma))
9192 return error(Loc,
"load operand must be a pointer to a first class type");
9195 return error(Loc,
"elementwise load must be atomic");
9198 return error(ExplicitTypeLoc,
9199 "atomic elementwise load operand must have fixed vector type");
9202 return error(Loc,
"atomic load must have explicit non-zero alignment");
9206 return error(Loc,
"atomic load cannot use Release ordering");
9209 "atomic elementwise load cannot be sequentially consistent");
9211 if (!Alignment && !Ty->
isSized())
9212 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9214 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9215 Inst =
new LoadInst(Ty, Val,
"",
9217 SSID, IsElementwise},
9219 return AteExtraComma ? InstExtraComma : InstNormal;
9227int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9231 bool AteExtraComma =
false;
9241 bool isVolatile =
false;
9247 bool IsElementwise =
false;
9249 IsElementwise =
true;
9253 if (parseTypeAndValue(Val, Loc, PFS) ||
9254 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9255 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9256 parseScopeAndOrdering(
isAtomic, SSID, Ordering) ||
9257 parseOptionalCommaAlign(Alignment, AteExtraComma))
9261 return error(PtrLoc,
"store operand must be a pointer");
9263 return error(Loc,
"store operand must be a first class value");
9265 return error(Loc,
"atomic store must have explicit non-zero alignment");
9268 return error(Loc,
"atomic store cannot use Acquire ordering");
9271 return error(Loc,
"elementwise store must be atomic");
9275 Loc,
"atomic elementwise store operand must have fixed vector type");
9279 "atomic elementwise store cannot be sequentially consistent");
9282 return error(Loc,
"storing unsized types is not allowed");
9286 Inst =
new StoreInst(Val, Ptr,
9288 SSID, IsElementwise},
9290 return AteExtraComma ? InstExtraComma : InstNormal;
9297int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9299 bool AteExtraComma =
false;
9303 bool isVolatile =
false;
9304 bool isWeak =
false;
9313 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9314 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9315 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9316 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9317 parseTypeAndValue(New, NewLoc, PFS) ||
9318 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9319 parseOrdering(FailureOrdering) ||
9320 parseOptionalCommaAlign(Alignment, AteExtraComma))
9324 return tokError(
"invalid cmpxchg success ordering");
9326 return tokError(
"invalid cmpxchg failure ordering");
9328 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9329 if (
Cmp->getType() !=
New->getType())
9330 return error(NewLoc,
"compare value and new value type do not match");
9331 if (!
New->getType()->isFirstClassType())
9332 return error(NewLoc,
"cmpxchg operand must be a first class value");
9334 const Align DefaultAlignment(
9335 PFS.getFunction().getDataLayout().getTypeStoreSize(
9338 AtomicCmpXchgInst *CXI =
9339 new AtomicCmpXchgInst(Ptr, Cmp, New,
Alignment.value_or(DefaultAlignment),
9340 SuccessOrdering, FailureOrdering, SSID);
9345 return AteExtraComma ? InstExtraComma : InstNormal;
9352int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9354 bool AteExtraComma =
false;
9358 bool IsElementwise =
false;
9366 IsElementwise =
true;
9368 switch (Lex.getKind()) {
9370 return tokError(
"expected binary operation in atomicrmw");
9429 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9430 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9431 parseTypeAndValue(Val, ValLoc, PFS) ||
9432 parseScopeAndOrdering(
true , SSID, Ordering) ||
9433 parseOptionalCommaAlign(Alignment, AteExtraComma))
9437 return tokError(
"atomicrmw cannot be unordered");
9439 return tokError(
"atomicrmw elementwise cannot be sequentially consistent");
9441 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9443 return error(ValLoc,
"atomicrmw operand may not be scalable");
9446 if (IsElementwise) {
9448 return error(ValLoc,
9449 "atomicrmw elementwise operand must be a fixed vector type");
9458 " operand must be an integer type, a floating-point type, a "
9459 "pointer type, or a fixed vector of any of these types");
9463 return error(ValLoc,
"atomicrmw " +
9465 " operand must be a floating point or fixed "
9466 "vector of floating point type");
9473 " operand must be an integer or fixed vector of integer type");
9478 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9480 return error(ValLoc,
9481 "atomicrmw operand must have a power-of-two byte size");
9482 const Align DefaultAlignment(
9483 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9484 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9486 Ordering, SSID, IsElementwise);
9489 return AteExtraComma ? InstExtraComma : InstNormal;
9494int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9497 if (parseScopeAndOrdering(
true , SSID, Ordering))
9501 return tokError(
"fence cannot be unordered");
9503 return tokError(
"fence cannot be monotonic");
9505 Inst =
new FenceInst(Context, Ordering, SSID);
9511int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9512 Value *Ptr =
nullptr;
9513 Value *Val =
nullptr;
9529 if (parseType(Ty) ||
9530 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9531 parseTypeAndValue(Ptr, Loc, PFS))
9536 if (!BasePointerType)
9537 return error(Loc,
"base of getelementptr must be a pointer");
9539 SmallVector<Value*, 16> Indices;
9540 bool AteExtraComma =
false;
9543 ElementCount GEPWidth =
BaseType->isVectorTy()
9549 AteExtraComma =
true;
9552 if (parseTypeAndValue(Val, EltLoc, PFS))
9555 return error(EltLoc,
"getelementptr index must be an integer");
9558 ElementCount ValNumEl = ValVTy->getElementCount();
9562 "getelementptr vector index has a wrong number of elements");
9563 GEPWidth = ValNumEl;
9569 return error(Loc,
"base element of getelementptr must be sized");
9572 return error(Loc,
"invalid getelementptr indices");
9575 GEP->setNoWrapFlags(NW);
9576 return AteExtraComma ? InstExtraComma : InstNormal;
9581int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9583 SmallVector<unsigned, 4> Indices;
9585 if (parseTypeAndValue(Val, Loc, PFS) ||
9586 parseIndexList(Indices, AteExtraComma))
9590 return error(Loc,
"extractvalue operand must be aggregate type");
9593 return error(Loc,
"invalid indices for extractvalue");
9595 return AteExtraComma ? InstExtraComma : InstNormal;
9600int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9602 SmallVector<unsigned, 4> Indices;
9604 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9605 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9606 parseTypeAndValue(Val1, Loc1, PFS) ||
9607 parseIndexList(Indices, AteExtraComma))
9611 return error(Loc0,
"insertvalue operand must be aggregate type");
9615 return error(Loc0,
"invalid indices for insertvalue");
9616 if (IndexedType != Val1->
getType())
9617 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9621 return AteExtraComma ? InstExtraComma : InstNormal;
9632bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9647 if (parseMetadata(MD,
nullptr))
9652 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9658bool LLParser::sortUseListOrder(
Value *
V, ArrayRef<unsigned> Indexes,
9660 if (!
V->hasUseList())
9663 return error(Loc,
"value has no uses");
9665 unsigned NumUses = 0;
9666 SmallDenseMap<const Use *, unsigned, 16> Order;
9667 for (
const Use &U :
V->uses()) {
9668 if (++NumUses > Indexes.
size())
9670 Order[&
U] = Indexes[NumUses - 1];
9673 return error(Loc,
"value only has one use");
9674 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9676 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9678 V->sortUseList([&](
const Use &L,
const Use &R) {
9686bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9687 SMLoc Loc = Lex.getLoc();
9691 return tokError(
"expected non-empty list of uselistorder indexes");
9698 bool IsOrdered =
true;
9699 assert(Indexes.
empty() &&
"Expected empty order vector");
9702 if (parseUInt32(Index))
9707 Max = std::max(Max, Index);
9708 IsOrdered &= Index == Indexes.
size();
9716 if (Indexes.
size() < 2)
9717 return error(Loc,
"expected >= 2 uselistorder indexes");
9720 "expected distinct uselistorder indexes in range [0, size)");
9722 return error(Loc,
"expected uselistorder indexes to change the order");
9729bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9730 SMLoc Loc = Lex.getLoc();
9735 SmallVector<unsigned, 16> Indexes;
9736 if (parseTypeAndValue(
V, PFS) ||
9737 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9738 parseUseListOrderIndexes(Indexes))
9741 return sortUseListOrder(
V, Indexes, Loc);
9747bool LLParser::parseModuleEntry(
unsigned ID) {
9756 parseStringConstant(Path) ||
9764 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9765 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9766 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9767 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9768 parseUInt32(Hash[4]))
9775 auto ModuleEntry = Index->addModule(Path, Hash);
9776 ModuleIdMap[
ID] = ModuleEntry->first();
9783bool LLParser::parseTypeIdEntry(
unsigned ID) {
9792 parseStringConstant(Name))
9795 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9797 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9802 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9803 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9804 for (
auto TIDRef : FwdRefTIDs->second) {
9806 "Forward referenced type id GUID expected to be 0");
9809 ForwardRefTypeIds.erase(FwdRefTIDs);
9817bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9821 parseTypeTestResolution(TIS.
TTRes))
9826 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9843bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9852 parseStringConstant(Name))
9856 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9863 IdToIndexMapType IdToIndexMap;
9876 if (parseGVReference(VI, GVId))
9883 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9884 TI.push_back({
Offset, VI});
9892 for (
auto I : IdToIndexMap) {
9893 auto &Infos = ForwardRefValueInfos[
I.first];
9894 for (
auto P :
I.second) {
9896 "Forward referenced ValueInfo expected to be empty");
9897 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9907 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9908 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9909 for (
auto TIDRef : FwdRefTIDs->second) {
9911 "Forward referenced type id GUID expected to be 0");
9914 ForwardRefTypeIds.erase(FwdRefTIDs);
9926bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9934 switch (Lex.getKind()) {
9954 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9966 switch (Lex.getKind()) {
9981 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9994 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
10007bool LLParser::parseOptionalWpdResolutions(
10008 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10016 WholeProgramDevirtResolution WPDRes;
10020 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
10023 WPDResMap[
Offset] = WPDRes;
10040bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10048 switch (Lex.getKind()) {
10062 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
10068 switch (Lex.getKind()) {
10076 if (parseOptionalResByArg(WPDRes.
ResByArg))
10080 return error(Lex.getLoc(),
10081 "expected optional WholeProgramDevirtResolution field");
10098bool LLParser::parseOptionalResByArg(
10099 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10107 std::vector<uint64_t>
Args;
10108 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
10116 WholeProgramDevirtResolution::ByArg ByArg;
10117 switch (Lex.getKind()) {
10131 return error(Lex.getLoc(),
10132 "unexpected WholeProgramDevirtResolution::ByArg kind");
10138 switch (Lex.getKind()) {
10142 parseUInt64(ByArg.
Info))
10148 parseUInt32(ByArg.
Byte))
10154 parseUInt32(ByArg.
Bit))
10158 return error(Lex.getLoc(),
10159 "expected optional whole program devirt field");
10166 ResByArg[
Args] = ByArg;
10177bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10185 if (parseUInt64(Val))
10187 Args.push_back(Val);
10211bool LLParser::addGlobalValueToIndex(
10213 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10218 VI = Index->getOrInsertValueInfo(GUID);
10222 auto *GV = M->getNamedValue(Name);
10224 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10230 VI = Index->getOrInsertValueInfo(GV, GUID);
10234 "Need a source_filename to compute GUID for local");
10237 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10242 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10243 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10244 for (
auto VIRef : FwdRefVIs->second) {
10246 "Forward referenced ValueInfo expected to be empty");
10249 ForwardRefValueInfos.erase(FwdRefVIs);
10253 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10254 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10255 for (
auto AliaseeRef : FwdRefAliasees->second) {
10256 assert(!AliaseeRef.first->hasAliasee() &&
10257 "Forward referencing alias already has aliasee");
10258 assert(Summary &&
"Aliasee must be a definition");
10259 AliaseeRef.first->setAliasee(VI,
Summary.get());
10261 ForwardRefAliasees.erase(FwdRefAliasees);
10266 Index->addGlobalValueSummary(VI, std::move(Summary));
10269 if (ID == NumberedValueInfos.size())
10270 NumberedValueInfos.push_back(VI);
10273 if (ID > NumberedValueInfos.size())
10274 NumberedValueInfos.resize(ID + 1);
10275 NumberedValueInfos[
ID] =
VI;
10283bool LLParser::parseSummaryIndexFlags() {
10290 if (parseUInt64(Flags))
10293 Index->setFlags(Flags);
10299bool LLParser::parseBlockCount() {
10306 if (parseUInt64(BlockCount))
10309 Index->setBlockCount(BlockCount);
10317bool LLParser::parseCfiFunctions() {
10321 ? Index->cfiFunctionDefs()
10322 : Index->cfiFunctionDecls();
10334 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID) ||
10338 parseStringConstant(Name) ||
10351bool LLParser::parseGVEntry(
unsigned ID) {
10359 LocTy Loc = Lex.getLoc();
10362 switch (Lex.getKind()) {
10366 parseStringConstant(Name))
10372 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10376 return error(Lex.getLoc(),
"expected name or guid tag");
10399 switch (Lex.getKind()) {
10401 if (parseFunctionSummary(Name, GUID, ID))
10405 if (parseVariableSummary(Name, GUID, ID))
10409 if (parseAliasSummary(Name, GUID, ID))
10413 return error(Lex.getLoc(),
"expected summary type");
10431 LocTy Loc = Lex.getLoc();
10435 StringRef ModulePath;
10436 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10439 false,
false,
false,
10441 unsigned InstCount;
10443 FunctionSummary::TypeIdInfo TypeIdInfo;
10444 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10446 std::vector<CallsiteInfo> Callsites;
10447 std::vector<AllocInfo> Allocs;
10449 FunctionSummary::FFlags FFlags = {};
10452 parseModuleReference(ModulePath) ||
10453 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10456 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10461 switch (Lex.getKind()) {
10463 if (parseOptionalFFlags(FFlags))
10467 if (parseOptionalCalls(Calls))
10471 if (parseOptionalTypeIdInfo(TypeIdInfo))
10475 if (parseOptionalRefs(Refs))
10479 if (parseOptionalParamAccesses(ParamAccesses))
10483 if (parseOptionalAllocs(Allocs))
10487 if (parseOptionalCallsites(Callsites))
10491 return error(Lex.getLoc(),
"expected optional function summary field");
10498 auto FS = std::make_unique<FunctionSummary>(
10499 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10505 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10507 FS->setModulePath(ModulePath);
10509 return addGlobalValueToIndex(Name, GUID,
10511 std::move(FS), Loc);
10519 LocTy Loc = Lex.getLoc();
10523 StringRef ModulePath;
10524 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10527 false,
false,
false,
10529 GlobalVarSummary::GVarFlags GVarFlags(
false,
10537 parseModuleReference(ModulePath) ||
10538 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10540 parseGVarFlags(GVarFlags))
10545 switch (Lex.getKind()) {
10547 if (parseOptionalVTableFuncs(VTableFuncs))
10551 if (parseOptionalRefs(Refs))
10555 return error(Lex.getLoc(),
"expected optional variable summary field");
10563 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10565 GS->setModulePath(ModulePath);
10566 GS->setVTableFuncs(std::move(VTableFuncs));
10568 return addGlobalValueToIndex(Name, GUID,
10570 std::move(GS), Loc);
10579 LocTy Loc = Lex.getLoc();
10582 StringRef ModulePath;
10583 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10586 false,
false,
false,
10590 parseModuleReference(ModulePath) ||
10591 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10597 ValueInfo AliaseeVI;
10599 auto AS = std::make_unique<AliasSummary>(GVFlags);
10600 AS->setModulePath(ModulePath);
10603 if (parseGVReference(AliaseeVI, GVId))
10608 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10610 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10611 assert(Summary &&
"Aliasee must be a definition");
10612 AS->setAliasee(AliaseeVI, Summary);
10619 return addGlobalValueToIndex(Name, GUID,
10621 std::move(AS), Loc);
10626bool LLParser::parseFlag(
unsigned &Val) {
10627 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10628 return tokError(
"expected integer");
10629 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10645bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10649 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10655 switch (Lex.getKind()) {
10658 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10664 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10670 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10676 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10682 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10688 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10694 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10700 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10706 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10712 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10717 return error(Lex.getLoc(),
"expected function flag type");
10721 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10732bool LLParser::parseOptionalCalls(
10733 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10737 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10741 IdToIndexMapType IdToIndexMap;
10750 LocTy Loc = Lex.getLoc();
10752 if (parseGVReference(VI, GVId))
10756 unsigned RelBF = 0;
10757 unsigned HasTailCall =
false;
10758 unsigned HasIndirectCall =
false;
10762 switch (Lex.getKind()) {
10765 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10771 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10776 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10782 parseFlag(HasIndirectCall))
10786 return error(Lex.getLoc(),
10787 "expected hotness, relbf, tail, or indirect");
10794 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10796 VI, CalleeInfo(Hotness, HasTailCall, HasIndirectCall)});
10804 for (
auto I : IdToIndexMap) {
10805 auto &Infos = ForwardRefValueInfos[
I.first];
10806 for (
auto P :
I.second) {
10808 "Forward referenced ValueInfo expected to be empty");
10809 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10822 switch (Lex.getKind()) {
10826 case lltok::kw_cold:
10832 case lltok::kw_hot:
10839 return error(Lex.getLoc(),
"invalid call edge hotness");
10848bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10852 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10856 IdToIndexMapType IdToIndexMap;
10860 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10865 LocTy Loc = Lex.getLoc();
10867 if (parseGVReference(VI, GVId))
10880 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10881 VTableFuncs.push_back({
VI,
Offset});
10883 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10889 for (
auto I : IdToIndexMap) {
10890 auto &Infos = ForwardRefValueInfos[
I.first];
10891 for (
auto P :
I.second) {
10893 "Forward referenced ValueInfo expected to be empty");
10894 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10898 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10905bool LLParser::parseParamNo(
uint64_t &ParamNo) {
10907 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10913bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10916 auto ParseAPSInt = [&](
APSInt &Val) {
10918 return tokError(
"expected integer");
10919 Val = Lex.getAPSIntVal();
10921 Val.setIsSigned(
true);
10943bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10944 IdLocListType &IdLocList) {
10952 LocTy Loc = Lex.getLoc();
10953 if (parseGVReference(VI, GVId))
10957 IdLocList.emplace_back(GVId, Loc);
10960 parseParamNo(
Call.ParamNo) ||
10962 parseParamAccessOffset(
Call.Offsets))
10974bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10975 IdLocListType &IdLocList) {
10977 parseParamNo(
Param.ParamNo) ||
10979 parseParamAccessOffset(
Param.Use))
10988 FunctionSummary::ParamAccess::Call
Call;
10989 if (parseParamAccessCall(
Call, IdLocList))
11006bool LLParser::parseOptionalParamAccesses(
11007 std::vector<FunctionSummary::ParamAccess> &Params) {
11015 IdLocListType VContexts;
11016 size_t CallsNum = 0;
11018 FunctionSummary::ParamAccess ParamAccess;
11019 if (parseParamAccess(ParamAccess, VContexts))
11021 CallsNum += ParamAccess.
Calls.size();
11022 assert(VContexts.size() == CallsNum);
11024 Params.emplace_back(std::move(ParamAccess));
11032 IdLocListType::const_iterator ItContext = VContexts.begin();
11033 for (
auto &PA : Params) {
11034 for (
auto &
C : PA.Calls) {
11036 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
11037 ItContext->second);
11041 assert(ItContext == VContexts.end());
11048bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
11052 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
11056 struct ValueContext {
11061 std::vector<ValueContext> VContexts;
11065 VC.Loc = Lex.getLoc();
11066 if (parseGVReference(
VC.VI,
VC.GVId))
11068 VContexts.push_back(VC);
11074 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
11075 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11078 IdToIndexMapType IdToIndexMap;
11079 for (
auto &VC : VContexts) {
11084 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
11090 for (
auto I : IdToIndexMap) {
11091 auto &Infos = ForwardRefValueInfos[
I.first];
11092 for (
auto P :
I.second) {
11094 "Forward referenced ValueInfo expected to be empty");
11095 Infos.emplace_back(&Refs[
P.first],
P.second);
11109bool LLParser::parseOptionalTypeIdInfo(
11110 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11119 switch (Lex.getKind()) {
11121 if (parseTypeTests(TypeIdInfo.
TypeTests))
11145 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
11149 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11158bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11166 IdToIndexMapType IdToIndexMap;
11170 unsigned ID = Lex.getUIntVal();
11171 LocTy Loc = Lex.getLoc();
11175 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
11177 }
else if (parseUInt64(GUID))
11179 TypeTests.push_back(GUID);
11184 for (
auto I : IdToIndexMap) {
11185 auto &Ids = ForwardRefTypeIds[
I.first];
11186 for (
auto P :
I.second) {
11187 assert(TypeTests[
P.first] == 0 &&
11188 "Forward referenced type id GUID expected to be 0");
11189 Ids.emplace_back(&TypeTests[
P.first],
P.second);
11193 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11201bool LLParser::parseVFuncIdList(
11202 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11203 assert(Lex.getKind() == Kind);
11210 IdToIndexMapType IdToIndexMap;
11212 FunctionSummary::VFuncId VFuncId;
11213 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11215 VFuncIdList.push_back(VFuncId);
11223 for (
auto I : IdToIndexMap) {
11224 auto &Ids = ForwardRefTypeIds[
I.first];
11225 for (
auto P :
I.second) {
11226 assert(VFuncIdList[
P.first].GUID == 0 &&
11227 "Forward referenced type id GUID expected to be 0");
11228 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
11237bool LLParser::parseConstVCallList(
11239 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11240 assert(Lex.getKind() == Kind);
11247 IdToIndexMapType IdToIndexMap;
11249 FunctionSummary::ConstVCall ConstVCall;
11250 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11252 ConstVCallList.push_back(ConstVCall);
11260 for (
auto I : IdToIndexMap) {
11261 auto &Ids = ForwardRefTypeIds[
I.first];
11262 for (
auto P :
I.second) {
11263 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11264 "Forward referenced type id GUID expected to be 0");
11265 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11274bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11275 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11277 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11281 if (parseArgs(ConstVCall.
Args))
11293bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11294 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11304 unsigned ID = Lex.getUIntVal();
11305 LocTy Loc = Lex.getLoc();
11309 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11311 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11313 parseUInt64(VFuncId.
GUID))
11319 parseUInt64(VFuncId.
Offset) ||
11331bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11341 switch (Lex.getKind()) {
11348 assert(HasLinkage &&
"Linkage not optional in summary entry");
11355 parseOptionalVisibility(Flag);
11360 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11366 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11372 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11378 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11387 if (parseOptionalImportType(Lex.getKind(), IK))
11389 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11394 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11399 return error(Lex.getLoc(),
"expected gv flag type");
11413bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11421 auto ParseRest = [
this](
unsigned int &Val) {
11425 return parseFlag(Val);
11430 switch (Lex.getKind()) {
11431 case lltok::kw_readonly:
11432 if (ParseRest(Flag))
11436 case lltok::kw_writeonly:
11437 if (ParseRest(Flag))
11442 if (ParseRest(Flag))
11447 if (ParseRest(Flag))
11452 return error(Lex.getLoc(),
"expected gvar flag type");
11460bool LLParser::parseModuleReference(StringRef &ModulePath) {
11467 unsigned ModuleID = Lex.getUIntVal();
11468 auto I = ModuleIdMap.find(ModuleID);
11470 assert(
I != ModuleIdMap.end());
11471 ModulePath =
I->second;
11477bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11480 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11484 GVId = Lex.getUIntVal();
11486 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11488 VI = NumberedValueInfos[GVId];
11505bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11509 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11521 SmallVector<uint8_t> Versions;
11524 if (parseAllocType(
V))
11529 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11533 std::vector<MIBInfo> MIBs;
11534 if (parseMemProfs(MIBs))
11537 Allocs.push_back({Versions, MIBs});
11554bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11558 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11564 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11573 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11579 SmallVector<unsigned> StackIdIndices;
11584 if (parseUInt64(StackId))
11586 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11607bool LLParser::parseAllocType(uint8_t &
AllocType) {
11608 switch (Lex.getKind()) {
11621 case lltok::kw_cold:
11624 case lltok::kw_hot:
11628 return error(Lex.getLoc(),
"invalid alloc type");
11641bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11645 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11649 IdToIndexMapType IdToIndexMap;
11652 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11659 LocTy Loc = Lex.getLoc();
11661 if (parseGVReference(VI, GVId))
11665 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11671 SmallVector<unsigned> Clones;
11674 if (parseUInt32(
V))
11680 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11686 SmallVector<unsigned> StackIdIndices;
11691 if (parseUInt64(StackId))
11693 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11704 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11705 Callsites.push_back({
VI, Clones, StackIdIndices});
11713 for (
auto I : IdToIndexMap) {
11714 auto &Infos = ForwardRefValueInfos[
I.first];
11715 for (
auto P :
I.second) {
11717 "Forward referenced ValueInfo expected to be empty");
11718 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11722 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
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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")
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static uint64_t align(uint64_t Size)
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 bool blockCommentCrossesBoundary(SMLoc BeginLoc, SMLoc EndLoc, SMLoc BoundaryLoc)
Return whether skipped trivia contains a block comment that crosses the boundary between two metadata...
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static SmallVector< MemoryEffects::Location, 2 > keywordToLoc(lltok::Kind Tok)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
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 isAtomic(MachineBasicBlock::iterator I)
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)
SmallVector< MachineOperand, 4 > Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
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 scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
static SymbolRef::Type getType(const Symbol *Sym)
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
static constexpr const fltSemantics & IEEEdouble()
opStatus
IEEE-754R 7: Default exception handling.
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
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
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
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)
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
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 const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
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)
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
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 CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
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_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH 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 Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
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 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, bool ImplicitTrunc=false)
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, Constant *DeactivationSymbol)
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)
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
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)
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)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
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 eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the 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.
std::pair< key_type, mapped_type > value_type
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.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
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
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
LLVM_ABI bool parseMetadataDefinitions(SlotMapping &Slots, ArrayRef< SMLoc > DefinitionEnds)
LLVM_ABI 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 auto targetMemLocations()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
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 PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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 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.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
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().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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
Represent a constant reference to a string, i.e.
constexpr bool empty() const
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.
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 isByteTy() const
True if this is an instance of ByteType.
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)
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.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this 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 isAggregateType() const
Return true if the type is an aggregate 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.
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
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.
LLVM_ABI const fltSemantics & getFltSemantics() const
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 UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
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 getSourceLanguageName(StringRef SourceLanguageNameString)
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
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 IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
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.
@ 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).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ 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).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ 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.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ 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.
@ WASM_EmscriptenInvoke
For emscripten __invoke_* functions.
@ 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 * > OverloadTys={})
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 isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr bool isPacked(const T &...O)
@ System
Synchronized with respect to all concurrently executing threads.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ 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_wasm_emscripten_invokecc
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ 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.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
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.
DebugVariableAggregate VarID
A unique key that represents one instance of a debug variable.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeInstructionMetadata(Module &M)
Discover metadata used by instructions in this module, and apply the suitable upgrade.
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.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
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.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
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.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
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.
IRMemLocation
The locations at which a function might access memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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
@ NearestTiesToEven
roundTiesToEven.
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.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
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)
@ End
Run the machine verifier once, at the end of the pipeline.
bool capturesNothing(CaptureComponents CC)
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
std::vector< uint64_t > Args
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
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 NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
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.
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
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.
@ Speculative
Speculative devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.