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();
164 SMLoc End = Lex.getLoc();
172 restoreParsingState(Slots);
176 SMLoc Start = Lex.getLoc();
178 bool Status = parseDIExpressionBody(Result,
false);
179 SMLoc End = Lex.getLoc();
187 restoreParsingState(&Slots);
190 for (
SMLoc End : DefinitionEnds) {
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();
541 for (
auto *Inst : InstsWithTBAATag) {
542 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
545 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
548 if (MD != UpgradedMD)
549 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
558 if (UpgradeDebugInfo)
572 Slots->GlobalValues = std::move(NumberedVals);
573 Slots->MetadataNodes = std::move(NumberedMetadata);
574 for (
const auto &
I : NamedTypes)
575 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
576 for (
const auto &
I : NumberedTypes)
577 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
583bool LLParser::validateEndOfIndex() {
587 if (!ForwardRefValueInfos.empty())
588 return error(ForwardRefValueInfos.begin()->second.front().second,
589 "use of undefined summary '^" +
590 Twine(ForwardRefValueInfos.begin()->first) +
"'");
592 if (!ForwardRefAliasees.empty())
593 return error(ForwardRefAliasees.begin()->second.front().second,
594 "use of undefined summary '^" +
595 Twine(ForwardRefAliasees.begin()->first) +
"'");
597 if (!ForwardRefTypeIds.empty())
598 return error(ForwardRefTypeIds.begin()->second.front().second,
599 "use of undefined type id summary '^" +
600 Twine(ForwardRefTypeIds.begin()->first) +
"'");
614 std::string TentativeDLStr = M->getDataLayoutStr();
619 switch (Lex.getKind()) {
621 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
625 if (parseSourceFileName())
634 if (
auto LayoutOverride =
635 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
636 TentativeDLStr = *LayoutOverride;
642 M->setDataLayout(MaybeDL.
get());
646bool LLParser::parseTopLevelEntities() {
650 switch (Lex.getKind()) {
654 if (parseSummaryEntry())
658 if (parseSourceFileName())
668 switch (Lex.getKind()) {
670 return tokError(
"expected top-level entity");
681 if (parseModuleAsm())
685 if (parseUnnamedType())
689 if (parseNamedType())
693 if (parseUnnamedGlobal())
697 if (parseNamedGlobal())
702 if (parseStandaloneMetadata())
706 if (parseSummaryEntry())
710 if (parseNamedMetadata())
714 if (parseUnnamedAttrGrp())
718 if (parseUseListOrder())
730bool LLParser::parseModuleAsm() {
738 Module::GlobalAsmProperties Props;
742 SMLoc Loc = Lex.getLoc();
744 return error(Loc,
"expected property name followed by ':'");
746 Key = Lex.getStrVal();
749 if (parseStringConstant(
Value))
753 return error(Loc,
"unknown property name");
763 std::string AsmStrPart;
764 if (parseStringConstant(AsmStrPart))
766 AsmStr += AsmStrPart +
"\n";
769 M->appendModuleInlineAsm({AsmStr, Props});
776bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
782 return tokError(
"unknown target property");
785 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
786 parseStringConstant(Str))
788 M->setTargetTriple(Triple(std::move(Str)));
792 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
794 DLStrLoc = Lex.getLoc();
795 if (parseStringConstant(TentativeDLStr))
803bool LLParser::parseSourceFileName() {
806 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
807 parseStringConstant(SourceFileName))
810 M->setSourceFileName(SourceFileName);
816bool LLParser::parseUnnamedType() {
817 LocTy TypeLoc = Lex.getLoc();
818 unsigned TypeID = Lex.getUIntVal();
821 if (parseToken(
lltok::equal,
"expected '=' after name") ||
826 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
830 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
832 return error(TypeLoc,
"non-struct types may not be recursive");
834 Entry.second = SMLoc();
842bool LLParser::parseNamedType() {
843 std::string
Name = Lex.getStrVal();
844 LocTy NameLoc = Lex.getLoc();
847 if (parseToken(
lltok::equal,
"expected '=' after name") ||
852 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
856 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
858 return error(NameLoc,
"non-struct types may not be recursive");
860 Entry.second = SMLoc();
868bool LLParser::parseDeclare() {
872 std::vector<std::pair<unsigned, MDNode *>> MDs;
876 if (parseMetadataAttachment(MDK,
N))
878 MDs.push_back({MDK,
N});
882 unsigned FunctionNumber = -1;
883 SmallVector<unsigned> UnnamedArgNums;
884 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
887 F->addMetadata(MD.first, *MD.second);
893bool LLParser::parseDefine() {
896 FileLoc FunctionStart = getTokLineColumnPos();
900 unsigned FunctionNumber = -1;
901 SmallVector<unsigned> UnnamedArgNums;
903 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
904 parseOptionalFunctionMetadata(*
F) ||
905 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
907 ParserContext->addFunctionLocation(
908 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
916bool LLParser::parseGlobalType(
bool &IsConstant) {
923 return tokError(
"expected 'global' or 'constant'");
929bool LLParser::parseOptionalUnnamedAddr(
950bool LLParser::parseUnnamedGlobal() {
953 LocTy NameLoc = Lex.getLoc();
957 VarID = Lex.getUIntVal();
958 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
962 if (parseToken(
lltok::equal,
"expected '=' after name"))
965 VarID = NumberedVals.getNext();
969 unsigned Linkage, Visibility, DLLStorageClass;
973 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
975 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
978 switch (Lex.getKind()) {
980 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
981 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
984 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
985 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
994bool LLParser::parseNamedGlobal() {
996 LocTy NameLoc = Lex.getLoc();
997 std::string
Name = Lex.getStrVal();
1001 unsigned Linkage, Visibility, DLLStorageClass;
1005 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
1006 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
1008 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
1011 switch (Lex.getKind()) {
1013 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
1014 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1017 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
1018 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1022bool LLParser::parseComdat() {
1024 std::string
Name = Lex.getStrVal();
1025 LocTy NameLoc = Lex.getLoc();
1032 return tokError(
"expected comdat type");
1035 switch (Lex.getKind()) {
1037 return tokError(
"unknown selection kind");
1059 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
1060 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
1063 if (
I != ComdatSymTab.
end())
1066 C = M->getOrInsertComdat(Name);
1067 C->setSelectionKind(SK);
1074bool LLParser::parseMDString(
MDString *&Result) {
1076 if (parseStringConstant(Str))
1084bool LLParser::parseMDNodeID(
MDNode *&Result) {
1086 LocTy IDLoc = Lex.getLoc();
1088 if (parseUInt32(MID))
1092 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
1099 auto &FwdRef = ForwardRefMDNodes[MID];
1102 Result = FwdRef.first.get();
1103 It->second.reset(Result);
1109bool LLParser::parseNamedMetadata() {
1111 std::string
Name = Lex.getStrVal();
1119 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1122 MDNode *
N =
nullptr;
1127 Lex.getStrVal() ==
"DIExpression") {
1128 if (parseDIExpression(
N,
false))
1133 Lex.getStrVal() ==
"DIArgList") {
1134 return tokError(
"found DIArgList outside of function");
1142 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1147bool LLParser::parseStandaloneMetadata() {
1150 unsigned MetadataID = 0;
1153 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1158 return tokError(
"unexpected type in metadata definition");
1162 if (parseSpecializedMDNode(Init, IsDistinct))
1165 parseMDTuple(Init, IsDistinct))
1169 auto FI = ForwardRefMDNodes.find(MetadataID);
1170 if (FI != ForwardRefMDNodes.end()) {
1171 auto *ToReplace = FI->second.first.get();
1175 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1176 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1177 "Inst unexpectedly already has DIAssignID attachment");
1178 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1182 ToReplace->replaceAllUsesWith(Init);
1183 ForwardRefMDNodes.erase(FI);
1185 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1187 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1189 return tokError(
"Metadata id is already used");
1190 It->second.reset(Init);
1197bool LLParser::skipModuleSummaryEntry() {
1207 return tokError(
"Expected 'gv', 'module', 'typeid', "
1208 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1209 "start of summary entry");
1211 return parseSummaryIndexFlags();
1213 return parseBlockCount();
1215 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1216 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1220 unsigned NumOpenParen = 1;
1222 switch (Lex.getKind()) {
1230 return tokError(
"found end of file while parsing summary entry");
1236 }
while (NumOpenParen > 0);
1242bool LLParser::parseSummaryEntry() {
1248 Lex.setIgnoreColonInIdentifiers(
true);
1256 return skipModuleSummaryEntry();
1258 bool result =
false;
1259 switch (Lex.getKind()) {
1261 result = parseGVEntry(SummaryID);
1264 result = parseModuleEntry(SummaryID);
1267 result = parseTypeIdEntry(SummaryID);
1270 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1273 result = parseSummaryIndexFlags();
1276 result = parseBlockCount();
1279 result =
error(Lex.getLoc(),
"unexpected summary kind");
1282 Lex.setIgnoreColonInIdentifiers(
false);
1316bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1317 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1318 unsigned DLLStorageClass,
bool DSOLocal,
1333 return error(NameLoc,
"invalid linkage type for alias");
1336 return error(NameLoc,
1337 "symbol with local linkage must have default visibility");
1340 return error(NameLoc,
1341 "symbol with local linkage cannot have a DLL storage class");
1344 LocTy ExplicitTypeLoc = Lex.getLoc();
1345 if (parseType(Ty) ||
1346 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1350 LocTy AliaseeLoc = Lex.getLoc();
1355 if (parseGlobalTypeAndValue(Aliasee))
1360 if (parseValID(ID,
nullptr))
1363 return error(AliaseeLoc,
"invalid aliasee");
1364 Aliasee =
ID.ConstantVal;
1370 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1371 unsigned AddrSpace = PTy->getAddressSpace();
1373 GlobalValue *GVal =
nullptr;
1377 if (!
Name.empty()) {
1378 auto I = ForwardRefVals.find(Name);
1379 if (
I != ForwardRefVals.end()) {
1380 GVal =
I->second.first;
1381 ForwardRefVals.erase(Name);
1382 }
else if (M->getNamedValue(Name)) {
1383 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1386 auto I = ForwardRefValIDs.find(NameID);
1387 if (
I != ForwardRefValIDs.end()) {
1388 GVal =
I->second.first;
1389 ForwardRefValIDs.erase(
I);
1394 std::unique_ptr<GlobalAlias> GA;
1395 std::unique_ptr<GlobalIFunc> GI;
1423 if (parseGlobalObjectMetadataAttachment(*GI))
1426 return tokError(
"unknown alias or ifunc property!");
1431 NumberedVals.add(NameID, GV);
1438 "forward reference and definition of alias have different types");
1448 M->insertAlias(GA.release());
1450 M->insertIFunc(GI.release());
1451 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1460 case lltok::kw_sanitize_memtag:
1474 switch (Lex.getKind()) {
1476 Meta.NoAddress =
true;
1479 Meta.NoHWAddress =
true;
1481 case lltok::kw_sanitize_memtag:
1485 Meta.IsDynInit =
true;
1488 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1508bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1509 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1510 unsigned Visibility,
unsigned DLLStorageClass,
1514 return error(NameLoc,
1515 "symbol with local linkage must have default visibility");
1518 return error(NameLoc,
1519 "symbol with local linkage cannot have a DLL storage class");
1523 LocTy IsExternallyInitializedLoc;
1527 if (parseOptionalAddrSpace(AddrSpace) ||
1529 IsExternallyInitialized,
1530 &IsExternallyInitializedLoc) ||
1531 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1540 if (parseGlobalValue(Ty, Init))
1545 return error(TyLoc,
"invalid type for global variable");
1547 GlobalValue *GVal =
nullptr;
1550 if (!
Name.empty()) {
1551 auto I = ForwardRefVals.find(Name);
1552 if (
I != ForwardRefVals.end()) {
1553 GVal =
I->second.first;
1554 ForwardRefVals.erase(
I);
1555 }
else if (M->getNamedValue(Name)) {
1556 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1561 if (NameID == (
unsigned)-1)
1562 NameID = NumberedVals.getNext();
1564 auto I = ForwardRefValIDs.find(NameID);
1565 if (
I != ForwardRefValIDs.end()) {
1566 GVal =
I->second.first;
1567 ForwardRefValIDs.erase(
I);
1571 GlobalVariable *GV =
new GlobalVariable(
1576 NumberedVals.add(NameID, GV);
1594 "forward reference and definition of global have different types");
1614 }
else if (Lex.getKind() == lltok::kw_align) {
1616 if (parseOptionalAlignment(Alignment))
1622 if (parseOptionalCodeModel(CodeModel))
1626 if (parseGlobalObjectMetadataAttachment(*GV))
1629 if (parseSanitizer(GV))
1633 if (parseOptionalComdat(Name,
C))
1638 return tokError(
"unknown global variable property!");
1642 AttrBuilder
Attrs(M->getContext());
1644 std::vector<unsigned> FwdRefAttrGrps;
1645 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1647 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1649 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1657bool LLParser::parseUnnamedAttrGrp() {
1659 LocTy AttrGrpLoc = Lex.getLoc();
1663 return tokError(
"expected attribute group id");
1665 unsigned VarID = Lex.getUIntVal();
1666 std::vector<unsigned> unused;
1674 auto R = NumberedAttrBuilders.find(
VarID);
1675 if (R == NumberedAttrBuilders.end())
1676 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1678 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1679 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1682 if (!
R->second.hasAttributes())
1683 return error(AttrGrpLoc,
"attribute group has no attributes");
1690#define GET_ATTR_NAMES
1691#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1692 case lltok::kw_##DISPLAY_NAME: \
1693 return Attribute::ENUM_NAME;
1694#include "llvm/IR/Attributes.inc"
1703 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1706 case Attribute::Alignment: {
1715 if (parseOptionalAlignment(Alignment,
true))
1718 B.addAlignmentAttr(Alignment);
1721 case Attribute::StackAlignment: {
1726 parseUInt32(Alignment))
1729 if (parseOptionalStackAlignment(Alignment))
1732 B.addStackAlignmentAttr(Alignment);
1735 case Attribute::AllocSize: {
1736 unsigned ElemSizeArg;
1737 std::optional<unsigned> NumElemsArg;
1738 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1740 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1743 case Attribute::VScaleRange: {
1744 unsigned MinValue, MaxValue;
1745 if (parseVScaleRangeArguments(MinValue, MaxValue))
1747 B.addVScaleRangeAttr(MinValue,
1748 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1751 case Attribute::Dereferenceable: {
1752 std::optional<uint64_t> Bytes;
1753 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1755 assert(Bytes.has_value());
1756 B.addDereferenceableAttr(Bytes.value());
1759 case Attribute::DeadOnReturn: {
1760 std::optional<uint64_t> Bytes;
1761 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1764 if (Bytes.has_value()) {
1765 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1767 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1771 case Attribute::DereferenceableOrNull: {
1772 std::optional<uint64_t> Bytes;
1773 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1775 assert(Bytes.has_value());
1776 B.addDereferenceableOrNullAttr(Bytes.value());
1779 case Attribute::UWTable: {
1781 if (parseOptionalUWTableKind(Kind))
1783 B.addUWTableAttr(Kind);
1786 case Attribute::AllocKind: {
1788 if (parseAllocKind(Kind))
1790 B.addAllocKindAttr(Kind);
1793 case Attribute::Memory: {
1794 std::optional<MemoryEffects> ME = parseMemoryAttr();
1797 B.addMemoryAttr(*ME);
1800 case Attribute::DenormalFPEnv: {
1801 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1805 B.addDenormalFPEnvAttr(*
Mode);
1808 case Attribute::NoFPClass: {
1811 B.addNoFPClassAttr(NoFPClass);
1817 case Attribute::Range:
1818 return parseRangeAttr(
B);
1819 case Attribute::Initializes:
1820 return parseInitializesAttr(
B);
1821 case Attribute::Captures:
1822 return parseCapturesAttr(
B);
1824 B.addAttribute(Attr);
1832 case lltok::kw_readnone:
1835 case lltok::kw_readonly:
1838 case lltok::kw_writeonly:
1857bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1858 std::vector<unsigned> &FwdRefAttrGrps,
1859 bool InAttrGrp, LocTy &BuiltinLoc) {
1860 bool HaveError =
false;
1871 if (parseStringAttribute(
B))
1883 "cannot have an attribute group reference in an attribute group");
1886 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1892 SMLoc Loc = Lex.getLoc();
1893 if (Token == lltok::kw_builtin)
1905 return error(Lex.getLoc(),
"unterminated attribute group");
1908 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1915 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1919 B.addMemoryAttr(ME);
1933 PTy->getAddressSpace());
1942 error(Loc,
"'" + Name +
"' is not a basic block");
1944 error(Loc,
"'" + Name +
"' defined with type '" +
1957 error(Loc,
"global variable reference must have pointer type");
1968 auto I = ForwardRefVals.find(Name);
1969 if (
I != ForwardRefVals.end())
1970 Val =
I->second.first;
1976 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1980 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1987 error(Loc,
"global variable reference must have pointer type");
1991 GlobalValue *Val = NumberedVals.get(ID);
1996 auto I = ForwardRefValIDs.find(ID);
1997 if (
I != ForwardRefValIDs.end())
1998 Val =
I->second.first;
2004 checkValidVariableType(Loc,
"@" + Twine(ID), Ty, Val));
2008 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
2016Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
2020 if (
I != ComdatSymTab.
end())
2024 Comdat *
C = M->getOrInsertComdat(Name);
2025 ForwardRefComdats[
Name] = Loc;
2035bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
2036 if (Lex.getKind() !=
T)
2037 return tokError(ErrMsg);
2044bool LLParser::parseStringConstant(std::string &Result) {
2046 return tokError(
"expected string constant");
2047 Result = Lex.getStrVal();
2054bool LLParser::parseUInt32(uint32_t &Val) {
2055 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2056 return tokError(
"expected integer");
2057 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2058 if (Val64 !=
unsigned(Val64))
2059 return tokError(
"expected 32-bit integer (too large)");
2067bool LLParser::parseUInt64(
uint64_t &Val) {
2068 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2069 return tokError(
"expected integer");
2070 Val = Lex.getAPSIntVal().getLimitedValue();
2080 switch (Lex.getKind()) {
2082 return tokError(
"expected localdynamic, initialexec or localexec");
2110 return parseTLSModel(TLM) ||
2111 parseToken(
lltok::rparen,
"expected ')' after thread local model");
2119bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
2120 AddrSpace = DefaultAS;
2124 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
2126 const std::string &AddrSpaceStr = Lex.getStrVal();
2127 if (AddrSpaceStr ==
"A") {
2128 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2129 }
else if (AddrSpaceStr ==
"G") {
2130 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2131 }
else if (AddrSpaceStr ==
"P") {
2132 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2133 }
else if (std::optional<unsigned> AS =
2134 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2137 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2143 return tokError(
"expected integer or string constant");
2144 SMLoc Loc = Lex.getLoc();
2145 if (parseUInt32(AddrSpace))
2148 return error(Loc,
"invalid address space, must be a 24-bit integer");
2152 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2153 ParseAddrspaceValue(AddrSpace) ||
2160bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2161 std::string Attr = Lex.getStrVal();
2164 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2166 B.addAttribute(Attr, Val);
2171bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2172 bool HaveError =
false;
2179 if (parseStringAttribute(
B))
2190 SMLoc Loc = Lex.getLoc();
2195 if (parseEnumAttribute(Attr,
B,
false))
2199 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2201 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2249bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2250 unsigned &Visibility,
2251 unsigned &DLLStorageClass,
bool &DSOLocal) {
2255 parseOptionalDSOLocal(DSOLocal);
2256 parseOptionalVisibility(Visibility);
2257 parseOptionalDLLStorageClass(DLLStorageClass);
2260 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2266void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2267 switch (Lex.getKind()) {
2288void LLParser::parseOptionalVisibility(
unsigned &Res) {
2289 switch (Lex.getKind()) {
2306bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2310 return tokError(
"unknown import kind. Expect definition or declaration.");
2325void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2326 switch (Lex.getKind()) {
2396bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2397 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);
2555 if (MDK == LLVMContext::MD_tbaa)
2556 InstsWithTBAATag.push_back(&Inst);
2565bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2568 if (parseMetadataAttachment(MDK,
N))
2577bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2579 if (parseGlobalObjectMetadataAttachment(
F))
2587bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2589 if (!EatIfPresent(lltok::kw_align))
2591 LocTy AlignLoc = Lex.getLoc();
2594 LocTy ParenLoc = Lex.getLoc();
2595 bool HaveParens =
false;
2601 if (parseUInt64(
Value))
2605 return error(ParenLoc,
"expected ')'");
2608 return error(AlignLoc,
"alignment is not a power of two");
2610 return error(AlignLoc,
"huge alignments are not supported yet");
2618bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2622 LocTy AlignLoc = Lex.getLoc();
2625 LocTy ParenLoc = Lex.getLoc();
2627 return error(ParenLoc,
"expected '('");
2629 if (parseUInt64(
Value))
2632 ParenLoc = Lex.getLoc();
2634 return error(ParenLoc,
"expected ')'");
2637 return error(AlignLoc,
"alignment is not a power of two");
2639 return error(AlignLoc,
"huge alignments are not supported yet");
2649 auto StrVal = Lex.getStrVal();
2650 auto ErrMsg =
"expected global code model string";
2651 if (StrVal ==
"tiny")
2653 else if (StrVal ==
"small")
2655 else if (StrVal ==
"kernel")
2657 else if (StrVal ==
"medium")
2659 else if (StrVal ==
"large")
2662 return tokError(ErrMsg);
2674bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2675 std::optional<uint64_t> &Bytes,
2676 bool ErrorNoBytes) {
2677 assert((AttrKind == lltok::kw_dereferenceable ||
2678 AttrKind == lltok::kw_dereferenceable_or_null ||
2679 AttrKind == lltok::kw_dead_on_return) &&
2683 if (!EatIfPresent(AttrKind))
2685 LocTy ParenLoc = Lex.getLoc();
2688 return error(ParenLoc,
"expected '('");
2689 Bytes = std::nullopt;
2692 LocTy DerefLoc = Lex.getLoc();
2693 if (parseUInt64(Bytes.value()))
2695 ParenLoc = Lex.getLoc();
2697 return error(ParenLoc,
"expected ')'");
2699 return error(DerefLoc,
"byte count specified must be non-zero");
2703bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2708 LocTy KindLoc = Lex.getLoc();
2714 return error(KindLoc,
"expected unwind table kind");
2721 LocTy ParenLoc = Lex.getLoc();
2723 return error(ParenLoc,
"expected '('");
2724 LocTy KindLoc = Lex.getLoc();
2726 if (parseStringConstant(Arg))
2727 return error(KindLoc,
"expected allockind value");
2731 }
else if (
A ==
"realloc") {
2733 }
else if (
A ==
"free") {
2735 }
else if (
A ==
"uninitialized") {
2737 }
else if (
A ==
"zeroed") {
2739 }
else if (
A ==
"aligned") {
2742 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2745 ParenLoc = Lex.getLoc();
2747 return error(ParenLoc,
"expected ')'");
2749 return error(KindLoc,
"expected allockind value");
2758 return {Loc::ArgMem};
2760 return {Loc::InaccessibleMem};
2762 return {Loc::ErrnoMem};
2764 return {Loc::TargetMem0};
2766 return {Loc::TargetMem1};
2789 return std::nullopt;
2793static std::optional<DenormalMode::DenormalModeKind>
2805 return std::nullopt;
2809std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2814 Lex.setIgnoreColonInIdentifiers(
true);
2819 tokError(
"expected '('");
2820 return std::nullopt;
2823 bool SeenLoc =
false;
2824 bool SeenTargetLoc =
false;
2827 if (!Locs.
empty()) {
2830 tokError(
"expected ':' after location");
2831 return std::nullopt;
2838 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2839 "or access kind (none, read, write, readwrite)");
2841 tokError(
"expected access kind (none, read, write, readwrite)");
2842 return std::nullopt;
2846 if (!Locs.
empty()) {
2851 SeenTargetLoc =
true;
2853 if (Locs.size() > 1 && SeenTargetLoc) {
2854 tokError(
"target memory default access kind must be specified first");
2855 return std::nullopt;
2860 tokError(
"default access kind must be specified first");
2861 return std::nullopt;
2870 tokError(
"unterminated memory attribute");
2871 return std::nullopt;
2874std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2875 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2878 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2879 "positivezero, dynamic)");
2885 std::optional<DenormalMode::DenormalModeKind> InputMode;
2889 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2890 "positivezero, dynamic)");
2897 InputMode = OutputMode;
2900 return DenormalMode(*OutputMode, *InputMode);
2903std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2906 Lex.setIgnoreColonInIdentifiers(
true);
2917 bool HasDefaultSection =
false;
2919 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2920 if (!ParsedDefaultMode)
2922 DefaultMode = *ParsedDefaultMode;
2923 HasDefaultSection =
true;
2928 if (HasDefaultSection && !HasComma) {
2929 tokError(
"expected ',' before float:");
2934 if (parseType(Ty) || !Ty->
isFloatTy()) {
2935 tokError(
"expected float:");
2939 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2942 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2946 F32Mode = *ParsedF32Mode;
2949 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2952 return DenormalFPEnv(DefaultMode, F32Mode);
2994unsigned LLParser::parseNoFPClassAttr() {
2999 tokError(
"expected '('");
3006 if (TestMask != 0) {
3010 !parseUInt64(
Value)) {
3012 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
3017 error(Lex.getLoc(),
"expected ')'");
3023 error(Lex.getLoc(),
"expected nofpclass test mask");
3041bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
3042 bool &AteExtraComma) {
3043 AteExtraComma =
false;
3047 AteExtraComma =
true;
3051 if (Lex.getKind() != lltok::kw_align)
3052 return error(Lex.getLoc(),
"expected metadata or 'align'");
3054 if (parseOptionalAlignment(Alignment))
3067bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
3068 bool &AteExtraComma) {
3069 AteExtraComma =
false;
3073 AteExtraComma =
true;
3079 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
3081 if (parseOptionalAddrSpace(AddrSpace))
3088bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
3089 std::optional<unsigned> &HowManyArg) {
3092 auto StartParen = Lex.getLoc();
3094 return error(StartParen,
"expected '('");
3096 if (parseUInt32(BaseSizeArg))
3100 auto HowManyAt = Lex.getLoc();
3102 if (parseUInt32(HowMany))
3104 if (HowMany == BaseSizeArg)
3105 return error(HowManyAt,
3106 "'allocsize' indices can't refer to the same parameter");
3107 HowManyArg = HowMany;
3109 HowManyArg = std::nullopt;
3111 auto EndParen = Lex.getLoc();
3113 return error(EndParen,
"expected ')'");
3117bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3118 unsigned &MaxValue) {
3121 auto StartParen = Lex.getLoc();
3123 return error(StartParen,
"expected '('");
3125 if (parseUInt32(MinValue))
3129 if (parseUInt32(MaxValue))
3132 MaxValue = MinValue;
3134 auto EndParen = Lex.getLoc();
3136 return error(EndParen,
"expected ')'");
3145bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3150 return parseScope(SSID) || parseOrdering(Ordering);
3160 auto StartParenAt = Lex.getLoc();
3162 return error(StartParenAt,
"Expected '(' in syncscope");
3165 auto SSNAt = Lex.getLoc();
3166 if (parseStringConstant(SSN))
3167 return error(SSNAt,
"Expected synchronization scope name");
3169 auto EndParenAt = Lex.getLoc();
3171 return error(EndParenAt,
"Expected ')' in syncscope");
3173 SSID = Context.getOrInsertSyncScopeID(SSN);
3184 switch (Lex.getKind()) {
3186 return tokError(
"Expected ordering on atomic instruction");
3205bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3207 if (!EatIfPresent(lltok::kw_alignstack))
3209 LocTy ParenLoc = Lex.getLoc();
3211 return error(ParenLoc,
"expected '('");
3212 LocTy AlignLoc = Lex.getLoc();
3213 if (parseUInt32(Alignment))
3215 ParenLoc = Lex.getLoc();
3217 return error(ParenLoc,
"expected ')'");
3219 return error(AlignLoc,
"stack alignment is not a power of two");
3233 bool &AteExtraComma) {
3234 AteExtraComma =
false;
3237 return tokError(
"expected ',' as start of index list");
3241 if (Indices.
empty())
3242 return tokError(
"expected index");
3243 AteExtraComma =
true;
3247 if (parseUInt32(Idx))
3260bool LLParser::parseType(
Type *&Result,
const Twine &
Msg,
bool AllowVoid) {
3261 SMLoc TypeLoc = Lex.getLoc();
3262 switch (Lex.getKind()) {
3264 return tokError(
Msg);
3273 if (
Result->isPointerTy()) {
3275 if (parseOptionalAddrSpace(AddrSpace))
3281 return tokError(
"ptr* is invalid - use ptr instead");
3292 if (parseTargetExtType(Result))
3298 if (parseAnonStructType(Result,
false))
3304 if (parseArrayVectorType(Result,
false))
3311 if (parseAnonStructType(Result,
true) ||
3312 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3314 }
else if (parseArrayVectorType(Result,
true))
3319 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3325 Entry.second = Lex.getLoc();
3334 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3340 Entry.second = Lex.getLoc();
3350 switch (Lex.getKind()) {
3353 if (!AllowVoid &&
Result->isVoidTy())
3354 return error(TypeLoc,
"void type only allowed for function results");
3360 return tokError(
"basic block pointers are invalid");
3362 return tokError(
"pointers to void are invalid - use i8* instead");
3364 return tokError(
"pointer to this type is invalid");
3372 return tokError(
"basic block pointers are invalid");
3374 return tokError(
"pointers to void are invalid; use i8* instead");
3376 return tokError(
"pointer to this type is invalid");
3378 if (parseOptionalAddrSpace(AddrSpace) ||
3379 parseToken(
lltok::star,
"expected '*' in address space"))
3388 if (parseFunctionType(Result))
3401 PerFunctionState &PFS,
bool IsMustTailCall,
3402 bool InVarArgsFunc) {
3408 if (!ArgList.
empty() &&
3409 parseToken(
lltok::comma,
"expected ',' in argument list"))
3414 const char *
Msg =
"unexpected ellipsis in argument list for ";
3415 if (!IsMustTailCall)
3416 return tokError(Twine(
Msg) +
"non-musttail call");
3418 return tokError(Twine(
Msg) +
"musttail call in non-varargs function");
3420 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3425 Type *ArgTy =
nullptr;
3427 if (parseType(ArgTy, ArgLoc))
3430 return error(ArgLoc,
"invalid type for function argument");
3432 AttrBuilder ArgAttrs(M->getContext());
3435 if (parseMetadataAsValue(V, PFS))
3439 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3446 if (IsMustTailCall && InVarArgsFunc)
3447 return tokError(
"expected '...' at end of argument list for musttail call "
3448 "in varargs function");
3456bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3459 if (!EatIfPresent(AttrToken))
3462 return error(Lex.getLoc(),
"expected '('");
3466 return error(Lex.getLoc(),
"expected ')'");
3468 B.addTypeAttr(AttrKind, Ty);
3474bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3482 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3484 return tokError(
"expected integer");
3485 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3487 "integer is too large for the bit width of specified type");
3488 Val = Lex.getAPSIntVal().extend(
BitWidth);
3493 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3496 return error(TyLoc,
"the range must have integer type!");
3504 return tokError(
"the range represent the empty set but limits aren't 0!");
3515bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3518 auto ParseAPSInt = [&](APInt &Val) {
3520 return tokError(
"expected integer");
3521 Val = Lex.getAPSIntVal().extend(64);
3541 return tokError(
"the range should not represent the full or empty set!");
3553 if (!CRLOrNull.has_value())
3554 return tokError(
"Invalid (unordered or overlapping) range list");
3555 B.addInitializesAttr(*CRLOrNull);
3559bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3561 std::optional<CaptureComponents> Ret;
3565 Lex.setIgnoreColonInIdentifiers(
true);
3573 bool SeenComponent =
false;
3579 return tokError(
"duplicate 'ret' location");
3582 SeenComponent =
false;
3587 return tokError(
"cannot use 'none' with other component");
3591 return tokError(
"cannot use 'none' with other component");
3602 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3603 "'provenance' or 'read_provenance'");
3606 SeenComponent =
true;
3614 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3627bool LLParser::parseOptionalOperandBundles(
3629 LocTy BeginLoc = Lex.getLoc();
3635 if (!BundleList.
empty() &&
3636 parseToken(
lltok::comma,
"expected ',' in input list"))
3640 if (parseStringConstant(
Tag))
3643 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3646 std::vector<Value *> Inputs;
3649 if (!Inputs.empty() &&
3650 parseToken(
lltok::comma,
"expected ',' in input list"))
3654 Value *Input =
nullptr;
3658 if (parseMetadataAsValue(Input, PFS))
3660 }
else if (parseValue(Ty, Input, PFS)) {
3663 Inputs.push_back(Input);
3671 if (BundleList.
empty())
3672 return error(BeginLoc,
"operand bundle set must not be empty");
3679 unsigned NextID,
unsigned ID) {
3681 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3682 Twine(NextID) +
"' or greater");
3699 unsigned CurValID = 0;
3713 LocTy TypeLoc = Lex.getLoc();
3714 Type *ArgTy =
nullptr;
3715 AttrBuilder
Attrs(M->getContext());
3716 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3720 return error(TypeLoc,
"argument can not have void type");
3725 bool Unnamed =
false;
3727 Name = Lex.getStrVal();
3728 IdentStart = getTokLineColumnPos();
3730 IdentEnd = getPrevTokEndLineColumnPos();
3734 ArgID = Lex.getUIntVal();
3735 IdentStart = getTokLineColumnPos();
3736 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3739 IdentEnd = getPrevTokEndLineColumnPos();
3745 CurValID = ArgID + 1;
3749 return error(TypeLoc,
"invalid type for function argument");
3753 Unnamed ? std::nullopt
3754 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3759 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3764bool LLParser::parseFunctionType(
Type *&Result) {
3768 return tokError(
"invalid function return type");
3772 SmallVector<unsigned> UnnamedArgNums;
3773 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3777 for (
const ArgInfo &Arg : ArgList) {
3778 if (!Arg.Name.empty())
3779 return error(Arg.Loc,
"argument name invalid in function type");
3780 if (Arg.Attrs.hasAttributes())
3781 return error(Arg.Loc,
"argument attributes invalid in function type");
3785 for (
const ArgInfo &Arg : ArgList)
3794bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3796 if (parseStructBody(Elts))
3804bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3805 std::pair<Type *, LocTy> &Entry,
3809 return error(TypeLoc,
"redefinition of type");
3815 Entry.second = SMLoc();
3820 ResultTy =
Entry.first;
3832 return error(TypeLoc,
"forward references to non-struct type");
3836 return parseArrayVectorType(ResultTy,
true);
3837 return parseType(ResultTy);
3841 Entry.second = SMLoc();
3850 if (parseStructBody(Body) ||
3851 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3855 return tokError(
toString(std::move(
E)));
3875 LocTy EltTyLoc = Lex.getLoc();
3882 return error(EltTyLoc,
"invalid element type for struct");
3885 EltTyLoc = Lex.getLoc();
3890 return error(EltTyLoc,
"invalid element type for struct");
3895 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3904bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3905 bool Scalable =
false;
3909 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3915 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3916 Lex.getAPSIntVal().getBitWidth() > 64)
3917 return tokError(
"expected number in address space");
3919 LocTy SizeLoc = Lex.getLoc();
3923 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3926 LocTy TypeLoc = Lex.getLoc();
3927 Type *EltTy =
nullptr;
3928 if (parseType(EltTy))
3932 "expected end of sequential type"))
3937 return error(SizeLoc,
"zero element vector is illegal");
3939 return error(SizeLoc,
"size too large for vector");
3941 return error(TypeLoc,
"invalid vector element type");
3945 return error(TypeLoc,
"invalid array element type");
3962bool LLParser::parseTargetExtType(
Type *&Result) {
3967 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3968 parseStringConstant(TypeName))
3975 SmallVector<unsigned> IntParams;
3976 bool SeenInt =
false;
3983 if (parseUInt32(IntVal))
3986 }
else if (SeenInt) {
3989 return tokError(
"expected uint32 param");
3992 if (parseType(TypeParam,
true))
3998 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
4003 if (
auto E = TTy.takeError())
4004 return tokError(
toString(std::move(
E)));
4017 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
4020 auto It = UnnamedArgNums.
begin();
4023 unsigned ArgNum = *It++;
4024 NumberedVals.add(ArgNum, &A);
4029LLParser::PerFunctionState::~PerFunctionState() {
4032 for (
const auto &P : ForwardRefVals) {
4035 P.second.first->replaceAllUsesWith(
4037 P.second.first->deleteValue();
4040 for (
const auto &P : ForwardRefValIDs) {
4043 P.second.first->replaceAllUsesWith(
4045 P.second.first->deleteValue();
4049bool LLParser::PerFunctionState::finishFunction() {
4050 if (!ForwardRefVals.empty())
4051 return P.error(ForwardRefVals.begin()->second.second,
4052 "use of undefined value '%" + ForwardRefVals.begin()->first +
4054 if (!ForwardRefValIDs.empty())
4055 return P.error(ForwardRefValIDs.begin()->second.second,
4056 "use of undefined value '%" +
4057 Twine(ForwardRefValIDs.begin()->first) +
"'");
4064Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
4067 Value *Val =
F.getValueSymbolTable()->lookup(Name);
4072 auto I = ForwardRefVals.find(Name);
4073 if (
I != ForwardRefVals.end())
4074 Val =
I->second.first;
4079 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
4083 P.error(Loc,
"invalid use of a non-first-class type");
4094 if (FwdVal->
getName() != Name) {
4095 P.error(Loc,
"name is too long which can result in name collisions, "
4096 "consider making the name shorter or "
4097 "increasing -non-global-value-max-name-size");
4101 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
4105Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
4107 Value *Val = NumberedVals.get(ID);
4112 auto I = ForwardRefValIDs.find(ID);
4113 if (
I != ForwardRefValIDs.end())
4114 Val =
I->second.first;
4119 return P.checkValidVariableType(Loc,
"%" + Twine(ID), Ty, Val);
4122 P.error(Loc,
"invalid use of a non-first-class type");
4134 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4140bool LLParser::PerFunctionState::setInstName(
int NameID,
4141 const std::string &NameStr,
4142 LocTy NameLoc, Instruction *Inst) {
4145 if (NameID != -1 || !NameStr.empty())
4146 return P.error(NameLoc,
"instructions returning void cannot have a name");
4152 if (NameStr.empty()) {
4155 NameID = NumberedVals.getNext();
4157 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4161 auto FI = ForwardRefValIDs.find(NameID);
4162 if (FI != ForwardRefValIDs.end()) {
4165 return P.error(NameLoc,
"instruction forward referenced with type '" +
4169 Sentinel->replaceAllUsesWith(Inst);
4171 ForwardRefValIDs.erase(FI);
4174 NumberedVals.add(NameID, Inst);
4179 auto FI = ForwardRefVals.find(NameStr);
4180 if (FI != ForwardRefVals.end()) {
4183 return P.error(NameLoc,
"instruction forward referenced with type '" +
4187 Sentinel->replaceAllUsesWith(Inst);
4189 ForwardRefVals.erase(FI);
4195 if (Inst->
getName() != NameStr)
4196 return P.error(NameLoc,
"multiple definition of local value named '" +
4203BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4209BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID,
LocTy Loc) {
4217BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4218 int NameID,
LocTy Loc) {
4222 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4225 NameID = NumberedVals.getNext();
4227 BB = getBB(NameID, Loc);
4229 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4233 BB = getBB(Name, Loc);
4235 P.error(Loc,
"unable to create block named '" + Name +
"'");
4246 ForwardRefValIDs.erase(NameID);
4247 NumberedVals.add(NameID, BB);
4250 ForwardRefVals.erase(Name);
4267bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4268 ID.Loc = Lex.getLoc();
4269 switch (Lex.getKind()) {
4271 return tokError(
"expected value token");
4273 ID.UIntVal = Lex.getUIntVal();
4277 ID.StrVal = Lex.getStrVal();
4281 ID.UIntVal = Lex.getUIntVal();
4285 ID.StrVal = Lex.getStrVal();
4289 ID.APSIntVal = Lex.getAPSIntVal();
4293 ID.APFloatVal = Lex.getAPFloatVal();
4299 return error(
ID.Loc,
"unexpected floating-point literal");
4301 return error(
ID.Loc,
"floating-point constant invalid for type");
4306 "Invalid float strings should be caught by the lexer");
4311 return error(
ID.Loc,
"floating-point constant overflowed type");
4313 return error(
ID.Loc,
"floating-point constant underflowed type");
4319 return error(
ID.Loc,
"unexpected floating-point literal");
4321 const APInt &
Bits = Lex.getAPSIntVal();
4323 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4324 ID.APFloatVal =
APFloat(Semantics, Bits);
4346 if (parseGlobalValueVector(Elts) ||
4347 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4350 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4351 ID.UIntVal = Elts.
size();
4352 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4353 Elts.
size() *
sizeof(Elts[0]));
4364 LocTy FirstEltLoc = Lex.getLoc();
4365 if (parseGlobalValueVector(Elts) ||
4367 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4371 if (isPackedStruct) {
4372 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4373 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4374 Elts.
size() *
sizeof(Elts[0]));
4375 ID.UIntVal = Elts.
size();
4381 return error(
ID.Loc,
"constant vector must not be empty");
4383 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4384 !Elts[0]->
getType()->isFloatingPointTy() &&
4388 "vector elements must have integer, byte, pointer or floating point "
4392 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4394 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4395 " is not of type '" +
4405 LocTy FirstEltLoc = Lex.getLoc();
4406 if (parseGlobalValueVector(Elts) ||
4418 if (!Elts[0]->
getType()->isFirstClassType())
4419 return error(FirstEltLoc,
"invalid array element type: " +
4425 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4427 return error(FirstEltLoc,
"array element #" + Twine(i) +
4428 " is not of type '" +
4440 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4449 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4452 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4455 parseStringConstant(
ID.StrVal) ||
4456 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4459 ID.StrVal2 = Lex.getStrVal();
4460 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4461 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4472 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4473 parseValID(Fn, PFS) ||
4475 "expected comma in block address expression") ||
4476 parseValID(Label, PFS) ||
4477 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4481 return error(Fn.
Loc,
"expected function name in blockaddress");
4483 return error(
Label.Loc,
"expected basic block name in blockaddress");
4486 GlobalValue *GV =
nullptr;
4488 GV = NumberedVals.get(Fn.
UIntVal);
4489 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4490 GV = M->getNamedValue(Fn.
StrVal);
4496 return error(Fn.
Loc,
"expected function name in blockaddress");
4498 if (
F->isDeclaration())
4499 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4504 GlobalValue *&FwdRef =
4505 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4513 "type of blockaddress must be a pointer and not '" +
4518 FwdDeclAS = PFS->getFunction().getAddressSpace();
4522 FwdRef =
new GlobalVariable(
4527 ID.ConstantVal = FwdRef;
4535 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4537 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4539 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4541 return error(
Label.Loc,
"referenced value is not a basic block");
4544 return error(
Label.Loc,
"cannot take address of numeric label after "
4545 "the function is defined");
4547 F->getValueSymbolTable()->lookup(
Label.StrVal));
4549 return error(
Label.Loc,
"referenced value is not a basic block");
4563 if (parseValID(Fn, PFS))
4568 "expected global value name in dso_local_equivalent");
4571 GlobalValue *GV =
nullptr;
4573 GV = NumberedVals.get(Fn.
UIntVal);
4574 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4575 GV = M->getNamedValue(Fn.
StrVal);
4581 ? ForwardRefDSOLocalEquivalentIDs
4582 : ForwardRefDSOLocalEquivalentNames;
4583 GlobalValue *&FwdRef = FwdRefMap[Fn];
4590 ID.ConstantVal = FwdRef;
4596 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4597 "in dso_local_equivalent");
4608 if (parseValID(ID, PFS))
4612 return error(
ID.Loc,
"expected global value name in no_cfi");
4624 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4625 *DeactivationSymbol =
nullptr;
4628 "expected '(' in constant ptrauth expression") ||
4629 parseGlobalTypeAndValue(Ptr) ||
4631 "expected comma in constant ptrauth expression") ||
4632 parseGlobalTypeAndValue(
Key))
4635 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4637 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4640 parseGlobalTypeAndValue(DeactivationSymbol))
4643 "expected ')' in constant ptrauth expression"))
4647 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4650 if (!KeyC || KeyC->getBitWidth() != 32)
4651 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4653 ConstantInt *DiscC =
nullptr;
4659 "constant ptrauth integer discriminator must be i64 constant");
4665 if (!AddrDisc->getType()->isPointerTy())
4667 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4672 if (!DeactivationSymbol)
4673 DeactivationSymbol =
4675 if (!DeactivationSymbol->getType()->isPointerTy())
4677 "constant ptrauth deactivation symbol must be a pointer");
4691 unsigned Opc = Lex.getUIntVal();
4692 Type *DestTy =
nullptr;
4695 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4696 parseGlobalTypeAndValue(SrcVal) ||
4697 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4698 parseType(DestTy) ||
4699 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4702 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4711 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4713 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4715 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4717 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4719 return error(
ID.Loc,
"urem constexprs are no longer supported");
4721 return error(
ID.Loc,
"srem constexprs are no longer supported");
4723 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4725 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4727 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4729 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4731 return error(
ID.Loc,
"frem constexprs are no longer supported");
4733 return error(
ID.Loc,
"and constexprs are no longer supported");
4735 return error(
ID.Loc,
"or constexprs are no longer supported");
4737 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4739 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4741 return error(
ID.Loc,
"shl constexprs are no longer supported");
4743 return error(
ID.Loc,
"mul constexprs are no longer supported");
4745 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4747 return error(
ID.Loc,
"select constexprs are no longer supported");
4749 return error(
ID.Loc,
"zext constexprs are no longer supported");
4751 return error(
ID.Loc,
"sext constexprs are no longer supported");
4753 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4755 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4757 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4759 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4761 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4763 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4765 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4767 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4775 unsigned Opc = Lex.getUIntVal();
4778 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4779 Opc == Instruction::Mul) {
4788 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4789 parseGlobalTypeAndValue(Val0) ||
4790 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4791 parseGlobalTypeAndValue(Val1) ||
4792 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4795 return error(
ID.Loc,
"operands of constexpr must have same type");
4799 "constexpr requires integer or integer vector operands");
4810 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4813 if (parseGlobalTypeAndValue(
C))
4815 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4827 unsigned Opc = Lex.getUIntVal();
4830 bool HasInRange =
false;
4836 if (
Opc == Instruction::GetElementPtr) {
4852 return tokError(
"expected integer");
4853 InRangeStart = Lex.getAPSIntVal();
4858 return tokError(
"expected integer");
4859 InRangeEnd = Lex.getAPSIntVal();
4867 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4870 if (
Opc == Instruction::GetElementPtr) {
4871 if (parseType(Ty) ||
4872 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4876 if (parseGlobalValueVector(Elts) ||
4880 if (
Opc == Instruction::GetElementPtr) {
4881 if (Elts.
size() == 0 ||
4882 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4883 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4886 std::optional<ConstantRange>
InRange;
4888 unsigned IndexWidth =
4889 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4890 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4891 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4892 if (InRangeStart.
sge(InRangeEnd))
4893 return error(
ID.Loc,
"expected end to be larger than start");
4903 for (Constant *Val : Indices) {
4906 return error(
ID.Loc,
"getelementptr index must be an integer");
4909 if (GEPWidth && (ValNumEl != GEPWidth))
4912 "getelementptr vector index has a wrong number of elements");
4915 GEPWidth = ValNumEl;
4919 if (!Indices.empty() && !Ty->
isSized())
4920 return error(
ID.Loc,
"base element of getelementptr must be sized");
4923 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4926 return error(
ID.Loc,
"invalid getelementptr indices");
4930 }
else if (
Opc == Instruction::ShuffleVector) {
4931 if (Elts.
size() != 3)
4932 return error(
ID.Loc,
"expected three operands to shufflevector");
4934 return error(
ID.Loc,
"invalid operands to shufflevector");
4935 SmallVector<int, 16>
Mask;
4938 }
else if (
Opc == Instruction::ExtractElement) {
4939 if (Elts.
size() != 2)
4940 return error(
ID.Loc,
"expected two operands to extractelement");
4942 return error(
ID.Loc,
"invalid extractelement operands");
4945 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4946 if (Elts.
size() != 3)
4947 return error(
ID.Loc,
"expected three operands to insertelement");
4949 return error(
ID.Loc,
"invalid insertelement operands");
4964bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4968 bool Parsed = parseValID(ID,
nullptr, Ty) ||
4969 convertValIDToValue(Ty, ID, V,
nullptr);
4971 return error(
ID.Loc,
"global values must be constants");
4975bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4977 return parseType(Ty) || parseGlobalValue(Ty, V);
4980bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4983 LocTy KwLoc = Lex.getLoc();
4989 return tokError(
"expected comdat variable");
4990 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4992 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4995 if (GlobalName.
empty())
4996 return tokError(
"comdat cannot be unnamed");
4997 C = getComdat(std::string(GlobalName), KwLoc);
5006bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5020 if (parseGlobalTypeAndValue(
C))
5028bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
5030 if (parseMDNodeVector(Elts))
5041bool LLParser::parseMDNode(MDNode *&
N) {
5043 return parseSpecializedMDNode(
N);
5045 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
5048bool LLParser::parseMDNodeTail(MDNode *&
N) {
5051 return parseMDTuple(
N);
5054 return parseMDNodeID(
N);
5060template <
class FieldTy>
struct MDFieldImpl {
5061 typedef MDFieldImpl ImplTy;
5065 void assign(FieldTy Val) {
5067 this->Val = std::move(Val);
5070 explicit MDFieldImpl(FieldTy
Default)
5078template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
5079 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5092 this->
A = std::move(
A);
5098 this->
B = std::move(
B);
5102 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5104 WhatIs(IsInvalid) {}
5107struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5114struct LineField :
public MDUnsignedField {
5115 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5118struct ColumnField :
public MDUnsignedField {
5119 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5122struct DwarfTagField :
public MDUnsignedField {
5128struct DwarfMacinfoTypeField :
public MDUnsignedField {
5134struct DwarfAttEncodingField :
public MDUnsignedField {
5135 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5138struct DwarfVirtualityField :
public MDUnsignedField {
5142struct DwarfLangField :
public MDUnsignedField {
5146struct DwarfSourceLangNameField :
public MDUnsignedField {
5147 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5150struct DwarfLangDialectField :
public MDUnsignedField {
5151 DwarfLangDialectField()
5155struct DwarfCCField :
public MDUnsignedField {
5156 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5159struct DwarfEnumKindField :
public MDUnsignedField {
5160 DwarfEnumKindField()
5165struct EmissionKindField :
public MDUnsignedField {
5166 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5169struct FixedPointKindField :
public MDUnsignedField {
5170 FixedPointKindField()
5171 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5174struct NameTableKindField :
public MDUnsignedField {
5175 NameTableKindField()
5178 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5181struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5182 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5185struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5186 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5189struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5190 MDAPSIntField() : ImplTy(
APSInt()) {}
5193struct MDSignedField :
public MDFieldImpl<int64_t> {
5197 MDSignedField(int64_t
Default = 0)
5199 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5203struct MDBoolField :
public MDFieldImpl<bool> {
5207struct MDField :
public MDFieldImpl<Metadata *> {
5210 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5213struct MDStringField :
public MDFieldImpl<MDString *> {
5214 enum class EmptyIs {
5219 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5220 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5223struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5227struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5231struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5232 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5233 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5235 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5236 bool AllowNull =
true)
5237 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5239 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5240 bool isMDField()
const {
return WhatIs == IsTypeB; }
5241 int64_t getMDSignedValue()
const {
5242 assert(isMDSignedField() &&
"Wrong field type");
5245 Metadata *getMDFieldValue()
const {
5246 assert(isMDField() &&
"Wrong field type");
5251struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5253 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5256 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5258 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5259 bool isMDField()
const {
return WhatIs == IsTypeB; }
5260 uint64_t getMDUnsignedValue()
const {
5261 assert(isMDUnsignedField() &&
"Wrong field type");
5264 Metadata *getMDFieldValue()
const {
5265 assert(isMDField() &&
"Wrong field type");
5270 if (isMDUnsignedField())
5272 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5274 return getMDFieldValue();
5286 return tokError(
"expected integer");
5288 Result.assign(Lex.getAPSIntVal());
5295 MDUnsignedField &Result) {
5296 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5297 return tokError(
"expected unsigned integer");
5299 auto &U = Lex.getAPSIntVal();
5300 if (U.ugt(Result.Max))
5301 return tokError(
"value for '" + Name +
"' too large, limit is " +
5303 Result.assign(U.getZExtValue());
5304 assert(Result.Val <= Result.Max &&
"Expected value in range");
5311 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5315 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5321 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5324 return tokError(
"expected DWARF tag");
5328 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5329 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5338 DwarfMacinfoTypeField &Result) {
5340 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5343 return tokError(
"expected DWARF macinfo type");
5347 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5348 Lex.getStrVal() +
"'");
5349 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5351 Result.assign(Macinfo);
5358 DwarfVirtualityField &Result) {
5360 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5363 return tokError(
"expected DWARF virtuality code");
5367 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5368 Lex.getStrVal() +
"'");
5369 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5370 Result.assign(Virtuality);
5377 DwarfEnumKindField &Result) {
5379 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5382 return tokError(
"expected DWARF enum kind code");
5386 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5387 Lex.getStrVal() +
"'");
5388 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5389 Result.assign(EnumKind);
5397 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5400 return tokError(
"expected DWARF language");
5404 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5406 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5407 Result.assign(Lang);
5414 DwarfSourceLangNameField &Result) {
5416 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5419 return tokError(
"expected DWARF source language name");
5423 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5424 Lex.getStrVal() +
"'");
5425 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5426 Result.assign(Lang);
5433 DwarfLangDialectField &Result) {
5438 if (Lex.getAPSIntVal() == 0)
5439 return tokError(
"value for 'dialect' must be a known DWARF language "
5440 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5441 "DW_LLVM_LANG_DIALECT_tile)");
5442 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5446 return tokError(
"expected DWARF language dialect");
5448 StringRef DialectString = Lex.getStrVal();
5453 if (Dialect > Result.Max)
5454 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5455 DialectString +
"'");
5456 Result.assign(Dialect);
5464 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5467 return tokError(
"expected DWARF calling convention");
5471 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5472 Lex.getStrVal() +
"'");
5473 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5481 EmissionKindField &Result) {
5483 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5486 return tokError(
"expected emission kind");
5490 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5492 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5493 Result.assign(*Kind);
5500 FixedPointKindField &Result) {
5502 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5505 return tokError(
"expected fixed-point kind");
5509 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5511 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5512 Result.assign(*Kind);
5519 NameTableKindField &Result) {
5521 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5524 return tokError(
"expected nameTable kind");
5528 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5530 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5531 Result.assign((
unsigned)*Kind);
5538 DwarfAttEncodingField &Result) {
5540 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5543 return tokError(
"expected DWARF type attribute encoding");
5547 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5548 Lex.getStrVal() +
"'");
5549 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5550 Result.assign(Encoding);
5564 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5566 bool Res = parseUInt32(TempVal);
5572 return tokError(
"expected debug info flag");
5576 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5591 Result.assign(Combined);
5604 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5606 bool Res = parseUInt32(TempVal);
5612 return tokError(
"expected debug info flag");
5616 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5617 Lex.getStrVal() +
"'");
5631 Result.assign(Combined);
5638 return tokError(
"expected signed integer");
5640 auto &S = Lex.getAPSIntVal();
5642 return tokError(
"value for '" + Name +
"' too small, limit is " +
5645 return tokError(
"value for '" + Name +
"' too large, limit is " +
5647 Result.assign(S.getExtValue());
5648 assert(Result.Val >= Result.Min &&
"Expected value in range");
5649 assert(Result.Val <= Result.Max &&
"Expected value in range");
5656 switch (Lex.getKind()) {
5658 return tokError(
"expected 'true' or 'false'");
5660 Result.assign(
true);
5663 Result.assign(
false);
5673 if (!Result.AllowNull)
5674 return tokError(
"'" + Name +
"' cannot be null");
5676 Result.assign(
nullptr);
5681 if (parseMetadata(MD,
nullptr))
5690 MDSignedOrMDField &Result) {
5693 MDSignedField Res = Result.A;
5694 if (!parseMDField(
Loc, Name, Res)) {
5702 MDField Res = Result.B;
5703 if (!parseMDField(
Loc, Name, Res)) {
5713 MDUnsignedOrMDField &Result) {
5716 MDUnsignedField Res = Result.A;
5717 if (!parseMDField(
Loc, Name, Res)) {
5725 MDField Res = Result.B;
5726 if (!parseMDField(
Loc, Name, Res)) {
5736 LocTy ValueLoc = Lex.getLoc();
5738 if (parseStringConstant(S))
5742 switch (Result.EmptyIs) {
5743 case MDStringField::EmptyIs::Null:
5744 Result.assign(
nullptr);
5746 case MDStringField::EmptyIs::Empty:
5748 case MDStringField::EmptyIs::Error:
5749 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5760 if (parseMDNodeVector(MDs))
5763 Result.assign(std::move(MDs));
5769 ChecksumKindField &Result) {
5770 std::optional<DIFile::ChecksumKind> CSKind =
5774 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5777 Result.assign(*CSKind);
5784template <
class ParserTy>
5785bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5788 return tokError(
"expected field label here");
5797template <
class ParserTy>
5798bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5805 if (parseMDFieldsImplBody(ParseField))
5808 ClosingLoc = Lex.getLoc();
5812template <
class FieldTy>
5813bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5815 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5817 LocTy Loc = Lex.getLoc();
5819 return parseMDField(Loc, Name, Result);
5822bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5825#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5826 if (Lex.getStrVal() == #CLASS) \
5827 return parse##CLASS(N, IsDistinct);
5828#include "llvm/IR/Metadata.def"
5830 return tokError(
"expected metadata type");
5833#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5834#define NOP_FIELD(NAME, TYPE, INIT)
5835#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5837 return error(ClosingLoc, "missing required field '" #NAME "'");
5838#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5839 if (Lex.getStrVal() == #NAME) \
5840 return parseMDField(#NAME, NAME);
5841#define PARSE_MD_FIELDS() \
5842 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5845 if (parseMDFieldsImpl( \
5847 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5848 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5853 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5855#define GET_OR_DISTINCT(CLASS, ARGS) \
5856 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5861bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5862#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5863 OPTIONAL(line, LineField, ); \
5864 OPTIONAL(column, ColumnField, ); \
5865 REQUIRED(scope, MDField, ( false)); \
5866 OPTIONAL(inlinedAt, MDField, ); \
5867 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5868 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5869 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5871#undef VISIT_MD_FIELDS
5874 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5875 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5881bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5883 return tokError(
"missing 'distinct', required for !DIAssignID()");
5899bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5900#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5901 REQUIRED(tag, DwarfTagField, ); \
5902 OPTIONAL(header, MDStringField, ); \
5903 OPTIONAL(operands, MDFieldList, );
5905#undef VISIT_MD_FIELDS
5908 (Context, tag.Val, header.Val, operands.Val));
5917bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5918#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5919 OPTIONAL(name, MDStringField, ); \
5920 OPTIONAL(file, MDField, ); \
5921 OPTIONAL(line, LineField, ); \
5922 OPTIONAL(scope, MDField, ); \
5923 OPTIONAL(baseType, MDField, ); \
5924 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5925 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5926 OPTIONAL(flags, DIFlagField, ); \
5927 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5928 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5929 OPTIONAL(stride, MDSignedOrMDField, ); \
5930 OPTIONAL(bias, MDSignedOrMDField, );
5932#undef VISIT_MD_FIELDS
5934 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5935 if (Bound.isMDSignedField())
5938 if (Bound.isMDField())
5939 return Bound.getMDFieldValue();
5945 Metadata *Stride = convToMetadata(stride);
5946 Metadata *Bias = convToMetadata(bias);
5949 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5950 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5951 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5960bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5961#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5962 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5963 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5964 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5965 OPTIONAL(stride, MDSignedOrMDField, );
5967#undef VISIT_MD_FIELDS
5974 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5975 if (Bound.isMDSignedField())
5978 if (Bound.isMDField())
5979 return Bound.getMDFieldValue();
5986 Stride = convToMetadata(stride);
5989 (Context,
Count, LowerBound, UpperBound, Stride));
5997bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5998#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5999 OPTIONAL(count, MDSignedOrMDField, ); \
6000 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6001 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6002 OPTIONAL(stride, MDSignedOrMDField, );
6004#undef VISIT_MD_FIELDS
6006 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6007 if (Bound.isMDSignedField())
6009 Context, {dwarf::DW_OP_consts,
6010 static_cast<uint64_t>(Bound.getMDSignedValue())});
6011 if (Bound.isMDField())
6012 return Bound.getMDFieldValue();
6019 Metadata *Stride = ConvToMetadata(stride);
6022 (Context,
Count, LowerBound, UpperBound, Stride));
6029bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
6030#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6031 REQUIRED(name, MDStringField, ); \
6032 REQUIRED(value, MDAPSIntField, ); \
6033 OPTIONAL(isUnsigned, MDBoolField, (false));
6035#undef VISIT_MD_FIELDS
6037 if (isUnsigned.Val && value.Val.isNegative())
6038 return tokError(
"unsigned enumerator with negative value");
6043 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6055bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
6056#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6057 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6058 OPTIONAL(name, MDStringField, ); \
6059 OPTIONAL(file, MDField, ); \
6060 OPTIONAL(line, LineField, ); \
6061 OPTIONAL(scope, MDField, ); \
6062 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6063 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6064 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6065 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6066 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6067 OPTIONAL(flags, DIFlagField, );
6069#undef VISIT_MD_FIELDS
6072 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6073 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
6074 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6083bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6084#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6085 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6086 OPTIONAL(name, MDStringField, ); \
6087 OPTIONAL(file, MDField, ); \
6088 OPTIONAL(line, LineField, ); \
6089 OPTIONAL(scope, MDField, ); \
6090 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6091 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6092 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6093 OPTIONAL(flags, DIFlagField, ); \
6094 OPTIONAL(kind, FixedPointKindField, ); \
6095 OPTIONAL(factor, MDSignedField, ); \
6096 OPTIONAL(numerator, MDAPSIntField, ); \
6097 OPTIONAL(denominator, MDAPSIntField, );
6099#undef VISIT_MD_FIELDS
6102 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6103 scope.Val,
size.getValueAsMetadata(Context),
6104 align.Val, encoding.Val, flags.Val, kind.Val,
6105 factor.Val, numerator.Val, denominator.Val));
6111bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6112#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6113 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6114 OPTIONAL(name, MDStringField, ); \
6115 OPTIONAL(stringLength, MDField, ); \
6116 OPTIONAL(stringLengthExpression, MDField, ); \
6117 OPTIONAL(stringLocationExpression, MDField, ); \
6118 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6119 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6120 OPTIONAL(encoding, DwarfAttEncodingField, );
6122#undef VISIT_MD_FIELDS
6126 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6127 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6128 align.Val, encoding.Val));
6141bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6142#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6143 REQUIRED(tag, DwarfTagField, ); \
6144 OPTIONAL(name, MDStringField, ); \
6145 OPTIONAL(file, MDField, ); \
6146 OPTIONAL(line, LineField, ); \
6147 OPTIONAL(scope, MDField, ); \
6148 REQUIRED(baseType, MDField, ); \
6149 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6150 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6151 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6152 OPTIONAL(flags, DIFlagField, ); \
6153 OPTIONAL(extraData, MDField, ); \
6154 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6155 OPTIONAL(annotations, MDField, ); \
6156 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6157 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6158 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6159 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6160 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6162#undef VISIT_MD_FIELDS
6164 std::optional<unsigned> DWARFAddressSpace;
6165 if (dwarfAddressSpace.Val != UINT32_MAX)
6166 DWARFAddressSpace = dwarfAddressSpace.Val;
6167 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6169 PtrAuthData.emplace(
6170 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6171 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6172 ptrAuthAuthenticatesNullValues.Val);
6175 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6176 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6177 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6178 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6182bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6183#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6184 REQUIRED(tag, DwarfTagField, ); \
6185 OPTIONAL(name, MDStringField, ); \
6186 OPTIONAL(file, MDField, ); \
6187 OPTIONAL(line, LineField, ); \
6188 OPTIONAL(scope, MDField, ); \
6189 OPTIONAL(baseType, MDField, ); \
6190 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6191 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6192 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6193 OPTIONAL(flags, DIFlagField, ); \
6194 OPTIONAL(elements, MDField, ); \
6195 OPTIONAL(runtimeLang, DwarfLangField, ); \
6196 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6197 OPTIONAL(vtableHolder, MDField, ); \
6198 OPTIONAL(templateParams, MDField, ); \
6199 OPTIONAL(identifier, MDStringField, ); \
6200 OPTIONAL(discriminator, MDField, ); \
6201 OPTIONAL(dataLocation, MDField, ); \
6202 OPTIONAL(associated, MDField, ); \
6203 OPTIONAL(allocated, MDField, ); \
6204 OPTIONAL(rank, MDSignedOrMDField, ); \
6205 OPTIONAL(annotations, MDField, ); \
6206 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6207 OPTIONAL(specification, MDField, ); \
6208 OPTIONAL(bitStride, MDField, );
6210#undef VISIT_MD_FIELDS
6213 if (rank.isMDSignedField())
6216 else if (rank.isMDField())
6217 Rank = rank.getMDFieldValue();
6219 std::optional<unsigned> EnumKind;
6221 EnumKind = enumKind.Val;
6226 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6227 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6228 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6229 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6230 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6231 dataLocation.Val, associated.Val, allocated.Val, Rank,
6232 annotations.Val, bitStride.Val)) {
6241 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6242 size.getValueAsMetadata(Context),
align.Val,
6243 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6244 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6245 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6246 allocated.Val, Rank, annotations.Val, specification.Val,
6247 num_extra_inhabitants.Val, bitStride.Val));
6251bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6252#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6253 OPTIONAL(flags, DIFlagField, ); \
6254 OPTIONAL(cc, DwarfCCField, ); \
6255 REQUIRED(types, MDField, );
6257#undef VISIT_MD_FIELDS
6260 (Context, flags.Val, cc.Val, types.Val));
6269bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6273#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6274 REQUIRED(filename, MDStringField, ); \
6275 REQUIRED(directory, MDStringField, ); \
6276 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6277 OPTIONAL(checksum, MDStringField, ); \
6278 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6280#undef VISIT_MD_FIELDS
6282 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6283 if (checksumkind.Seen && checksum.Seen)
6284 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6285 else if (checksumkind.Seen || checksum.Seen)
6286 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6288 MDString *
Source =
nullptr;
6292 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6304bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6306 return tokError(
"missing 'distinct', required for !DICompileUnit");
6308 LocTy Loc = Lex.getLoc();
6310#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6311 REQUIRED(file, MDField, ( false)); \
6312 OPTIONAL(language, DwarfLangField, ); \
6313 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6314 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6315 OPTIONAL(producer, MDStringField, ); \
6316 OPTIONAL(isOptimized, MDBoolField, ); \
6317 OPTIONAL(flags, MDStringField, ); \
6318 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6319 OPTIONAL(splitDebugFilename, MDStringField, ); \
6320 OPTIONAL(emissionKind, EmissionKindField, ); \
6321 OPTIONAL(enums, MDField, ); \
6322 OPTIONAL(retainedTypes, MDField, ); \
6323 OPTIONAL(globals, MDField, ); \
6324 OPTIONAL(imports, MDField, ); \
6325 OPTIONAL(macros, MDField, ); \
6326 OPTIONAL(dwoId, MDUnsignedField, ); \
6327 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6328 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6329 OPTIONAL(nameTableKind, NameTableKindField, ); \
6330 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6331 OPTIONAL(sysroot, MDStringField, ); \
6332 OPTIONAL(sdk, MDStringField, ); \
6333 OPTIONAL(dialect, DwarfLangDialectField, );
6335#undef VISIT_MD_FIELDS
6337 if (!language.Seen && !sourceLanguageName.Seen)
6338 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6339 "required for !DICompileUnit");
6341 if (language.Seen && sourceLanguageName.Seen)
6342 return error(Loc,
"can only specify one of 'language' and "
6343 "'sourceLanguageName' on !DICompileUnit");
6345 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6346 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6347 "'sourceLanguageName' on !DICompileUnit");
6349 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6352 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6353 : DISourceLanguageName(
6354 static_cast<uint16_t>(sourceLanguageName.Val),
6355 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6358 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6359 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6360 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6361 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6362 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6375bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6376 auto Loc = Lex.getLoc();
6377#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6378 OPTIONAL(scope, MDField, ); \
6379 OPTIONAL(name, MDStringField, ); \
6380 OPTIONAL(linkageName, MDStringField, ); \
6381 OPTIONAL(file, MDField, ); \
6382 OPTIONAL(line, LineField, ); \
6383 REQUIRED(type, MDField, ( false)); \
6384 OPTIONAL(isLocal, MDBoolField, ); \
6385 OPTIONAL(isDefinition, MDBoolField, (true)); \
6386 OPTIONAL(scopeLine, LineField, ); \
6387 OPTIONAL(containingType, MDField, ); \
6388 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6389 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6390 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6391 OPTIONAL(flags, DIFlagField, ); \
6392 OPTIONAL(spFlags, DISPFlagField, ); \
6393 OPTIONAL(isOptimized, MDBoolField, ); \
6394 OPTIONAL(unit, MDField, ); \
6395 OPTIONAL(templateParams, MDField, ); \
6396 OPTIONAL(declaration, MDField, ); \
6397 OPTIONAL(retainedNodes, MDField, ); \
6398 OPTIONAL(thrownTypes, MDField, ); \
6399 OPTIONAL(annotations, MDField, ); \
6400 OPTIONAL(targetFuncName, MDStringField, ); \
6401 OPTIONAL(keyInstructions, MDBoolField, );
6403#undef VISIT_MD_FIELDS
6408 spFlags.Seen ? spFlags.Val
6410 isOptimized.Val, virtuality.Val);
6411 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6414 "missing 'distinct', required for !DISubprogram that is a Definition");
6417 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6418 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6419 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6420 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6421 targetFuncName.Val, keyInstructions.Val));
6431bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6432#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6433 REQUIRED(scope, MDField, ( false)); \
6434 OPTIONAL(file, MDField, ); \
6435 OPTIONAL(line, LineField, ); \
6436 OPTIONAL(column, ColumnField, );
6438#undef VISIT_MD_FIELDS
6441 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6447bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6448#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6449 REQUIRED(scope, MDField, ( false)); \
6450 OPTIONAL(file, MDField, ); \
6451 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6453#undef VISIT_MD_FIELDS
6456 (Context, scope.Val,
file.Val, discriminator.Val));
6462bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6463#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6464 REQUIRED(scope, MDField, ); \
6465 OPTIONAL(declaration, MDField, ); \
6466 OPTIONAL(name, MDStringField, ); \
6467 OPTIONAL(file, MDField, ); \
6468 OPTIONAL(line, LineField, );
6470#undef VISIT_MD_FIELDS
6473 (Context, scope.Val, declaration.Val,
name.Val,
6474 file.Val, line.Val));
6480bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6481#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6482 REQUIRED(scope, MDField, ); \
6483 OPTIONAL(name, MDStringField, ); \
6484 OPTIONAL(exportSymbols, MDBoolField, );
6486#undef VISIT_MD_FIELDS
6489 (Context, scope.Val,
name.Val, exportSymbols.Val));
6496bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6497#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6498 REQUIRED(type, DwarfMacinfoTypeField, ); \
6499 OPTIONAL(line, LineField, ); \
6500 REQUIRED(name, MDStringField, ); \
6501 OPTIONAL(value, MDStringField, );
6503#undef VISIT_MD_FIELDS
6506 (Context, type.Val, line.Val,
name.Val, value.Val));
6512bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6513#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6514 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6515 OPTIONAL(line, LineField, ); \
6516 REQUIRED(file, MDField, ); \
6517 OPTIONAL(nodes, MDField, );
6519#undef VISIT_MD_FIELDS
6522 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6530bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6531#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6532 REQUIRED(scope, MDField, ); \
6533 REQUIRED(name, MDStringField, ); \
6534 OPTIONAL(configMacros, MDStringField, ); \
6535 OPTIONAL(includePath, MDStringField, ); \
6536 OPTIONAL(apinotes, MDStringField, ); \
6537 OPTIONAL(file, MDField, ); \
6538 OPTIONAL(line, LineField, ); \
6539 OPTIONAL(isDecl, MDBoolField, );
6541#undef VISIT_MD_FIELDS
6544 configMacros.Val, includePath.Val,
6545 apinotes.Val, line.Val, isDecl.Val));
6551bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6552#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6553 OPTIONAL(name, MDStringField, ); \
6554 REQUIRED(type, MDField, ); \
6555 OPTIONAL(defaulted, MDBoolField, );
6557#undef VISIT_MD_FIELDS
6560 (Context,
name.Val, type.Val, defaulted.Val));
6568bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6569#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6570 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6571 OPTIONAL(name, MDStringField, ); \
6572 OPTIONAL(type, MDField, ); \
6573 OPTIONAL(defaulted, MDBoolField, ); \
6574 REQUIRED(value, MDField, );
6577#undef VISIT_MD_FIELDS
6580 DITemplateValueParameter,
6581 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6590bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6591#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6592 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6593 OPTIONAL(scope, MDField, ); \
6594 OPTIONAL(linkageName, MDStringField, ); \
6595 OPTIONAL(file, MDField, ); \
6596 OPTIONAL(line, LineField, ); \
6597 OPTIONAL(type, MDField, ); \
6598 OPTIONAL(isLocal, MDBoolField, ); \
6599 OPTIONAL(isDefinition, MDBoolField, (true)); \
6600 OPTIONAL(templateParams, MDField, ); \
6601 OPTIONAL(declaration, MDField, ); \
6602 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6603 OPTIONAL(annotations, MDField, );
6605#undef VISIT_MD_FIELDS
6609 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6610 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6611 declaration.Val, templateParams.Val,
align.Val,
6623bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6624#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6625 REQUIRED(scope, MDField, ( false)); \
6626 OPTIONAL(name, MDStringField, ); \
6627 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6628 OPTIONAL(file, MDField, ); \
6629 OPTIONAL(line, LineField, ); \
6630 OPTIONAL(type, MDField, ); \
6631 OPTIONAL(flags, DIFlagField, ); \
6632 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6633 OPTIONAL(annotations, MDField, );
6635#undef VISIT_MD_FIELDS
6638 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6639 type.Val, arg.Val, flags.Val,
align.Val,
6646bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6647#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6648 REQUIRED(scope, MDField, ( false)); \
6649 REQUIRED(name, MDStringField, ); \
6650 REQUIRED(file, MDField, ); \
6651 REQUIRED(line, LineField, ); \
6652 OPTIONAL(column, ColumnField, ); \
6653 OPTIONAL(isArtificial, MDBoolField, ); \
6654 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6656#undef VISIT_MD_FIELDS
6658 std::optional<unsigned> CoroSuspendIdx =
6659 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6663 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6664 column.Val, isArtificial.Val, CoroSuspendIdx));
6670bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6683 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6692 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6693 Lex.getStrVal() +
"'");
6696 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6697 return tokError(
"expected unsigned integer");
6699 auto &
U = Lex.getAPSIntVal();
6701 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6715bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6717 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6720 return parseDIExpressionBody(Result, IsDistinct);
6725bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6726 assert(PFS &&
"Expected valid function state");
6737 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6751bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6753#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6754 REQUIRED(var, MDField, ); \
6755 REQUIRED(expr, MDField, );
6757#undef VISIT_MD_FIELDS
6760 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6767bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6768#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6769 OPTIONAL(name, MDStringField, ); \
6770 OPTIONAL(file, MDField, ); \
6771 OPTIONAL(line, LineField, ); \
6772 OPTIONAL(setter, MDStringField, ); \
6773 OPTIONAL(getter, MDStringField, ); \
6774 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6775 OPTIONAL(type, MDField, );
6777#undef VISIT_MD_FIELDS
6780 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6781 setter.Val, attributes.Val, type.Val));
6788bool LLParser::parseDIProperty(
MDNode *&Result,
bool IsDistinct) {
6789#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6790 OPTIONAL(name, MDStringField, ); \
6791 OPTIONAL(file, MDField, ); \
6792 OPTIONAL(line, LineField, ); \
6793 OPTIONAL(type, MDField, ); \
6794 OPTIONAL(backing_storage, MDField, );
6796#undef VISIT_MD_FIELDS
6799 type.Val, backing_storage.Val));
6806bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6807#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6808 REQUIRED(tag, DwarfTagField, ); \
6809 REQUIRED(scope, MDField, ); \
6810 OPTIONAL(entity, MDField, ); \
6811 OPTIONAL(file, MDField, ); \
6812 OPTIONAL(line, LineField, ); \
6813 OPTIONAL(name, MDStringField, ); \
6814 OPTIONAL(elements, MDField, );
6816#undef VISIT_MD_FIELDS
6819 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6820 line.Val,
name.Val, elements.Val));
6824#undef PARSE_MD_FIELD
6836bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6839 if (parseMetadata(MD, &PFS))
6850bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6851 PerFunctionState *PFS) {
6854 if (parseType(Ty, TypeMsg, Loc))
6857 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6860 if (parseValue(Ty, V, PFS))
6875bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6879 if (Lex.getStrVal() ==
"DIArgList") {
6881 if (parseDIArgList(AL, PFS))
6887 if (parseSpecializedMDNode(
N)) {
6897 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6907 if (parseMDString(S))
6917 if (parseMDNodeTail(
N))
6927bool LLParser::convertValIDToValue(
Type *Ty,
ValID &ID,
Value *&V,
6928 PerFunctionState *PFS) {
6930 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6935 return error(
ID.Loc,
"invalid use of function-local name");
6936 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6937 return V ==
nullptr;
6940 return error(
ID.Loc,
"invalid use of function-local name");
6941 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6942 return V ==
nullptr;
6945 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6949 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6954 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6957 return V ==
nullptr;
6959 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6962 return V ==
nullptr;
6965 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6968 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
6973 return error(
ID.Loc,
"floating point constant invalid for type");
6979 bool IsSNAN = ID.APFloatVal.isSignaling();
6982 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6984 else if (Ty->isBFloatTy())
6985 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6987 else if (Ty->isFloatTy())
6988 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6994 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6995 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6996 ID.APFloatVal.isNegative(), &Payload);
6999 V = ConstantFP::get(Context,
ID.APFloatVal);
7001 if (
V->getType() != Ty)
7002 return error(
ID.Loc,
"floating point constant does not have type '" +
7008 return error(
ID.Loc,
"null must be a pointer type");
7014 return error(
ID.Loc,
"invalid type for undef constant");
7019 return error(
ID.Loc,
"invalid empty array initializer");
7025 return error(
ID.Loc,
"invalid type for null constant");
7028 return error(
ID.Loc,
"invalid type for null constant");
7033 return error(
ID.Loc,
"invalid type for none constant");
7039 return error(
ID.Loc,
"invalid type for poison constant");
7043 if (
ID.ConstantVal->getType() != Ty)
7044 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7051 return error(
ID.Loc,
"vector constant must have vector type");
7053 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7055 "' but expected '" +
7063 if (
ST->getNumElements() !=
ID.UIntVal)
7065 "initializer with struct type has wrong # elements");
7067 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
7070 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
7071 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
7074 "element " + Twine(i) +
7075 " of struct initializer doesn't match struct element type");
7078 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
7080 return error(
ID.Loc,
"constant expression type mismatch");
7089 auto Loc = Lex.getLoc();
7090 if (parseValID(ID,
nullptr, Ty))
7103 if (convertValIDToValue(Ty, ID, V,
nullptr))
7113 return error(Loc,
"expected a constant value");
7117bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
7121 FileLoc
Start = getTokLineColumnPos();
7122 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7123 if (!Ret && ParserContext) {
7124 FileLoc End = getPrevTokEndLineColumnPos();
7125 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7130bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
7132 return parseType(Ty) || parseValue(Ty, V, PFS);
7135bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7136 PerFunctionState &PFS) {
7139 if (parseTypeAndValue(V, PFS))
7142 return error(Loc,
"expected a basic block");
7151 if (!Name.starts_with(
"llvm.dbg."))
7154 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7155 FnID == Intrinsic::dbg_assign;
7163bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7164 unsigned &FunctionNumber,
7167 LocTy LinkageLoc = Lex.getLoc();
7169 unsigned Visibility;
7170 unsigned DLLStorageClass;
7172 AttrBuilder RetAttrs(M->getContext());
7175 Type *RetType =
nullptr;
7176 LocTy RetTypeLoc = Lex.getLoc();
7177 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7179 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7180 parseType(RetType, RetTypeLoc,
true ))
7189 return error(LinkageLoc,
"invalid linkage for function definition");
7199 return error(LinkageLoc,
"invalid linkage for function declaration");
7203 return error(LinkageLoc,
"invalid function linkage type");
7207 return error(LinkageLoc,
7208 "symbol with local linkage must have default visibility");
7211 return error(LinkageLoc,
7212 "symbol with local linkage cannot have a DLL storage class");
7215 return error(RetTypeLoc,
"invalid function return type");
7217 LocTy NameLoc = Lex.getLoc();
7219 std::string FunctionName;
7221 FunctionName = Lex.getStrVal();
7223 FunctionNumber = Lex.getUIntVal();
7224 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7228 return tokError(
"expected function name");
7234 return tokError(
"expected '(' in function argument list");
7238 AttrBuilder FuncAttrs(M->getContext());
7239 std::vector<unsigned> FwdRefAttrGrps;
7242 std::string Partition;
7246 unsigned AddrSpace = 0;
7252 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7253 parseOptionalUnnamedAddr(UnnamedAddr) ||
7254 parseOptionalProgramAddrSpace(AddrSpace) ||
7255 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7259 parseOptionalComdat(FunctionName,
C) ||
7260 parseOptionalAlignment(Alignment) ||
7261 parseOptionalPrefAlignment(PrefAlignment) ||
7262 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7266 parseGlobalTypeAndValue(PersonalityFn)))
7269 if (FuncAttrs.contains(Attribute::Builtin))
7270 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7273 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7275 FuncAttrs.removeAttribute(Attribute::Alignment);
7280 std::vector<Type*> ParamTypeList;
7283 for (
const ArgInfo &Arg : ArgList) {
7284 ParamTypeList.push_back(Arg.Ty);
7285 Attrs.push_back(Arg.Attrs);
7292 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7293 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7299 GlobalValue *FwdFn =
nullptr;
7300 if (!FunctionName.empty()) {
7303 auto FRVI = ForwardRefVals.find(FunctionName);
7304 if (FRVI != ForwardRefVals.end()) {
7305 FwdFn = FRVI->second.first;
7307 return error(FRVI->second.second,
7308 "invalid forward reference to "
7311 "' with wrong type: "
7315 ForwardRefVals.erase(FRVI);
7316 }
else if ((Fn = M->getFunction(FunctionName))) {
7318 return error(NameLoc,
7319 "invalid redefinition of function '" + FunctionName +
"'");
7320 }
else if (M->getNamedValue(FunctionName)) {
7321 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7327 if (FunctionNumber == (
unsigned)-1)
7328 FunctionNumber = NumberedVals.getNext();
7332 auto I = ForwardRefValIDs.find(FunctionNumber);
7333 if (
I != ForwardRefValIDs.end()) {
7334 FwdFn =
I->second.first;
7336 return error(NameLoc,
"type of definition and forward reference of '@" +
7337 Twine(FunctionNumber) +
7342 ForwardRefValIDs.erase(
I);
7351 if (FunctionName.empty())
7352 NumberedVals.add(FunctionNumber, Fn);
7368 if (!
GC.empty()) Fn->
setGC(GC);
7371 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7375 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7376 if (ParserContext && ArgList[i].IdentLoc)
7377 ParserContext->addInstructionOrArgumentLocation(
7378 &*ArgIt, ArgList[i].IdentLoc.value());
7380 if (ArgList[i].
Name.empty())
continue;
7383 ArgIt->
setName(ArgList[i].Name);
7385 if (ArgIt->
getName() != ArgList[i].Name)
7386 return error(ArgList[i].Loc,
7387 "redefinition of argument '%" + ArgList[i].Name +
"'");
7400 if (FunctionName.empty()) {
7402 ID.UIntVal = FunctionNumber;
7405 ID.StrVal = FunctionName;
7407 auto Blocks = ForwardRefBlockAddresses.find(ID);
7408 if (Blocks != ForwardRefBlockAddresses.end())
7409 return error(Blocks->first.Loc,
7410 "cannot take blockaddress inside a declaration");
7414bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7416 if (FunctionNumber == -1) {
7418 ID.StrVal = std::string(F.getName());
7421 ID.UIntVal = FunctionNumber;
7424 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7425 if (Blocks == P.ForwardRefBlockAddresses.end())
7428 for (
const auto &
I : Blocks->second) {
7429 const ValID &BBID =
I.first;
7430 GlobalValue *GV =
I.second;
7433 "Expected local id or name");
7440 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7443 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7451 P.ForwardRefBlockAddresses.erase(Blocks);
7457bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
7458 ArrayRef<unsigned> UnnamedArgNums) {
7460 return tokError(
"expected '{' in function body");
7463 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7467 if (PFS.resolveForwardRefBlockAddresses())
7473 return tokError(
"function body requires at least one basic block");
7477 if (parseBasicBlock(PFS))
7481 if (parseUseListOrder(&PFS))
7488 return PFS.finishFunction();
7493bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7494 FileLoc BBStart = getTokLineColumnPos();
7499 LocTy NameLoc = Lex.getLoc();
7501 Name = Lex.getStrVal();
7504 NameID = Lex.getUIntVal();
7508 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7512 std::string NameStr;
7517 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7518 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7525 if (SeenOldDbgInfoFormat)
7526 return error(Lex.getLoc(),
"debug record should not appear in a module "
7527 "containing debug info intrinsics");
7528 SeenNewDbgInfoFormat =
true;
7532 if (parseDebugRecord(DR, PFS))
7534 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7537 FileLoc InstStart = getTokLineColumnPos();
7540 LocTy NameLoc = Lex.getLoc();
7545 NameID = Lex.getUIntVal();
7547 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7550 NameStr = Lex.getStrVal();
7552 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7556 switch (parseInstruction(Inst, BB, PFS)) {
7559 case InstError:
return true;
7566 if (parseInstructionMetadata(*Inst))
7569 case InstExtraComma:
7574 if (parseInstructionMetadata(*Inst))
7580 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7584 for (DbgRecordPtr &DR : TrailingDbgRecord)
7586 TrailingDbgRecord.clear();
7587 if (ParserContext) {
7588 ParserContext->addInstructionOrArgumentLocation(
7589 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7594 ParserContext->addBlockLocation(
7595 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7597 assert(TrailingDbgRecord.empty() &&
7598 "All debug values should have been attached to an instruction.");
7607bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7610 LocTy DVRLoc = Lex.getLoc();
7612 return error(DVRLoc,
"expected debug record type here");
7613 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7614 .Case(
"declare", RecordKind::ValueKind)
7615 .Case(
"value", RecordKind::ValueKind)
7616 .Case(
"assign", RecordKind::ValueKind)
7617 .Case(
"label", RecordKind::LabelKind)
7618 .Case(
"declare_value", RecordKind::ValueKind);
7627 if (parseMDNode(Label))
7632 if (parseMDNode(DbgLoc))
7637 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7641 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7642 .Case(
"declare", LocType::Declare)
7643 .Case(
"value", LocType::Value)
7644 .Case(
"assign", LocType::Assign)
7645 .Case(
"declare_value", LocType::DeclareValue);
7653 if (parseMetadata(ValLocMD, &PFS))
7660 if (parseMDNode(Variable))
7667 if (parseMDNode(Expression))
7673 MDNode *AssignID =
nullptr;
7674 Metadata *AddressLocation =
nullptr;
7675 MDNode *AddressExpression =
nullptr;
7678 if (parseMDNode(AssignID))
7684 if (parseMetadata(AddressLocation, &PFS))
7690 if (parseMDNode(AddressExpression))
7704 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7706 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7715int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7716 PerFunctionState &PFS) {
7719 return tokError(
"found end of file when expecting more instructions");
7720 LocTy Loc = Lex.getLoc();
7721 unsigned KeywordVal = Lex.getUIntVal();
7726 return error(Loc,
"expected instruction opcode");
7730 return parseRet(Inst, BB, PFS);
7732 return parseBr(Inst, PFS);
7734 return parseSwitch(Inst, PFS);
7736 return parseIndirectBr(Inst, PFS);
7738 return parseInvoke(Inst, PFS);
7740 return parseResume(Inst, PFS);
7742 return parseCleanupRet(Inst, PFS);
7744 return parseCatchRet(Inst, PFS);
7746 return parseCatchSwitch(Inst, PFS);
7748 return parseCatchPad(Inst, PFS);
7750 return parseCleanupPad(Inst, PFS);
7752 return parseCallBr(Inst, PFS);
7755 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7756 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7772 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7784 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7785 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7799 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7807 return parseArithmetic(Inst, PFS, KeywordVal,
7811 if (parseLogical(Inst, PFS, KeywordVal))
7819 return parseLogical(Inst, PFS, KeywordVal);
7822 if (parseCompare(Inst, PFS, KeywordVal))
7829 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7830 int Res = parseCompare(Inst, PFS, KeywordVal);
7840 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7842 bool Res = parseCast(Inst, PFS, KeywordVal);
7852 bool Res = parseCast(Inst, PFS, KeywordVal);
7864 if (parseCast(Inst, PFS, KeywordVal))
7873 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7874 if (parseCast(Inst, PFS, KeywordVal))
7887 return parseCast(Inst, PFS, KeywordVal);
7891 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7892 if (parseCast(Inst, PFS, KeywordVal))
7901 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7902 int Res = parseSelect(Inst, PFS);
7908 return error(Loc,
"fast-math-flags specified for select without "
7909 "floating-point scalar or vector return type");
7916 return parseVAArg(Inst, PFS);
7918 return parseExtractElement(Inst, PFS);
7920 return parseInsertElement(Inst, PFS);
7922 return parseShuffleVector(Inst, PFS);
7924 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7925 int Res = parsePHI(Inst, PFS);
7931 return error(Loc,
"fast-math-flags specified for phi without "
7932 "floating-point scalar or vector return type");
7939 return parseLandingPad(Inst, PFS);
7941 return parseFreeze(Inst, PFS);
7953 return parseAlloc(Inst, PFS);
7955 return parseLoad(Inst, PFS);
7957 return parseStore(Inst, PFS);
7959 return parseCmpXchg(Inst, PFS);
7961 return parseAtomicRMW(Inst, PFS);
7963 return parseFence(Inst, PFS);
7965 return parseGetElementPtr(Inst, PFS);
7967 return parseExtractValue(Inst, PFS);
7969 return parseInsertValue(Inst, PFS);
7974bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7975 if (
Opc == Instruction::FCmp) {
7976 switch (Lex.getKind()) {
7978 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7997 switch (Lex.getKind()) {
7999 return tokError(
"expected icmp predicate (e.g. 'eq')");
8023bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8024 PerFunctionState &PFS) {
8025 SMLoc TypeLoc = Lex.getLoc();
8027 if (parseType(Ty,
true ))
8030 Type *ResType = PFS.getFunction().getReturnType();
8034 return error(TypeLoc,
"value doesn't match function result type '" +
8042 if (parseValue(Ty, RV, PFS))
8046 return error(TypeLoc,
"value doesn't match function result type '" +
8056bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8060 if (parseTypeAndValue(Op0, Loc, PFS))
8069 return error(Loc,
"branch condition must have 'i1' type");
8071 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
8072 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8073 parseToken(
lltok::comma,
"expected ',' after true destination") ||
8074 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8086bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8087 LocTy CondLoc, BBLoc;
8090 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
8091 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
8092 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8096 if (!
Cond->getType()->isIntegerTy())
8097 return error(CondLoc,
"switch condition must have integer type");
8100 SmallPtrSet<Value*, 32> SeenCases;
8106 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8107 parseToken(
lltok::comma,
"expected ',' after case value") ||
8108 parseTypeAndBasicBlock(DestBB, PFS))
8111 if (!SeenCases.
insert(Constant).second)
8112 return error(CondLoc,
"duplicate case value in switch");
8114 return error(CondLoc,
"case value is not a constant integer");
8122 for (
const auto &[OnVal, Dest] :
Table)
8123 SI->addCase(OnVal, Dest);
8131bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8134 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8135 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8139 if (!
Address->getType()->isPointerTy())
8140 return error(AddrLoc,
"indirectbr address must have pointer type");
8143 SmallVector<BasicBlock*, 16> DestList;
8147 if (parseTypeAndBasicBlock(DestBB, PFS))
8152 if (parseTypeAndBasicBlock(DestBB, PFS))
8158 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8162 for (BasicBlock *Dest : DestList)
8172 FunctionType *&FuncTy) {
8178 for (
const ParamInfo &Arg : ArgList)
8192bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8193 LocTy CallLoc = Lex.getLoc();
8194 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8195 std::vector<unsigned> FwdRefAttrGrps;
8198 unsigned InvokeAddrSpace;
8199 Type *RetType =
nullptr;
8206 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8207 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8208 parseType(RetType, RetTypeLoc,
true ) ||
8209 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8210 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8212 parseOptionalOperandBundles(BundleList, PFS) ||
8214 parseTypeAndBasicBlock(NormalBB, PFS) ||
8216 parseTypeAndBasicBlock(UnwindBB, PFS))
8223 if (resolveFunctionType(RetType, ArgList, Ty))
8224 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8230 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8235 SmallVector<Value *, 8>
Args;
8242 for (
const ParamInfo &Arg : ArgList) {
8243 Type *ExpectedTy =
nullptr;
8246 }
else if (!Ty->isVarArg()) {
8247 return error(Arg.Loc,
"too many arguments specified");
8250 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8251 return error(Arg.Loc,
"argument is not of expected type '" +
8253 Args.push_back(Arg.V);
8258 return error(CallLoc,
"not enough parameters specified for call");
8267 II->setCallingConv(CC);
8268 II->setAttributes(PAL);
8269 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8276bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8278 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8286bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8287 PerFunctionState &PFS) {
8288 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8293 if (!
Args.empty() &&
8294 parseToken(
lltok::comma,
"expected ',' in argument list"))
8299 Type *ArgTy =
nullptr;
8300 if (parseType(ArgTy, ArgLoc))
8305 if (parseMetadataAsValue(V, PFS))
8308 if (parseValue(ArgTy, V, PFS))
8320bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8321 Value *CleanupPad =
nullptr;
8323 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8338 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8349bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8350 Value *CatchPad =
nullptr;
8352 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8359 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8360 parseTypeAndBasicBlock(BB, PFS))
8369bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8377 return tokError(
"expected scope value for catchswitch");
8382 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8388 if (parseTypeAndBasicBlock(DestBB, PFS))
8390 Table.push_back(DestBB);
8393 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8396 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8404 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8410 for (BasicBlock *DestBB :
Table)
8411 CatchSwitch->addHandler(DestBB);
8418bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8419 Value *CatchSwitch =
nullptr;
8425 return tokError(
"expected scope value for catchpad");
8430 SmallVector<Value *, 8>
Args;
8431 if (parseExceptionArgs(Args, PFS))
8440bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8441 Value *ParentPad =
nullptr;
8448 return tokError(
"expected scope value for cleanuppad");
8453 SmallVector<Value *, 8>
Args;
8454 if (parseExceptionArgs(Args, PFS))
8470bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8471 unsigned Opc,
bool IsFP) {
8473 if (parseTypeAndValue(
LHS, Loc, PFS))
8480 return error(Loc,
"invalid operand type for instruction");
8490bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8491 LocTy CallLoc = Lex.getLoc();
8492 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8493 std::vector<unsigned> FwdRefAttrGrps;
8496 Type *RetType =
nullptr;
8503 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8504 parseType(RetType, RetTypeLoc,
true ) ||
8505 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8506 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8508 parseOptionalOperandBundles(BundleList, PFS) ||
8510 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8515 SmallVector<BasicBlock *, 16> IndirectDests;
8519 if (parseTypeAndBasicBlock(DestBB, PFS))
8524 if (parseTypeAndBasicBlock(DestBB, PFS))
8530 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8537 if (resolveFunctionType(RetType, ArgList, Ty))
8538 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8549 SmallVector<Value *, 8>
Args;
8556 for (
const ParamInfo &Arg : ArgList) {
8557 Type *ExpectedTy =
nullptr;
8560 }
else if (!Ty->isVarArg()) {
8561 return error(Arg.Loc,
"too many arguments specified");
8564 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8565 return error(Arg.Loc,
"argument is not of expected type '" +
8567 Args.push_back(Arg.V);
8572 return error(CallLoc,
"not enough parameters specified for call");
8584 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8598bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8599 unsigned Opc,
bool IsFP) {
8601 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8602 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8610 return error(Loc,
"invalid operand type for instruction");
8618bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8621 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8622 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8628 "instruction requires integer or integer vector operands");
8637bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8643 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8644 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8648 if (
Opc == Instruction::FCmp) {
8650 return error(Loc,
"fcmp requires floating point operands");
8653 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8656 return error(Loc,
"icmp requires integer operands");
8668bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8672 Type *DestTy =
nullptr;
8673 if (parseTypeAndValue(
Op, Loc, PFS) ||
8674 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8679 return error(Loc,
"invalid cast opcode for cast from '" +
8688bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8690 Value *Op0, *Op1, *Op2;
8691 if (parseTypeAndValue(Op0, Loc, PFS) ||
8692 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8693 parseTypeAndValue(Op1, PFS) ||
8694 parseToken(
lltok::comma,
"expected ',' after select value") ||
8695 parseTypeAndValue(Op2, PFS))
8699 return error(Loc, Reason);
8707bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8709 Type *EltTy =
nullptr;
8711 if (parseTypeAndValue(
Op, PFS) ||
8712 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8713 parseType(EltTy, TypeLoc))
8717 return error(TypeLoc,
"va_arg requires operand with first class type");
8719 Inst =
new VAArgInst(
Op, EltTy);
8725bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8728 if (parseTypeAndValue(Op0, Loc, PFS) ||
8729 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8730 parseTypeAndValue(Op1, PFS))
8734 return error(Loc,
"invalid extractelement operands");
8742bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8744 Value *Op0, *Op1, *Op2;
8745 if (parseTypeAndValue(Op0, Loc, PFS) ||
8746 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8747 parseTypeAndValue(Op1, PFS) ||
8748 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8749 parseTypeAndValue(Op2, PFS))
8753 return error(Loc,
"invalid insertelement operands");
8761bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8763 Value *Op0, *Op1, *Op2;
8764 if (parseTypeAndValue(Op0, Loc, PFS) ||
8765 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8766 parseTypeAndValue(Op1, PFS) ||
8767 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8768 parseTypeAndValue(Op2, PFS))
8772 return error(Loc,
"invalid shufflevector operands");
8774 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8780int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8784 if (parseType(Ty, TypeLoc))
8788 return error(TypeLoc,
"phi node must have first class type");
8791 bool AteExtraComma =
false;
8803 AteExtraComma =
true;
8807 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8808 parseValue(Ty, Op0, PFS) ||
8809 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8818 for (
const auto &[Val, BB] : PHIVals)
8821 return AteExtraComma ? InstExtraComma : InstNormal;
8830bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8833 if (parseType(Ty, TyLoc))
8846 return tokError(
"expected 'catch' or 'filter' clause type");
8850 if (parseTypeAndValue(V, VLoc, PFS))
8857 return error(VLoc,
"'catch' clause has an invalid type");
8860 return error(VLoc,
"'filter' clause has an invalid type");
8865 return error(VLoc,
"clause argument must be a constant");
8869 Inst = LP.release();
8875bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8878 if (parseTypeAndValue(
Op, Loc, PFS))
8881 Inst =
new FreezeInst(
Op);
8894bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8896 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8897 std::vector<unsigned> FwdRefAttrGrps;
8899 unsigned CallAddrSpace;
8901 Type *RetType =
nullptr;
8906 LocTy CallLoc = Lex.getLoc();
8910 "expected 'tail call', 'musttail call', or 'notail call'"))
8913 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8915 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8916 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8917 parseType(RetType, RetTypeLoc,
true ) ||
8918 parseValID(CalleeID, &PFS) ||
8920 PFS.getFunction().isVarArg()) ||
8921 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8922 parseOptionalOperandBundles(BundleList, PFS))
8929 if (resolveFunctionType(RetType, ArgList, Ty))
8930 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8936 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8943 SmallVector<Value*, 8>
Args;
8949 for (
const ParamInfo &Arg : ArgList) {
8950 Type *ExpectedTy =
nullptr;
8953 }
else if (!Ty->isVarArg()) {
8954 return error(Arg.Loc,
"too many arguments specified");
8957 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8958 return error(Arg.Loc,
"argument is not of expected type '" +
8960 Args.push_back(Arg.V);
8961 Attrs.push_back(Arg.Attrs);
8965 return error(CallLoc,
"not enough parameters specified for call");
8978 return error(CallLoc,
"fast-math-flags specified for call without "
8979 "floating-point scalar or vector return type");
8986 if (SeenNewDbgInfoFormat) {
8988 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8989 "using non-intrinsic debug info");
8991 SeenOldDbgInfoFormat =
true;
8994 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9006int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9008 LocTy SizeLoc, TyLoc, ASLoc;
9010 unsigned AddrSpace = 0;
9013 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9014 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9016 if (parseType(Ty, TyLoc))
9020 return error(TyLoc,
"invalid type for alloca");
9022 bool AteExtraComma =
false;
9024 if (Lex.getKind() == lltok::kw_align) {
9025 if (parseOptionalAlignment(Alignment))
9027 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9030 ASLoc = Lex.getLoc();
9031 if (parseOptionalAddrSpace(AddrSpace))
9034 AteExtraComma =
true;
9036 if (parseTypeAndValue(
Size, SizeLoc, PFS))
9039 if (Lex.getKind() == lltok::kw_align) {
9040 if (parseOptionalAlignment(Alignment))
9042 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9045 ASLoc = Lex.getLoc();
9046 if (parseOptionalAddrSpace(AddrSpace))
9049 AteExtraComma =
true;
9055 if (
Size && !
Size->getType()->isIntegerTy())
9056 return error(SizeLoc,
"element count must have integer type");
9058 if (!Alignment && !Ty->
isSized())
9059 return error(TyLoc,
"Cannot allocate unsized type");
9061 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9062 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
9066 return AteExtraComma ? InstExtraComma : InstNormal;
9073int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9076 bool AteExtraComma =
false;
9086 bool isVolatile =
false;
9092 bool IsElementwise =
false;
9094 IsElementwise =
true;
9099 LocTy ExplicitTypeLoc = Lex.getLoc();
9100 if (parseType(Ty) ||
9101 parseToken(
lltok::comma,
"expected comma after load's type") ||
9102 parseTypeAndValue(Val, Loc, PFS) ||
9103 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9104 parseOptionalCommaAlign(Alignment, AteExtraComma))
9108 return error(Loc,
"load operand must be a pointer to a first class type");
9110 if (IsElementwise && !isAtomic)
9111 return error(Loc,
"elementwise load must be atomic");
9114 return error(ExplicitTypeLoc,
9115 "atomic elementwise load operand must have fixed vector type");
9117 if (isAtomic && !Alignment)
9118 return error(Loc,
"atomic load must have explicit non-zero alignment");
9122 return error(Loc,
"atomic load cannot use Release ordering");
9125 "atomic elementwise load cannot be sequentially consistent");
9127 if (!Alignment && !Ty->
isSized())
9128 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9130 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9131 Inst =
new LoadInst(Ty, Val,
"",
9133 SSID, IsElementwise},
9135 return AteExtraComma ? InstExtraComma : InstNormal;
9143int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9147 bool AteExtraComma =
false;
9157 bool isVolatile =
false;
9163 bool IsElementwise =
false;
9165 IsElementwise =
true;
9169 if (parseTypeAndValue(Val, Loc, PFS) ||
9170 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9171 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9172 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9173 parseOptionalCommaAlign(Alignment, AteExtraComma))
9177 return error(PtrLoc,
"store operand must be a pointer");
9179 return error(Loc,
"store operand must be a first class value");
9180 if (isAtomic && !Alignment)
9181 return error(Loc,
"atomic store must have explicit non-zero alignment");
9184 return error(Loc,
"atomic store cannot use Acquire ordering");
9186 if (IsElementwise && !isAtomic)
9187 return error(Loc,
"elementwise store must be atomic");
9191 Loc,
"atomic elementwise store operand must have fixed vector type");
9195 "atomic elementwise store cannot be sequentially consistent");
9198 return error(Loc,
"storing unsized types is not allowed");
9202 Inst =
new StoreInst(Val, Ptr,
9204 SSID, IsElementwise},
9206 return AteExtraComma ? InstExtraComma : InstNormal;
9213int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9215 bool AteExtraComma =
false;
9219 bool isVolatile =
false;
9220 bool isWeak =
false;
9229 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9230 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9231 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9232 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9233 parseTypeAndValue(New, NewLoc, PFS) ||
9234 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9235 parseOrdering(FailureOrdering) ||
9236 parseOptionalCommaAlign(Alignment, AteExtraComma))
9240 return tokError(
"invalid cmpxchg success ordering");
9242 return tokError(
"invalid cmpxchg failure ordering");
9244 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9245 if (
Cmp->getType() !=
New->getType())
9246 return error(NewLoc,
"compare value and new value type do not match");
9247 if (!
New->getType()->isFirstClassType())
9248 return error(NewLoc,
"cmpxchg operand must be a first class value");
9250 const Align DefaultAlignment(
9251 PFS.getFunction().getDataLayout().getTypeStoreSize(
9254 AtomicCmpXchgInst *CXI =
9255 new AtomicCmpXchgInst(Ptr, Cmp, New,
Alignment.value_or(DefaultAlignment),
9256 SuccessOrdering, FailureOrdering, SSID);
9261 return AteExtraComma ? InstExtraComma : InstNormal;
9268int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9270 bool AteExtraComma =
false;
9274 bool IsElementwise =
false;
9282 IsElementwise =
true;
9284 switch (Lex.getKind()) {
9286 return tokError(
"expected binary operation in atomicrmw");
9345 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9346 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9347 parseTypeAndValue(Val, ValLoc, PFS) ||
9348 parseScopeAndOrdering(
true , SSID, Ordering) ||
9349 parseOptionalCommaAlign(Alignment, AteExtraComma))
9353 return tokError(
"atomicrmw cannot be unordered");
9355 return tokError(
"atomicrmw elementwise cannot be sequentially consistent");
9357 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9359 return error(ValLoc,
"atomicrmw operand may not be scalable");
9362 if (IsElementwise) {
9364 return error(ValLoc,
9365 "atomicrmw elementwise operand must be a fixed vector type");
9374 " operand must be an integer type, a floating-point type, a "
9375 "pointer type, or a fixed vector of any of these types");
9379 return error(ValLoc,
"atomicrmw " +
9381 " operand must be a floating point or fixed "
9382 "vector of floating point type");
9389 " operand must be an integer or fixed vector of integer type");
9394 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9396 return error(ValLoc,
9397 "atomicrmw operand must have a power-of-two byte size");
9398 const Align DefaultAlignment(
9399 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9400 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9402 Ordering, SSID, IsElementwise);
9405 return AteExtraComma ? InstExtraComma : InstNormal;
9410int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9413 if (parseScopeAndOrdering(
true , SSID, Ordering))
9417 return tokError(
"fence cannot be unordered");
9419 return tokError(
"fence cannot be monotonic");
9421 Inst =
new FenceInst(Context, Ordering, SSID);
9427int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9428 Value *Ptr =
nullptr;
9429 Value *Val =
nullptr;
9445 if (parseType(Ty) ||
9446 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9447 parseTypeAndValue(Ptr, Loc, PFS))
9452 if (!BasePointerType)
9453 return error(Loc,
"base of getelementptr must be a pointer");
9455 SmallVector<Value*, 16> Indices;
9456 bool AteExtraComma =
false;
9459 ElementCount GEPWidth =
BaseType->isVectorTy()
9465 AteExtraComma =
true;
9468 if (parseTypeAndValue(Val, EltLoc, PFS))
9471 return error(EltLoc,
"getelementptr index must be an integer");
9474 ElementCount ValNumEl = ValVTy->getElementCount();
9478 "getelementptr vector index has a wrong number of elements");
9479 GEPWidth = ValNumEl;
9485 return error(Loc,
"base element of getelementptr must be sized");
9489 return error(Loc,
"getelementptr cannot target structure that contains "
9490 "scalable vector type");
9493 return error(Loc,
"invalid getelementptr indices");
9496 GEP->setNoWrapFlags(NW);
9497 return AteExtraComma ? InstExtraComma : InstNormal;
9502int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9504 SmallVector<unsigned, 4> Indices;
9506 if (parseTypeAndValue(Val, Loc, PFS) ||
9507 parseIndexList(Indices, AteExtraComma))
9511 return error(Loc,
"extractvalue operand must be aggregate type");
9514 return error(Loc,
"invalid indices for extractvalue");
9516 return AteExtraComma ? InstExtraComma : InstNormal;
9521int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9523 SmallVector<unsigned, 4> Indices;
9525 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9526 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9527 parseTypeAndValue(Val1, Loc1, PFS) ||
9528 parseIndexList(Indices, AteExtraComma))
9532 return error(Loc0,
"insertvalue operand must be aggregate type");
9536 return error(Loc0,
"invalid indices for insertvalue");
9537 if (IndexedType != Val1->
getType())
9538 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9542 return AteExtraComma ? InstExtraComma : InstNormal;
9553bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9568 if (parseMetadata(MD,
nullptr))
9573 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9579bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9581 if (!
V->hasUseList())
9584 return error(Loc,
"value has no uses");
9586 unsigned NumUses = 0;
9587 SmallDenseMap<const Use *, unsigned, 16> Order;
9588 for (
const Use &U :
V->uses()) {
9589 if (++NumUses > Indexes.
size())
9591 Order[&
U] = Indexes[NumUses - 1];
9594 return error(Loc,
"value only has one use");
9595 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9597 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9599 V->sortUseList([&](
const Use &L,
const Use &R) {
9607bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9608 SMLoc Loc = Lex.getLoc();
9612 return tokError(
"expected non-empty list of uselistorder indexes");
9619 bool IsOrdered =
true;
9620 assert(Indexes.
empty() &&
"Expected empty order vector");
9623 if (parseUInt32(Index))
9628 Max = std::max(Max, Index);
9629 IsOrdered &= Index == Indexes.
size();
9637 if (Indexes.
size() < 2)
9638 return error(Loc,
"expected >= 2 uselistorder indexes");
9641 "expected distinct uselistorder indexes in range [0, size)");
9643 return error(Loc,
"expected uselistorder indexes to change the order");
9650bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9651 SMLoc Loc = Lex.getLoc();
9656 SmallVector<unsigned, 16> Indexes;
9657 if (parseTypeAndValue(V, PFS) ||
9658 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9659 parseUseListOrderIndexes(Indexes))
9662 return sortUseListOrder(V, Indexes, Loc);
9668bool LLParser::parseModuleEntry(
unsigned ID) {
9677 parseStringConstant(Path) ||
9685 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9686 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9687 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9688 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9689 parseUInt32(Hash[4]))
9696 auto ModuleEntry = Index->addModule(Path, Hash);
9697 ModuleIdMap[
ID] = ModuleEntry->first();
9704bool LLParser::parseTypeIdEntry(
unsigned ID) {
9713 parseStringConstant(Name))
9716 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9718 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9723 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9724 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9725 for (
auto TIDRef : FwdRefTIDs->second) {
9727 "Forward referenced type id GUID expected to be 0");
9730 ForwardRefTypeIds.erase(FwdRefTIDs);
9738bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9742 parseTypeTestResolution(TIS.
TTRes))
9747 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9764bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9773 parseStringConstant(Name))
9777 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9784 IdToIndexMapType IdToIndexMap;
9797 if (parseGVReference(VI, GVId))
9804 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9805 TI.push_back({
Offset, VI});
9813 for (
auto I : IdToIndexMap) {
9814 auto &Infos = ForwardRefValueInfos[
I.first];
9815 for (
auto P :
I.second) {
9817 "Forward referenced ValueInfo expected to be empty");
9818 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9828 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9829 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9830 for (
auto TIDRef : FwdRefTIDs->second) {
9832 "Forward referenced type id GUID expected to be 0");
9835 ForwardRefTypeIds.erase(FwdRefTIDs);
9847bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9855 switch (Lex.getKind()) {
9875 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9887 switch (Lex.getKind()) {
9902 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9915 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9928bool LLParser::parseOptionalWpdResolutions(
9929 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9937 WholeProgramDevirtResolution WPDRes;
9941 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9944 WPDResMap[
Offset] = WPDRes;
9961bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9969 switch (Lex.getKind()) {
9980 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9986 switch (Lex.getKind()) {
9994 if (parseOptionalResByArg(WPDRes.
ResByArg))
9998 return error(Lex.getLoc(),
9999 "expected optional WholeProgramDevirtResolution field");
10016bool LLParser::parseOptionalResByArg(
10017 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10025 std::vector<uint64_t>
Args;
10026 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
10034 WholeProgramDevirtResolution::ByArg ByArg;
10035 switch (Lex.getKind()) {
10049 return error(Lex.getLoc(),
10050 "unexpected WholeProgramDevirtResolution::ByArg kind");
10056 switch (Lex.getKind()) {
10060 parseUInt64(ByArg.
Info))
10066 parseUInt32(ByArg.
Byte))
10072 parseUInt32(ByArg.
Bit))
10076 return error(Lex.getLoc(),
10077 "expected optional whole program devirt field");
10084 ResByArg[
Args] = ByArg;
10095bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10103 if (parseUInt64(Val))
10105 Args.push_back(Val);
10129bool LLParser::addGlobalValueToIndex(
10131 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10136 VI = Index->getOrInsertValueInfo(GUID);
10140 auto *GV = M->getNamedValue(Name);
10142 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10148 VI = Index->getOrInsertValueInfo(GV, GUID);
10152 "Need a source_filename to compute GUID for local");
10155 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10160 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10161 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10162 for (
auto VIRef : FwdRefVIs->second) {
10164 "Forward referenced ValueInfo expected to be empty");
10167 ForwardRefValueInfos.erase(FwdRefVIs);
10171 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10172 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10173 for (
auto AliaseeRef : FwdRefAliasees->second) {
10174 assert(!AliaseeRef.first->hasAliasee() &&
10175 "Forward referencing alias already has aliasee");
10176 assert(Summary &&
"Aliasee must be a definition");
10177 AliaseeRef.first->setAliasee(VI,
Summary.get());
10179 ForwardRefAliasees.erase(FwdRefAliasees);
10184 Index->addGlobalValueSummary(VI, std::move(Summary));
10187 if (ID == NumberedValueInfos.size())
10188 NumberedValueInfos.push_back(VI);
10191 if (ID > NumberedValueInfos.size())
10192 NumberedValueInfos.resize(ID + 1);
10193 NumberedValueInfos[
ID] =
VI;
10201bool LLParser::parseSummaryIndexFlags() {
10208 if (parseUInt64(Flags))
10211 Index->setFlags(Flags);
10217bool LLParser::parseBlockCount() {
10224 if (parseUInt64(BlockCount))
10227 Index->setBlockCount(BlockCount);
10235bool LLParser::parseGVEntry(
unsigned ID) {
10243 LocTy Loc = Lex.getLoc();
10246 switch (Lex.getKind()) {
10250 parseStringConstant(Name))
10256 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10260 return error(Lex.getLoc(),
"expected name or guid tag");
10283 switch (Lex.getKind()) {
10285 if (parseFunctionSummary(Name, GUID, ID))
10289 if (parseVariableSummary(Name, GUID, ID))
10293 if (parseAliasSummary(Name, GUID, ID))
10297 return error(Lex.getLoc(),
"expected summary type");
10315 LocTy Loc = Lex.getLoc();
10319 StringRef ModulePath;
10320 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10323 false,
false,
false,
10325 unsigned InstCount;
10327 FunctionSummary::TypeIdInfo TypeIdInfo;
10328 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10330 std::vector<CallsiteInfo> Callsites;
10331 std::vector<AllocInfo> Allocs;
10333 FunctionSummary::FFlags FFlags = {};
10336 parseModuleReference(ModulePath) ||
10337 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10340 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10345 switch (Lex.getKind()) {
10347 if (parseOptionalFFlags(FFlags))
10351 if (parseOptionalCalls(Calls))
10355 if (parseOptionalTypeIdInfo(TypeIdInfo))
10359 if (parseOptionalRefs(Refs))
10363 if (parseOptionalParamAccesses(ParamAccesses))
10367 if (parseOptionalAllocs(Allocs))
10371 if (parseOptionalCallsites(Callsites))
10375 return error(Lex.getLoc(),
"expected optional function summary field");
10382 auto FS = std::make_unique<FunctionSummary>(
10383 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10389 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10391 FS->setModulePath(ModulePath);
10393 return addGlobalValueToIndex(Name, GUID,
10395 std::move(FS), Loc);
10403 LocTy Loc = Lex.getLoc();
10407 StringRef ModulePath;
10408 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10411 false,
false,
false,
10413 GlobalVarSummary::GVarFlags GVarFlags(
false,
10421 parseModuleReference(ModulePath) ||
10422 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10424 parseGVarFlags(GVarFlags))
10429 switch (Lex.getKind()) {
10431 if (parseOptionalVTableFuncs(VTableFuncs))
10435 if (parseOptionalRefs(Refs))
10439 return error(Lex.getLoc(),
"expected optional variable summary field");
10447 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10449 GS->setModulePath(ModulePath);
10450 GS->setVTableFuncs(std::move(VTableFuncs));
10452 return addGlobalValueToIndex(Name, GUID,
10454 std::move(GS), Loc);
10463 LocTy Loc = Lex.getLoc();
10466 StringRef ModulePath;
10467 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10470 false,
false,
false,
10474 parseModuleReference(ModulePath) ||
10475 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10481 ValueInfo AliaseeVI;
10483 auto AS = std::make_unique<AliasSummary>(GVFlags);
10484 AS->setModulePath(ModulePath);
10487 if (parseGVReference(AliaseeVI, GVId))
10492 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10494 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10495 assert(Summary &&
"Aliasee must be a definition");
10496 AS->setAliasee(AliaseeVI, Summary);
10503 return addGlobalValueToIndex(Name, GUID,
10505 std::move(AS), Loc);
10510bool LLParser::parseFlag(
unsigned &Val) {
10511 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10512 return tokError(
"expected integer");
10513 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10529bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10533 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10539 switch (Lex.getKind()) {
10542 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10548 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10554 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10560 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10566 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10572 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10578 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10584 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10590 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10596 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10601 return error(Lex.getLoc(),
"expected function flag type");
10605 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10616bool LLParser::parseOptionalCalls(
10617 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10621 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10625 IdToIndexMapType IdToIndexMap;
10634 LocTy Loc = Lex.getLoc();
10636 if (parseGVReference(VI, GVId))
10640 unsigned RelBF = 0;
10641 unsigned HasTailCall =
false;
10645 switch (Lex.getKind()) {
10648 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10654 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10659 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10663 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10670 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10680 for (
auto I : IdToIndexMap) {
10681 auto &Infos = ForwardRefValueInfos[
I.first];
10682 for (
auto P :
I.second) {
10684 "Forward referenced ValueInfo expected to be empty");
10685 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10698 switch (Lex.getKind()) {
10702 case lltok::kw_cold:
10708 case lltok::kw_hot:
10715 return error(Lex.getLoc(),
"invalid call edge hotness");
10724bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10728 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10732 IdToIndexMapType IdToIndexMap;
10736 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10741 LocTy Loc = Lex.getLoc();
10743 if (parseGVReference(VI, GVId))
10756 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10757 VTableFuncs.push_back({
VI,
Offset});
10759 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10765 for (
auto I : IdToIndexMap) {
10766 auto &Infos = ForwardRefValueInfos[
I.first];
10767 for (
auto P :
I.second) {
10769 "Forward referenced ValueInfo expected to be empty");
10770 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10774 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10781bool LLParser::parseParamNo(
uint64_t &ParamNo) {
10783 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10789bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10792 auto ParseAPSInt = [&](
APSInt &Val) {
10794 return tokError(
"expected integer");
10795 Val = Lex.getAPSIntVal();
10797 Val.setIsSigned(
true);
10819bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10820 IdLocListType &IdLocList) {
10828 LocTy Loc = Lex.getLoc();
10829 if (parseGVReference(VI, GVId))
10833 IdLocList.emplace_back(GVId, Loc);
10836 parseParamNo(
Call.ParamNo) ||
10838 parseParamAccessOffset(
Call.Offsets))
10850bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10851 IdLocListType &IdLocList) {
10853 parseParamNo(
Param.ParamNo) ||
10855 parseParamAccessOffset(
Param.Use))
10864 FunctionSummary::ParamAccess::Call
Call;
10865 if (parseParamAccessCall(
Call, IdLocList))
10882bool LLParser::parseOptionalParamAccesses(
10883 std::vector<FunctionSummary::ParamAccess> &Params) {
10891 IdLocListType VContexts;
10892 size_t CallsNum = 0;
10894 FunctionSummary::ParamAccess ParamAccess;
10895 if (parseParamAccess(ParamAccess, VContexts))
10897 CallsNum += ParamAccess.
Calls.size();
10898 assert(VContexts.size() == CallsNum);
10900 Params.emplace_back(std::move(ParamAccess));
10908 IdLocListType::const_iterator ItContext = VContexts.begin();
10909 for (
auto &PA : Params) {
10910 for (
auto &
C : PA.Calls) {
10912 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10913 ItContext->second);
10917 assert(ItContext == VContexts.end());
10924bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10928 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10932 struct ValueContext {
10937 std::vector<ValueContext> VContexts;
10941 VC.Loc = Lex.getLoc();
10942 if (parseGVReference(
VC.VI,
VC.GVId))
10944 VContexts.push_back(VC);
10950 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10951 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10954 IdToIndexMapType IdToIndexMap;
10955 for (
auto &VC : VContexts) {
10960 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10966 for (
auto I : IdToIndexMap) {
10967 auto &Infos = ForwardRefValueInfos[
I.first];
10968 for (
auto P :
I.second) {
10970 "Forward referenced ValueInfo expected to be empty");
10971 Infos.emplace_back(&Refs[
P.first],
P.second);
10985bool LLParser::parseOptionalTypeIdInfo(
10986 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10995 switch (Lex.getKind()) {
10997 if (parseTypeTests(TypeIdInfo.
TypeTests))
11021 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
11025 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11034bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11042 IdToIndexMapType IdToIndexMap;
11046 unsigned ID = Lex.getUIntVal();
11047 LocTy Loc = Lex.getLoc();
11051 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
11053 }
else if (parseUInt64(GUID))
11055 TypeTests.push_back(GUID);
11060 for (
auto I : IdToIndexMap) {
11061 auto &Ids = ForwardRefTypeIds[
I.first];
11062 for (
auto P :
I.second) {
11063 assert(TypeTests[
P.first] == 0 &&
11064 "Forward referenced type id GUID expected to be 0");
11065 Ids.emplace_back(&TypeTests[
P.first],
P.second);
11069 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11077bool LLParser::parseVFuncIdList(
11078 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11079 assert(Lex.getKind() == Kind);
11086 IdToIndexMapType IdToIndexMap;
11088 FunctionSummary::VFuncId VFuncId;
11089 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11091 VFuncIdList.push_back(VFuncId);
11099 for (
auto I : IdToIndexMap) {
11100 auto &Ids = ForwardRefTypeIds[
I.first];
11101 for (
auto P :
I.second) {
11102 assert(VFuncIdList[
P.first].GUID == 0 &&
11103 "Forward referenced type id GUID expected to be 0");
11104 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
11113bool LLParser::parseConstVCallList(
11115 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11116 assert(Lex.getKind() == Kind);
11123 IdToIndexMapType IdToIndexMap;
11125 FunctionSummary::ConstVCall ConstVCall;
11126 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11128 ConstVCallList.push_back(ConstVCall);
11136 for (
auto I : IdToIndexMap) {
11137 auto &Ids = ForwardRefTypeIds[
I.first];
11138 for (
auto P :
I.second) {
11139 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11140 "Forward referenced type id GUID expected to be 0");
11141 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11150bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11151 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11153 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11157 if (parseArgs(ConstVCall.
Args))
11169bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11170 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11180 unsigned ID = Lex.getUIntVal();
11181 LocTy Loc = Lex.getLoc();
11185 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11187 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11189 parseUInt64(VFuncId.
GUID))
11195 parseUInt64(VFuncId.
Offset) ||
11207bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11217 switch (Lex.getKind()) {
11224 assert(HasLinkage &&
"Linkage not optional in summary entry");
11231 parseOptionalVisibility(Flag);
11236 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11242 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11248 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11254 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11263 if (parseOptionalImportType(Lex.getKind(), IK))
11265 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11270 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11275 return error(Lex.getLoc(),
"expected gv flag type");
11289bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11297 auto ParseRest = [
this](
unsigned int &Val) {
11301 return parseFlag(Val);
11306 switch (Lex.getKind()) {
11307 case lltok::kw_readonly:
11308 if (ParseRest(Flag))
11312 case lltok::kw_writeonly:
11313 if (ParseRest(Flag))
11318 if (ParseRest(Flag))
11323 if (ParseRest(Flag))
11328 return error(Lex.getLoc(),
"expected gvar flag type");
11336bool LLParser::parseModuleReference(StringRef &ModulePath) {
11343 unsigned ModuleID = Lex.getUIntVal();
11344 auto I = ModuleIdMap.find(ModuleID);
11346 assert(
I != ModuleIdMap.end());
11347 ModulePath =
I->second;
11353bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11356 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11360 GVId = Lex.getUIntVal();
11362 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11364 VI = NumberedValueInfos[GVId];
11381bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11385 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11397 SmallVector<uint8_t> Versions;
11400 if (parseAllocType(V))
11405 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11409 std::vector<MIBInfo> MIBs;
11410 if (parseMemProfs(MIBs))
11413 Allocs.push_back({Versions, MIBs});
11430bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11434 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11440 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11449 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11455 SmallVector<unsigned> StackIdIndices;
11460 if (parseUInt64(StackId))
11462 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11483bool LLParser::parseAllocType(uint8_t &
AllocType) {
11484 switch (Lex.getKind()) {
11491 case lltok::kw_cold:
11494 case lltok::kw_hot:
11498 return error(Lex.getLoc(),
"invalid alloc type");
11511bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11515 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11519 IdToIndexMapType IdToIndexMap;
11522 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11529 LocTy Loc = Lex.getLoc();
11531 if (parseGVReference(VI, GVId))
11535 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11541 SmallVector<unsigned> Clones;
11544 if (parseUInt32(V))
11550 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11556 SmallVector<unsigned> StackIdIndices;
11561 if (parseUInt64(StackId))
11563 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11574 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11575 Callsites.push_back({
VI, Clones, StackIdIndices});
11583 for (
auto I : IdToIndexMap) {
11584 auto &Infos = ForwardRefValueInfos[
I.first];
11585 for (
auto P :
I.second) {
11587 "Forward referenced ValueInfo expected to be empty");
11588 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11592 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")
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 InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
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)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static 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_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 Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, 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.
LLVM_ABI bool isScalableTy() const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool 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.
@ 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 isAtomic(const T &...O)
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_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.
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
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.
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)
bool capturesNothing(CaptureComponents CC)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
@ 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.