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))
137 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
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();
546 if (UpgradeDebugInfo)
560 Slots->GlobalValues = std::move(NumberedVals);
561 Slots->MetadataNodes = std::move(NumberedMetadata);
562 for (
const auto &
I : NamedTypes)
563 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
564 for (
const auto &
I : NumberedTypes)
565 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
571bool LLParser::validateEndOfIndex() {
575 if (!ForwardRefValueInfos.empty())
576 return error(ForwardRefValueInfos.begin()->second.front().second,
577 "use of undefined summary '^" +
578 Twine(ForwardRefValueInfos.begin()->first) +
"'");
580 if (!ForwardRefAliasees.empty())
581 return error(ForwardRefAliasees.begin()->second.front().second,
582 "use of undefined summary '^" +
583 Twine(ForwardRefAliasees.begin()->first) +
"'");
585 if (!ForwardRefTypeIds.empty())
586 return error(ForwardRefTypeIds.begin()->second.front().second,
587 "use of undefined type id summary '^" +
588 Twine(ForwardRefTypeIds.begin()->first) +
"'");
602 std::string TentativeDLStr = M->getDataLayoutStr();
607 switch (Lex.getKind()) {
609 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
613 if (parseSourceFileName())
622 if (
auto LayoutOverride =
623 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
624 TentativeDLStr = *LayoutOverride;
630 M->setDataLayout(MaybeDL.
get());
634bool LLParser::parseTopLevelEntities() {
638 switch (Lex.getKind()) {
642 if (parseSummaryEntry())
646 if (parseSourceFileName())
656 switch (Lex.getKind()) {
658 return tokError(
"expected top-level entity");
669 if (parseModuleAsm())
673 if (parseUnnamedType())
677 if (parseNamedType())
681 if (parseUnnamedGlobal())
685 if (parseNamedGlobal())
690 if (parseStandaloneMetadata())
694 if (parseSummaryEntry())
698 if (parseNamedMetadata())
702 if (parseUnnamedAttrGrp())
706 if (parseUseListOrder())
718bool LLParser::parseModuleAsm() {
726 Module::GlobalAsmProperties Props;
730 SMLoc Loc = Lex.getLoc();
732 return error(Loc,
"expected property name followed by ':'");
734 Key = Lex.getStrVal();
737 if (parseStringConstant(
Value))
741 return error(Loc,
"unknown property name");
751 std::string AsmStrPart;
752 if (parseStringConstant(AsmStrPart))
754 AsmStr += AsmStrPart +
"\n";
757 M->appendModuleInlineAsm({AsmStr, Props});
764bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
770 return tokError(
"unknown target property");
773 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
774 parseStringConstant(Str))
776 M->setTargetTriple(Triple(std::move(Str)));
780 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
782 DLStrLoc = Lex.getLoc();
783 if (parseStringConstant(TentativeDLStr))
791bool LLParser::parseSourceFileName() {
794 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
795 parseStringConstant(SourceFileName))
798 M->setSourceFileName(SourceFileName);
804bool LLParser::parseUnnamedType() {
805 LocTy TypeLoc = Lex.getLoc();
806 unsigned TypeID = Lex.getUIntVal();
809 if (parseToken(
lltok::equal,
"expected '=' after name") ||
814 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
818 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
820 return error(TypeLoc,
"non-struct types may not be recursive");
822 Entry.second = SMLoc();
830bool LLParser::parseNamedType() {
831 std::string
Name = Lex.getStrVal();
832 LocTy NameLoc = Lex.getLoc();
835 if (parseToken(
lltok::equal,
"expected '=' after name") ||
840 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
844 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
846 return error(NameLoc,
"non-struct types may not be recursive");
848 Entry.second = SMLoc();
856bool LLParser::parseDeclare() {
860 std::vector<std::pair<unsigned, MDNode *>> MDs;
864 if (parseMetadataAttachment(MDK,
N))
866 MDs.push_back({MDK,
N});
870 unsigned FunctionNumber = -1;
871 SmallVector<unsigned> UnnamedArgNums;
872 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
875 F->addMetadata(MD.first, *MD.second);
881bool LLParser::parseDefine() {
884 FileLoc FunctionStart = getTokLineColumnPos();
888 unsigned FunctionNumber = -1;
889 SmallVector<unsigned> UnnamedArgNums;
891 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
892 parseOptionalFunctionMetadata(*
F) ||
893 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
895 ParserContext->addFunctionLocation(
896 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
904bool LLParser::parseGlobalType(
bool &IsConstant) {
911 return tokError(
"expected 'global' or 'constant'");
917bool LLParser::parseOptionalUnnamedAddr(
938bool LLParser::parseUnnamedGlobal() {
941 LocTy NameLoc = Lex.getLoc();
945 VarID = Lex.getUIntVal();
946 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
950 if (parseToken(
lltok::equal,
"expected '=' after name"))
953 VarID = NumberedVals.getNext();
957 unsigned Linkage, Visibility, DLLStorageClass;
961 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
963 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
966 switch (Lex.getKind()) {
968 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
969 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
972 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
973 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
982bool LLParser::parseNamedGlobal() {
984 LocTy NameLoc = Lex.getLoc();
985 std::string
Name = Lex.getStrVal();
989 unsigned Linkage, Visibility, DLLStorageClass;
993 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
994 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
996 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
999 switch (Lex.getKind()) {
1001 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
1002 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1005 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
1006 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1010bool LLParser::parseComdat() {
1012 std::string
Name = Lex.getStrVal();
1013 LocTy NameLoc = Lex.getLoc();
1020 return tokError(
"expected comdat type");
1023 switch (Lex.getKind()) {
1025 return tokError(
"unknown selection kind");
1047 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
1048 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
1051 if (
I != ComdatSymTab.
end())
1054 C = M->getOrInsertComdat(Name);
1055 C->setSelectionKind(SK);
1062bool LLParser::parseMDString(
MDString *&Result) {
1064 if (parseStringConstant(Str))
1072bool LLParser::parseMDNodeID(
MDNode *&Result) {
1074 LocTy IDLoc = Lex.getLoc();
1076 if (parseUInt32(MID))
1080 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
1087 auto &FwdRef = ForwardRefMDNodes[MID];
1090 Result = FwdRef.first.get();
1091 It->second.reset(Result);
1097bool LLParser::parseNamedMetadata() {
1099 std::string
Name = Lex.getStrVal();
1107 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1110 MDNode *
N =
nullptr;
1115 Lex.getStrVal() ==
"DIExpression") {
1116 if (parseDIExpression(
N,
false))
1121 Lex.getStrVal() ==
"DIArgList") {
1122 return tokError(
"found DIArgList outside of function");
1130 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1135bool LLParser::parseStandaloneMetadata() {
1138 unsigned MetadataID = 0;
1141 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1146 return tokError(
"unexpected type in metadata definition");
1150 if (parseSpecializedMDNode(Init, IsDistinct))
1153 parseMDTuple(Init, IsDistinct))
1157 auto FI = ForwardRefMDNodes.find(MetadataID);
1158 if (FI != ForwardRefMDNodes.end()) {
1159 auto *ToReplace = FI->second.first.get();
1163 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1164 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1165 "Inst unexpectedly already has DIAssignID attachment");
1166 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1170 ToReplace->replaceAllUsesWith(Init);
1171 ForwardRefMDNodes.erase(FI);
1173 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1175 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1177 return tokError(
"Metadata id is already used");
1178 It->second.reset(Init);
1185bool LLParser::skipModuleSummaryEntry() {
1198 return tokError(
"Expected 'gv', 'module', 'typeid', "
1199 "'typeidCompatibleVTable', 'flags', 'blockcount', "
1200 "'cfiFunctionDefs' or 'cfiFunctionDecls' at the start of "
1203 return parseSummaryIndexFlags();
1205 return parseBlockCount();
1207 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1208 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1212 unsigned NumOpenParen = 1;
1214 switch (Lex.getKind()) {
1222 return tokError(
"found end of file while parsing summary entry");
1228 }
while (NumOpenParen > 0);
1234bool LLParser::parseSummaryEntry() {
1240 Lex.setIgnoreColonInIdentifiers(
true);
1248 return skipModuleSummaryEntry();
1250 bool result =
false;
1251 switch (Lex.getKind()) {
1253 result = parseGVEntry(SummaryID);
1256 result = parseModuleEntry(SummaryID);
1259 result = parseTypeIdEntry(SummaryID);
1262 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1265 result = parseSummaryIndexFlags();
1268 result = parseBlockCount();
1272 result = parseCfiFunctions();
1275 result =
error(Lex.getLoc(),
"unexpected summary kind");
1278 Lex.setIgnoreColonInIdentifiers(
false);
1312bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1313 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1314 unsigned DLLStorageClass,
bool DSOLocal,
1329 return error(NameLoc,
"invalid linkage type for alias");
1332 return error(NameLoc,
1333 "symbol with local linkage must have default visibility");
1336 return error(NameLoc,
1337 "symbol with local linkage cannot have a DLL storage class");
1340 LocTy ExplicitTypeLoc = Lex.getLoc();
1341 if (parseType(Ty) ||
1342 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1346 LocTy AliaseeLoc = Lex.getLoc();
1351 if (parseGlobalTypeAndValue(Aliasee))
1356 if (parseValID(ID,
nullptr))
1359 return error(AliaseeLoc,
"invalid aliasee");
1360 Aliasee =
ID.ConstantVal;
1366 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1367 unsigned AddrSpace = PTy->getAddressSpace();
1369 GlobalValue *GVal =
nullptr;
1373 if (!
Name.empty()) {
1374 auto I = ForwardRefVals.find(Name);
1375 if (
I != ForwardRefVals.end()) {
1376 GVal =
I->second.first;
1377 ForwardRefVals.erase(Name);
1378 }
else if (M->getNamedValue(Name)) {
1379 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1382 auto I = ForwardRefValIDs.find(NameID);
1383 if (
I != ForwardRefValIDs.end()) {
1384 GVal =
I->second.first;
1385 ForwardRefValIDs.erase(
I);
1390 std::unique_ptr<GlobalAlias> GA;
1391 std::unique_ptr<GlobalIFunc> GI;
1419 if (parseGlobalObjectMetadataAttachment(*GI))
1422 return tokError(
"unknown alias or ifunc property!");
1427 NumberedVals.add(NameID, GV);
1434 "forward reference and definition of alias have different types");
1444 M->insertAlias(GA.release());
1446 M->insertIFunc(GI.release());
1447 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1456 case lltok::kw_sanitize_memtag:
1470 switch (Lex.getKind()) {
1472 Meta.NoAddress =
true;
1475 Meta.NoHWAddress =
true;
1477 case lltok::kw_sanitize_memtag:
1481 Meta.IsDynInit =
true;
1484 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1504bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1505 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1506 unsigned Visibility,
unsigned DLLStorageClass,
1510 return error(NameLoc,
1511 "symbol with local linkage must have default visibility");
1514 return error(NameLoc,
1515 "symbol with local linkage cannot have a DLL storage class");
1519 LocTy IsExternallyInitializedLoc;
1523 if (parseOptionalAddrSpace(AddrSpace) ||
1525 IsExternallyInitialized,
1526 &IsExternallyInitializedLoc) ||
1527 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1536 if (parseGlobalValue(Ty, Init))
1541 return error(TyLoc,
"invalid type for global variable");
1543 GlobalValue *GVal =
nullptr;
1546 if (!
Name.empty()) {
1547 auto I = ForwardRefVals.find(Name);
1548 if (
I != ForwardRefVals.end()) {
1549 GVal =
I->second.first;
1550 ForwardRefVals.erase(
I);
1551 }
else if (M->getNamedValue(Name)) {
1552 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1557 if (NameID == (
unsigned)-1)
1558 NameID = NumberedVals.getNext();
1560 auto I = ForwardRefValIDs.find(NameID);
1561 if (
I != ForwardRefValIDs.end()) {
1562 GVal =
I->second.first;
1563 ForwardRefValIDs.erase(
I);
1567 GlobalVariable *GV =
new GlobalVariable(
1572 NumberedVals.add(NameID, GV);
1590 "forward reference and definition of global have different types");
1610 }
else if (Lex.getKind() == lltok::kw_align) {
1612 if (parseOptionalAlignment(Alignment))
1618 if (parseOptionalCodeModel(CodeModel))
1622 if (parseGlobalObjectMetadataAttachment(*GV))
1625 if (parseSanitizer(GV))
1629 if (parseOptionalComdat(Name,
C))
1634 return tokError(
"unknown global variable property!");
1638 AttrBuilder
Attrs(M->getContext());
1640 std::vector<unsigned> FwdRefAttrGrps;
1641 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1643 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1645 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1653bool LLParser::parseUnnamedAttrGrp() {
1655 LocTy AttrGrpLoc = Lex.getLoc();
1659 return tokError(
"expected attribute group id");
1661 unsigned VarID = Lex.getUIntVal();
1662 std::vector<unsigned> unused;
1670 auto R = NumberedAttrBuilders.find(
VarID);
1671 if (R == NumberedAttrBuilders.end())
1672 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1674 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1675 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1678 if (!
R->second.hasAttributes())
1679 return error(AttrGrpLoc,
"attribute group has no attributes");
1686#define GET_ATTR_NAMES
1687#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1688 case lltok::kw_##DISPLAY_NAME: \
1689 return Attribute::ENUM_NAME;
1690#include "llvm/IR/Attributes.inc"
1699 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1702 case Attribute::Alignment: {
1711 if (parseOptionalAlignment(Alignment,
true))
1714 B.addAlignmentAttr(Alignment);
1717 case Attribute::StackAlignment: {
1722 parseUInt32(Alignment))
1725 if (parseOptionalStackAlignment(Alignment))
1728 B.addStackAlignmentAttr(Alignment);
1731 case Attribute::AllocSize: {
1732 unsigned ElemSizeArg;
1733 std::optional<unsigned> NumElemsArg;
1734 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1736 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1739 case Attribute::VScaleRange: {
1740 unsigned MinValue, MaxValue;
1741 if (parseVScaleRangeArguments(MinValue, MaxValue))
1743 B.addVScaleRangeAttr(MinValue,
1744 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1747 case Attribute::Dereferenceable: {
1748 std::optional<uint64_t> Bytes;
1749 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1751 assert(Bytes.has_value());
1752 B.addDereferenceableAttr(Bytes.value());
1755 case Attribute::DeadOnReturn: {
1756 std::optional<uint64_t> Bytes;
1757 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1760 if (Bytes.has_value()) {
1761 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1763 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1767 case Attribute::DereferenceableOrNull: {
1768 std::optional<uint64_t> Bytes;
1769 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1771 assert(Bytes.has_value());
1772 B.addDereferenceableOrNullAttr(Bytes.value());
1775 case Attribute::UWTable: {
1777 if (parseOptionalUWTableKind(Kind))
1779 B.addUWTableAttr(Kind);
1782 case Attribute::AllocKind: {
1784 if (parseAllocKind(Kind))
1786 B.addAllocKindAttr(Kind);
1789 case Attribute::Memory: {
1790 std::optional<MemoryEffects> ME = parseMemoryAttr();
1793 B.addMemoryAttr(*ME);
1796 case Attribute::DenormalFPEnv: {
1797 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1801 B.addDenormalFPEnvAttr(*
Mode);
1804 case Attribute::NoFPClass: {
1807 B.addNoFPClassAttr(NoFPClass);
1813 case Attribute::Range:
1814 return parseRangeAttr(
B);
1815 case Attribute::Initializes:
1816 return parseInitializesAttr(
B);
1817 case Attribute::Captures:
1818 return parseCapturesAttr(
B);
1820 B.addAttribute(Attr);
1828 case lltok::kw_readnone:
1831 case lltok::kw_readonly:
1834 case lltok::kw_writeonly:
1853bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1854 std::vector<unsigned> &FwdRefAttrGrps,
1855 bool InAttrGrp, LocTy &BuiltinLoc) {
1856 bool HaveError =
false;
1867 if (parseStringAttribute(
B))
1879 "cannot have an attribute group reference in an attribute group");
1882 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1888 SMLoc Loc = Lex.getLoc();
1889 if (Token == lltok::kw_builtin)
1901 return error(Lex.getLoc(),
"unterminated attribute group");
1904 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1911 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1915 B.addMemoryAttr(ME);
1929 PTy->getAddressSpace());
1938 error(Loc,
"'" + Name +
"' is not a basic block");
1940 error(Loc,
"'" + Name +
"' defined with type '" +
1953 error(Loc,
"global variable reference must have pointer type");
1964 auto I = ForwardRefVals.find(Name);
1965 if (
I != ForwardRefVals.end())
1966 Val =
I->second.first;
1972 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1976 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1983 error(Loc,
"global variable reference must have pointer type");
1987 GlobalValue *Val = NumberedVals.get(ID);
1992 auto I = ForwardRefValIDs.find(ID);
1993 if (
I != ForwardRefValIDs.end())
1994 Val =
I->second.first;
2000 checkValidVariableType(Loc,
"@" + Twine(ID), Ty, Val));
2004 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
2012Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
2016 if (
I != ComdatSymTab.
end())
2020 Comdat *
C = M->getOrInsertComdat(Name);
2021 ForwardRefComdats[
Name] = Loc;
2031bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
2032 if (Lex.getKind() !=
T)
2033 return tokError(ErrMsg);
2040bool LLParser::parseStringConstant(std::string &Result) {
2042 return tokError(
"expected string constant");
2043 Result = Lex.getStrVal();
2050bool LLParser::parseUInt32(uint32_t &Val) {
2051 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2052 return tokError(
"expected integer");
2053 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2054 if (Val64 !=
unsigned(Val64))
2055 return tokError(
"expected 32-bit integer (too large)");
2063bool LLParser::parseUInt64(
uint64_t &Val) {
2064 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2065 return tokError(
"expected integer");
2066 Val = Lex.getAPSIntVal().getLimitedValue();
2076 switch (Lex.getKind()) {
2078 return tokError(
"expected localdynamic, initialexec or localexec");
2106 return parseTLSModel(TLM) ||
2107 parseToken(
lltok::rparen,
"expected ')' after thread local model");
2115bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
2116 AddrSpace = DefaultAS;
2120 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
2122 const std::string &AddrSpaceStr = Lex.getStrVal();
2123 if (AddrSpaceStr ==
"A") {
2124 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2125 }
else if (AddrSpaceStr ==
"G") {
2126 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2127 }
else if (AddrSpaceStr ==
"P") {
2128 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2129 }
else if (std::optional<unsigned> AS =
2130 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2133 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2139 return tokError(
"expected integer or string constant");
2140 SMLoc Loc = Lex.getLoc();
2141 if (parseUInt32(AddrSpace))
2144 return error(Loc,
"invalid address space, must be a 24-bit integer");
2148 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2149 ParseAddrspaceValue(AddrSpace) ||
2156bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2157 std::string Attr = Lex.getStrVal();
2160 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2162 B.addAttribute(Attr, Val);
2167bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2168 bool HaveError =
false;
2175 if (parseStringAttribute(
B))
2186 SMLoc Loc = Lex.getLoc();
2191 if (parseEnumAttribute(Attr,
B,
false))
2195 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2197 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2245bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2246 unsigned &Visibility,
2247 unsigned &DLLStorageClass,
bool &DSOLocal) {
2251 parseOptionalDSOLocal(DSOLocal);
2252 parseOptionalVisibility(Visibility);
2253 parseOptionalDLLStorageClass(DLLStorageClass);
2256 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2262void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2263 switch (Lex.getKind()) {
2284void LLParser::parseOptionalVisibility(
unsigned &Res) {
2285 switch (Lex.getKind()) {
2302bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2306 return tokError(
"unknown import kind. Expect definition or declaration.");
2321void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2322 switch (Lex.getKind()) {
2393bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2394 switch (Lex.getKind()) {
2484 return tokError(
"unknown RISC-V ABI VLEN");
2485#define CC_VLS_CASE(ABIVlen) \
2487 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2515 return parseUInt32(
CC);
2525bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2528 std::string
Name = Lex.getStrVal();
2529 Kind = M->getMDKindID(Name);
2532 return parseMDNode(MD);
2537bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2540 return tokError(
"expected metadata after comma");
2544 auto Loc = Lex.getLoc();
2545 if (parseMetadataAttachment(MDK,
N))
2548 if (MDK == LLVMContext::MD_DIAssignID)
2549 TempDIAssignIDAttachments[
N].push_back(&Inst);
2550 else if (MDK == LLVMContext::MD_dbg)
2551 PendingDbgInsts.emplace_back(Loc, &Inst,
N);
2562bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2565 if (parseMetadataAttachment(MDK,
N))
2574bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2576 if (parseGlobalObjectMetadataAttachment(
F))
2584bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2586 if (!EatIfPresent(lltok::kw_align))
2588 LocTy AlignLoc = Lex.getLoc();
2591 LocTy ParenLoc = Lex.getLoc();
2592 bool HaveParens =
false;
2598 if (parseUInt64(
Value))
2602 return error(ParenLoc,
"expected ')'");
2605 return error(AlignLoc,
"alignment is not a power of two");
2607 return error(AlignLoc,
"huge alignments are not supported yet");
2615bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2619 LocTy AlignLoc = Lex.getLoc();
2622 LocTy ParenLoc = Lex.getLoc();
2624 return error(ParenLoc,
"expected '('");
2626 if (parseUInt64(
Value))
2629 ParenLoc = Lex.getLoc();
2631 return error(ParenLoc,
"expected ')'");
2634 return error(AlignLoc,
"alignment is not a power of two");
2636 return error(AlignLoc,
"huge alignments are not supported yet");
2646 auto StrVal = Lex.getStrVal();
2647 auto ErrMsg =
"expected global code model string";
2648 if (StrVal ==
"tiny")
2650 else if (StrVal ==
"small")
2652 else if (StrVal ==
"kernel")
2654 else if (StrVal ==
"medium")
2656 else if (StrVal ==
"large")
2659 return tokError(ErrMsg);
2671bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2672 std::optional<uint64_t> &Bytes,
2673 bool ErrorNoBytes) {
2674 assert((AttrKind == lltok::kw_dereferenceable ||
2675 AttrKind == lltok::kw_dereferenceable_or_null ||
2676 AttrKind == lltok::kw_dead_on_return) &&
2680 if (!EatIfPresent(AttrKind))
2682 LocTy ParenLoc = Lex.getLoc();
2685 return error(ParenLoc,
"expected '('");
2686 Bytes = std::nullopt;
2689 LocTy DerefLoc = Lex.getLoc();
2690 if (parseUInt64(Bytes.value()))
2692 ParenLoc = Lex.getLoc();
2694 return error(ParenLoc,
"expected ')'");
2696 return error(DerefLoc,
"byte count specified must be non-zero");
2700bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2705 LocTy KindLoc = Lex.getLoc();
2711 return error(KindLoc,
"expected unwind table kind");
2718 LocTy ParenLoc = Lex.getLoc();
2720 return error(ParenLoc,
"expected '('");
2721 LocTy KindLoc = Lex.getLoc();
2723 if (parseStringConstant(Arg))
2724 return error(KindLoc,
"expected allockind value");
2728 }
else if (
A ==
"realloc") {
2730 }
else if (
A ==
"free") {
2732 }
else if (
A ==
"uninitialized") {
2734 }
else if (
A ==
"zeroed") {
2736 }
else if (
A ==
"aligned") {
2739 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2742 ParenLoc = Lex.getLoc();
2744 return error(ParenLoc,
"expected ')'");
2746 return error(KindLoc,
"expected allockind value");
2755 return {Loc::ArgMem};
2757 return {Loc::InaccessibleMem};
2759 return {Loc::ErrnoMem};
2761 return {Loc::TargetMem0};
2763 return {Loc::TargetMem1};
2786 return std::nullopt;
2790static std::optional<DenormalMode::DenormalModeKind>
2802 return std::nullopt;
2806std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2811 Lex.setIgnoreColonInIdentifiers(
true);
2816 tokError(
"expected '('");
2817 return std::nullopt;
2820 bool SeenLoc =
false;
2821 bool SeenTargetLoc =
false;
2824 if (!Locs.
empty()) {
2827 tokError(
"expected ':' after location");
2828 return std::nullopt;
2835 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2836 "or access kind (none, read, write, readwrite)");
2838 tokError(
"expected access kind (none, read, write, readwrite)");
2839 return std::nullopt;
2843 if (!Locs.
empty()) {
2848 SeenTargetLoc =
true;
2850 if (Locs.size() > 1 && SeenTargetLoc) {
2851 tokError(
"target memory default access kind must be specified first");
2852 return std::nullopt;
2857 tokError(
"default access kind must be specified first");
2858 return std::nullopt;
2867 tokError(
"unterminated memory attribute");
2868 return std::nullopt;
2871std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2872 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2875 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2876 "positivezero, dynamic)");
2882 std::optional<DenormalMode::DenormalModeKind> InputMode;
2886 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2887 "positivezero, dynamic)");
2894 InputMode = OutputMode;
2897 return DenormalMode(*OutputMode, *InputMode);
2900std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2903 Lex.setIgnoreColonInIdentifiers(
true);
2914 bool HasDefaultSection =
false;
2916 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2917 if (!ParsedDefaultMode)
2919 DefaultMode = *ParsedDefaultMode;
2920 HasDefaultSection =
true;
2925 if (HasDefaultSection && !HasComma) {
2926 tokError(
"expected ',' before float:");
2931 if (parseType(Ty) || !Ty->
isFloatTy()) {
2932 tokError(
"expected float:");
2936 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2939 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2943 F32Mode = *ParsedF32Mode;
2946 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2949 return DenormalFPEnv(DefaultMode, F32Mode);
2991unsigned LLParser::parseNoFPClassAttr() {
2996 tokError(
"expected '('");
3003 if (TestMask != 0) {
3007 !parseUInt64(
Value)) {
3009 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
3014 error(Lex.getLoc(),
"expected ')'");
3020 error(Lex.getLoc(),
"expected nofpclass test mask");
3038bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
3039 bool &AteExtraComma) {
3040 AteExtraComma =
false;
3044 AteExtraComma =
true;
3048 if (Lex.getKind() != lltok::kw_align)
3049 return error(Lex.getLoc(),
"expected metadata or 'align'");
3051 if (parseOptionalAlignment(Alignment))
3064bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
3065 bool &AteExtraComma) {
3066 AteExtraComma =
false;
3070 AteExtraComma =
true;
3076 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
3078 if (parseOptionalAddrSpace(AddrSpace))
3085bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
3086 std::optional<unsigned> &HowManyArg) {
3089 auto StartParen = Lex.getLoc();
3091 return error(StartParen,
"expected '('");
3093 if (parseUInt32(BaseSizeArg))
3097 auto HowManyAt = Lex.getLoc();
3099 if (parseUInt32(HowMany))
3101 if (HowMany == BaseSizeArg)
3102 return error(HowManyAt,
3103 "'allocsize' indices can't refer to the same parameter");
3104 HowManyArg = HowMany;
3106 HowManyArg = std::nullopt;
3108 auto EndParen = Lex.getLoc();
3110 return error(EndParen,
"expected ')'");
3114bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3115 unsigned &MaxValue) {
3118 auto StartParen = Lex.getLoc();
3120 return error(StartParen,
"expected '('");
3122 if (parseUInt32(MinValue))
3126 if (parseUInt32(MaxValue))
3129 MaxValue = MinValue;
3131 auto EndParen = Lex.getLoc();
3133 return error(EndParen,
"expected ')'");
3142bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3147 return parseScope(SSID) || parseOrdering(Ordering);
3157 auto StartParenAt = Lex.getLoc();
3159 return error(StartParenAt,
"Expected '(' in syncscope");
3162 auto SSNAt = Lex.getLoc();
3163 if (parseStringConstant(SSN))
3164 return error(SSNAt,
"Expected synchronization scope name");
3166 auto EndParenAt = Lex.getLoc();
3168 return error(EndParenAt,
"Expected ')' in syncscope");
3170 SSID = Context.getOrInsertSyncScopeID(SSN);
3181 switch (Lex.getKind()) {
3183 return tokError(
"Expected ordering on atomic instruction");
3202bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3204 if (!EatIfPresent(lltok::kw_alignstack))
3206 LocTy ParenLoc = Lex.getLoc();
3208 return error(ParenLoc,
"expected '('");
3209 LocTy AlignLoc = Lex.getLoc();
3210 if (parseUInt32(Alignment))
3212 ParenLoc = Lex.getLoc();
3214 return error(ParenLoc,
"expected ')'");
3216 return error(AlignLoc,
"stack alignment is not a power of two");
3230 bool &AteExtraComma) {
3231 AteExtraComma =
false;
3234 return tokError(
"expected ',' as start of index list");
3238 if (Indices.
empty())
3239 return tokError(
"expected index");
3240 AteExtraComma =
true;
3244 if (parseUInt32(Idx))
3257bool LLParser::parseType(
Type *&Result,
const Twine &
Msg,
bool AllowVoid) {
3258 SMLoc TypeLoc = Lex.getLoc();
3259 switch (Lex.getKind()) {
3261 return tokError(
Msg);
3270 if (
Result->isPointerTy()) {
3272 if (parseOptionalAddrSpace(AddrSpace))
3278 return tokError(
"ptr* is invalid - use ptr instead");
3289 if (parseTargetExtType(Result))
3295 if (parseAnonStructType(Result,
false))
3301 if (parseArrayVectorType(Result,
false))
3308 if (parseAnonStructType(Result,
true) ||
3309 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3311 }
else if (parseArrayVectorType(Result,
true))
3316 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3322 Entry.second = Lex.getLoc();
3331 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3337 Entry.second = Lex.getLoc();
3347 switch (Lex.getKind()) {
3350 if (!AllowVoid &&
Result->isVoidTy())
3351 return error(TypeLoc,
"void type only allowed for function results");
3357 return tokError(
"basic block pointers are invalid");
3359 return tokError(
"pointers to void are invalid - use i8* instead");
3361 return tokError(
"pointer to this type is invalid");
3369 return tokError(
"basic block pointers are invalid");
3371 return tokError(
"pointers to void are invalid; use i8* instead");
3373 return tokError(
"pointer to this type is invalid");
3375 if (parseOptionalAddrSpace(AddrSpace) ||
3376 parseToken(
lltok::star,
"expected '*' in address space"))
3385 if (parseFunctionType(Result))
3398 PerFunctionState &PFS,
bool IsMustTailCall,
3399 bool InVarArgsFunc) {
3405 if (!ArgList.
empty() &&
3406 parseToken(
lltok::comma,
"expected ',' in argument list"))
3411 const char *
Msg =
"unexpected ellipsis in argument list for ";
3412 if (!IsMustTailCall)
3413 return tokError(Twine(
Msg) +
"non-musttail call");
3415 return tokError(Twine(
Msg) +
"musttail call in non-varargs function");
3417 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3422 Type *ArgTy =
nullptr;
3424 if (parseType(ArgTy, ArgLoc))
3427 return error(ArgLoc,
"invalid type for function argument");
3429 AttrBuilder ArgAttrs(M->getContext());
3432 if (parseMetadataAsValue(
V, PFS))
3436 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy,
V, PFS))
3443 if (IsMustTailCall && InVarArgsFunc)
3444 return tokError(
"expected '...' at end of argument list for musttail call "
3445 "in varargs function");
3453bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3456 if (!EatIfPresent(AttrToken))
3459 return error(Lex.getLoc(),
"expected '('");
3463 return error(Lex.getLoc(),
"expected ')'");
3465 B.addTypeAttr(AttrKind, Ty);
3471bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3479 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3481 return tokError(
"expected integer");
3482 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3484 "integer is too large for the bit width of specified type");
3485 Val = Lex.getAPSIntVal().extend(
BitWidth);
3490 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3493 return error(TyLoc,
"the range must have integer type!");
3501 return tokError(
"the range represent the empty set but limits aren't 0!");
3512bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3515 auto ParseAPSInt = [&](APInt &Val) {
3517 return tokError(
"expected integer");
3518 Val = Lex.getAPSIntVal().extend(64);
3538 return tokError(
"the range should not represent the full or empty set!");
3550 if (!CRLOrNull.has_value())
3551 return tokError(
"Invalid (unordered or overlapping) range list");
3552 B.addInitializesAttr(*CRLOrNull);
3556bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3558 std::optional<CaptureComponents> Ret;
3562 Lex.setIgnoreColonInIdentifiers(
true);
3570 bool SeenComponent =
false;
3576 return tokError(
"duplicate 'ret' location");
3579 SeenComponent =
false;
3584 return tokError(
"cannot use 'none' with other component");
3588 return tokError(
"cannot use 'none' with other component");
3599 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3600 "'provenance' or 'read_provenance'");
3603 SeenComponent =
true;
3611 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3624bool LLParser::parseOptionalOperandBundles(
3626 LocTy BeginLoc = Lex.getLoc();
3632 if (!BundleList.
empty() &&
3633 parseToken(
lltok::comma,
"expected ',' in input list"))
3637 if (parseStringConstant(
Tag))
3640 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3643 std::vector<Value *> Inputs;
3646 if (!Inputs.empty() &&
3647 parseToken(
lltok::comma,
"expected ',' in input list"))
3655 if (parseMetadataAsValue(Input, PFS))
3657 }
else if (parseValue(Ty, Input, PFS)) {
3660 Inputs.push_back(Input);
3668 if (BundleList.
empty())
3669 return error(BeginLoc,
"operand bundle set must not be empty");
3676 unsigned NextID,
unsigned ID) {
3678 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3679 Twine(NextID) +
"' or greater");
3696 unsigned CurValID = 0;
3710 LocTy TypeLoc = Lex.getLoc();
3711 Type *ArgTy =
nullptr;
3712 AttrBuilder
Attrs(M->getContext());
3713 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3717 return error(TypeLoc,
"argument can not have void type");
3722 bool Unnamed =
false;
3724 Name = Lex.getStrVal();
3725 IdentStart = getTokLineColumnPos();
3727 IdentEnd = getPrevTokEndLineColumnPos();
3731 ArgID = Lex.getUIntVal();
3732 IdentStart = getTokLineColumnPos();
3733 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3736 IdentEnd = getPrevTokEndLineColumnPos();
3742 CurValID = ArgID + 1;
3746 return error(TypeLoc,
"invalid type for function argument");
3750 Unnamed ? std::nullopt
3751 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3756 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3761bool LLParser::parseFunctionType(
Type *&Result) {
3765 return tokError(
"invalid function return type");
3769 SmallVector<unsigned> UnnamedArgNums;
3770 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3774 for (
const ArgInfo &Arg : ArgList) {
3775 if (!Arg.Name.empty())
3776 return error(Arg.Loc,
"argument name invalid in function type");
3777 if (Arg.Attrs.hasAttributes())
3778 return error(Arg.Loc,
"argument attributes invalid in function type");
3782 for (
const ArgInfo &Arg : ArgList)
3791bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3793 if (parseStructBody(Elts))
3801bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3802 std::pair<Type *, LocTy> &Entry,
3806 return error(TypeLoc,
"redefinition of type");
3812 Entry.second = SMLoc();
3817 ResultTy =
Entry.first;
3829 return error(TypeLoc,
"forward references to non-struct type");
3833 return parseArrayVectorType(ResultTy,
true);
3834 return parseType(ResultTy);
3838 Entry.second = SMLoc();
3847 if (parseStructBody(Body) ||
3848 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3852 return tokError(
toString(std::move(
E)));
3872 LocTy EltTyLoc = Lex.getLoc();
3879 return error(EltTyLoc,
"invalid element type for struct");
3882 EltTyLoc = Lex.getLoc();
3887 return error(EltTyLoc,
"invalid element type for struct");
3892 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3901bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3902 bool Scalable =
false;
3906 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3912 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3913 Lex.getAPSIntVal().getBitWidth() > 64)
3914 return tokError(
"expected number in address space");
3916 LocTy SizeLoc = Lex.getLoc();
3920 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3923 LocTy TypeLoc = Lex.getLoc();
3924 Type *EltTy =
nullptr;
3925 if (parseType(EltTy))
3929 "expected end of sequential type"))
3934 return error(SizeLoc,
"zero element vector is illegal");
3936 return error(SizeLoc,
"size too large for vector");
3938 return error(TypeLoc,
"invalid vector element type");
3942 return error(TypeLoc,
"invalid array element type");
3959bool LLParser::parseTargetExtType(
Type *&Result) {
3964 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3965 parseStringConstant(TypeName))
3972 SmallVector<unsigned> IntParams;
3973 bool SeenInt =
false;
3980 if (parseUInt32(IntVal))
3983 }
else if (SeenInt) {
3986 return tokError(
"expected uint32 param");
3989 if (parseType(TypeParam,
true))
3995 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
4000 if (
auto E = TTy.takeError())
4001 return tokError(
toString(std::move(
E)));
4014 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
4017 auto It = UnnamedArgNums.
begin();
4020 unsigned ArgNum = *It++;
4021 NumberedVals.add(ArgNum, &A);
4026LLParser::PerFunctionState::~PerFunctionState() {
4029 for (
const auto &P : ForwardRefVals) {
4032 P.second.first->replaceAllUsesWith(
4034 P.second.first->deleteValue();
4037 for (
const auto &P : ForwardRefValIDs) {
4040 P.second.first->replaceAllUsesWith(
4042 P.second.first->deleteValue();
4046bool LLParser::PerFunctionState::finishFunction() {
4047 if (!ForwardRefVals.empty())
4048 return P.error(ForwardRefVals.begin()->second.second,
4049 "use of undefined value '%" + ForwardRefVals.begin()->first +
4051 if (!ForwardRefValIDs.empty())
4052 return P.error(ForwardRefValIDs.begin()->second.second,
4053 "use of undefined value '%" +
4054 Twine(ForwardRefValIDs.begin()->first) +
"'");
4061Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
4064 Value *Val =
F.getValueSymbolTable()->lookup(Name);
4069 auto I = ForwardRefVals.find(Name);
4070 if (
I != ForwardRefVals.end())
4071 Val =
I->second.first;
4076 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
4080 P.error(Loc,
"invalid use of a non-first-class type");
4091 if (FwdVal->
getName() != Name) {
4092 P.error(Loc,
"name is too long which can result in name collisions, "
4093 "consider making the name shorter or "
4094 "increasing -non-global-value-max-name-size");
4098 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
4102Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
4104 Value *Val = NumberedVals.get(ID);
4109 auto I = ForwardRefValIDs.find(ID);
4110 if (
I != ForwardRefValIDs.end())
4111 Val =
I->second.first;
4116 return P.checkValidVariableType(Loc,
"%" + Twine(ID), Ty, Val);
4119 P.error(Loc,
"invalid use of a non-first-class type");
4131 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4137bool LLParser::PerFunctionState::setInstName(
int NameID,
4138 const std::string &NameStr,
4139 LocTy NameLoc, Instruction *Inst) {
4142 if (NameID != -1 || !NameStr.empty())
4143 return P.error(NameLoc,
"instructions returning void cannot have a name");
4149 if (NameStr.empty()) {
4152 NameID = NumberedVals.getNext();
4154 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4158 auto FI = ForwardRefValIDs.find(NameID);
4159 if (FI != ForwardRefValIDs.end()) {
4162 return P.error(NameLoc,
"instruction forward referenced with type '" +
4166 Sentinel->replaceAllUsesWith(Inst);
4168 ForwardRefValIDs.erase(FI);
4171 NumberedVals.add(NameID, Inst);
4176 auto FI = ForwardRefVals.find(NameStr);
4177 if (FI != ForwardRefVals.end()) {
4180 return P.error(NameLoc,
"instruction forward referenced with type '" +
4184 Sentinel->replaceAllUsesWith(Inst);
4186 ForwardRefVals.erase(FI);
4192 if (Inst->
getName() != NameStr)
4193 return P.error(NameLoc,
"multiple definition of local value named '" +
4200BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4206BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID,
LocTy Loc) {
4214BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4215 int NameID,
LocTy Loc) {
4219 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4222 NameID = NumberedVals.getNext();
4224 BB = getBB(NameID, Loc);
4226 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4230 BB = getBB(Name, Loc);
4232 P.error(Loc,
"unable to create block named '" + Name +
"'");
4243 ForwardRefValIDs.erase(NameID);
4244 NumberedVals.add(NameID, BB);
4247 ForwardRefVals.erase(Name);
4264bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4265 ID.Loc = Lex.getLoc();
4266 switch (Lex.getKind()) {
4268 return tokError(
"expected value token");
4270 ID.UIntVal = Lex.getUIntVal();
4274 ID.StrVal = Lex.getStrVal();
4278 ID.UIntVal = Lex.getUIntVal();
4282 ID.StrVal = Lex.getStrVal();
4286 ID.APSIntVal = Lex.getAPSIntVal();
4290 ID.APFloatVal = Lex.getAPFloatVal();
4296 return error(
ID.Loc,
"unexpected floating-point literal");
4298 return error(
ID.Loc,
"floating-point constant invalid for type");
4303 "Invalid float strings should be caught by the lexer");
4308 return error(
ID.Loc,
"floating-point constant overflowed type");
4310 return error(
ID.Loc,
"floating-point constant underflowed type");
4316 return error(
ID.Loc,
"unexpected floating-point literal");
4318 const APInt &
Bits = Lex.getAPSIntVal();
4320 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4321 ID.APFloatVal =
APFloat(Semantics, Bits);
4343 if (parseGlobalValueVector(Elts) ||
4344 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4347 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4348 ID.UIntVal = Elts.
size();
4349 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4350 Elts.
size() *
sizeof(Elts[0]));
4361 LocTy FirstEltLoc = Lex.getLoc();
4362 if (parseGlobalValueVector(Elts) ||
4364 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4368 if (isPackedStruct) {
4369 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4370 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4371 Elts.
size() *
sizeof(Elts[0]));
4372 ID.UIntVal = Elts.
size();
4378 return error(
ID.Loc,
"constant vector must not be empty");
4380 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4381 !Elts[0]->
getType()->isFloatingPointTy() &&
4385 "vector elements must have integer, byte, pointer or floating point "
4389 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4391 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4392 " is not of type '" +
4402 LocTy FirstEltLoc = Lex.getLoc();
4403 if (parseGlobalValueVector(Elts) ||
4415 if (!Elts[0]->
getType()->isFirstClassType())
4416 return error(FirstEltLoc,
"invalid array element type: " +
4422 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4424 return error(FirstEltLoc,
"array element #" + Twine(i) +
4425 " is not of type '" +
4437 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4446 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4449 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4452 parseStringConstant(
ID.StrVal) ||
4453 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4456 ID.StrVal2 = Lex.getStrVal();
4457 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4458 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4469 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4470 parseValID(Fn, PFS) ||
4472 "expected comma in block address expression") ||
4473 parseValID(Label, PFS) ||
4474 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4478 return error(Fn.
Loc,
"expected function name in blockaddress");
4480 return error(
Label.Loc,
"expected basic block name in blockaddress");
4483 GlobalValue *GV =
nullptr;
4485 GV = NumberedVals.get(Fn.
UIntVal);
4486 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4487 GV = M->getNamedValue(Fn.
StrVal);
4493 return error(Fn.
Loc,
"expected function name in blockaddress");
4495 if (
F->isDeclaration())
4496 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4501 GlobalValue *&FwdRef =
4502 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4510 "type of blockaddress must be a pointer and not '" +
4515 FwdDeclAS = PFS->getFunction().getAddressSpace();
4519 FwdRef =
new GlobalVariable(
4524 ID.ConstantVal = FwdRef;
4532 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4534 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4536 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4538 return error(
Label.Loc,
"referenced value is not a basic block");
4541 return error(
Label.Loc,
"cannot take address of numeric label after "
4542 "the function is defined");
4544 F->getValueSymbolTable()->lookup(
Label.StrVal));
4546 return error(
Label.Loc,
"referenced value is not a basic block");
4560 if (parseValID(Fn, PFS))
4565 "expected global value name in dso_local_equivalent");
4568 GlobalValue *GV =
nullptr;
4570 GV = NumberedVals.get(Fn.
UIntVal);
4571 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4572 GV = M->getNamedValue(Fn.
StrVal);
4578 ? ForwardRefDSOLocalEquivalentIDs
4579 : ForwardRefDSOLocalEquivalentNames;
4580 GlobalValue *&FwdRef = FwdRefMap[Fn];
4587 ID.ConstantVal = FwdRef;
4593 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4594 "in dso_local_equivalent");
4605 if (parseValID(ID, PFS))
4609 return error(
ID.Loc,
"expected global value name in no_cfi");
4621 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4622 *DeactivationSymbol =
nullptr;
4625 "expected '(' in constant ptrauth expression") ||
4626 parseGlobalTypeAndValue(Ptr) ||
4628 "expected comma in constant ptrauth expression") ||
4629 parseGlobalTypeAndValue(
Key))
4632 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4634 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4637 parseGlobalTypeAndValue(DeactivationSymbol))
4640 "expected ')' in constant ptrauth expression"))
4644 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4647 if (!KeyC || KeyC->getBitWidth() != 32)
4648 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4650 ConstantInt *DiscC =
nullptr;
4656 "constant ptrauth integer discriminator must be i64 constant");
4662 if (!AddrDisc->getType()->isPointerTy())
4664 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4669 if (!DeactivationSymbol)
4670 DeactivationSymbol =
4672 if (!DeactivationSymbol->getType()->isPointerTy())
4674 "constant ptrauth deactivation symbol must be a pointer");
4688 unsigned Opc = Lex.getUIntVal();
4689 Type *DestTy =
nullptr;
4692 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4693 parseGlobalTypeAndValue(SrcVal) ||
4694 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4695 parseType(DestTy) ||
4696 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4699 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4708 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4710 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4712 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4714 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4716 return error(
ID.Loc,
"urem constexprs are no longer supported");
4718 return error(
ID.Loc,
"srem constexprs are no longer supported");
4720 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4722 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4724 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4726 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4728 return error(
ID.Loc,
"frem constexprs are no longer supported");
4730 return error(
ID.Loc,
"and constexprs are no longer supported");
4732 return error(
ID.Loc,
"or constexprs are no longer supported");
4734 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4736 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4738 return error(
ID.Loc,
"shl constexprs are no longer supported");
4740 return error(
ID.Loc,
"mul constexprs are no longer supported");
4742 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4744 return error(
ID.Loc,
"select constexprs are no longer supported");
4746 return error(
ID.Loc,
"zext constexprs are no longer supported");
4748 return error(
ID.Loc,
"sext constexprs are no longer supported");
4750 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4752 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4754 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4756 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4758 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4760 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4762 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4764 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4772 unsigned Opc = Lex.getUIntVal();
4775 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4776 Opc == Instruction::Mul) {
4785 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4786 parseGlobalTypeAndValue(Val0) ||
4787 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4788 parseGlobalTypeAndValue(Val1) ||
4789 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4792 return error(
ID.Loc,
"operands of constexpr must have same type");
4796 "constexpr requires integer or integer vector operands");
4807 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4810 if (parseGlobalTypeAndValue(
C))
4812 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4824 unsigned Opc = Lex.getUIntVal();
4827 bool HasInRange =
false;
4833 if (
Opc == Instruction::GetElementPtr) {
4849 return tokError(
"expected integer");
4850 InRangeStart = Lex.getAPSIntVal();
4855 return tokError(
"expected integer");
4856 InRangeEnd = Lex.getAPSIntVal();
4864 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4867 if (
Opc == Instruction::GetElementPtr) {
4868 if (parseType(Ty) ||
4869 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4873 if (parseGlobalValueVector(Elts) ||
4877 if (
Opc == Instruction::GetElementPtr) {
4878 if (Elts.
size() == 0 ||
4879 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4880 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4883 std::optional<ConstantRange>
InRange;
4885 unsigned IndexWidth =
4886 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4887 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4888 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4889 if (InRangeStart.
sge(InRangeEnd))
4890 return error(
ID.Loc,
"expected end to be larger than start");
4900 for (Constant *Val : Indices) {
4903 return error(
ID.Loc,
"getelementptr index must be an integer");
4906 if (GEPWidth && (ValNumEl != GEPWidth))
4909 "getelementptr vector index has a wrong number of elements");
4912 GEPWidth = ValNumEl;
4916 if (!Indices.empty() && !Ty->
isSized())
4917 return error(
ID.Loc,
"base element of getelementptr must be sized");
4920 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4923 return error(
ID.Loc,
"invalid getelementptr indices");
4929 }
else if (
Opc == Instruction::ShuffleVector) {
4930 if (Elts.
size() != 3)
4931 return error(
ID.Loc,
"expected three operands to shufflevector");
4933 return error(
ID.Loc,
"invalid operands to shufflevector");
4934 SmallVector<int, 16>
Mask;
4937 }
else if (
Opc == Instruction::ExtractElement) {
4938 if (Elts.
size() != 2)
4939 return error(
ID.Loc,
"expected two operands to extractelement");
4941 return error(
ID.Loc,
"invalid extractelement operands");
4944 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4945 if (Elts.
size() != 3)
4946 return error(
ID.Loc,
"expected three operands to insertelement");
4948 return error(
ID.Loc,
"invalid insertelement operands");
4963bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4967 bool Parsed = parseValID(ID,
nullptr, Ty) ||
4968 convertValIDToValue(Ty, ID,
V,
nullptr);
4970 return error(
ID.Loc,
"global values must be constants");
4974bool LLParser::parseGlobalTypeAndValue(Constant *&
V) {
4976 return parseType(Ty) || parseGlobalValue(Ty,
V);
4979bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4982 LocTy KwLoc = Lex.getLoc();
4988 return tokError(
"expected comdat variable");
4989 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4991 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4994 if (GlobalName.
empty())
4995 return tokError(
"comdat cannot be unnamed");
4996 C = getComdat(std::string(GlobalName), KwLoc);
5005bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5019 if (parseGlobalTypeAndValue(
C))
5027bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
5029 if (parseMDNodeVector(Elts))
5040bool LLParser::parseMDNode(MDNode *&
N) {
5042 return parseSpecializedMDNode(
N);
5044 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
5047bool LLParser::parseMDNodeTail(MDNode *&
N) {
5050 return parseMDTuple(
N);
5053 return parseMDNodeID(
N);
5059template <
class FieldTy>
struct MDFieldImpl {
5060 typedef MDFieldImpl ImplTy;
5064 void assign(FieldTy Val) {
5066 this->Val = std::move(Val);
5069 explicit MDFieldImpl(FieldTy
Default)
5077template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
5078 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5091 this->
A = std::move(
A);
5097 this->
B = std::move(
B);
5101 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5103 WhatIs(IsInvalid) {}
5106struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5113struct LineField :
public MDUnsignedField {
5114 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5117struct ColumnField :
public MDUnsignedField {
5118 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5121struct DwarfTagField :
public MDUnsignedField {
5127struct DwarfMacinfoTypeField :
public MDUnsignedField {
5133struct DwarfAttEncodingField :
public MDUnsignedField {
5134 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5137struct DwarfVirtualityField :
public MDUnsignedField {
5141struct DwarfLangField :
public MDUnsignedField {
5145struct DwarfSourceLangNameField :
public MDUnsignedField {
5146 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5149struct DwarfLangDialectField :
public MDUnsignedField {
5150 DwarfLangDialectField()
5154struct DwarfCCField :
public MDUnsignedField {
5155 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5158struct DwarfEnumKindField :
public MDUnsignedField {
5159 DwarfEnumKindField()
5164struct EmissionKindField :
public MDUnsignedField {
5165 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5168struct FixedPointKindField :
public MDUnsignedField {
5169 FixedPointKindField()
5170 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5173struct NameTableKindField :
public MDUnsignedField {
5174 NameTableKindField()
5177 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5180struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5181 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5184struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5185 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5188struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5189 MDAPSIntField() : ImplTy(
APSInt()) {}
5192struct MDSignedField :
public MDFieldImpl<int64_t> {
5196 MDSignedField(int64_t
Default = 0)
5198 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5202struct MDBoolField :
public MDFieldImpl<bool> {
5206struct MDField :
public MDFieldImpl<Metadata *> {
5209 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5212struct MDStringField :
public MDFieldImpl<MDString *> {
5213 enum class EmptyIs {
5218 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5219 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5222struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5226struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5230struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5231 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5232 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5234 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5235 bool AllowNull =
true)
5236 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5238 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5239 bool isMDField()
const {
return WhatIs == IsTypeB; }
5240 int64_t getMDSignedValue()
const {
5241 assert(isMDSignedField() &&
"Wrong field type");
5244 Metadata *getMDFieldValue()
const {
5245 assert(isMDField() &&
"Wrong field type");
5250struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5252 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5255 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5257 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5258 bool isMDField()
const {
return WhatIs == IsTypeB; }
5259 uint64_t getMDUnsignedValue()
const {
5260 assert(isMDUnsignedField() &&
"Wrong field type");
5263 Metadata *getMDFieldValue()
const {
5264 assert(isMDField() &&
"Wrong field type");
5269 if (isMDUnsignedField())
5271 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5273 return getMDFieldValue();
5285 return tokError(
"expected integer");
5287 Result.assign(Lex.getAPSIntVal());
5294 MDUnsignedField &Result) {
5295 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5296 return tokError(
"expected unsigned integer");
5298 auto &U = Lex.getAPSIntVal();
5299 if (U.ugt(Result.Max))
5300 return tokError(
"value for '" + Name +
"' too large, limit is " +
5302 Result.assign(U.getZExtValue());
5303 assert(Result.Val <= Result.Max &&
"Expected value in range");
5310 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5314 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5320 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5323 return tokError(
"expected DWARF tag");
5327 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5328 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5337 DwarfMacinfoTypeField &Result) {
5339 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5342 return tokError(
"expected DWARF macinfo type");
5346 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5347 Lex.getStrVal() +
"'");
5348 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5350 Result.assign(Macinfo);
5357 DwarfVirtualityField &Result) {
5359 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5362 return tokError(
"expected DWARF virtuality code");
5366 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5367 Lex.getStrVal() +
"'");
5368 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5369 Result.assign(Virtuality);
5376 DwarfEnumKindField &Result) {
5378 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5381 return tokError(
"expected DWARF enum kind code");
5385 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5386 Lex.getStrVal() +
"'");
5387 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5388 Result.assign(EnumKind);
5396 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5399 return tokError(
"expected DWARF language");
5403 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5405 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5406 Result.assign(Lang);
5413 DwarfSourceLangNameField &Result) {
5415 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5418 return tokError(
"expected DWARF source language name");
5422 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5423 Lex.getStrVal() +
"'");
5424 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5425 Result.assign(Lang);
5432 DwarfLangDialectField &Result) {
5437 if (Lex.getAPSIntVal() == 0)
5438 return tokError(
"value for 'dialect' must be a known DWARF language "
5439 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5440 "DW_LLVM_LANG_DIALECT_tile)");
5441 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5445 return tokError(
"expected DWARF language dialect");
5447 StringRef DialectString = Lex.getStrVal();
5452 if (Dialect > Result.Max)
5453 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5454 DialectString +
"'");
5455 Result.assign(Dialect);
5463 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5466 return tokError(
"expected DWARF calling convention");
5470 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5471 Lex.getStrVal() +
"'");
5472 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
5480 EmissionKindField &Result) {
5482 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5485 return tokError(
"expected emission kind");
5489 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5491 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5492 Result.assign(*Kind);
5499 FixedPointKindField &Result) {
5501 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5504 return tokError(
"expected fixed-point kind");
5508 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5510 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5511 Result.assign(*Kind);
5518 NameTableKindField &Result) {
5520 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5523 return tokError(
"expected nameTable kind");
5527 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5529 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5530 Result.assign((
unsigned)*Kind);
5537 DwarfAttEncodingField &Result) {
5539 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5542 return tokError(
"expected DWARF type attribute encoding");
5546 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5547 Lex.getStrVal() +
"'");
5548 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5549 Result.assign(Encoding);
5563 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5565 bool Res = parseUInt32(TempVal);
5571 return tokError(
"expected debug info flag");
5575 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5590 Result.assign(Combined);
5603 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5605 bool Res = parseUInt32(TempVal);
5611 return tokError(
"expected debug info flag");
5615 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5616 Lex.getStrVal() +
"'");
5630 Result.assign(Combined);
5637 return tokError(
"expected signed integer");
5639 auto &S = Lex.getAPSIntVal();
5641 return tokError(
"value for '" + Name +
"' too small, limit is " +
5644 return tokError(
"value for '" + Name +
"' too large, limit is " +
5646 Result.assign(S.getExtValue());
5647 assert(Result.Val >= Result.Min &&
"Expected value in range");
5648 assert(Result.Val <= Result.Max &&
"Expected value in range");
5655 switch (Lex.getKind()) {
5657 return tokError(
"expected 'true' or 'false'");
5659 Result.assign(
true);
5662 Result.assign(
false);
5672 if (!Result.AllowNull)
5673 return tokError(
"'" + Name +
"' cannot be null");
5675 Result.assign(
nullptr);
5680 if (parseMetadata(MD,
nullptr))
5689 MDSignedOrMDField &Result) {
5692 MDSignedField Res = Result.A;
5693 if (!parseMDField(
Loc, Name, Res)) {
5701 MDField Res = Result.B;
5702 if (!parseMDField(
Loc, Name, Res)) {
5712 MDUnsignedOrMDField &Result) {
5715 MDUnsignedField Res = Result.A;
5716 if (!parseMDField(
Loc, Name, Res)) {
5724 MDField Res = Result.B;
5725 if (!parseMDField(
Loc, Name, Res)) {
5735 LocTy ValueLoc = Lex.getLoc();
5737 if (parseStringConstant(S))
5741 switch (Result.EmptyIs) {
5742 case MDStringField::EmptyIs::Null:
5743 Result.assign(
nullptr);
5745 case MDStringField::EmptyIs::Empty:
5747 case MDStringField::EmptyIs::Error:
5748 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5759 if (parseMDNodeVector(MDs))
5762 Result.assign(std::move(MDs));
5768 ChecksumKindField &Result) {
5769 std::optional<DIFile::ChecksumKind> CSKind =
5773 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5776 Result.assign(*CSKind);
5783template <
class ParserTy>
5784bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5787 return tokError(
"expected field label here");
5796template <
class ParserTy>
5797bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5804 if (parseMDFieldsImplBody(ParseField))
5807 ClosingLoc = Lex.getLoc();
5811template <
class FieldTy>
5812bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5814 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5816 LocTy Loc = Lex.getLoc();
5818 return parseMDField(Loc, Name, Result);
5821bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5824#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5825 if (Lex.getStrVal() == #CLASS) \
5826 return parse##CLASS(N, IsDistinct);
5827#include "llvm/IR/Metadata.def"
5829 return tokError(
"expected metadata type");
5832#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5833#define NOP_FIELD(NAME, TYPE, INIT)
5834#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5836 return error(ClosingLoc, "missing required field '" #NAME "'");
5837#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5838 if (Lex.getStrVal() == #NAME) \
5839 return parseMDField(#NAME, NAME);
5840#define PARSE_MD_FIELDS() \
5841 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5844 if (parseMDFieldsImpl( \
5846 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5847 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5852 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5854#define GET_OR_DISTINCT(CLASS, ARGS) \
5855 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5860bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5861#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5862 OPTIONAL(line, LineField, ); \
5863 OPTIONAL(column, ColumnField, ); \
5864 REQUIRED(scope, MDField, ( false)); \
5865 OPTIONAL(inlinedAt, MDField, ); \
5866 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5867 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5868 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
5869 OPTIONAL(irlayers, MDField, );
5871#undef VISIT_MD_FIELDS
5875 inlinedAt.Val, isImplicitCode.Val,
5876 atomGroup.Val, atomRank.Val, irlayers.Val));
5880bool LLParser::parseDILayerLoc(
MDNode *&Result,
bool IsDistinct) {
5881#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5882 OPTIONAL(line, LineField, ); \
5883 OPTIONAL(column, ColumnField, ); \
5884 REQUIRED(file, MDField, ( false)); \
5885 REQUIRED(kind, MDStringField, );
5887#undef VISIT_MD_FIELDS
5890 (Context, kind.Val,
file.Val, line.Val, column.Val));
5894bool LLParser::parseDILayerLocList(
MDNode *&Result,
bool IsDistinct) {
5903 if (parseMetadata(MD,
nullptr))
5916bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5918 return tokError(
"missing 'distinct', required for !DIAssignID()");
5934bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5935#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5936 REQUIRED(tag, DwarfTagField, ); \
5937 OPTIONAL(header, MDStringField, ); \
5938 OPTIONAL(operands, MDFieldList, );
5940#undef VISIT_MD_FIELDS
5943 (Context, tag.Val, header.Val, operands.Val));
5952bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5953#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5954 OPTIONAL(name, MDStringField, ); \
5955 OPTIONAL(file, MDField, ); \
5956 OPTIONAL(line, LineField, ); \
5957 OPTIONAL(scope, MDField, ); \
5958 OPTIONAL(baseType, MDField, ); \
5959 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5960 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5961 OPTIONAL(flags, DIFlagField, ); \
5962 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5963 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5964 OPTIONAL(stride, MDSignedOrMDField, ); \
5965 OPTIONAL(bias, MDSignedOrMDField, );
5967#undef VISIT_MD_FIELDS
5969 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5970 if (Bound.isMDSignedField())
5973 if (Bound.isMDField())
5974 return Bound.getMDFieldValue();
5980 Metadata *Stride = convToMetadata(stride);
5981 Metadata *Bias = convToMetadata(bias);
5984 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5985 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5986 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5995bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5996#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5997 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5998 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5999 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6000 OPTIONAL(stride, MDSignedOrMDField, );
6002#undef VISIT_MD_FIELDS
6009 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6010 if (Bound.isMDSignedField())
6013 if (Bound.isMDField())
6014 return Bound.getMDFieldValue();
6021 Stride = convToMetadata(stride);
6024 (Context,
Count, LowerBound, UpperBound, Stride));
6032bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
6033#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6034 OPTIONAL(count, MDSignedOrMDField, ); \
6035 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6036 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6037 OPTIONAL(stride, MDSignedOrMDField, );
6039#undef VISIT_MD_FIELDS
6041 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6042 if (Bound.isMDSignedField())
6044 Context, {dwarf::DW_OP_consts,
6045 static_cast<uint64_t>(Bound.getMDSignedValue())});
6046 if (Bound.isMDField())
6047 return Bound.getMDFieldValue();
6054 Metadata *Stride = ConvToMetadata(stride);
6057 (Context,
Count, LowerBound, UpperBound, Stride));
6064bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
6065#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6066 REQUIRED(name, MDStringField, ); \
6067 REQUIRED(value, MDAPSIntField, ); \
6068 OPTIONAL(isUnsigned, MDBoolField, (false));
6070#undef VISIT_MD_FIELDS
6072 if (isUnsigned.Val && value.Val.isNegative())
6073 return tokError(
"unsigned enumerator with negative value");
6078 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6090bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
6091#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6092 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6093 OPTIONAL(name, MDStringField, ); \
6094 OPTIONAL(file, MDField, ); \
6095 OPTIONAL(line, LineField, ); \
6096 OPTIONAL(scope, MDField, ); \
6097 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6098 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6099 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6100 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6101 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6102 OPTIONAL(flags, DIFlagField, );
6104#undef VISIT_MD_FIELDS
6107 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6108 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
6109 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6118bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6119#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6120 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6121 OPTIONAL(name, MDStringField, ); \
6122 OPTIONAL(file, MDField, ); \
6123 OPTIONAL(line, LineField, ); \
6124 OPTIONAL(scope, MDField, ); \
6125 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6126 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6127 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6128 OPTIONAL(flags, DIFlagField, ); \
6129 OPTIONAL(kind, FixedPointKindField, ); \
6130 OPTIONAL(factor, MDSignedField, ); \
6131 OPTIONAL(numerator, MDAPSIntField, ); \
6132 OPTIONAL(denominator, MDAPSIntField, );
6134#undef VISIT_MD_FIELDS
6137 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6138 scope.Val,
size.getValueAsMetadata(Context),
6139 align.Val, encoding.Val, flags.Val, kind.Val,
6140 factor.Val, numerator.Val, denominator.Val));
6146bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6147#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6148 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6149 OPTIONAL(name, MDStringField, ); \
6150 OPTIONAL(stringLength, MDField, ); \
6151 OPTIONAL(stringLengthExpression, MDField, ); \
6152 OPTIONAL(stringLocationExpression, MDField, ); \
6153 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6154 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6155 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6156 OPTIONAL(charType, MDField, );
6158#undef VISIT_MD_FIELDS
6162 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6163 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6164 align.Val, encoding.Val, charType.Val));
6177bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6178#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6179 REQUIRED(tag, DwarfTagField, ); \
6180 OPTIONAL(name, MDStringField, ); \
6181 OPTIONAL(file, MDField, ); \
6182 OPTIONAL(line, LineField, ); \
6183 OPTIONAL(scope, MDField, ); \
6184 REQUIRED(baseType, MDField, ); \
6185 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6186 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6187 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6188 OPTIONAL(flags, DIFlagField, ); \
6189 OPTIONAL(extraData, MDField, ); \
6190 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6191 OPTIONAL(annotations, MDField, ); \
6192 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6193 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6194 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6195 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6196 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6198#undef VISIT_MD_FIELDS
6200 std::optional<unsigned> DWARFAddressSpace;
6201 if (dwarfAddressSpace.Val != UINT32_MAX)
6202 DWARFAddressSpace = dwarfAddressSpace.Val;
6203 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6205 PtrAuthData.emplace(
6206 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6207 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6208 ptrAuthAuthenticatesNullValues.Val);
6211 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6212 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6213 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6214 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6218bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6219#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6220 REQUIRED(tag, DwarfTagField, ); \
6221 OPTIONAL(name, MDStringField, ); \
6222 OPTIONAL(file, MDField, ); \
6223 OPTIONAL(line, LineField, ); \
6224 OPTIONAL(scope, MDField, ); \
6225 OPTIONAL(baseType, MDField, ); \
6226 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6227 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6228 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6229 OPTIONAL(flags, DIFlagField, ); \
6230 OPTIONAL(elements, MDField, ); \
6231 OPTIONAL(runtimeLang, DwarfLangField, ); \
6232 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6233 OPTIONAL(vtableHolder, MDField, ); \
6234 OPTIONAL(templateParams, MDField, ); \
6235 OPTIONAL(identifier, MDStringField, ); \
6236 OPTIONAL(discriminator, MDField, ); \
6237 OPTIONAL(dataLocation, MDField, ); \
6238 OPTIONAL(associated, MDField, ); \
6239 OPTIONAL(allocated, MDField, ); \
6240 OPTIONAL(rank, MDSignedOrMDField, ); \
6241 OPTIONAL(annotations, MDField, ); \
6242 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6243 OPTIONAL(specification, MDField, ); \
6244 OPTIONAL(bitStride, MDField, );
6246#undef VISIT_MD_FIELDS
6249 if (rank.isMDSignedField())
6252 else if (rank.isMDField())
6253 Rank = rank.getMDFieldValue();
6255 std::optional<unsigned> EnumKind;
6257 EnumKind = enumKind.Val;
6262 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6263 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6264 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6265 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6266 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6267 dataLocation.Val, associated.Val, allocated.Val, Rank,
6268 annotations.Val, bitStride.Val)) {
6277 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6278 size.getValueAsMetadata(Context),
align.Val,
6279 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6280 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6281 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6282 allocated.Val, Rank, annotations.Val, specification.Val,
6283 num_extra_inhabitants.Val, bitStride.Val));
6287bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6288#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6289 OPTIONAL(flags, DIFlagField, ); \
6290 OPTIONAL(cc, DwarfCCField, ); \
6291 REQUIRED(types, MDField, );
6293#undef VISIT_MD_FIELDS
6296 (Context, flags.Val, cc.Val, types.Val));
6305bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6309#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6310 REQUIRED(filename, MDStringField, ); \
6311 REQUIRED(directory, MDStringField, ); \
6312 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6313 OPTIONAL(checksum, MDStringField, ); \
6314 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6316#undef VISIT_MD_FIELDS
6318 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6319 if (checksumkind.Seen && checksum.Seen)
6320 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6321 else if (checksumkind.Seen || checksum.Seen)
6322 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6324 MDString *
Source =
nullptr;
6328 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6340bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6342 return tokError(
"missing 'distinct', required for !DICompileUnit");
6344 LocTy Loc = Lex.getLoc();
6346#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6347 REQUIRED(file, MDField, ( false)); \
6348 OPTIONAL(language, DwarfLangField, ); \
6349 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6350 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6351 OPTIONAL(producer, MDStringField, ); \
6352 OPTIONAL(isOptimized, MDBoolField, ); \
6353 OPTIONAL(flags, MDStringField, ); \
6354 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6355 OPTIONAL(splitDebugFilename, MDStringField, ); \
6356 OPTIONAL(emissionKind, EmissionKindField, ); \
6357 OPTIONAL(enums, MDField, ); \
6358 OPTIONAL(retainedTypes, MDField, ); \
6359 OPTIONAL(globals, MDField, ); \
6360 OPTIONAL(imports, MDField, ); \
6361 OPTIONAL(macros, MDField, ); \
6362 OPTIONAL(dwoId, MDUnsignedField, ); \
6363 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6364 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6365 OPTIONAL(nameTableKind, NameTableKindField, ); \
6366 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6367 OPTIONAL(sysroot, MDStringField, ); \
6368 OPTIONAL(sdk, MDStringField, ); \
6369 OPTIONAL(dialect, DwarfLangDialectField, );
6371#undef VISIT_MD_FIELDS
6373 if (!language.Seen && !sourceLanguageName.Seen)
6374 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6375 "required for !DICompileUnit");
6377 if (language.Seen && sourceLanguageName.Seen)
6378 return error(Loc,
"can only specify one of 'language' and "
6379 "'sourceLanguageName' on !DICompileUnit");
6381 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6382 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6383 "'sourceLanguageName' on !DICompileUnit");
6385 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6388 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6389 : DISourceLanguageName(
6390 static_cast<uint16_t>(sourceLanguageName.Val),
6391 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6394 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6395 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6396 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6397 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6398 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6411bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6412 auto Loc = Lex.getLoc();
6413#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6414 OPTIONAL(scope, MDField, ); \
6415 OPTIONAL(name, MDStringField, ); \
6416 OPTIONAL(linkageName, MDStringField, ); \
6417 OPTIONAL(file, MDField, ); \
6418 OPTIONAL(line, LineField, ); \
6419 REQUIRED(type, MDField, ( false)); \
6420 OPTIONAL(isLocal, MDBoolField, ); \
6421 OPTIONAL(isDefinition, MDBoolField, (true)); \
6422 OPTIONAL(scopeLine, LineField, ); \
6423 OPTIONAL(containingType, MDField, ); \
6424 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6425 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6426 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6427 OPTIONAL(flags, DIFlagField, ); \
6428 OPTIONAL(spFlags, DISPFlagField, ); \
6429 OPTIONAL(isOptimized, MDBoolField, ); \
6430 OPTIONAL(unit, MDField, ); \
6431 OPTIONAL(templateParams, MDField, ); \
6432 OPTIONAL(declaration, MDField, ); \
6433 OPTIONAL(retainedNodes, MDField, ); \
6434 OPTIONAL(thrownTypes, MDField, ); \
6435 OPTIONAL(annotations, MDField, ); \
6436 OPTIONAL(targetFuncName, MDStringField, ); \
6437 OPTIONAL(keyInstructions, MDBoolField, );
6439#undef VISIT_MD_FIELDS
6444 spFlags.Seen ? spFlags.Val
6446 isOptimized.Val, virtuality.Val);
6447 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6450 "missing 'distinct', required for !DISubprogram that is a Definition");
6453 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6454 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6455 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6456 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6457 targetFuncName.Val, keyInstructions.Val));
6467bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6468#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6469 REQUIRED(scope, MDField, ( false)); \
6470 OPTIONAL(file, MDField, ); \
6471 OPTIONAL(line, LineField, ); \
6472 OPTIONAL(column, ColumnField, );
6474#undef VISIT_MD_FIELDS
6477 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6483bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6484#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6485 REQUIRED(scope, MDField, ( false)); \
6486 OPTIONAL(file, MDField, ); \
6487 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6489#undef VISIT_MD_FIELDS
6492 (Context, scope.Val,
file.Val, discriminator.Val));
6498bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6499#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6500 REQUIRED(scope, MDField, ); \
6501 OPTIONAL(declaration, MDField, ); \
6502 OPTIONAL(name, MDStringField, ); \
6503 OPTIONAL(file, MDField, ); \
6504 OPTIONAL(line, LineField, );
6506#undef VISIT_MD_FIELDS
6509 (Context, scope.Val, declaration.Val,
name.Val,
6510 file.Val, line.Val));
6516bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6517#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6518 REQUIRED(scope, MDField, ); \
6519 OPTIONAL(name, MDStringField, ); \
6520 OPTIONAL(exportSymbols, MDBoolField, );
6522#undef VISIT_MD_FIELDS
6525 (Context, scope.Val,
name.Val, exportSymbols.Val));
6532bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6533#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6534 REQUIRED(type, DwarfMacinfoTypeField, ); \
6535 OPTIONAL(line, LineField, ); \
6536 REQUIRED(name, MDStringField, ); \
6537 OPTIONAL(value, MDStringField, );
6539#undef VISIT_MD_FIELDS
6542 (Context, type.Val, line.Val,
name.Val, value.Val));
6548bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6549#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6550 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6551 OPTIONAL(line, LineField, ); \
6552 REQUIRED(file, MDField, ); \
6553 OPTIONAL(nodes, MDField, );
6555#undef VISIT_MD_FIELDS
6558 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6566bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6567#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6568 REQUIRED(scope, MDField, ); \
6569 REQUIRED(name, MDStringField, ); \
6570 OPTIONAL(configMacros, MDStringField, ); \
6571 OPTIONAL(includePath, MDStringField, ); \
6572 OPTIONAL(apinotes, MDStringField, ); \
6573 OPTIONAL(file, MDField, ); \
6574 OPTIONAL(line, LineField, ); \
6575 OPTIONAL(isDecl, MDBoolField, );
6577#undef VISIT_MD_FIELDS
6580 configMacros.Val, includePath.Val,
6581 apinotes.Val, line.Val, isDecl.Val));
6587bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6588#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6589 OPTIONAL(name, MDStringField, ); \
6590 REQUIRED(type, MDField, ); \
6591 OPTIONAL(defaulted, MDBoolField, );
6593#undef VISIT_MD_FIELDS
6596 (Context,
name.Val, type.Val, defaulted.Val));
6604bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6605#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6606 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6607 OPTIONAL(name, MDStringField, ); \
6608 OPTIONAL(type, MDField, ); \
6609 OPTIONAL(defaulted, MDBoolField, ); \
6610 REQUIRED(value, MDField, );
6613#undef VISIT_MD_FIELDS
6616 DITemplateValueParameter,
6617 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6626bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6627#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6628 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6629 OPTIONAL(scope, MDField, ); \
6630 OPTIONAL(linkageName, MDStringField, ); \
6631 OPTIONAL(file, MDField, ); \
6632 OPTIONAL(line, LineField, ); \
6633 OPTIONAL(type, MDField, ); \
6634 OPTIONAL(isLocal, MDBoolField, ); \
6635 OPTIONAL(isDefinition, MDBoolField, (true)); \
6636 OPTIONAL(templateParams, MDField, ); \
6637 OPTIONAL(declaration, MDField, ); \
6638 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6639 OPTIONAL(annotations, MDField, );
6641#undef VISIT_MD_FIELDS
6645 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6646 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6647 declaration.Val, templateParams.Val,
align.Val,
6659bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6660#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6661 REQUIRED(scope, MDField, ( false)); \
6662 OPTIONAL(name, MDStringField, ); \
6663 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6664 OPTIONAL(file, MDField, ); \
6665 OPTIONAL(line, LineField, ); \
6666 OPTIONAL(type, MDField, ); \
6667 OPTIONAL(flags, DIFlagField, ); \
6668 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6669 OPTIONAL(annotations, MDField, );
6671#undef VISIT_MD_FIELDS
6674 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6675 type.Val, arg.Val, flags.Val,
align.Val,
6682bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6683#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6684 REQUIRED(scope, MDField, ( false)); \
6685 REQUIRED(name, MDStringField, ); \
6686 REQUIRED(file, MDField, ); \
6687 REQUIRED(line, LineField, ); \
6688 OPTIONAL(column, ColumnField, ); \
6689 OPTIONAL(isArtificial, MDBoolField, ); \
6690 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6692#undef VISIT_MD_FIELDS
6694 std::optional<unsigned> CoroSuspendIdx =
6695 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6699 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6700 column.Val, isArtificial.Val, CoroSuspendIdx));
6706bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6719 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6728 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6729 Lex.getStrVal() +
"'");
6732 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6733 return tokError(
"expected unsigned integer");
6735 auto &
U = Lex.getAPSIntVal();
6737 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6751bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6753 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6756 return parseDIExpressionBody(Result, IsDistinct);
6761bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6762 assert(PFS &&
"Expected valid function state");
6773 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6787bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6789#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6790 REQUIRED(var, MDField, ); \
6791 REQUIRED(expr, MDField, );
6793#undef VISIT_MD_FIELDS
6796 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6803bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6804#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6805 OPTIONAL(name, MDStringField, ); \
6806 OPTIONAL(file, MDField, ); \
6807 OPTIONAL(line, LineField, ); \
6808 OPTIONAL(setter, MDStringField, ); \
6809 OPTIONAL(getter, MDStringField, ); \
6810 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6811 OPTIONAL(type, MDField, );
6813#undef VISIT_MD_FIELDS
6816 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6817 setter.Val, attributes.Val, type.Val));
6824bool LLParser::parseDIProperty(
MDNode *&Result,
bool IsDistinct) {
6825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6826 OPTIONAL(name, MDStringField, ); \
6827 OPTIONAL(file, MDField, ); \
6828 OPTIONAL(line, LineField, ); \
6829 OPTIONAL(type, MDField, ); \
6830 OPTIONAL(backing_storage, MDField, );
6832#undef VISIT_MD_FIELDS
6835 type.Val, backing_storage.Val));
6842bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6843#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6844 REQUIRED(tag, DwarfTagField, ); \
6845 REQUIRED(scope, MDField, ); \
6846 OPTIONAL(entity, MDField, ); \
6847 OPTIONAL(file, MDField, ); \
6848 OPTIONAL(line, LineField, ); \
6849 OPTIONAL(name, MDStringField, ); \
6850 OPTIONAL(elements, MDField, );
6852#undef VISIT_MD_FIELDS
6855 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6856 line.Val,
name.Val, elements.Val));
6860#undef PARSE_MD_FIELD
6872bool LLParser::parseMetadataAsValue(
Value *&
V, PerFunctionState &PFS) {
6875 if (parseMetadata(MD, &PFS))
6886bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6887 PerFunctionState *PFS) {
6890 if (parseType(Ty, TypeMsg, Loc))
6893 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6896 if (parseValue(Ty,
V, PFS))
6911bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6915 if (Lex.getStrVal() ==
"DIArgList") {
6917 if (parseDIArgList(AL, PFS))
6923 if (parseSpecializedMDNode(
N)) {
6933 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6943 if (parseMDString(S))
6953 if (parseMDNodeTail(
N))
6964 PerFunctionState *PFS) {
6966 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6971 return error(
ID.Loc,
"invalid use of function-local name");
6972 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6973 return V ==
nullptr;
6976 return error(
ID.Loc,
"invalid use of function-local name");
6977 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6978 return V ==
nullptr;
6981 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6985 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6990 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6993 return V ==
nullptr;
6995 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6998 return V ==
nullptr;
7001 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
7004 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
7009 return error(
ID.Loc,
"floating point constant invalid for type");
7015 bool IsSNAN = ID.APFloatVal.isSignaling();
7018 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7020 else if (Ty->isBFloatTy())
7021 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7023 else if (Ty->isFloatTy())
7024 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7030 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7031 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7032 ID.APFloatVal.isNegative(), &Payload);
7035 V = ConstantFP::get(Context,
ID.APFloatVal);
7037 if (
V->getType() != Ty)
7038 return error(
ID.Loc,
"floating point constant does not have type '" +
7044 return error(
ID.Loc,
"null must be a pointer type");
7050 return error(
ID.Loc,
"invalid type for undef constant");
7055 return error(
ID.Loc,
"invalid empty array initializer");
7061 return error(
ID.Loc,
"invalid type for null constant");
7064 return error(
ID.Loc,
"invalid type for null constant");
7069 return error(
ID.Loc,
"invalid type for none constant");
7075 return error(
ID.Loc,
"invalid type for poison constant");
7079 if (
ID.ConstantVal->getType() != Ty)
7080 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7087 return error(
ID.Loc,
"vector constant must have vector type");
7089 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7091 "' but expected '" +
7099 if (
ST->getNumElements() !=
ID.UIntVal)
7101 "initializer with struct type has wrong # elements");
7103 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
7106 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
7107 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
7110 "element " + Twine(i) +
7111 " of struct initializer doesn't match struct element type");
7114 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
7116 return error(
ID.Loc,
"constant expression type mismatch");
7125 auto Loc = Lex.getLoc();
7126 if (parseValID(ID,
nullptr, Ty))
7139 if (convertValIDToValue(Ty, ID,
V,
nullptr))
7149 return error(Loc,
"expected a constant value");
7153bool LLParser::parseValue(
Type *Ty,
Value *&
V, PerFunctionState *PFS) {
7157 FileLoc
Start = getTokLineColumnPos();
7158 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID,
V, PFS);
7159 if (!Ret && ParserContext) {
7160 FileLoc
End = getPrevTokEndLineColumnPos();
7161 ParserContext->addValueReferenceAtLocation(
V, FileLocRange(Start,
End));
7166bool LLParser::parseTypeAndValue(
Value *&
V, PerFunctionState *PFS) {
7168 return parseType(Ty) || parseValue(Ty,
V, PFS);
7171bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7172 PerFunctionState &PFS) {
7175 if (parseTypeAndValue(
V, PFS))
7178 return error(Loc,
"expected a basic block");
7187 if (!Name.starts_with(
"llvm.dbg."))
7190 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7191 FnID == Intrinsic::dbg_assign;
7199bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7200 unsigned &FunctionNumber,
7203 LocTy LinkageLoc = Lex.getLoc();
7205 unsigned Visibility;
7206 unsigned DLLStorageClass;
7208 AttrBuilder RetAttrs(M->getContext());
7211 Type *RetType =
nullptr;
7212 LocTy RetTypeLoc = Lex.getLoc();
7213 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7215 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7216 parseType(RetType, RetTypeLoc,
true ))
7225 return error(LinkageLoc,
"invalid linkage for function definition");
7235 return error(LinkageLoc,
"invalid linkage for function declaration");
7239 return error(LinkageLoc,
"invalid function linkage type");
7243 return error(LinkageLoc,
7244 "symbol with local linkage must have default visibility");
7247 return error(LinkageLoc,
7248 "symbol with local linkage cannot have a DLL storage class");
7251 return error(RetTypeLoc,
"invalid function return type");
7253 LocTy NameLoc = Lex.getLoc();
7255 std::string FunctionName;
7257 FunctionName = Lex.getStrVal();
7259 FunctionNumber = Lex.getUIntVal();
7260 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7264 return tokError(
"expected function name");
7270 return tokError(
"expected '(' in function argument list");
7274 AttrBuilder FuncAttrs(M->getContext());
7275 std::vector<unsigned> FwdRefAttrGrps;
7278 std::string Partition;
7282 unsigned AddrSpace = 0;
7288 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7289 parseOptionalUnnamedAddr(UnnamedAddr) ||
7290 parseOptionalProgramAddrSpace(AddrSpace) ||
7291 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7295 parseOptionalComdat(FunctionName,
C) ||
7296 parseOptionalAlignment(Alignment) ||
7297 parseOptionalPrefAlignment(PrefAlignment) ||
7298 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7302 parseGlobalTypeAndValue(PersonalityFn)))
7305 if (FuncAttrs.contains(Attribute::Builtin))
7306 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7309 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7311 FuncAttrs.removeAttribute(Attribute::Alignment);
7316 std::vector<Type*> ParamTypeList;
7319 for (
const ArgInfo &Arg : ArgList) {
7320 ParamTypeList.push_back(Arg.Ty);
7321 Attrs.push_back(Arg.Attrs);
7328 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7329 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7335 GlobalValue *FwdFn =
nullptr;
7336 if (!FunctionName.empty()) {
7339 auto FRVI = ForwardRefVals.find(FunctionName);
7340 if (FRVI != ForwardRefVals.end()) {
7341 FwdFn = FRVI->second.first;
7343 return error(FRVI->second.second,
7344 "invalid forward reference to "
7347 "' with wrong type: "
7351 ForwardRefVals.erase(FRVI);
7352 }
else if ((Fn = M->getFunction(FunctionName))) {
7354 return error(NameLoc,
7355 "invalid redefinition of function '" + FunctionName +
"'");
7356 }
else if (M->getNamedValue(FunctionName)) {
7357 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7363 if (FunctionNumber == (
unsigned)-1)
7364 FunctionNumber = NumberedVals.getNext();
7368 auto I = ForwardRefValIDs.find(FunctionNumber);
7369 if (
I != ForwardRefValIDs.end()) {
7370 FwdFn =
I->second.first;
7372 return error(NameLoc,
"type of definition and forward reference of '@" +
7373 Twine(FunctionNumber) +
7378 ForwardRefValIDs.erase(
I);
7387 if (FunctionName.empty())
7388 NumberedVals.add(FunctionNumber, Fn);
7404 if (!
GC.empty()) Fn->
setGC(GC);
7407 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7411 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7412 if (ParserContext && ArgList[i].IdentLoc)
7413 ParserContext->addInstructionOrArgumentLocation(
7414 &*ArgIt, ArgList[i].IdentLoc.value());
7416 if (ArgList[i].
Name.empty())
continue;
7419 ArgIt->
setName(ArgList[i].Name);
7421 if (ArgIt->
getName() != ArgList[i].Name)
7422 return error(ArgList[i].Loc,
7423 "redefinition of argument '%" + ArgList[i].Name +
"'");
7436 if (FunctionName.empty()) {
7438 ID.UIntVal = FunctionNumber;
7441 ID.StrVal = FunctionName;
7443 auto Blocks = ForwardRefBlockAddresses.find(ID);
7444 if (Blocks != ForwardRefBlockAddresses.end())
7445 return error(Blocks->first.Loc,
7446 "cannot take blockaddress inside a declaration");
7450bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7452 if (FunctionNumber == -1) {
7454 ID.StrVal = std::string(F.getName());
7457 ID.UIntVal = FunctionNumber;
7460 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7461 if (Blocks == P.ForwardRefBlockAddresses.end())
7464 for (
const auto &
I : Blocks->second) {
7465 const ValID &BBID =
I.first;
7466 GlobalValue *GV =
I.second;
7469 "Expected local id or name");
7476 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7479 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7487 P.ForwardRefBlockAddresses.erase(Blocks);
7493bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
7494 ArrayRef<unsigned> UnnamedArgNums) {
7496 return tokError(
"expected '{' in function body");
7499 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7503 if (PFS.resolveForwardRefBlockAddresses())
7509 return tokError(
"function body requires at least one basic block");
7513 if (parseBasicBlock(PFS))
7517 if (parseUseListOrder(&PFS))
7524 return PFS.finishFunction();
7529bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7530 FileLoc BBStart = getTokLineColumnPos();
7535 LocTy NameLoc = Lex.getLoc();
7537 Name = Lex.getStrVal();
7540 NameID = Lex.getUIntVal();
7544 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7548 std::string NameStr;
7553 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7554 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7561 if (SeenOldDbgInfoFormat)
7562 return error(Lex.getLoc(),
"debug record should not appear in a module "
7563 "containing debug info intrinsics");
7564 SeenNewDbgInfoFormat =
true;
7568 if (parseDebugRecord(DR, PFS))
7570 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7573 FileLoc InstStart = getTokLineColumnPos();
7576 LocTy NameLoc = Lex.getLoc();
7581 NameID = Lex.getUIntVal();
7583 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7586 NameStr = Lex.getStrVal();
7588 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7592 switch (parseInstruction(Inst, BB, PFS)) {
7595 case InstError:
return true;
7602 if (parseInstructionMetadata(*Inst))
7605 case InstExtraComma:
7610 if (parseInstructionMetadata(*Inst))
7616 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7620 for (DbgRecordPtr &DR : TrailingDbgRecord)
7622 TrailingDbgRecord.clear();
7623 if (ParserContext) {
7624 ParserContext->addInstructionOrArgumentLocation(
7625 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7630 ParserContext->addBlockLocation(
7631 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7633 assert(TrailingDbgRecord.empty() &&
7634 "All debug values should have been attached to an instruction.");
7643bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7646 LocTy DVRLoc = Lex.getLoc();
7648 return error(DVRLoc,
"expected debug record type here");
7649 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7650 .Case(
"declare", RecordKind::ValueKind)
7651 .Case(
"value", RecordKind::ValueKind)
7652 .Case(
"assign", RecordKind::ValueKind)
7653 .Case(
"label", RecordKind::LabelKind)
7654 .Case(
"declare_value", RecordKind::ValueKind);
7663 if (parseMDNode(Label))
7668 if (parseMDNode(DbgLoc))
7673 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7677 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7678 .Case(
"declare", LocType::Declare)
7679 .Case(
"value", LocType::Value)
7680 .Case(
"assign", LocType::Assign)
7681 .Case(
"declare_value", LocType::DeclareValue);
7689 if (parseMetadata(ValLocMD, &PFS))
7696 if (parseMDNode(Variable))
7703 if (parseMDNode(Expression))
7709 MDNode *AssignID =
nullptr;
7710 Metadata *AddressLocation =
nullptr;
7711 MDNode *AddressExpression =
nullptr;
7714 if (parseMDNode(AssignID))
7720 if (parseMetadata(AddressLocation, &PFS))
7726 if (parseMDNode(AddressExpression))
7740 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7742 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7751int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7752 PerFunctionState &PFS) {
7755 return tokError(
"found end of file when expecting more instructions");
7756 LocTy Loc = Lex.getLoc();
7757 unsigned KeywordVal = Lex.getUIntVal();
7762 return error(Loc,
"expected instruction opcode");
7766 return parseRet(Inst, BB, PFS);
7768 return parseBr(Inst, PFS);
7770 return parseSwitch(Inst, PFS);
7772 return parseIndirectBr(Inst, PFS);
7774 return parseInvoke(Inst, PFS);
7776 return parseResume(Inst, PFS);
7778 return parseCleanupRet(Inst, PFS);
7780 return parseCatchRet(Inst, PFS);
7782 return parseCatchSwitch(Inst, PFS);
7784 return parseCatchPad(Inst, PFS);
7786 return parseCleanupPad(Inst, PFS);
7788 return parseCallBr(Inst, PFS);
7791 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7792 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7808 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7820 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7821 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7835 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7843 return parseArithmetic(Inst, PFS, KeywordVal,
7847 if (parseLogical(Inst, PFS, KeywordVal))
7855 return parseLogical(Inst, PFS, KeywordVal);
7858 if (parseCompare(Inst, PFS, KeywordVal))
7865 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7866 int Res = parseCompare(Inst, PFS, KeywordVal);
7876 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7878 bool Res = parseCast(Inst, PFS, KeywordVal);
7888 bool Res = parseCast(Inst, PFS, KeywordVal);
7900 if (parseCast(Inst, PFS, KeywordVal))
7909 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7910 if (parseCast(Inst, PFS, KeywordVal))
7923 return parseCast(Inst, PFS, KeywordVal);
7927 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7928 if (parseCast(Inst, PFS, KeywordVal))
7937 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7938 int Res = parseSelect(Inst, PFS);
7944 return error(Loc,
"fast-math-flags specified for select without "
7945 "floating-point scalar or vector return type");
7952 return parseVAArg(Inst, PFS);
7954 return parseExtractElement(Inst, PFS);
7956 return parseInsertElement(Inst, PFS);
7958 return parseShuffleVector(Inst, PFS);
7960 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7961 int Res = parsePHI(Inst, PFS);
7967 return error(Loc,
"fast-math-flags specified for phi without "
7968 "floating-point scalar or vector return type");
7975 return parseLandingPad(Inst, PFS);
7977 return parseFreeze(Inst, PFS);
7979 return parseBitInsert(Inst, PFS);
7981 return parseBitExtract(Inst, PFS);
7993 return parseAlloc(Inst, PFS);
7995 return parseLoad(Inst, PFS);
7997 return parseStore(Inst, PFS);
7999 return parseCmpXchg(Inst, PFS);
8001 return parseAtomicRMW(Inst, PFS);
8003 return parseFence(Inst, PFS);
8005 return parseGetElementPtr(Inst, PFS);
8007 return parseExtractValue(Inst, PFS);
8009 return parseInsertValue(Inst, PFS);
8014bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
8015 if (
Opc == Instruction::FCmp) {
8016 switch (Lex.getKind()) {
8018 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
8037 switch (Lex.getKind()) {
8039 return tokError(
"expected icmp predicate (e.g. 'eq')");
8063bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8064 PerFunctionState &PFS) {
8065 SMLoc TypeLoc = Lex.getLoc();
8067 if (parseType(Ty,
true ))
8070 Type *ResType = PFS.getFunction().getReturnType();
8074 return error(TypeLoc,
"value doesn't match function result type '" +
8082 if (parseValue(Ty, RV, PFS))
8086 return error(TypeLoc,
"value doesn't match function result type '" +
8096bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8100 if (parseTypeAndValue(Op0, Loc, PFS))
8109 return error(Loc,
"branch condition must have 'i1' type");
8111 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
8112 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8113 parseToken(
lltok::comma,
"expected ',' after true destination") ||
8114 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8126bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8127 LocTy CondLoc, BBLoc;
8130 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
8131 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
8132 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8136 if (!
Cond->getType()->isIntegerTy())
8137 return error(CondLoc,
"switch condition must have integer type");
8140 SmallPtrSet<Value*, 32> SeenCases;
8146 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8147 parseToken(
lltok::comma,
"expected ',' after case value") ||
8148 parseTypeAndBasicBlock(DestBB, PFS))
8151 if (!SeenCases.
insert(Constant).second)
8152 return error(CondLoc,
"duplicate case value in switch");
8154 return error(CondLoc,
"case value is not a constant integer");
8162 for (
const auto &[OnVal, Dest] :
Table)
8163 SI->addCase(OnVal, Dest);
8171bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8174 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8175 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8179 if (!
Address->getType()->isPointerTy())
8180 return error(AddrLoc,
"indirectbr address must have pointer type");
8183 SmallVector<BasicBlock*, 16> DestList;
8187 if (parseTypeAndBasicBlock(DestBB, PFS))
8192 if (parseTypeAndBasicBlock(DestBB, PFS))
8198 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8202 for (BasicBlock *Dest : DestList)
8212 FunctionType *&FuncTy) {
8218 for (
const ParamInfo &Arg : ArgList)
8232bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8233 LocTy CallLoc = Lex.getLoc();
8234 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8235 std::vector<unsigned> FwdRefAttrGrps;
8238 unsigned InvokeAddrSpace;
8239 Type *RetType =
nullptr;
8246 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8247 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8248 parseType(RetType, RetTypeLoc,
true ) ||
8249 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8250 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8252 parseOptionalOperandBundles(BundleList, PFS) ||
8254 parseTypeAndBasicBlock(NormalBB, PFS) ||
8256 parseTypeAndBasicBlock(UnwindBB, PFS))
8263 if (resolveFunctionType(RetType, ArgList, Ty))
8264 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8270 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8275 SmallVector<Value *, 8>
Args;
8282 for (
const ParamInfo &Arg : ArgList) {
8283 Type *ExpectedTy =
nullptr;
8286 }
else if (!Ty->isVarArg()) {
8287 return error(Arg.Loc,
"too many arguments specified");
8290 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8291 return error(Arg.Loc,
"argument is not of expected type '" +
8293 Args.push_back(Arg.V);
8298 return error(CallLoc,
"not enough parameters specified for call");
8307 II->setCallingConv(
CC);
8308 II->setAttributes(PAL);
8309 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8316bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8318 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8326bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8327 PerFunctionState &PFS) {
8328 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8333 if (!
Args.empty() &&
8334 parseToken(
lltok::comma,
"expected ',' in argument list"))
8339 Type *ArgTy =
nullptr;
8340 if (parseType(ArgTy, ArgLoc))
8345 if (parseMetadataAsValue(
V, PFS))
8348 if (parseValue(ArgTy,
V, PFS))
8360bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8361 Value *CleanupPad =
nullptr;
8363 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8378 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8389bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8390 Value *CatchPad =
nullptr;
8392 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8399 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8400 parseTypeAndBasicBlock(BB, PFS))
8409bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8417 return tokError(
"expected scope value for catchswitch");
8422 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8428 if (parseTypeAndBasicBlock(DestBB, PFS))
8430 Table.push_back(DestBB);
8433 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8436 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8444 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8450 for (BasicBlock *DestBB :
Table)
8451 CatchSwitch->addHandler(DestBB);
8458bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8459 Value *CatchSwitch =
nullptr;
8465 return tokError(
"expected scope value for catchpad");
8470 SmallVector<Value *, 8>
Args;
8471 if (parseExceptionArgs(Args, PFS))
8480bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8481 Value *ParentPad =
nullptr;
8488 return tokError(
"expected scope value for cleanuppad");
8493 SmallVector<Value *, 8>
Args;
8494 if (parseExceptionArgs(Args, PFS))
8510bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8511 unsigned Opc,
bool IsFP) {
8513 if (parseTypeAndValue(
LHS, Loc, PFS))
8520 return error(Loc,
"invalid operand type for instruction");
8530bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8531 LocTy CallLoc = Lex.getLoc();
8532 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8533 std::vector<unsigned> FwdRefAttrGrps;
8536 Type *RetType =
nullptr;
8543 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8544 parseType(RetType, RetTypeLoc,
true ) ||
8545 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8546 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8548 parseOptionalOperandBundles(BundleList, PFS) ||
8550 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8555 SmallVector<BasicBlock *, 16> IndirectDests;
8559 if (parseTypeAndBasicBlock(DestBB, PFS))
8564 if (parseTypeAndBasicBlock(DestBB, PFS))
8570 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8577 if (resolveFunctionType(RetType, ArgList, Ty))
8578 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8589 SmallVector<Value *, 8>
Args;
8596 for (
const ParamInfo &Arg : ArgList) {
8597 Type *ExpectedTy =
nullptr;
8600 }
else if (!Ty->isVarArg()) {
8601 return error(Arg.Loc,
"too many arguments specified");
8604 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8605 return error(Arg.Loc,
"argument is not of expected type '" +
8607 Args.push_back(Arg.V);
8612 return error(CallLoc,
"not enough parameters specified for call");
8624 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8638bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8639 unsigned Opc,
bool IsFP) {
8641 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8642 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8650 return error(Loc,
"invalid operand type for instruction");
8658bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8661 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8662 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8668 "instruction requires integer or integer vector operands");
8677bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8683 if (parseCmpPredicate(
Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8684 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8688 if (
Opc == Instruction::FCmp) {
8690 return error(Loc,
"fcmp requires floating point operands");
8693 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8696 return error(Loc,
"icmp requires integer operands");
8708bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8712 Type *DestTy =
nullptr;
8713 if (parseTypeAndValue(
Op, Loc, PFS) ||
8714 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8719 return error(Loc,
"invalid cast opcode for cast from '" +
8728bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8730 Value *Op0, *Op1, *Op2;
8731 if (parseTypeAndValue(Op0, Loc, PFS) ||
8732 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8733 parseTypeAndValue(Op1, PFS) ||
8734 parseToken(
lltok::comma,
"expected ',' after select value") ||
8735 parseTypeAndValue(Op2, PFS))
8739 return error(Loc, Reason);
8747bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8749 Type *EltTy =
nullptr;
8751 if (parseTypeAndValue(
Op, PFS) ||
8752 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8753 parseType(EltTy, TypeLoc))
8757 return error(TypeLoc,
"va_arg requires operand with first class type");
8759 Inst =
new VAArgInst(
Op, EltTy);
8765bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8768 if (parseTypeAndValue(Op0, Loc, PFS) ||
8769 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8770 parseTypeAndValue(Op1, PFS))
8774 return error(Loc,
"invalid extractelement operands");
8782bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8784 Value *Op0, *Op1, *Op2;
8785 if (parseTypeAndValue(Op0, Loc, PFS) ||
8786 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8787 parseTypeAndValue(Op1, PFS) ||
8788 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8789 parseTypeAndValue(Op2, PFS))
8793 return error(Loc,
"invalid insertelement operands");
8801bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
8805 if (parseType(Ty, Loc) ||
8806 parseToken(
lltok::comma,
"expected ',' after bitextract type") ||
8807 parseTypeAndValue(Op0, Loc, PFS) ||
8808 parseToken(
lltok::comma,
"expected ',' after bitextract source value") ||
8809 parseTypeAndValue(Op1, PFS))
8813 return error(Loc, Reason);
8821bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
8823 Value *Op0, *Op1, *Op2;
8824 if (parseTypeAndValue(Op0, Loc, PFS) ||
8825 parseToken(
lltok::comma,
"expected ',' after bitinsert source value") ||
8826 parseTypeAndValue(Op1, PFS) ||
8827 parseToken(
lltok::comma,
"expected ',' after bitinsert insert value") ||
8828 parseTypeAndValue(Op2, PFS))
8832 return error(Loc, Reason);
8840bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8842 Value *Op0, *Op1, *Op2;
8843 if (parseTypeAndValue(Op0, Loc, PFS) ||
8844 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8845 parseTypeAndValue(Op1, PFS) ||
8846 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8847 parseTypeAndValue(Op2, PFS))
8851 return error(Loc,
"invalid shufflevector operands");
8853 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8859int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8863 if (parseType(Ty, TypeLoc))
8867 return error(TypeLoc,
"phi node must have first class type");
8870 bool AteExtraComma =
false;
8882 AteExtraComma =
true;
8886 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8887 parseValue(Ty, Op0, PFS) ||
8888 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8897 for (
const auto &[Val, BB] : PHIVals)
8900 return AteExtraComma ? InstExtraComma : InstNormal;
8909bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8912 if (parseType(Ty, TyLoc))
8925 return tokError(
"expected 'catch' or 'filter' clause type");
8929 if (parseTypeAndValue(
V, VLoc, PFS))
8936 return error(VLoc,
"'catch' clause has an invalid type");
8939 return error(VLoc,
"'filter' clause has an invalid type");
8944 return error(VLoc,
"clause argument must be a constant");
8948 Inst = LP.release();
8954bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8957 if (parseTypeAndValue(
Op, Loc, PFS))
8960 Inst =
new FreezeInst(
Op);
8973bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8975 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8976 std::vector<unsigned> FwdRefAttrGrps;
8978 unsigned CallAddrSpace;
8980 Type *RetType =
nullptr;
8985 LocTy CallLoc = Lex.getLoc();
8989 "expected 'tail call', 'musttail call', or 'notail call'"))
8992 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8994 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8995 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8996 parseType(RetType, RetTypeLoc,
true ) ||
8997 parseValID(CalleeID, &PFS) ||
8999 PFS.getFunction().isVarArg()) ||
9000 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
9001 parseOptionalOperandBundles(BundleList, PFS))
9008 if (resolveFunctionType(RetType, ArgList, Ty))
9009 return error(RetTypeLoc,
"Invalid result type for LLVM function");
9015 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
9022 SmallVector<Value*, 8>
Args;
9028 for (
const ParamInfo &Arg : ArgList) {
9029 Type *ExpectedTy =
nullptr;
9032 }
else if (!Ty->isVarArg()) {
9033 return error(Arg.Loc,
"too many arguments specified");
9036 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9037 return error(Arg.Loc,
"argument is not of expected type '" +
9039 Args.push_back(Arg.V);
9040 Attrs.push_back(Arg.Attrs);
9044 return error(CallLoc,
"not enough parameters specified for call");
9057 return error(CallLoc,
"fast-math-flags specified for call without "
9058 "floating-point scalar or vector return type");
9065 if (SeenNewDbgInfoFormat) {
9067 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
9068 "using non-intrinsic debug info");
9070 SeenOldDbgInfoFormat =
true;
9073 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9085int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9087 LocTy SizeLoc, TyLoc, ASLoc;
9089 unsigned AddrSpace = 0;
9092 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9093 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9095 if (parseType(Ty, TyLoc))
9099 return error(TyLoc,
"invalid type for alloca");
9101 bool AteExtraComma =
false;
9103 if (Lex.getKind() == lltok::kw_align) {
9104 if (parseOptionalAlignment(Alignment))
9106 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9109 ASLoc = Lex.getLoc();
9110 if (parseOptionalAddrSpace(AddrSpace))
9113 AteExtraComma =
true;
9115 if (parseTypeAndValue(
Size, SizeLoc, PFS))
9118 if (Lex.getKind() == lltok::kw_align) {
9119 if (parseOptionalAlignment(Alignment))
9121 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9124 ASLoc = Lex.getLoc();
9125 if (parseOptionalAddrSpace(AddrSpace))
9128 AteExtraComma =
true;
9134 if (
Size && !
Size->getType()->isIntegerTy())
9135 return error(SizeLoc,
"element count must have integer type");
9137 if (!Alignment && !Ty->
isSized())
9138 return error(TyLoc,
"Cannot allocate unsized type");
9140 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9141 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
9145 return AteExtraComma ? InstExtraComma : InstNormal;
9152int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9155 bool AteExtraComma =
false;
9165 bool isVolatile =
false;
9171 bool IsElementwise =
false;
9173 IsElementwise =
true;
9178 LocTy ExplicitTypeLoc = Lex.getLoc();
9179 if (parseType(Ty) ||
9180 parseToken(
lltok::comma,
"expected comma after load's type") ||
9181 parseTypeAndValue(Val, Loc, PFS) ||
9182 parseScopeAndOrdering(
isAtomic, SSID, Ordering) ||
9183 parseOptionalCommaAlign(Alignment, AteExtraComma))
9187 return error(Loc,
"load operand must be a pointer to a first class type");
9190 return error(Loc,
"elementwise load must be atomic");
9193 return error(ExplicitTypeLoc,
9194 "atomic elementwise load operand must have fixed vector type");
9197 return error(Loc,
"atomic load must have explicit non-zero alignment");
9201 return error(Loc,
"atomic load cannot use Release ordering");
9204 "atomic elementwise load cannot be sequentially consistent");
9206 if (!Alignment && !Ty->
isSized())
9207 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9209 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9210 Inst =
new LoadInst(Ty, Val,
"",
9212 SSID, IsElementwise},
9214 return AteExtraComma ? InstExtraComma : InstNormal;
9222int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9226 bool AteExtraComma =
false;
9236 bool isVolatile =
false;
9242 bool IsElementwise =
false;
9244 IsElementwise =
true;
9248 if (parseTypeAndValue(Val, Loc, PFS) ||
9249 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9250 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9251 parseScopeAndOrdering(
isAtomic, SSID, Ordering) ||
9252 parseOptionalCommaAlign(Alignment, AteExtraComma))
9256 return error(PtrLoc,
"store operand must be a pointer");
9258 return error(Loc,
"store operand must be a first class value");
9260 return error(Loc,
"atomic store must have explicit non-zero alignment");
9263 return error(Loc,
"atomic store cannot use Acquire ordering");
9266 return error(Loc,
"elementwise store must be atomic");
9270 Loc,
"atomic elementwise store operand must have fixed vector type");
9274 "atomic elementwise store cannot be sequentially consistent");
9277 return error(Loc,
"storing unsized types is not allowed");
9281 Inst =
new StoreInst(Val, Ptr,
9283 SSID, IsElementwise},
9285 return AteExtraComma ? InstExtraComma : InstNormal;
9292int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9294 bool AteExtraComma =
false;
9298 bool isVolatile =
false;
9299 bool isWeak =
false;
9308 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9309 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9310 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9311 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9312 parseTypeAndValue(New, NewLoc, PFS) ||
9313 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9314 parseOrdering(FailureOrdering) ||
9315 parseOptionalCommaAlign(Alignment, AteExtraComma))
9319 return tokError(
"invalid cmpxchg success ordering");
9321 return tokError(
"invalid cmpxchg failure ordering");
9323 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9324 if (
Cmp->getType() !=
New->getType())
9325 return error(NewLoc,
"compare value and new value type do not match");
9326 if (!
New->getType()->isFirstClassType())
9327 return error(NewLoc,
"cmpxchg operand must be a first class value");
9329 const Align DefaultAlignment(
9330 PFS.getFunction().getDataLayout().getTypeStoreSize(
9333 AtomicCmpXchgInst *CXI =
9334 new AtomicCmpXchgInst(Ptr, Cmp, New,
Alignment.value_or(DefaultAlignment),
9335 SuccessOrdering, FailureOrdering, SSID);
9340 return AteExtraComma ? InstExtraComma : InstNormal;
9347int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9349 bool AteExtraComma =
false;
9353 bool IsElementwise =
false;
9361 IsElementwise =
true;
9363 switch (Lex.getKind()) {
9365 return tokError(
"expected binary operation in atomicrmw");
9424 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9425 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9426 parseTypeAndValue(Val, ValLoc, PFS) ||
9427 parseScopeAndOrdering(
true , SSID, Ordering) ||
9428 parseOptionalCommaAlign(Alignment, AteExtraComma))
9432 return tokError(
"atomicrmw cannot be unordered");
9434 return tokError(
"atomicrmw elementwise cannot be sequentially consistent");
9436 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9438 return error(ValLoc,
"atomicrmw operand may not be scalable");
9441 if (IsElementwise) {
9443 return error(ValLoc,
9444 "atomicrmw elementwise operand must be a fixed vector type");
9453 " operand must be an integer type, a floating-point type, a "
9454 "pointer type, or a fixed vector of any of these types");
9458 return error(ValLoc,
"atomicrmw " +
9460 " operand must be a floating point or fixed "
9461 "vector of floating point type");
9468 " operand must be an integer or fixed vector of integer type");
9473 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9475 return error(ValLoc,
9476 "atomicrmw operand must have a power-of-two byte size");
9477 const Align DefaultAlignment(
9478 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9479 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9481 Ordering, SSID, IsElementwise);
9484 return AteExtraComma ? InstExtraComma : InstNormal;
9489int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9492 if (parseScopeAndOrdering(
true , SSID, Ordering))
9496 return tokError(
"fence cannot be unordered");
9498 return tokError(
"fence cannot be monotonic");
9500 Inst =
new FenceInst(Context, Ordering, SSID);
9506int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9507 Value *Ptr =
nullptr;
9508 Value *Val =
nullptr;
9524 if (parseType(Ty) ||
9525 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9526 parseTypeAndValue(Ptr, Loc, PFS))
9531 if (!BasePointerType)
9532 return error(Loc,
"base of getelementptr must be a pointer");
9534 SmallVector<Value*, 16> Indices;
9535 bool AteExtraComma =
false;
9538 ElementCount GEPWidth =
BaseType->isVectorTy()
9544 AteExtraComma =
true;
9547 if (parseTypeAndValue(Val, EltLoc, PFS))
9550 return error(EltLoc,
"getelementptr index must be an integer");
9553 ElementCount ValNumEl = ValVTy->getElementCount();
9557 "getelementptr vector index has a wrong number of elements");
9558 GEPWidth = ValNumEl;
9564 return error(Loc,
"base element of getelementptr must be sized");
9567 return error(Loc,
"invalid getelementptr indices");
9570 GEP->setNoWrapFlags(NW);
9571 return AteExtraComma ? InstExtraComma : InstNormal;
9576int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9578 SmallVector<unsigned, 4> Indices;
9580 if (parseTypeAndValue(Val, Loc, PFS) ||
9581 parseIndexList(Indices, AteExtraComma))
9585 return error(Loc,
"extractvalue operand must be aggregate type");
9588 return error(Loc,
"invalid indices for extractvalue");
9590 return AteExtraComma ? InstExtraComma : InstNormal;
9595int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9597 SmallVector<unsigned, 4> Indices;
9599 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9600 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9601 parseTypeAndValue(Val1, Loc1, PFS) ||
9602 parseIndexList(Indices, AteExtraComma))
9606 return error(Loc0,
"insertvalue operand must be aggregate type");
9610 return error(Loc0,
"invalid indices for insertvalue");
9611 if (IndexedType != Val1->
getType())
9612 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9616 return AteExtraComma ? InstExtraComma : InstNormal;
9627bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9642 if (parseMetadata(MD,
nullptr))
9647 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9653bool LLParser::sortUseListOrder(
Value *
V, ArrayRef<unsigned> Indexes,
9655 if (!
V->hasUseList())
9658 return error(Loc,
"value has no uses");
9660 unsigned NumUses = 0;
9661 SmallDenseMap<const Use *, unsigned, 16> Order;
9662 for (
const Use &U :
V->uses()) {
9663 if (++NumUses > Indexes.
size())
9665 Order[&
U] = Indexes[NumUses - 1];
9668 return error(Loc,
"value only has one use");
9669 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9671 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9673 V->sortUseList([&](
const Use &L,
const Use &R) {
9681bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9682 SMLoc Loc = Lex.getLoc();
9686 return tokError(
"expected non-empty list of uselistorder indexes");
9693 bool IsOrdered =
true;
9694 assert(Indexes.
empty() &&
"Expected empty order vector");
9697 if (parseUInt32(Index))
9702 Max = std::max(Max, Index);
9703 IsOrdered &= Index == Indexes.
size();
9711 if (Indexes.
size() < 2)
9712 return error(Loc,
"expected >= 2 uselistorder indexes");
9715 "expected distinct uselistorder indexes in range [0, size)");
9717 return error(Loc,
"expected uselistorder indexes to change the order");
9724bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9725 SMLoc Loc = Lex.getLoc();
9730 SmallVector<unsigned, 16> Indexes;
9731 if (parseTypeAndValue(
V, PFS) ||
9732 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9733 parseUseListOrderIndexes(Indexes))
9736 return sortUseListOrder(
V, Indexes, Loc);
9742bool LLParser::parseModuleEntry(
unsigned ID) {
9751 parseStringConstant(Path) ||
9759 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9760 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9761 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9762 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9763 parseUInt32(Hash[4]))
9770 auto ModuleEntry = Index->addModule(Path, Hash);
9771 ModuleIdMap[
ID] = ModuleEntry->first();
9778bool LLParser::parseTypeIdEntry(
unsigned ID) {
9787 parseStringConstant(Name))
9790 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9792 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9797 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9798 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9799 for (
auto TIDRef : FwdRefTIDs->second) {
9801 "Forward referenced type id GUID expected to be 0");
9804 ForwardRefTypeIds.erase(FwdRefTIDs);
9812bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9816 parseTypeTestResolution(TIS.
TTRes))
9821 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9838bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9847 parseStringConstant(Name))
9851 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9858 IdToIndexMapType IdToIndexMap;
9871 if (parseGVReference(VI, GVId))
9878 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9879 TI.push_back({
Offset, VI});
9887 for (
auto I : IdToIndexMap) {
9888 auto &Infos = ForwardRefValueInfos[
I.first];
9889 for (
auto P :
I.second) {
9891 "Forward referenced ValueInfo expected to be empty");
9892 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9902 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9903 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9904 for (
auto TIDRef : FwdRefTIDs->second) {
9906 "Forward referenced type id GUID expected to be 0");
9909 ForwardRefTypeIds.erase(FwdRefTIDs);
9921bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9929 switch (Lex.getKind()) {
9949 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9961 switch (Lex.getKind()) {
9976 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9989 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
10002bool LLParser::parseOptionalWpdResolutions(
10003 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10011 WholeProgramDevirtResolution WPDRes;
10015 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
10018 WPDResMap[
Offset] = WPDRes;
10035bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10043 switch (Lex.getKind()) {
10054 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
10060 switch (Lex.getKind()) {
10068 if (parseOptionalResByArg(WPDRes.
ResByArg))
10072 return error(Lex.getLoc(),
10073 "expected optional WholeProgramDevirtResolution field");
10090bool LLParser::parseOptionalResByArg(
10091 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10099 std::vector<uint64_t>
Args;
10100 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
10108 WholeProgramDevirtResolution::ByArg ByArg;
10109 switch (Lex.getKind()) {
10123 return error(Lex.getLoc(),
10124 "unexpected WholeProgramDevirtResolution::ByArg kind");
10130 switch (Lex.getKind()) {
10134 parseUInt64(ByArg.
Info))
10140 parseUInt32(ByArg.
Byte))
10146 parseUInt32(ByArg.
Bit))
10150 return error(Lex.getLoc(),
10151 "expected optional whole program devirt field");
10158 ResByArg[
Args] = ByArg;
10169bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10177 if (parseUInt64(Val))
10179 Args.push_back(Val);
10203bool LLParser::addGlobalValueToIndex(
10205 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10210 VI = Index->getOrInsertValueInfo(GUID);
10214 auto *GV = M->getNamedValue(Name);
10216 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10222 VI = Index->getOrInsertValueInfo(GV, GUID);
10226 "Need a source_filename to compute GUID for local");
10229 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10234 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10235 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10236 for (
auto VIRef : FwdRefVIs->second) {
10238 "Forward referenced ValueInfo expected to be empty");
10241 ForwardRefValueInfos.erase(FwdRefVIs);
10245 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10246 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10247 for (
auto AliaseeRef : FwdRefAliasees->second) {
10248 assert(!AliaseeRef.first->hasAliasee() &&
10249 "Forward referencing alias already has aliasee");
10250 assert(Summary &&
"Aliasee must be a definition");
10251 AliaseeRef.first->setAliasee(VI,
Summary.get());
10253 ForwardRefAliasees.erase(FwdRefAliasees);
10258 Index->addGlobalValueSummary(VI, std::move(Summary));
10261 if (ID == NumberedValueInfos.size())
10262 NumberedValueInfos.push_back(VI);
10265 if (ID > NumberedValueInfos.size())
10266 NumberedValueInfos.resize(ID + 1);
10267 NumberedValueInfos[
ID] =
VI;
10275bool LLParser::parseSummaryIndexFlags() {
10282 if (parseUInt64(Flags))
10285 Index->setFlags(Flags);
10291bool LLParser::parseBlockCount() {
10298 if (parseUInt64(BlockCount))
10301 Index->setBlockCount(BlockCount);
10309bool LLParser::parseCfiFunctions() {
10313 ? Index->cfiFunctionDefs()
10314 : Index->cfiFunctionDecls();
10326 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID) ||
10330 parseStringConstant(Name) ||
10343bool LLParser::parseGVEntry(
unsigned ID) {
10351 LocTy Loc = Lex.getLoc();
10354 switch (Lex.getKind()) {
10358 parseStringConstant(Name))
10364 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10368 return error(Lex.getLoc(),
"expected name or guid tag");
10391 switch (Lex.getKind()) {
10393 if (parseFunctionSummary(Name, GUID, ID))
10397 if (parseVariableSummary(Name, GUID, ID))
10401 if (parseAliasSummary(Name, GUID, ID))
10405 return error(Lex.getLoc(),
"expected summary type");
10423 LocTy Loc = Lex.getLoc();
10427 StringRef ModulePath;
10428 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10431 false,
false,
false,
10433 unsigned InstCount;
10435 FunctionSummary::TypeIdInfo TypeIdInfo;
10436 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10438 std::vector<CallsiteInfo> Callsites;
10439 std::vector<AllocInfo> Allocs;
10441 FunctionSummary::FFlags FFlags = {};
10444 parseModuleReference(ModulePath) ||
10445 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10448 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10453 switch (Lex.getKind()) {
10455 if (parseOptionalFFlags(FFlags))
10459 if (parseOptionalCalls(Calls))
10463 if (parseOptionalTypeIdInfo(TypeIdInfo))
10467 if (parseOptionalRefs(Refs))
10471 if (parseOptionalParamAccesses(ParamAccesses))
10475 if (parseOptionalAllocs(Allocs))
10479 if (parseOptionalCallsites(Callsites))
10483 return error(Lex.getLoc(),
"expected optional function summary field");
10490 auto FS = std::make_unique<FunctionSummary>(
10491 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10497 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10499 FS->setModulePath(ModulePath);
10501 return addGlobalValueToIndex(Name, GUID,
10503 std::move(FS), Loc);
10511 LocTy Loc = Lex.getLoc();
10515 StringRef ModulePath;
10516 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10519 false,
false,
false,
10521 GlobalVarSummary::GVarFlags GVarFlags(
false,
10529 parseModuleReference(ModulePath) ||
10530 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10532 parseGVarFlags(GVarFlags))
10537 switch (Lex.getKind()) {
10539 if (parseOptionalVTableFuncs(VTableFuncs))
10543 if (parseOptionalRefs(Refs))
10547 return error(Lex.getLoc(),
"expected optional variable summary field");
10555 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10557 GS->setModulePath(ModulePath);
10558 GS->setVTableFuncs(std::move(VTableFuncs));
10560 return addGlobalValueToIndex(Name, GUID,
10562 std::move(GS), Loc);
10571 LocTy Loc = Lex.getLoc();
10574 StringRef ModulePath;
10575 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10578 false,
false,
false,
10582 parseModuleReference(ModulePath) ||
10583 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10589 ValueInfo AliaseeVI;
10591 auto AS = std::make_unique<AliasSummary>(GVFlags);
10592 AS->setModulePath(ModulePath);
10595 if (parseGVReference(AliaseeVI, GVId))
10600 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10602 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10603 assert(Summary &&
"Aliasee must be a definition");
10604 AS->setAliasee(AliaseeVI, Summary);
10611 return addGlobalValueToIndex(Name, GUID,
10613 std::move(AS), Loc);
10618bool LLParser::parseFlag(
unsigned &Val) {
10619 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10620 return tokError(
"expected integer");
10621 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10637bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10641 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10647 switch (Lex.getKind()) {
10650 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10656 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10662 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10668 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10674 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10680 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10686 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10692 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10698 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10704 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10709 return error(Lex.getLoc(),
"expected function flag type");
10713 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10724bool LLParser::parseOptionalCalls(
10725 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10729 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10733 IdToIndexMapType IdToIndexMap;
10742 LocTy Loc = Lex.getLoc();
10744 if (parseGVReference(VI, GVId))
10748 unsigned RelBF = 0;
10749 unsigned HasTailCall =
false;
10750 unsigned HasIndirectCall =
false;
10754 switch (Lex.getKind()) {
10757 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10763 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10768 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10774 parseFlag(HasIndirectCall))
10778 return error(Lex.getLoc(),
10779 "expected hotness, relbf, tail, or indirect");
10786 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10788 VI, CalleeInfo(Hotness, HasTailCall, HasIndirectCall)});
10796 for (
auto I : IdToIndexMap) {
10797 auto &Infos = ForwardRefValueInfos[
I.first];
10798 for (
auto P :
I.second) {
10800 "Forward referenced ValueInfo expected to be empty");
10801 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10814 switch (Lex.getKind()) {
10818 case lltok::kw_cold:
10824 case lltok::kw_hot:
10831 return error(Lex.getLoc(),
"invalid call edge hotness");
10840bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10844 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10848 IdToIndexMapType IdToIndexMap;
10852 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10857 LocTy Loc = Lex.getLoc();
10859 if (parseGVReference(VI, GVId))
10872 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10873 VTableFuncs.push_back({
VI,
Offset});
10875 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10881 for (
auto I : IdToIndexMap) {
10882 auto &Infos = ForwardRefValueInfos[
I.first];
10883 for (
auto P :
I.second) {
10885 "Forward referenced ValueInfo expected to be empty");
10886 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10890 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10897bool LLParser::parseParamNo(
uint64_t &ParamNo) {
10899 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10905bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10908 auto ParseAPSInt = [&](
APSInt &Val) {
10910 return tokError(
"expected integer");
10911 Val = Lex.getAPSIntVal();
10913 Val.setIsSigned(
true);
10935bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10936 IdLocListType &IdLocList) {
10944 LocTy Loc = Lex.getLoc();
10945 if (parseGVReference(VI, GVId))
10949 IdLocList.emplace_back(GVId, Loc);
10952 parseParamNo(
Call.ParamNo) ||
10954 parseParamAccessOffset(
Call.Offsets))
10966bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10967 IdLocListType &IdLocList) {
10969 parseParamNo(
Param.ParamNo) ||
10971 parseParamAccessOffset(
Param.Use))
10980 FunctionSummary::ParamAccess::Call
Call;
10981 if (parseParamAccessCall(
Call, IdLocList))
10998bool LLParser::parseOptionalParamAccesses(
10999 std::vector<FunctionSummary::ParamAccess> &Params) {
11007 IdLocListType VContexts;
11008 size_t CallsNum = 0;
11010 FunctionSummary::ParamAccess ParamAccess;
11011 if (parseParamAccess(ParamAccess, VContexts))
11013 CallsNum += ParamAccess.
Calls.size();
11014 assert(VContexts.size() == CallsNum);
11016 Params.emplace_back(std::move(ParamAccess));
11024 IdLocListType::const_iterator ItContext = VContexts.begin();
11025 for (
auto &PA : Params) {
11026 for (
auto &
C : PA.Calls) {
11028 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
11029 ItContext->second);
11033 assert(ItContext == VContexts.end());
11040bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
11044 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
11048 struct ValueContext {
11053 std::vector<ValueContext> VContexts;
11057 VC.Loc = Lex.getLoc();
11058 if (parseGVReference(
VC.VI,
VC.GVId))
11060 VContexts.push_back(VC);
11066 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
11067 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11070 IdToIndexMapType IdToIndexMap;
11071 for (
auto &VC : VContexts) {
11076 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
11082 for (
auto I : IdToIndexMap) {
11083 auto &Infos = ForwardRefValueInfos[
I.first];
11084 for (
auto P :
I.second) {
11086 "Forward referenced ValueInfo expected to be empty");
11087 Infos.emplace_back(&Refs[
P.first],
P.second);
11101bool LLParser::parseOptionalTypeIdInfo(
11102 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11111 switch (Lex.getKind()) {
11113 if (parseTypeTests(TypeIdInfo.
TypeTests))
11137 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
11141 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11150bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11158 IdToIndexMapType IdToIndexMap;
11162 unsigned ID = Lex.getUIntVal();
11163 LocTy Loc = Lex.getLoc();
11167 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
11169 }
else if (parseUInt64(GUID))
11171 TypeTests.push_back(GUID);
11176 for (
auto I : IdToIndexMap) {
11177 auto &Ids = ForwardRefTypeIds[
I.first];
11178 for (
auto P :
I.second) {
11179 assert(TypeTests[
P.first] == 0 &&
11180 "Forward referenced type id GUID expected to be 0");
11181 Ids.emplace_back(&TypeTests[
P.first],
P.second);
11185 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11193bool LLParser::parseVFuncIdList(
11194 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11195 assert(Lex.getKind() == Kind);
11202 IdToIndexMapType IdToIndexMap;
11204 FunctionSummary::VFuncId VFuncId;
11205 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11207 VFuncIdList.push_back(VFuncId);
11215 for (
auto I : IdToIndexMap) {
11216 auto &Ids = ForwardRefTypeIds[
I.first];
11217 for (
auto P :
I.second) {
11218 assert(VFuncIdList[
P.first].GUID == 0 &&
11219 "Forward referenced type id GUID expected to be 0");
11220 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
11229bool LLParser::parseConstVCallList(
11231 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11232 assert(Lex.getKind() == Kind);
11239 IdToIndexMapType IdToIndexMap;
11241 FunctionSummary::ConstVCall ConstVCall;
11242 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11244 ConstVCallList.push_back(ConstVCall);
11252 for (
auto I : IdToIndexMap) {
11253 auto &Ids = ForwardRefTypeIds[
I.first];
11254 for (
auto P :
I.second) {
11255 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11256 "Forward referenced type id GUID expected to be 0");
11257 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11266bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11267 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11269 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11273 if (parseArgs(ConstVCall.
Args))
11285bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11286 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11296 unsigned ID = Lex.getUIntVal();
11297 LocTy Loc = Lex.getLoc();
11301 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11303 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11305 parseUInt64(VFuncId.
GUID))
11311 parseUInt64(VFuncId.
Offset) ||
11323bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11333 switch (Lex.getKind()) {
11340 assert(HasLinkage &&
"Linkage not optional in summary entry");
11347 parseOptionalVisibility(Flag);
11352 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11358 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11364 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11370 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11379 if (parseOptionalImportType(Lex.getKind(), IK))
11381 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11386 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11391 return error(Lex.getLoc(),
"expected gv flag type");
11405bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11413 auto ParseRest = [
this](
unsigned int &Val) {
11417 return parseFlag(Val);
11422 switch (Lex.getKind()) {
11423 case lltok::kw_readonly:
11424 if (ParseRest(Flag))
11428 case lltok::kw_writeonly:
11429 if (ParseRest(Flag))
11434 if (ParseRest(Flag))
11439 if (ParseRest(Flag))
11444 return error(Lex.getLoc(),
"expected gvar flag type");
11452bool LLParser::parseModuleReference(StringRef &ModulePath) {
11459 unsigned ModuleID = Lex.getUIntVal();
11460 auto I = ModuleIdMap.find(ModuleID);
11462 assert(
I != ModuleIdMap.end());
11463 ModulePath =
I->second;
11469bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11472 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11476 GVId = Lex.getUIntVal();
11478 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11480 VI = NumberedValueInfos[GVId];
11497bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11501 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11513 SmallVector<uint8_t> Versions;
11516 if (parseAllocType(
V))
11521 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11525 std::vector<MIBInfo> MIBs;
11526 if (parseMemProfs(MIBs))
11529 Allocs.push_back({Versions, MIBs});
11546bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11550 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11556 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11565 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11571 SmallVector<unsigned> StackIdIndices;
11576 if (parseUInt64(StackId))
11578 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11599bool LLParser::parseAllocType(uint8_t &
AllocType) {
11600 switch (Lex.getKind()) {
11613 case lltok::kw_cold:
11616 case lltok::kw_hot:
11620 return error(Lex.getLoc(),
"invalid alloc type");
11633bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11637 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11641 IdToIndexMapType IdToIndexMap;
11644 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11651 LocTy Loc = Lex.getLoc();
11653 if (parseGVReference(VI, GVId))
11657 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11663 SmallVector<unsigned> Clones;
11666 if (parseUInt32(
V))
11672 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11678 SmallVector<unsigned> StackIdIndices;
11683 if (parseUInt64(StackId))
11685 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11696 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11697 Callsites.push_back({
VI, Clones, StackIdIndices});
11705 for (
auto I : IdToIndexMap) {
11706 auto &Infos = ForwardRefValueInfos[
I.first];
11707 for (
auto P :
I.second) {
11709 "Forward referenced ValueInfo expected to be empty");
11710 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11714 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 const fltSemantics & IEEEdouble()
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
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().
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 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.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.