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 SmallPtrSet<Type*, 4> Visited;
4920 if (!Indices.empty() && !Ty->
isSized(&Visited))
4921 return error(
ID.Loc,
"base element of getelementptr must be sized");
4924 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4927 return error(
ID.Loc,
"invalid getelementptr indices");
4931 }
else if (
Opc == Instruction::ShuffleVector) {
4932 if (Elts.
size() != 3)
4933 return error(
ID.Loc,
"expected three operands to shufflevector");
4935 return error(
ID.Loc,
"invalid operands to shufflevector");
4936 SmallVector<int, 16>
Mask;
4939 }
else if (
Opc == Instruction::ExtractElement) {
4940 if (Elts.
size() != 2)
4941 return error(
ID.Loc,
"expected two operands to extractelement");
4943 return error(
ID.Loc,
"invalid extractelement operands");
4946 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4947 if (Elts.
size() != 3)
4948 return error(
ID.Loc,
"expected three operands to insertelement");
4950 return error(
ID.Loc,
"invalid insertelement operands");
4965bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4969 bool Parsed = parseValID(ID,
nullptr, Ty) ||
4970 convertValIDToValue(Ty, ID, V,
nullptr);
4972 return error(
ID.Loc,
"global values must be constants");
4976bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4978 return parseType(Ty) || parseGlobalValue(Ty, V);
4981bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4984 LocTy KwLoc = Lex.getLoc();
4990 return tokError(
"expected comdat variable");
4991 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4993 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4996 if (GlobalName.
empty())
4997 return tokError(
"comdat cannot be unnamed");
4998 C = getComdat(std::string(GlobalName), KwLoc);
5007bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5021 if (parseGlobalTypeAndValue(
C))
5029bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
5031 if (parseMDNodeVector(Elts))
5042bool LLParser::parseMDNode(MDNode *&
N) {
5044 return parseSpecializedMDNode(
N);
5046 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
5049bool LLParser::parseMDNodeTail(MDNode *&
N) {
5052 return parseMDTuple(
N);
5055 return parseMDNodeID(
N);
5061template <
class FieldTy>
struct MDFieldImpl {
5062 typedef MDFieldImpl ImplTy;
5066 void assign(FieldTy Val) {
5068 this->Val = std::move(Val);
5071 explicit MDFieldImpl(FieldTy
Default)
5079template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
5080 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5093 this->
A = std::move(
A);
5099 this->
B = std::move(
B);
5103 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5105 WhatIs(IsInvalid) {}
5108struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5115struct LineField :
public MDUnsignedField {
5116 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5119struct ColumnField :
public MDUnsignedField {
5120 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5123struct DwarfTagField :
public MDUnsignedField {
5129struct DwarfMacinfoTypeField :
public MDUnsignedField {
5135struct DwarfAttEncodingField :
public MDUnsignedField {
5136 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5139struct DwarfVirtualityField :
public MDUnsignedField {
5143struct DwarfLangField :
public MDUnsignedField {
5147struct DwarfSourceLangNameField :
public MDUnsignedField {
5148 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5151struct DwarfLangDialectField :
public MDUnsignedField {
5152 DwarfLangDialectField()
5156struct DwarfCCField :
public MDUnsignedField {
5157 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5160struct DwarfEnumKindField :
public MDUnsignedField {
5161 DwarfEnumKindField()
5166struct EmissionKindField :
public MDUnsignedField {
5167 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5170struct FixedPointKindField :
public MDUnsignedField {
5171 FixedPointKindField()
5172 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5175struct NameTableKindField :
public MDUnsignedField {
5176 NameTableKindField()
5179 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5182struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5183 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5186struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5187 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5190struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5191 MDAPSIntField() : ImplTy(
APSInt()) {}
5194struct MDSignedField :
public MDFieldImpl<int64_t> {
5198 MDSignedField(int64_t
Default = 0)
5200 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5204struct MDBoolField :
public MDFieldImpl<bool> {
5208struct MDField :
public MDFieldImpl<Metadata *> {
5211 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5214struct MDStringField :
public MDFieldImpl<MDString *> {
5215 enum class EmptyIs {
5220 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5221 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5224struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5228struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5232struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5233 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5234 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5236 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5237 bool AllowNull =
true)
5238 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5240 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5241 bool isMDField()
const {
return WhatIs == IsTypeB; }
5242 int64_t getMDSignedValue()
const {
5243 assert(isMDSignedField() &&
"Wrong field type");
5246 Metadata *getMDFieldValue()
const {
5247 assert(isMDField() &&
"Wrong field type");
5252struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5254 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5257 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5259 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5260 bool isMDField()
const {
return WhatIs == IsTypeB; }
5261 uint64_t getMDUnsignedValue()
const {
5262 assert(isMDUnsignedField() &&
"Wrong field type");
5265 Metadata *getMDFieldValue()
const {
5266 assert(isMDField() &&
"Wrong field type");
5271 if (isMDUnsignedField())
5273 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5275 return getMDFieldValue();
5287 return tokError(
"expected integer");
5289 Result.assign(Lex.getAPSIntVal());
5296 MDUnsignedField &Result) {
5297 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5298 return tokError(
"expected unsigned integer");
5300 auto &U = Lex.getAPSIntVal();
5301 if (U.ugt(Result.Max))
5302 return tokError(
"value for '" + Name +
"' too large, limit is " +
5304 Result.assign(U.getZExtValue());
5305 assert(Result.Val <= Result.Max &&
"Expected value in range");
5312 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5316 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5322 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5325 return tokError(
"expected DWARF tag");
5329 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5330 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5339 DwarfMacinfoTypeField &Result) {
5341 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5344 return tokError(
"expected DWARF macinfo type");
5348 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5349 Lex.getStrVal() +
"'");
5350 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5352 Result.assign(Macinfo);
5359 DwarfVirtualityField &Result) {
5361 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5364 return tokError(
"expected DWARF virtuality code");
5368 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5369 Lex.getStrVal() +
"'");
5370 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5371 Result.assign(Virtuality);
5378 DwarfEnumKindField &Result) {
5380 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5383 return tokError(
"expected DWARF enum kind code");
5387 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5388 Lex.getStrVal() +
"'");
5389 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5390 Result.assign(EnumKind);
5398 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5401 return tokError(
"expected DWARF language");
5405 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5407 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5408 Result.assign(Lang);
5415 DwarfSourceLangNameField &Result) {
5417 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5420 return tokError(
"expected DWARF source language name");
5424 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5425 Lex.getStrVal() +
"'");
5426 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5427 Result.assign(Lang);
5434 DwarfLangDialectField &Result) {
5439 if (Lex.getAPSIntVal() == 0)
5440 return tokError(
"value for 'dialect' must be a known DWARF language "
5441 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5442 "DW_LLVM_LANG_DIALECT_tile)");
5443 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5447 return tokError(
"expected DWARF language dialect");
5449 StringRef DialectString = Lex.getStrVal();
5454 if (Dialect > Result.Max)
5455 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5456 DialectString +
"'");
5457 Result.assign(Dialect);
5465 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5468 return tokError(
"expected DWARF calling convention");
5472 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5473 Lex.getStrVal() +
"'");
5474 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5482 EmissionKindField &Result) {
5484 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5487 return tokError(
"expected emission kind");
5491 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5493 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5494 Result.assign(*Kind);
5501 FixedPointKindField &Result) {
5503 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5506 return tokError(
"expected fixed-point kind");
5510 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5512 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5513 Result.assign(*Kind);
5520 NameTableKindField &Result) {
5522 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5525 return tokError(
"expected nameTable kind");
5529 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5531 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5532 Result.assign((
unsigned)*Kind);
5539 DwarfAttEncodingField &Result) {
5541 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5544 return tokError(
"expected DWARF type attribute encoding");
5548 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5549 Lex.getStrVal() +
"'");
5550 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5551 Result.assign(Encoding);
5565 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5567 bool Res = parseUInt32(TempVal);
5573 return tokError(
"expected debug info flag");
5577 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5592 Result.assign(Combined);
5605 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5607 bool Res = parseUInt32(TempVal);
5613 return tokError(
"expected debug info flag");
5617 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5618 Lex.getStrVal() +
"'");
5632 Result.assign(Combined);
5639 return tokError(
"expected signed integer");
5641 auto &S = Lex.getAPSIntVal();
5643 return tokError(
"value for '" + Name +
"' too small, limit is " +
5646 return tokError(
"value for '" + Name +
"' too large, limit is " +
5648 Result.assign(S.getExtValue());
5649 assert(Result.Val >= Result.Min &&
"Expected value in range");
5650 assert(Result.Val <= Result.Max &&
"Expected value in range");
5657 switch (Lex.getKind()) {
5659 return tokError(
"expected 'true' or 'false'");
5661 Result.assign(
true);
5664 Result.assign(
false);
5674 if (!Result.AllowNull)
5675 return tokError(
"'" + Name +
"' cannot be null");
5677 Result.assign(
nullptr);
5682 if (parseMetadata(MD,
nullptr))
5691 MDSignedOrMDField &Result) {
5694 MDSignedField Res = Result.A;
5695 if (!parseMDField(
Loc, Name, Res)) {
5703 MDField Res = Result.B;
5704 if (!parseMDField(
Loc, Name, Res)) {
5714 MDUnsignedOrMDField &Result) {
5717 MDUnsignedField Res = Result.A;
5718 if (!parseMDField(
Loc, Name, Res)) {
5726 MDField Res = Result.B;
5727 if (!parseMDField(
Loc, Name, Res)) {
5737 LocTy ValueLoc = Lex.getLoc();
5739 if (parseStringConstant(S))
5743 switch (Result.EmptyIs) {
5744 case MDStringField::EmptyIs::Null:
5745 Result.assign(
nullptr);
5747 case MDStringField::EmptyIs::Empty:
5749 case MDStringField::EmptyIs::Error:
5750 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5761 if (parseMDNodeVector(MDs))
5764 Result.assign(std::move(MDs));
5770 ChecksumKindField &Result) {
5771 std::optional<DIFile::ChecksumKind> CSKind =
5775 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5778 Result.assign(*CSKind);
5785template <
class ParserTy>
5786bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5789 return tokError(
"expected field label here");
5798template <
class ParserTy>
5799bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5806 if (parseMDFieldsImplBody(ParseField))
5809 ClosingLoc = Lex.getLoc();
5813template <
class FieldTy>
5814bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5816 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5818 LocTy Loc = Lex.getLoc();
5820 return parseMDField(Loc, Name, Result);
5823bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5826#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5827 if (Lex.getStrVal() == #CLASS) \
5828 return parse##CLASS(N, IsDistinct);
5829#include "llvm/IR/Metadata.def"
5831 return tokError(
"expected metadata type");
5834#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5835#define NOP_FIELD(NAME, TYPE, INIT)
5836#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5838 return error(ClosingLoc, "missing required field '" #NAME "'");
5839#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5840 if (Lex.getStrVal() == #NAME) \
5841 return parseMDField(#NAME, NAME);
5842#define PARSE_MD_FIELDS() \
5843 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5846 if (parseMDFieldsImpl( \
5848 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5849 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5854 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5856#define GET_OR_DISTINCT(CLASS, ARGS) \
5857 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5862bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5863#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5864 OPTIONAL(line, LineField, ); \
5865 OPTIONAL(column, ColumnField, ); \
5866 REQUIRED(scope, MDField, ( false)); \
5867 OPTIONAL(inlinedAt, MDField, ); \
5868 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5869 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5870 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5872#undef VISIT_MD_FIELDS
5875 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5876 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5882bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5884 return tokError(
"missing 'distinct', required for !DIAssignID()");
5900bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5901#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5902 REQUIRED(tag, DwarfTagField, ); \
5903 OPTIONAL(header, MDStringField, ); \
5904 OPTIONAL(operands, MDFieldList, );
5906#undef VISIT_MD_FIELDS
5909 (Context, tag.Val, header.Val, operands.Val));
5918bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5919#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5920 OPTIONAL(name, MDStringField, ); \
5921 OPTIONAL(file, MDField, ); \
5922 OPTIONAL(line, LineField, ); \
5923 OPTIONAL(scope, MDField, ); \
5924 OPTIONAL(baseType, MDField, ); \
5925 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5926 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5927 OPTIONAL(flags, DIFlagField, ); \
5928 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5929 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5930 OPTIONAL(stride, MDSignedOrMDField, ); \
5931 OPTIONAL(bias, MDSignedOrMDField, );
5933#undef VISIT_MD_FIELDS
5935 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5936 if (Bound.isMDSignedField())
5939 if (Bound.isMDField())
5940 return Bound.getMDFieldValue();
5946 Metadata *Stride = convToMetadata(stride);
5947 Metadata *Bias = convToMetadata(bias);
5950 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5951 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5952 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5961bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5962#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5963 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5964 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5965 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5966 OPTIONAL(stride, MDSignedOrMDField, );
5968#undef VISIT_MD_FIELDS
5975 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5976 if (Bound.isMDSignedField())
5979 if (Bound.isMDField())
5980 return Bound.getMDFieldValue();
5987 Stride = convToMetadata(stride);
5990 (Context,
Count, LowerBound, UpperBound, Stride));
5998bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5999#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6000 OPTIONAL(count, MDSignedOrMDField, ); \
6001 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6002 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6003 OPTIONAL(stride, MDSignedOrMDField, );
6005#undef VISIT_MD_FIELDS
6007 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6008 if (Bound.isMDSignedField())
6010 Context, {dwarf::DW_OP_consts,
6011 static_cast<uint64_t>(Bound.getMDSignedValue())});
6012 if (Bound.isMDField())
6013 return Bound.getMDFieldValue();
6020 Metadata *Stride = ConvToMetadata(stride);
6023 (Context,
Count, LowerBound, UpperBound, Stride));
6030bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
6031#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6032 REQUIRED(name, MDStringField, ); \
6033 REQUIRED(value, MDAPSIntField, ); \
6034 OPTIONAL(isUnsigned, MDBoolField, (false));
6036#undef VISIT_MD_FIELDS
6038 if (isUnsigned.Val && value.Val.isNegative())
6039 return tokError(
"unsigned enumerator with negative value");
6044 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6056bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
6057#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6058 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6059 OPTIONAL(name, MDStringField, ); \
6060 OPTIONAL(file, MDField, ); \
6061 OPTIONAL(line, LineField, ); \
6062 OPTIONAL(scope, MDField, ); \
6063 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6064 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6065 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6066 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6067 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6068 OPTIONAL(flags, DIFlagField, );
6070#undef VISIT_MD_FIELDS
6073 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6074 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
6075 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6084bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6085#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6086 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6087 OPTIONAL(name, MDStringField, ); \
6088 OPTIONAL(file, MDField, ); \
6089 OPTIONAL(line, LineField, ); \
6090 OPTIONAL(scope, MDField, ); \
6091 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6092 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6093 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6094 OPTIONAL(flags, DIFlagField, ); \
6095 OPTIONAL(kind, FixedPointKindField, ); \
6096 OPTIONAL(factor, MDSignedField, ); \
6097 OPTIONAL(numerator, MDAPSIntField, ); \
6098 OPTIONAL(denominator, MDAPSIntField, );
6100#undef VISIT_MD_FIELDS
6103 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6104 scope.Val,
size.getValueAsMetadata(Context),
6105 align.Val, encoding.Val, flags.Val, kind.Val,
6106 factor.Val, numerator.Val, denominator.Val));
6112bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6113#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6114 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6115 OPTIONAL(name, MDStringField, ); \
6116 OPTIONAL(stringLength, MDField, ); \
6117 OPTIONAL(stringLengthExpression, MDField, ); \
6118 OPTIONAL(stringLocationExpression, MDField, ); \
6119 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6120 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6121 OPTIONAL(encoding, DwarfAttEncodingField, );
6123#undef VISIT_MD_FIELDS
6127 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6128 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6129 align.Val, encoding.Val));
6142bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6143#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6144 REQUIRED(tag, DwarfTagField, ); \
6145 OPTIONAL(name, MDStringField, ); \
6146 OPTIONAL(file, MDField, ); \
6147 OPTIONAL(line, LineField, ); \
6148 OPTIONAL(scope, MDField, ); \
6149 REQUIRED(baseType, MDField, ); \
6150 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6151 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6152 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6153 OPTIONAL(flags, DIFlagField, ); \
6154 OPTIONAL(extraData, MDField, ); \
6155 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6156 OPTIONAL(annotations, MDField, ); \
6157 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6158 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6159 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6160 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6161 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6163#undef VISIT_MD_FIELDS
6165 std::optional<unsigned> DWARFAddressSpace;
6166 if (dwarfAddressSpace.Val != UINT32_MAX)
6167 DWARFAddressSpace = dwarfAddressSpace.Val;
6168 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6170 PtrAuthData.emplace(
6171 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6172 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6173 ptrAuthAuthenticatesNullValues.Val);
6176 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6177 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6178 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6179 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6183bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6184#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6185 REQUIRED(tag, DwarfTagField, ); \
6186 OPTIONAL(name, MDStringField, ); \
6187 OPTIONAL(file, MDField, ); \
6188 OPTIONAL(line, LineField, ); \
6189 OPTIONAL(scope, MDField, ); \
6190 OPTIONAL(baseType, MDField, ); \
6191 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6192 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6193 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6194 OPTIONAL(flags, DIFlagField, ); \
6195 OPTIONAL(elements, MDField, ); \
6196 OPTIONAL(runtimeLang, DwarfLangField, ); \
6197 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6198 OPTIONAL(vtableHolder, MDField, ); \
6199 OPTIONAL(templateParams, MDField, ); \
6200 OPTIONAL(identifier, MDStringField, ); \
6201 OPTIONAL(discriminator, MDField, ); \
6202 OPTIONAL(dataLocation, MDField, ); \
6203 OPTIONAL(associated, MDField, ); \
6204 OPTIONAL(allocated, MDField, ); \
6205 OPTIONAL(rank, MDSignedOrMDField, ); \
6206 OPTIONAL(annotations, MDField, ); \
6207 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6208 OPTIONAL(specification, MDField, ); \
6209 OPTIONAL(bitStride, MDField, );
6211#undef VISIT_MD_FIELDS
6214 if (rank.isMDSignedField())
6217 else if (rank.isMDField())
6218 Rank = rank.getMDFieldValue();
6220 std::optional<unsigned> EnumKind;
6222 EnumKind = enumKind.Val;
6227 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6228 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6229 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6230 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6231 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6232 dataLocation.Val, associated.Val, allocated.Val, Rank,
6233 annotations.Val, bitStride.Val)) {
6242 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6243 size.getValueAsMetadata(Context),
align.Val,
6244 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6245 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6246 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6247 allocated.Val, Rank, annotations.Val, specification.Val,
6248 num_extra_inhabitants.Val, bitStride.Val));
6252bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6253#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6254 OPTIONAL(flags, DIFlagField, ); \
6255 OPTIONAL(cc, DwarfCCField, ); \
6256 REQUIRED(types, MDField, );
6258#undef VISIT_MD_FIELDS
6261 (Context, flags.Val, cc.Val, types.Val));
6270bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6274#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6275 REQUIRED(filename, MDStringField, ); \
6276 REQUIRED(directory, MDStringField, ); \
6277 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6278 OPTIONAL(checksum, MDStringField, ); \
6279 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6281#undef VISIT_MD_FIELDS
6283 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6284 if (checksumkind.Seen && checksum.Seen)
6285 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6286 else if (checksumkind.Seen || checksum.Seen)
6287 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6289 MDString *
Source =
nullptr;
6293 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6305bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6307 return tokError(
"missing 'distinct', required for !DICompileUnit");
6309 LocTy Loc = Lex.getLoc();
6311#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6312 REQUIRED(file, MDField, ( false)); \
6313 OPTIONAL(language, DwarfLangField, ); \
6314 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6315 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6316 OPTIONAL(producer, MDStringField, ); \
6317 OPTIONAL(isOptimized, MDBoolField, ); \
6318 OPTIONAL(flags, MDStringField, ); \
6319 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6320 OPTIONAL(splitDebugFilename, MDStringField, ); \
6321 OPTIONAL(emissionKind, EmissionKindField, ); \
6322 OPTIONAL(enums, MDField, ); \
6323 OPTIONAL(retainedTypes, MDField, ); \
6324 OPTIONAL(globals, MDField, ); \
6325 OPTIONAL(imports, MDField, ); \
6326 OPTIONAL(macros, MDField, ); \
6327 OPTIONAL(dwoId, MDUnsignedField, ); \
6328 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6329 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6330 OPTIONAL(nameTableKind, NameTableKindField, ); \
6331 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6332 OPTIONAL(sysroot, MDStringField, ); \
6333 OPTIONAL(sdk, MDStringField, ); \
6334 OPTIONAL(dialect, DwarfLangDialectField, );
6336#undef VISIT_MD_FIELDS
6338 if (!language.Seen && !sourceLanguageName.Seen)
6339 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6340 "required for !DICompileUnit");
6342 if (language.Seen && sourceLanguageName.Seen)
6343 return error(Loc,
"can only specify one of 'language' and "
6344 "'sourceLanguageName' on !DICompileUnit");
6346 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6347 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6348 "'sourceLanguageName' on !DICompileUnit");
6350 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6353 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6354 : DISourceLanguageName(
6355 static_cast<uint16_t>(sourceLanguageName.Val),
6356 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6359 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6360 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6361 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6362 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6363 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6376bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6377 auto Loc = Lex.getLoc();
6378#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6379 OPTIONAL(scope, MDField, ); \
6380 OPTIONAL(name, MDStringField, ); \
6381 OPTIONAL(linkageName, MDStringField, ); \
6382 OPTIONAL(file, MDField, ); \
6383 OPTIONAL(line, LineField, ); \
6384 REQUIRED(type, MDField, ( false)); \
6385 OPTIONAL(isLocal, MDBoolField, ); \
6386 OPTIONAL(isDefinition, MDBoolField, (true)); \
6387 OPTIONAL(scopeLine, LineField, ); \
6388 OPTIONAL(containingType, MDField, ); \
6389 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6390 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6391 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6392 OPTIONAL(flags, DIFlagField, ); \
6393 OPTIONAL(spFlags, DISPFlagField, ); \
6394 OPTIONAL(isOptimized, MDBoolField, ); \
6395 OPTIONAL(unit, MDField, ); \
6396 OPTIONAL(templateParams, MDField, ); \
6397 OPTIONAL(declaration, MDField, ); \
6398 OPTIONAL(retainedNodes, MDField, ); \
6399 OPTIONAL(thrownTypes, MDField, ); \
6400 OPTIONAL(annotations, MDField, ); \
6401 OPTIONAL(targetFuncName, MDStringField, ); \
6402 OPTIONAL(keyInstructions, MDBoolField, );
6404#undef VISIT_MD_FIELDS
6409 spFlags.Seen ? spFlags.Val
6411 isOptimized.Val, virtuality.Val);
6412 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6415 "missing 'distinct', required for !DISubprogram that is a Definition");
6418 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6419 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6420 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6421 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6422 targetFuncName.Val, keyInstructions.Val));
6432bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6433#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6434 REQUIRED(scope, MDField, ( false)); \
6435 OPTIONAL(file, MDField, ); \
6436 OPTIONAL(line, LineField, ); \
6437 OPTIONAL(column, ColumnField, );
6439#undef VISIT_MD_FIELDS
6442 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6448bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6449#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6450 REQUIRED(scope, MDField, ( false)); \
6451 OPTIONAL(file, MDField, ); \
6452 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6454#undef VISIT_MD_FIELDS
6457 (Context, scope.Val,
file.Val, discriminator.Val));
6463bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6464#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6465 REQUIRED(scope, MDField, ); \
6466 OPTIONAL(declaration, MDField, ); \
6467 OPTIONAL(name, MDStringField, ); \
6468 OPTIONAL(file, MDField, ); \
6469 OPTIONAL(line, LineField, );
6471#undef VISIT_MD_FIELDS
6474 (Context, scope.Val, declaration.Val,
name.Val,
6475 file.Val, line.Val));
6481bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6482#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6483 REQUIRED(scope, MDField, ); \
6484 OPTIONAL(name, MDStringField, ); \
6485 OPTIONAL(exportSymbols, MDBoolField, );
6487#undef VISIT_MD_FIELDS
6490 (Context, scope.Val,
name.Val, exportSymbols.Val));
6497bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6498#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6499 REQUIRED(type, DwarfMacinfoTypeField, ); \
6500 OPTIONAL(line, LineField, ); \
6501 REQUIRED(name, MDStringField, ); \
6502 OPTIONAL(value, MDStringField, );
6504#undef VISIT_MD_FIELDS
6507 (Context, type.Val, line.Val,
name.Val, value.Val));
6513bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6514#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6515 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6516 OPTIONAL(line, LineField, ); \
6517 REQUIRED(file, MDField, ); \
6518 OPTIONAL(nodes, MDField, );
6520#undef VISIT_MD_FIELDS
6523 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6531bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6532#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6533 REQUIRED(scope, MDField, ); \
6534 REQUIRED(name, MDStringField, ); \
6535 OPTIONAL(configMacros, MDStringField, ); \
6536 OPTIONAL(includePath, MDStringField, ); \
6537 OPTIONAL(apinotes, MDStringField, ); \
6538 OPTIONAL(file, MDField, ); \
6539 OPTIONAL(line, LineField, ); \
6540 OPTIONAL(isDecl, MDBoolField, );
6542#undef VISIT_MD_FIELDS
6545 configMacros.Val, includePath.Val,
6546 apinotes.Val, line.Val, isDecl.Val));
6552bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6553#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6554 OPTIONAL(name, MDStringField, ); \
6555 REQUIRED(type, MDField, ); \
6556 OPTIONAL(defaulted, MDBoolField, );
6558#undef VISIT_MD_FIELDS
6561 (Context,
name.Val, type.Val, defaulted.Val));
6569bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6570#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6571 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6572 OPTIONAL(name, MDStringField, ); \
6573 OPTIONAL(type, MDField, ); \
6574 OPTIONAL(defaulted, MDBoolField, ); \
6575 REQUIRED(value, MDField, );
6578#undef VISIT_MD_FIELDS
6581 DITemplateValueParameter,
6582 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6591bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6592#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6593 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6594 OPTIONAL(scope, MDField, ); \
6595 OPTIONAL(linkageName, MDStringField, ); \
6596 OPTIONAL(file, MDField, ); \
6597 OPTIONAL(line, LineField, ); \
6598 OPTIONAL(type, MDField, ); \
6599 OPTIONAL(isLocal, MDBoolField, ); \
6600 OPTIONAL(isDefinition, MDBoolField, (true)); \
6601 OPTIONAL(templateParams, MDField, ); \
6602 OPTIONAL(declaration, MDField, ); \
6603 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6604 OPTIONAL(annotations, MDField, );
6606#undef VISIT_MD_FIELDS
6610 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6611 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6612 declaration.Val, templateParams.Val,
align.Val,
6624bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6625#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6626 REQUIRED(scope, MDField, ( false)); \
6627 OPTIONAL(name, MDStringField, ); \
6628 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6629 OPTIONAL(file, MDField, ); \
6630 OPTIONAL(line, LineField, ); \
6631 OPTIONAL(type, MDField, ); \
6632 OPTIONAL(flags, DIFlagField, ); \
6633 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6634 OPTIONAL(annotations, MDField, );
6636#undef VISIT_MD_FIELDS
6639 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6640 type.Val, arg.Val, flags.Val,
align.Val,
6647bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6648#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6649 REQUIRED(scope, MDField, ( false)); \
6650 REQUIRED(name, MDStringField, ); \
6651 REQUIRED(file, MDField, ); \
6652 REQUIRED(line, LineField, ); \
6653 OPTIONAL(column, ColumnField, ); \
6654 OPTIONAL(isArtificial, MDBoolField, ); \
6655 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6657#undef VISIT_MD_FIELDS
6659 std::optional<unsigned> CoroSuspendIdx =
6660 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6664 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6665 column.Val, isArtificial.Val, CoroSuspendIdx));
6671bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6684 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6693 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6694 Lex.getStrVal() +
"'");
6697 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6698 return tokError(
"expected unsigned integer");
6700 auto &
U = Lex.getAPSIntVal();
6702 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6716bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6718 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6721 return parseDIExpressionBody(Result, IsDistinct);
6726bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6727 assert(PFS &&
"Expected valid function state");
6738 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6752bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6754#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6755 REQUIRED(var, MDField, ); \
6756 REQUIRED(expr, MDField, );
6758#undef VISIT_MD_FIELDS
6761 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6768bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6769#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6770 OPTIONAL(name, MDStringField, ); \
6771 OPTIONAL(file, MDField, ); \
6772 OPTIONAL(line, LineField, ); \
6773 OPTIONAL(setter, MDStringField, ); \
6774 OPTIONAL(getter, MDStringField, ); \
6775 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6776 OPTIONAL(type, MDField, );
6778#undef VISIT_MD_FIELDS
6781 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6782 setter.Val, attributes.Val, type.Val));
6789bool LLParser::parseDIProperty(
MDNode *&Result,
bool IsDistinct) {
6790#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6791 OPTIONAL(name, MDStringField, ); \
6792 OPTIONAL(file, MDField, ); \
6793 OPTIONAL(line, LineField, ); \
6794 OPTIONAL(type, MDField, ); \
6795 OPTIONAL(backing_storage, MDField, );
6797#undef VISIT_MD_FIELDS
6800 type.Val, backing_storage.Val));
6807bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6808#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6809 REQUIRED(tag, DwarfTagField, ); \
6810 REQUIRED(scope, MDField, ); \
6811 OPTIONAL(entity, MDField, ); \
6812 OPTIONAL(file, MDField, ); \
6813 OPTIONAL(line, LineField, ); \
6814 OPTIONAL(name, MDStringField, ); \
6815 OPTIONAL(elements, MDField, );
6817#undef VISIT_MD_FIELDS
6820 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6821 line.Val,
name.Val, elements.Val));
6825#undef PARSE_MD_FIELD
6837bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6840 if (parseMetadata(MD, &PFS))
6851bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6852 PerFunctionState *PFS) {
6855 if (parseType(Ty, TypeMsg, Loc))
6858 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6861 if (parseValue(Ty, V, PFS))
6876bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6880 if (Lex.getStrVal() ==
"DIArgList") {
6882 if (parseDIArgList(AL, PFS))
6888 if (parseSpecializedMDNode(
N)) {
6898 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6908 if (parseMDString(S))
6918 if (parseMDNodeTail(
N))
6928bool LLParser::convertValIDToValue(
Type *Ty,
ValID &ID,
Value *&V,
6929 PerFunctionState *PFS) {
6931 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6936 return error(
ID.Loc,
"invalid use of function-local name");
6937 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6938 return V ==
nullptr;
6941 return error(
ID.Loc,
"invalid use of function-local name");
6942 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6943 return V ==
nullptr;
6946 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6950 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6955 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6958 return V ==
nullptr;
6960 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6963 return V ==
nullptr;
6966 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6969 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
6974 return error(
ID.Loc,
"floating point constant invalid for type");
6980 bool IsSNAN = ID.APFloatVal.isSignaling();
6983 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6985 else if (Ty->isBFloatTy())
6986 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6988 else if (Ty->isFloatTy())
6989 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6995 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6996 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6997 ID.APFloatVal.isNegative(), &Payload);
7000 V = ConstantFP::get(Context,
ID.APFloatVal);
7002 if (
V->getType() != Ty)
7003 return error(
ID.Loc,
"floating point constant does not have type '" +
7009 return error(
ID.Loc,
"null must be a pointer type");
7015 return error(
ID.Loc,
"invalid type for undef constant");
7020 return error(
ID.Loc,
"invalid empty array initializer");
7026 return error(
ID.Loc,
"invalid type for null constant");
7029 return error(
ID.Loc,
"invalid type for null constant");
7034 return error(
ID.Loc,
"invalid type for none constant");
7040 return error(
ID.Loc,
"invalid type for poison constant");
7044 if (
ID.ConstantVal->getType() != Ty)
7045 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7052 return error(
ID.Loc,
"vector constant must have vector type");
7054 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7056 "' but expected '" +
7064 if (
ST->getNumElements() !=
ID.UIntVal)
7066 "initializer with struct type has wrong # elements");
7068 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
7071 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
7072 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
7075 "element " + Twine(i) +
7076 " of struct initializer doesn't match struct element type");
7079 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
7081 return error(
ID.Loc,
"constant expression type mismatch");
7090 auto Loc = Lex.getLoc();
7091 if (parseValID(ID,
nullptr, Ty))
7104 if (convertValIDToValue(Ty, ID, V,
nullptr))
7114 return error(Loc,
"expected a constant value");
7118bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
7122 FileLoc
Start = getTokLineColumnPos();
7123 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7124 if (!Ret && ParserContext) {
7125 FileLoc End = getPrevTokEndLineColumnPos();
7126 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7131bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
7133 return parseType(Ty) || parseValue(Ty, V, PFS);
7136bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7137 PerFunctionState &PFS) {
7140 if (parseTypeAndValue(V, PFS))
7143 return error(Loc,
"expected a basic block");
7152 if (!Name.starts_with(
"llvm.dbg."))
7155 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7156 FnID == Intrinsic::dbg_assign;
7164bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7165 unsigned &FunctionNumber,
7168 LocTy LinkageLoc = Lex.getLoc();
7170 unsigned Visibility;
7171 unsigned DLLStorageClass;
7173 AttrBuilder RetAttrs(M->getContext());
7176 Type *RetType =
nullptr;
7177 LocTy RetTypeLoc = Lex.getLoc();
7178 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7180 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7181 parseType(RetType, RetTypeLoc,
true ))
7190 return error(LinkageLoc,
"invalid linkage for function definition");
7200 return error(LinkageLoc,
"invalid linkage for function declaration");
7204 return error(LinkageLoc,
"invalid function linkage type");
7208 return error(LinkageLoc,
7209 "symbol with local linkage must have default visibility");
7212 return error(LinkageLoc,
7213 "symbol with local linkage cannot have a DLL storage class");
7216 return error(RetTypeLoc,
"invalid function return type");
7218 LocTy NameLoc = Lex.getLoc();
7220 std::string FunctionName;
7222 FunctionName = Lex.getStrVal();
7224 FunctionNumber = Lex.getUIntVal();
7225 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7229 return tokError(
"expected function name");
7235 return tokError(
"expected '(' in function argument list");
7239 AttrBuilder FuncAttrs(M->getContext());
7240 std::vector<unsigned> FwdRefAttrGrps;
7243 std::string Partition;
7247 unsigned AddrSpace = 0;
7253 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7254 parseOptionalUnnamedAddr(UnnamedAddr) ||
7255 parseOptionalProgramAddrSpace(AddrSpace) ||
7256 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7260 parseOptionalComdat(FunctionName,
C) ||
7261 parseOptionalAlignment(Alignment) ||
7262 parseOptionalPrefAlignment(PrefAlignment) ||
7263 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7267 parseGlobalTypeAndValue(PersonalityFn)))
7270 if (FuncAttrs.contains(Attribute::Builtin))
7271 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7274 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7276 FuncAttrs.removeAttribute(Attribute::Alignment);
7281 std::vector<Type*> ParamTypeList;
7284 for (
const ArgInfo &Arg : ArgList) {
7285 ParamTypeList.push_back(Arg.Ty);
7286 Attrs.push_back(Arg.Attrs);
7293 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7294 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7300 GlobalValue *FwdFn =
nullptr;
7301 if (!FunctionName.empty()) {
7304 auto FRVI = ForwardRefVals.find(FunctionName);
7305 if (FRVI != ForwardRefVals.end()) {
7306 FwdFn = FRVI->second.first;
7308 return error(FRVI->second.second,
7309 "invalid forward reference to "
7312 "' with wrong type: "
7316 ForwardRefVals.erase(FRVI);
7317 }
else if ((Fn = M->getFunction(FunctionName))) {
7319 return error(NameLoc,
7320 "invalid redefinition of function '" + FunctionName +
"'");
7321 }
else if (M->getNamedValue(FunctionName)) {
7322 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7328 if (FunctionNumber == (
unsigned)-1)
7329 FunctionNumber = NumberedVals.getNext();
7333 auto I = ForwardRefValIDs.find(FunctionNumber);
7334 if (
I != ForwardRefValIDs.end()) {
7335 FwdFn =
I->second.first;
7337 return error(NameLoc,
"type of definition and forward reference of '@" +
7338 Twine(FunctionNumber) +
7343 ForwardRefValIDs.erase(
I);
7352 if (FunctionName.empty())
7353 NumberedVals.add(FunctionNumber, Fn);
7369 if (!
GC.empty()) Fn->
setGC(GC);
7372 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7376 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7377 if (ParserContext && ArgList[i].IdentLoc)
7378 ParserContext->addInstructionOrArgumentLocation(
7379 &*ArgIt, ArgList[i].IdentLoc.value());
7381 if (ArgList[i].
Name.empty())
continue;
7384 ArgIt->
setName(ArgList[i].Name);
7386 if (ArgIt->
getName() != ArgList[i].Name)
7387 return error(ArgList[i].Loc,
7388 "redefinition of argument '%" + ArgList[i].Name +
"'");
7401 if (FunctionName.empty()) {
7403 ID.UIntVal = FunctionNumber;
7406 ID.StrVal = FunctionName;
7408 auto Blocks = ForwardRefBlockAddresses.find(ID);
7409 if (Blocks != ForwardRefBlockAddresses.end())
7410 return error(Blocks->first.Loc,
7411 "cannot take blockaddress inside a declaration");
7415bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7417 if (FunctionNumber == -1) {
7419 ID.StrVal = std::string(F.getName());
7422 ID.UIntVal = FunctionNumber;
7425 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7426 if (Blocks == P.ForwardRefBlockAddresses.end())
7429 for (
const auto &
I : Blocks->second) {
7430 const ValID &BBID =
I.first;
7431 GlobalValue *GV =
I.second;
7434 "Expected local id or name");
7441 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7444 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7452 P.ForwardRefBlockAddresses.erase(Blocks);
7458bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
7459 ArrayRef<unsigned> UnnamedArgNums) {
7461 return tokError(
"expected '{' in function body");
7464 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7468 if (PFS.resolveForwardRefBlockAddresses())
7474 return tokError(
"function body requires at least one basic block");
7478 if (parseBasicBlock(PFS))
7482 if (parseUseListOrder(&PFS))
7489 return PFS.finishFunction();
7494bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7495 FileLoc BBStart = getTokLineColumnPos();
7500 LocTy NameLoc = Lex.getLoc();
7502 Name = Lex.getStrVal();
7505 NameID = Lex.getUIntVal();
7509 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7513 std::string NameStr;
7518 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7519 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7526 if (SeenOldDbgInfoFormat)
7527 return error(Lex.getLoc(),
"debug record should not appear in a module "
7528 "containing debug info intrinsics");
7529 SeenNewDbgInfoFormat =
true;
7533 if (parseDebugRecord(DR, PFS))
7535 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7538 FileLoc InstStart = getTokLineColumnPos();
7541 LocTy NameLoc = Lex.getLoc();
7546 NameID = Lex.getUIntVal();
7548 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7551 NameStr = Lex.getStrVal();
7553 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7557 switch (parseInstruction(Inst, BB, PFS)) {
7560 case InstError:
return true;
7567 if (parseInstructionMetadata(*Inst))
7570 case InstExtraComma:
7575 if (parseInstructionMetadata(*Inst))
7581 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7585 for (DbgRecordPtr &DR : TrailingDbgRecord)
7587 TrailingDbgRecord.clear();
7588 if (ParserContext) {
7589 ParserContext->addInstructionOrArgumentLocation(
7590 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7595 ParserContext->addBlockLocation(
7596 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7598 assert(TrailingDbgRecord.empty() &&
7599 "All debug values should have been attached to an instruction.");
7608bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7611 LocTy DVRLoc = Lex.getLoc();
7613 return error(DVRLoc,
"expected debug record type here");
7614 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7615 .Case(
"declare", RecordKind::ValueKind)
7616 .Case(
"value", RecordKind::ValueKind)
7617 .Case(
"assign", RecordKind::ValueKind)
7618 .Case(
"label", RecordKind::LabelKind)
7619 .Case(
"declare_value", RecordKind::ValueKind);
7628 if (parseMDNode(Label))
7633 if (parseMDNode(DbgLoc))
7638 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7642 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7643 .Case(
"declare", LocType::Declare)
7644 .Case(
"value", LocType::Value)
7645 .Case(
"assign", LocType::Assign)
7646 .Case(
"declare_value", LocType::DeclareValue);
7654 if (parseMetadata(ValLocMD, &PFS))
7661 if (parseMDNode(Variable))
7668 if (parseMDNode(Expression))
7674 MDNode *AssignID =
nullptr;
7675 Metadata *AddressLocation =
nullptr;
7676 MDNode *AddressExpression =
nullptr;
7679 if (parseMDNode(AssignID))
7685 if (parseMetadata(AddressLocation, &PFS))
7691 if (parseMDNode(AddressExpression))
7705 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7707 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7716int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7717 PerFunctionState &PFS) {
7720 return tokError(
"found end of file when expecting more instructions");
7721 LocTy Loc = Lex.getLoc();
7722 unsigned KeywordVal = Lex.getUIntVal();
7727 return error(Loc,
"expected instruction opcode");
7731 return parseRet(Inst, BB, PFS);
7733 return parseBr(Inst, PFS);
7735 return parseSwitch(Inst, PFS);
7737 return parseIndirectBr(Inst, PFS);
7739 return parseInvoke(Inst, PFS);
7741 return parseResume(Inst, PFS);
7743 return parseCleanupRet(Inst, PFS);
7745 return parseCatchRet(Inst, PFS);
7747 return parseCatchSwitch(Inst, PFS);
7749 return parseCatchPad(Inst, PFS);
7751 return parseCleanupPad(Inst, PFS);
7753 return parseCallBr(Inst, PFS);
7756 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7757 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7773 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7785 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7786 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7800 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7808 return parseArithmetic(Inst, PFS, KeywordVal,
7812 if (parseLogical(Inst, PFS, KeywordVal))
7820 return parseLogical(Inst, PFS, KeywordVal);
7823 if (parseCompare(Inst, PFS, KeywordVal))
7830 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7831 int Res = parseCompare(Inst, PFS, KeywordVal);
7841 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7843 bool Res = parseCast(Inst, PFS, KeywordVal);
7853 bool Res = parseCast(Inst, PFS, KeywordVal);
7865 if (parseCast(Inst, PFS, KeywordVal))
7874 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7875 if (parseCast(Inst, PFS, KeywordVal))
7888 return parseCast(Inst, PFS, KeywordVal);
7892 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7893 if (parseCast(Inst, PFS, KeywordVal))
7902 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7903 int Res = parseSelect(Inst, PFS);
7909 return error(Loc,
"fast-math-flags specified for select without "
7910 "floating-point scalar or vector return type");
7917 return parseVAArg(Inst, PFS);
7919 return parseExtractElement(Inst, PFS);
7921 return parseInsertElement(Inst, PFS);
7923 return parseShuffleVector(Inst, PFS);
7925 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7926 int Res = parsePHI(Inst, PFS);
7932 return error(Loc,
"fast-math-flags specified for phi without "
7933 "floating-point scalar or vector return type");
7940 return parseLandingPad(Inst, PFS);
7942 return parseFreeze(Inst, PFS);
7954 return parseAlloc(Inst, PFS);
7956 return parseLoad(Inst, PFS);
7958 return parseStore(Inst, PFS);
7960 return parseCmpXchg(Inst, PFS);
7962 return parseAtomicRMW(Inst, PFS);
7964 return parseFence(Inst, PFS);
7966 return parseGetElementPtr(Inst, PFS);
7968 return parseExtractValue(Inst, PFS);
7970 return parseInsertValue(Inst, PFS);
7975bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7976 if (
Opc == Instruction::FCmp) {
7977 switch (Lex.getKind()) {
7979 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7998 switch (Lex.getKind()) {
8000 return tokError(
"expected icmp predicate (e.g. 'eq')");
8024bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8025 PerFunctionState &PFS) {
8026 SMLoc TypeLoc = Lex.getLoc();
8028 if (parseType(Ty,
true ))
8031 Type *ResType = PFS.getFunction().getReturnType();
8035 return error(TypeLoc,
"value doesn't match function result type '" +
8043 if (parseValue(Ty, RV, PFS))
8047 return error(TypeLoc,
"value doesn't match function result type '" +
8057bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8061 if (parseTypeAndValue(Op0, Loc, PFS))
8070 return error(Loc,
"branch condition must have 'i1' type");
8072 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
8073 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8074 parseToken(
lltok::comma,
"expected ',' after true destination") ||
8075 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8087bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8088 LocTy CondLoc, BBLoc;
8091 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
8092 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
8093 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8097 if (!
Cond->getType()->isIntegerTy())
8098 return error(CondLoc,
"switch condition must have integer type");
8101 SmallPtrSet<Value*, 32> SeenCases;
8107 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8108 parseToken(
lltok::comma,
"expected ',' after case value") ||
8109 parseTypeAndBasicBlock(DestBB, PFS))
8112 if (!SeenCases.
insert(Constant).second)
8113 return error(CondLoc,
"duplicate case value in switch");
8115 return error(CondLoc,
"case value is not a constant integer");
8123 for (
const auto &[OnVal, Dest] :
Table)
8124 SI->addCase(OnVal, Dest);
8132bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8135 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8136 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8140 if (!
Address->getType()->isPointerTy())
8141 return error(AddrLoc,
"indirectbr address must have pointer type");
8144 SmallVector<BasicBlock*, 16> DestList;
8148 if (parseTypeAndBasicBlock(DestBB, PFS))
8153 if (parseTypeAndBasicBlock(DestBB, PFS))
8159 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8163 for (BasicBlock *Dest : DestList)
8173 FunctionType *&FuncTy) {
8179 for (
const ParamInfo &Arg : ArgList)
8193bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8194 LocTy CallLoc = Lex.getLoc();
8195 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8196 std::vector<unsigned> FwdRefAttrGrps;
8199 unsigned InvokeAddrSpace;
8200 Type *RetType =
nullptr;
8207 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8208 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8209 parseType(RetType, RetTypeLoc,
true ) ||
8210 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8211 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8213 parseOptionalOperandBundles(BundleList, PFS) ||
8215 parseTypeAndBasicBlock(NormalBB, PFS) ||
8217 parseTypeAndBasicBlock(UnwindBB, PFS))
8224 if (resolveFunctionType(RetType, ArgList, Ty))
8225 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8231 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8236 SmallVector<Value *, 8>
Args;
8243 for (
const ParamInfo &Arg : ArgList) {
8244 Type *ExpectedTy =
nullptr;
8247 }
else if (!Ty->isVarArg()) {
8248 return error(Arg.Loc,
"too many arguments specified");
8251 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8252 return error(Arg.Loc,
"argument is not of expected type '" +
8254 Args.push_back(Arg.V);
8259 return error(CallLoc,
"not enough parameters specified for call");
8268 II->setCallingConv(CC);
8269 II->setAttributes(PAL);
8270 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8277bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8279 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8287bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8288 PerFunctionState &PFS) {
8289 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8294 if (!
Args.empty() &&
8295 parseToken(
lltok::comma,
"expected ',' in argument list"))
8300 Type *ArgTy =
nullptr;
8301 if (parseType(ArgTy, ArgLoc))
8306 if (parseMetadataAsValue(V, PFS))
8309 if (parseValue(ArgTy, V, PFS))
8321bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8322 Value *CleanupPad =
nullptr;
8324 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8339 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8350bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8351 Value *CatchPad =
nullptr;
8353 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8360 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8361 parseTypeAndBasicBlock(BB, PFS))
8370bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8378 return tokError(
"expected scope value for catchswitch");
8383 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8389 if (parseTypeAndBasicBlock(DestBB, PFS))
8391 Table.push_back(DestBB);
8394 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8397 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8405 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8411 for (BasicBlock *DestBB :
Table)
8412 CatchSwitch->addHandler(DestBB);
8419bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8420 Value *CatchSwitch =
nullptr;
8426 return tokError(
"expected scope value for catchpad");
8431 SmallVector<Value *, 8>
Args;
8432 if (parseExceptionArgs(Args, PFS))
8441bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8442 Value *ParentPad =
nullptr;
8449 return tokError(
"expected scope value for cleanuppad");
8454 SmallVector<Value *, 8>
Args;
8455 if (parseExceptionArgs(Args, PFS))
8471bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8472 unsigned Opc,
bool IsFP) {
8474 if (parseTypeAndValue(
LHS, Loc, PFS))
8481 return error(Loc,
"invalid operand type for instruction");
8491bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8492 LocTy CallLoc = Lex.getLoc();
8493 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8494 std::vector<unsigned> FwdRefAttrGrps;
8497 Type *RetType =
nullptr;
8504 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8505 parseType(RetType, RetTypeLoc,
true ) ||
8506 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8507 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8509 parseOptionalOperandBundles(BundleList, PFS) ||
8511 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8516 SmallVector<BasicBlock *, 16> IndirectDests;
8520 if (parseTypeAndBasicBlock(DestBB, PFS))
8525 if (parseTypeAndBasicBlock(DestBB, PFS))
8531 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8538 if (resolveFunctionType(RetType, ArgList, Ty))
8539 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8550 SmallVector<Value *, 8>
Args;
8557 for (
const ParamInfo &Arg : ArgList) {
8558 Type *ExpectedTy =
nullptr;
8561 }
else if (!Ty->isVarArg()) {
8562 return error(Arg.Loc,
"too many arguments specified");
8565 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8566 return error(Arg.Loc,
"argument is not of expected type '" +
8568 Args.push_back(Arg.V);
8573 return error(CallLoc,
"not enough parameters specified for call");
8585 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8599bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8600 unsigned Opc,
bool IsFP) {
8602 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8603 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8611 return error(Loc,
"invalid operand type for instruction");
8619bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8622 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8623 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8629 "instruction requires integer or integer vector operands");
8638bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8644 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8645 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8649 if (
Opc == Instruction::FCmp) {
8651 return error(Loc,
"fcmp requires floating point operands");
8654 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8657 return error(Loc,
"icmp requires integer operands");
8669bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8673 Type *DestTy =
nullptr;
8674 if (parseTypeAndValue(
Op, Loc, PFS) ||
8675 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8680 return error(Loc,
"invalid cast opcode for cast from '" +
8689bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8691 Value *Op0, *Op1, *Op2;
8692 if (parseTypeAndValue(Op0, Loc, PFS) ||
8693 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8694 parseTypeAndValue(Op1, PFS) ||
8695 parseToken(
lltok::comma,
"expected ',' after select value") ||
8696 parseTypeAndValue(Op2, PFS))
8700 return error(Loc, Reason);
8708bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8710 Type *EltTy =
nullptr;
8712 if (parseTypeAndValue(
Op, PFS) ||
8713 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8714 parseType(EltTy, TypeLoc))
8718 return error(TypeLoc,
"va_arg requires operand with first class type");
8720 Inst =
new VAArgInst(
Op, EltTy);
8726bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8729 if (parseTypeAndValue(Op0, Loc, PFS) ||
8730 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8731 parseTypeAndValue(Op1, PFS))
8735 return error(Loc,
"invalid extractelement operands");
8743bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8745 Value *Op0, *Op1, *Op2;
8746 if (parseTypeAndValue(Op0, Loc, PFS) ||
8747 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8748 parseTypeAndValue(Op1, PFS) ||
8749 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8750 parseTypeAndValue(Op2, PFS))
8754 return error(Loc,
"invalid insertelement operands");
8762bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8764 Value *Op0, *Op1, *Op2;
8765 if (parseTypeAndValue(Op0, Loc, PFS) ||
8766 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8767 parseTypeAndValue(Op1, PFS) ||
8768 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8769 parseTypeAndValue(Op2, PFS))
8773 return error(Loc,
"invalid shufflevector operands");
8775 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8781int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8785 if (parseType(Ty, TypeLoc))
8789 return error(TypeLoc,
"phi node must have first class type");
8792 bool AteExtraComma =
false;
8804 AteExtraComma =
true;
8808 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8809 parseValue(Ty, Op0, PFS) ||
8810 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8819 for (
const auto &[Val, BB] : PHIVals)
8822 return AteExtraComma ? InstExtraComma : InstNormal;
8831bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8834 if (parseType(Ty, TyLoc))
8847 return tokError(
"expected 'catch' or 'filter' clause type");
8851 if (parseTypeAndValue(V, VLoc, PFS))
8858 return error(VLoc,
"'catch' clause has an invalid type");
8861 return error(VLoc,
"'filter' clause has an invalid type");
8866 return error(VLoc,
"clause argument must be a constant");
8870 Inst = LP.release();
8876bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8879 if (parseTypeAndValue(
Op, Loc, PFS))
8882 Inst =
new FreezeInst(
Op);
8895bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8897 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8898 std::vector<unsigned> FwdRefAttrGrps;
8900 unsigned CallAddrSpace;
8902 Type *RetType =
nullptr;
8907 LocTy CallLoc = Lex.getLoc();
8911 "expected 'tail call', 'musttail call', or 'notail call'"))
8914 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8916 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8917 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8918 parseType(RetType, RetTypeLoc,
true ) ||
8919 parseValID(CalleeID, &PFS) ||
8921 PFS.getFunction().isVarArg()) ||
8922 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8923 parseOptionalOperandBundles(BundleList, PFS))
8930 if (resolveFunctionType(RetType, ArgList, Ty))
8931 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8937 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8944 SmallVector<Value*, 8>
Args;
8950 for (
const ParamInfo &Arg : ArgList) {
8951 Type *ExpectedTy =
nullptr;
8954 }
else if (!Ty->isVarArg()) {
8955 return error(Arg.Loc,
"too many arguments specified");
8958 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8959 return error(Arg.Loc,
"argument is not of expected type '" +
8961 Args.push_back(Arg.V);
8962 Attrs.push_back(Arg.Attrs);
8966 return error(CallLoc,
"not enough parameters specified for call");
8979 return error(CallLoc,
"fast-math-flags specified for call without "
8980 "floating-point scalar or vector return type");
8987 if (SeenNewDbgInfoFormat) {
8989 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8990 "using non-intrinsic debug info");
8992 SeenOldDbgInfoFormat =
true;
8995 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9007int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9009 LocTy SizeLoc, TyLoc, ASLoc;
9011 unsigned AddrSpace = 0;
9014 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9015 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9017 if (parseType(Ty, TyLoc))
9021 return error(TyLoc,
"invalid type for alloca");
9023 bool AteExtraComma =
false;
9025 if (Lex.getKind() == lltok::kw_align) {
9026 if (parseOptionalAlignment(Alignment))
9028 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9031 ASLoc = Lex.getLoc();
9032 if (parseOptionalAddrSpace(AddrSpace))
9035 AteExtraComma =
true;
9037 if (parseTypeAndValue(
Size, SizeLoc, PFS))
9040 if (Lex.getKind() == lltok::kw_align) {
9041 if (parseOptionalAlignment(Alignment))
9043 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9046 ASLoc = Lex.getLoc();
9047 if (parseOptionalAddrSpace(AddrSpace))
9050 AteExtraComma =
true;
9056 if (
Size && !
Size->getType()->isIntegerTy())
9057 return error(SizeLoc,
"element count must have integer type");
9059 SmallPtrSet<Type *, 4> Visited;
9060 if (!Alignment && !Ty->
isSized(&Visited))
9061 return error(TyLoc,
"Cannot allocate unsized type");
9063 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9064 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
9068 return AteExtraComma ? InstExtraComma : InstNormal;
9075int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9078 bool AteExtraComma =
false;
9088 bool isVolatile =
false;
9094 bool IsElementwise =
false;
9096 IsElementwise =
true;
9101 LocTy ExplicitTypeLoc = Lex.getLoc();
9102 if (parseType(Ty) ||
9103 parseToken(
lltok::comma,
"expected comma after load's type") ||
9104 parseTypeAndValue(Val, Loc, PFS) ||
9105 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9106 parseOptionalCommaAlign(Alignment, AteExtraComma))
9110 return error(Loc,
"load operand must be a pointer to a first class type");
9112 if (IsElementwise && !isAtomic)
9113 return error(Loc,
"elementwise load must be atomic");
9116 return error(ExplicitTypeLoc,
9117 "atomic elementwise load operand must have fixed vector type");
9119 if (isAtomic && !Alignment)
9120 return error(Loc,
"atomic load must have explicit non-zero alignment");
9124 return error(Loc,
"atomic load cannot use Release ordering");
9127 "atomic elementwise load cannot be sequentially consistent");
9129 SmallPtrSet<Type *, 4> Visited;
9130 if (!Alignment && !Ty->
isSized(&Visited))
9131 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9133 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9134 Inst =
new LoadInst(Ty, Val,
"",
9136 SSID, IsElementwise},
9138 return AteExtraComma ? InstExtraComma : InstNormal;
9146int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9150 bool AteExtraComma =
false;
9160 bool isVolatile =
false;
9166 bool IsElementwise =
false;
9168 IsElementwise =
true;
9172 if (parseTypeAndValue(Val, Loc, PFS) ||
9173 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9174 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9175 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9176 parseOptionalCommaAlign(Alignment, AteExtraComma))
9180 return error(PtrLoc,
"store operand must be a pointer");
9182 return error(Loc,
"store operand must be a first class value");
9183 if (isAtomic && !Alignment)
9184 return error(Loc,
"atomic store must have explicit non-zero alignment");
9187 return error(Loc,
"atomic store cannot use Acquire ordering");
9189 if (IsElementwise && !isAtomic)
9190 return error(Loc,
"elementwise store must be atomic");
9194 Loc,
"atomic elementwise store operand must have fixed vector type");
9198 "atomic elementwise store cannot be sequentially consistent");
9200 SmallPtrSet<Type *, 4> Visited;
9202 return error(Loc,
"storing unsized types is not allowed");
9206 Inst =
new StoreInst(Val, Ptr,
9208 SSID, IsElementwise},
9210 return AteExtraComma ? InstExtraComma : InstNormal;
9217int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9219 bool AteExtraComma =
false;
9223 bool isVolatile =
false;
9224 bool isWeak =
false;
9233 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9234 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9235 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9236 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9237 parseTypeAndValue(New, NewLoc, PFS) ||
9238 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9239 parseOrdering(FailureOrdering) ||
9240 parseOptionalCommaAlign(Alignment, AteExtraComma))
9244 return tokError(
"invalid cmpxchg success ordering");
9246 return tokError(
"invalid cmpxchg failure ordering");
9248 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9249 if (
Cmp->getType() !=
New->getType())
9250 return error(NewLoc,
"compare value and new value type do not match");
9251 if (!
New->getType()->isFirstClassType())
9252 return error(NewLoc,
"cmpxchg operand must be a first class value");
9254 const Align DefaultAlignment(
9255 PFS.getFunction().getDataLayout().getTypeStoreSize(
9258 AtomicCmpXchgInst *CXI =
9259 new AtomicCmpXchgInst(Ptr, Cmp, New,
Alignment.value_or(DefaultAlignment),
9260 SuccessOrdering, FailureOrdering, SSID);
9265 return AteExtraComma ? InstExtraComma : InstNormal;
9272int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9274 bool AteExtraComma =
false;
9278 bool IsElementwise =
false;
9286 IsElementwise =
true;
9288 switch (Lex.getKind()) {
9290 return tokError(
"expected binary operation in atomicrmw");
9349 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9350 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9351 parseTypeAndValue(Val, ValLoc, PFS) ||
9352 parseScopeAndOrdering(
true , SSID, Ordering) ||
9353 parseOptionalCommaAlign(Alignment, AteExtraComma))
9357 return tokError(
"atomicrmw cannot be unordered");
9359 return tokError(
"atomicrmw elementwise cannot be sequentially consistent");
9361 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9363 return error(ValLoc,
"atomicrmw operand may not be scalable");
9366 if (IsElementwise) {
9368 return error(ValLoc,
9369 "atomicrmw elementwise operand must be a fixed vector type");
9378 " operand must be an integer type, a floating-point type, a "
9379 "pointer type, or a fixed vector of any of these types");
9383 return error(ValLoc,
"atomicrmw " +
9385 " operand must be a floating point or fixed "
9386 "vector of floating point type");
9393 " operand must be an integer or fixed vector of integer type");
9398 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9400 return error(ValLoc,
9401 "atomicrmw operand must have a power-of-two byte size");
9402 const Align DefaultAlignment(
9403 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9404 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9406 Ordering, SSID, IsElementwise);
9409 return AteExtraComma ? InstExtraComma : InstNormal;
9414int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9417 if (parseScopeAndOrdering(
true , SSID, Ordering))
9421 return tokError(
"fence cannot be unordered");
9423 return tokError(
"fence cannot be monotonic");
9425 Inst =
new FenceInst(Context, Ordering, SSID);
9431int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9432 Value *Ptr =
nullptr;
9433 Value *Val =
nullptr;
9449 if (parseType(Ty) ||
9450 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9451 parseTypeAndValue(Ptr, Loc, PFS))
9456 if (!BasePointerType)
9457 return error(Loc,
"base of getelementptr must be a pointer");
9459 SmallVector<Value*, 16> Indices;
9460 bool AteExtraComma =
false;
9463 ElementCount GEPWidth =
BaseType->isVectorTy()
9469 AteExtraComma =
true;
9472 if (parseTypeAndValue(Val, EltLoc, PFS))
9475 return error(EltLoc,
"getelementptr index must be an integer");
9478 ElementCount ValNumEl = ValVTy->getElementCount();
9482 "getelementptr vector index has a wrong number of elements");
9483 GEPWidth = ValNumEl;
9488 SmallPtrSet<Type*, 4> Visited;
9490 return error(Loc,
"base element of getelementptr must be sized");
9494 return error(Loc,
"getelementptr cannot target structure that contains "
9495 "scalable vector type");
9498 return error(Loc,
"invalid getelementptr indices");
9501 GEP->setNoWrapFlags(NW);
9502 return AteExtraComma ? InstExtraComma : InstNormal;
9507int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9509 SmallVector<unsigned, 4> Indices;
9511 if (parseTypeAndValue(Val, Loc, PFS) ||
9512 parseIndexList(Indices, AteExtraComma))
9516 return error(Loc,
"extractvalue operand must be aggregate type");
9519 return error(Loc,
"invalid indices for extractvalue");
9521 return AteExtraComma ? InstExtraComma : InstNormal;
9526int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9528 SmallVector<unsigned, 4> Indices;
9530 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9531 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9532 parseTypeAndValue(Val1, Loc1, PFS) ||
9533 parseIndexList(Indices, AteExtraComma))
9537 return error(Loc0,
"insertvalue operand must be aggregate type");
9541 return error(Loc0,
"invalid indices for insertvalue");
9542 if (IndexedType != Val1->
getType())
9543 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9547 return AteExtraComma ? InstExtraComma : InstNormal;
9558bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9573 if (parseMetadata(MD,
nullptr))
9578 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9584bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9586 if (!
V->hasUseList())
9589 return error(Loc,
"value has no uses");
9591 unsigned NumUses = 0;
9592 SmallDenseMap<const Use *, unsigned, 16> Order;
9593 for (
const Use &U :
V->uses()) {
9594 if (++NumUses > Indexes.
size())
9596 Order[&
U] = Indexes[NumUses - 1];
9599 return error(Loc,
"value only has one use");
9600 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9602 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9604 V->sortUseList([&](
const Use &L,
const Use &R) {
9612bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9613 SMLoc Loc = Lex.getLoc();
9617 return tokError(
"expected non-empty list of uselistorder indexes");
9624 bool IsOrdered =
true;
9625 assert(Indexes.
empty() &&
"Expected empty order vector");
9628 if (parseUInt32(Index))
9633 Max = std::max(Max, Index);
9634 IsOrdered &= Index == Indexes.
size();
9642 if (Indexes.
size() < 2)
9643 return error(Loc,
"expected >= 2 uselistorder indexes");
9646 "expected distinct uselistorder indexes in range [0, size)");
9648 return error(Loc,
"expected uselistorder indexes to change the order");
9655bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9656 SMLoc Loc = Lex.getLoc();
9661 SmallVector<unsigned, 16> Indexes;
9662 if (parseTypeAndValue(V, PFS) ||
9663 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9664 parseUseListOrderIndexes(Indexes))
9667 return sortUseListOrder(V, Indexes, Loc);
9673bool LLParser::parseModuleEntry(
unsigned ID) {
9682 parseStringConstant(Path) ||
9690 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9691 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9692 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9693 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9694 parseUInt32(Hash[4]))
9701 auto ModuleEntry = Index->addModule(Path, Hash);
9702 ModuleIdMap[
ID] = ModuleEntry->first();
9709bool LLParser::parseTypeIdEntry(
unsigned ID) {
9718 parseStringConstant(Name))
9721 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9723 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9728 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9729 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9730 for (
auto TIDRef : FwdRefTIDs->second) {
9732 "Forward referenced type id GUID expected to be 0");
9735 ForwardRefTypeIds.erase(FwdRefTIDs);
9743bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9747 parseTypeTestResolution(TIS.
TTRes))
9752 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9769bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9778 parseStringConstant(Name))
9782 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9789 IdToIndexMapType IdToIndexMap;
9802 if (parseGVReference(VI, GVId))
9809 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9810 TI.push_back({
Offset, VI});
9818 for (
auto I : IdToIndexMap) {
9819 auto &Infos = ForwardRefValueInfos[
I.first];
9820 for (
auto P :
I.second) {
9822 "Forward referenced ValueInfo expected to be empty");
9823 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9833 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9834 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9835 for (
auto TIDRef : FwdRefTIDs->second) {
9837 "Forward referenced type id GUID expected to be 0");
9840 ForwardRefTypeIds.erase(FwdRefTIDs);
9852bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9860 switch (Lex.getKind()) {
9880 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9892 switch (Lex.getKind()) {
9907 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9920 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9933bool LLParser::parseOptionalWpdResolutions(
9934 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9942 WholeProgramDevirtResolution WPDRes;
9946 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9949 WPDResMap[
Offset] = WPDRes;
9966bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9974 switch (Lex.getKind()) {
9985 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9991 switch (Lex.getKind()) {
9999 if (parseOptionalResByArg(WPDRes.
ResByArg))
10003 return error(Lex.getLoc(),
10004 "expected optional WholeProgramDevirtResolution field");
10021bool LLParser::parseOptionalResByArg(
10022 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10030 std::vector<uint64_t>
Args;
10031 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
10039 WholeProgramDevirtResolution::ByArg ByArg;
10040 switch (Lex.getKind()) {
10054 return error(Lex.getLoc(),
10055 "unexpected WholeProgramDevirtResolution::ByArg kind");
10061 switch (Lex.getKind()) {
10065 parseUInt64(ByArg.
Info))
10071 parseUInt32(ByArg.
Byte))
10077 parseUInt32(ByArg.
Bit))
10081 return error(Lex.getLoc(),
10082 "expected optional whole program devirt field");
10089 ResByArg[
Args] = ByArg;
10100bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10108 if (parseUInt64(Val))
10110 Args.push_back(Val);
10134bool LLParser::addGlobalValueToIndex(
10136 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10141 VI = Index->getOrInsertValueInfo(GUID);
10145 auto *GV = M->getNamedValue(Name);
10147 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10153 VI = Index->getOrInsertValueInfo(GV, GUID);
10157 "Need a source_filename to compute GUID for local");
10160 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10165 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10166 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10167 for (
auto VIRef : FwdRefVIs->second) {
10169 "Forward referenced ValueInfo expected to be empty");
10172 ForwardRefValueInfos.erase(FwdRefVIs);
10176 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10177 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10178 for (
auto AliaseeRef : FwdRefAliasees->second) {
10179 assert(!AliaseeRef.first->hasAliasee() &&
10180 "Forward referencing alias already has aliasee");
10181 assert(Summary &&
"Aliasee must be a definition");
10182 AliaseeRef.first->setAliasee(VI,
Summary.get());
10184 ForwardRefAliasees.erase(FwdRefAliasees);
10189 Index->addGlobalValueSummary(VI, std::move(Summary));
10192 if (ID == NumberedValueInfos.size())
10193 NumberedValueInfos.push_back(VI);
10196 if (ID > NumberedValueInfos.size())
10197 NumberedValueInfos.resize(ID + 1);
10198 NumberedValueInfos[
ID] =
VI;
10206bool LLParser::parseSummaryIndexFlags() {
10213 if (parseUInt64(Flags))
10216 Index->setFlags(Flags);
10222bool LLParser::parseBlockCount() {
10229 if (parseUInt64(BlockCount))
10232 Index->setBlockCount(BlockCount);
10240bool LLParser::parseGVEntry(
unsigned ID) {
10248 LocTy Loc = Lex.getLoc();
10251 switch (Lex.getKind()) {
10255 parseStringConstant(Name))
10261 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10265 return error(Lex.getLoc(),
"expected name or guid tag");
10288 switch (Lex.getKind()) {
10290 if (parseFunctionSummary(Name, GUID, ID))
10294 if (parseVariableSummary(Name, GUID, ID))
10298 if (parseAliasSummary(Name, GUID, ID))
10302 return error(Lex.getLoc(),
"expected summary type");
10320 LocTy Loc = Lex.getLoc();
10324 StringRef ModulePath;
10325 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10328 false,
false,
false,
10330 unsigned InstCount;
10332 FunctionSummary::TypeIdInfo TypeIdInfo;
10333 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10335 std::vector<CallsiteInfo> Callsites;
10336 std::vector<AllocInfo> Allocs;
10338 FunctionSummary::FFlags FFlags = {};
10341 parseModuleReference(ModulePath) ||
10342 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10345 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10350 switch (Lex.getKind()) {
10352 if (parseOptionalFFlags(FFlags))
10356 if (parseOptionalCalls(Calls))
10360 if (parseOptionalTypeIdInfo(TypeIdInfo))
10364 if (parseOptionalRefs(Refs))
10368 if (parseOptionalParamAccesses(ParamAccesses))
10372 if (parseOptionalAllocs(Allocs))
10376 if (parseOptionalCallsites(Callsites))
10380 return error(Lex.getLoc(),
"expected optional function summary field");
10387 auto FS = std::make_unique<FunctionSummary>(
10388 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10394 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10396 FS->setModulePath(ModulePath);
10398 return addGlobalValueToIndex(Name, GUID,
10400 std::move(FS), Loc);
10408 LocTy Loc = Lex.getLoc();
10412 StringRef ModulePath;
10413 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10416 false,
false,
false,
10418 GlobalVarSummary::GVarFlags GVarFlags(
false,
10426 parseModuleReference(ModulePath) ||
10427 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10429 parseGVarFlags(GVarFlags))
10434 switch (Lex.getKind()) {
10436 if (parseOptionalVTableFuncs(VTableFuncs))
10440 if (parseOptionalRefs(Refs))
10444 return error(Lex.getLoc(),
"expected optional variable summary field");
10452 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10454 GS->setModulePath(ModulePath);
10455 GS->setVTableFuncs(std::move(VTableFuncs));
10457 return addGlobalValueToIndex(Name, GUID,
10459 std::move(GS), Loc);
10468 LocTy Loc = Lex.getLoc();
10471 StringRef ModulePath;
10472 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10475 false,
false,
false,
10479 parseModuleReference(ModulePath) ||
10480 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10486 ValueInfo AliaseeVI;
10488 auto AS = std::make_unique<AliasSummary>(GVFlags);
10489 AS->setModulePath(ModulePath);
10492 if (parseGVReference(AliaseeVI, GVId))
10497 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10499 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10500 assert(Summary &&
"Aliasee must be a definition");
10501 AS->setAliasee(AliaseeVI, Summary);
10508 return addGlobalValueToIndex(Name, GUID,
10510 std::move(AS), Loc);
10515bool LLParser::parseFlag(
unsigned &Val) {
10516 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10517 return tokError(
"expected integer");
10518 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10534bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10538 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10544 switch (Lex.getKind()) {
10547 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10553 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10559 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10565 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10571 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10577 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10583 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10589 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10595 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10601 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10606 return error(Lex.getLoc(),
"expected function flag type");
10610 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10621bool LLParser::parseOptionalCalls(
10622 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10626 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10630 IdToIndexMapType IdToIndexMap;
10639 LocTy Loc = Lex.getLoc();
10641 if (parseGVReference(VI, GVId))
10645 unsigned RelBF = 0;
10646 unsigned HasTailCall =
false;
10650 switch (Lex.getKind()) {
10653 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10659 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10664 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10668 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10675 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10685 for (
auto I : IdToIndexMap) {
10686 auto &Infos = ForwardRefValueInfos[
I.first];
10687 for (
auto P :
I.second) {
10689 "Forward referenced ValueInfo expected to be empty");
10690 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10703 switch (Lex.getKind()) {
10707 case lltok::kw_cold:
10713 case lltok::kw_hot:
10720 return error(Lex.getLoc(),
"invalid call edge hotness");
10729bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10733 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10737 IdToIndexMapType IdToIndexMap;
10741 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10746 LocTy Loc = Lex.getLoc();
10748 if (parseGVReference(VI, GVId))
10761 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10762 VTableFuncs.push_back({
VI,
Offset});
10764 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10770 for (
auto I : IdToIndexMap) {
10771 auto &Infos = ForwardRefValueInfos[
I.first];
10772 for (
auto P :
I.second) {
10774 "Forward referenced ValueInfo expected to be empty");
10775 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10779 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10786bool LLParser::parseParamNo(
uint64_t &ParamNo) {
10788 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10794bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10797 auto ParseAPSInt = [&](
APSInt &Val) {
10799 return tokError(
"expected integer");
10800 Val = Lex.getAPSIntVal();
10802 Val.setIsSigned(
true);
10824bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10825 IdLocListType &IdLocList) {
10833 LocTy Loc = Lex.getLoc();
10834 if (parseGVReference(VI, GVId))
10838 IdLocList.emplace_back(GVId, Loc);
10841 parseParamNo(
Call.ParamNo) ||
10843 parseParamAccessOffset(
Call.Offsets))
10855bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10856 IdLocListType &IdLocList) {
10858 parseParamNo(
Param.ParamNo) ||
10860 parseParamAccessOffset(
Param.Use))
10869 FunctionSummary::ParamAccess::Call
Call;
10870 if (parseParamAccessCall(
Call, IdLocList))
10887bool LLParser::parseOptionalParamAccesses(
10888 std::vector<FunctionSummary::ParamAccess> &Params) {
10896 IdLocListType VContexts;
10897 size_t CallsNum = 0;
10899 FunctionSummary::ParamAccess ParamAccess;
10900 if (parseParamAccess(ParamAccess, VContexts))
10902 CallsNum += ParamAccess.
Calls.size();
10903 assert(VContexts.size() == CallsNum);
10905 Params.emplace_back(std::move(ParamAccess));
10913 IdLocListType::const_iterator ItContext = VContexts.begin();
10914 for (
auto &PA : Params) {
10915 for (
auto &
C : PA.Calls) {
10917 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10918 ItContext->second);
10922 assert(ItContext == VContexts.end());
10929bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10933 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10937 struct ValueContext {
10942 std::vector<ValueContext> VContexts;
10946 VC.Loc = Lex.getLoc();
10947 if (parseGVReference(
VC.VI,
VC.GVId))
10949 VContexts.push_back(VC);
10955 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10956 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10959 IdToIndexMapType IdToIndexMap;
10960 for (
auto &VC : VContexts) {
10965 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10971 for (
auto I : IdToIndexMap) {
10972 auto &Infos = ForwardRefValueInfos[
I.first];
10973 for (
auto P :
I.second) {
10975 "Forward referenced ValueInfo expected to be empty");
10976 Infos.emplace_back(&Refs[
P.first],
P.second);
10990bool LLParser::parseOptionalTypeIdInfo(
10991 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11000 switch (Lex.getKind()) {
11002 if (parseTypeTests(TypeIdInfo.
TypeTests))
11026 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
11030 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11039bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11047 IdToIndexMapType IdToIndexMap;
11051 unsigned ID = Lex.getUIntVal();
11052 LocTy Loc = Lex.getLoc();
11056 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
11058 }
else if (parseUInt64(GUID))
11060 TypeTests.push_back(GUID);
11065 for (
auto I : IdToIndexMap) {
11066 auto &Ids = ForwardRefTypeIds[
I.first];
11067 for (
auto P :
I.second) {
11068 assert(TypeTests[
P.first] == 0 &&
11069 "Forward referenced type id GUID expected to be 0");
11070 Ids.emplace_back(&TypeTests[
P.first],
P.second);
11074 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11082bool LLParser::parseVFuncIdList(
11083 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11084 assert(Lex.getKind() == Kind);
11091 IdToIndexMapType IdToIndexMap;
11093 FunctionSummary::VFuncId VFuncId;
11094 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11096 VFuncIdList.push_back(VFuncId);
11104 for (
auto I : IdToIndexMap) {
11105 auto &Ids = ForwardRefTypeIds[
I.first];
11106 for (
auto P :
I.second) {
11107 assert(VFuncIdList[
P.first].GUID == 0 &&
11108 "Forward referenced type id GUID expected to be 0");
11109 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
11118bool LLParser::parseConstVCallList(
11120 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11121 assert(Lex.getKind() == Kind);
11128 IdToIndexMapType IdToIndexMap;
11130 FunctionSummary::ConstVCall ConstVCall;
11131 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11133 ConstVCallList.push_back(ConstVCall);
11141 for (
auto I : IdToIndexMap) {
11142 auto &Ids = ForwardRefTypeIds[
I.first];
11143 for (
auto P :
I.second) {
11144 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11145 "Forward referenced type id GUID expected to be 0");
11146 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11155bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11156 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11158 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11162 if (parseArgs(ConstVCall.
Args))
11174bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11175 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11185 unsigned ID = Lex.getUIntVal();
11186 LocTy Loc = Lex.getLoc();
11190 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11192 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11194 parseUInt64(VFuncId.
GUID))
11200 parseUInt64(VFuncId.
Offset) ||
11212bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11222 switch (Lex.getKind()) {
11229 assert(HasLinkage &&
"Linkage not optional in summary entry");
11236 parseOptionalVisibility(Flag);
11241 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11247 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11253 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11259 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11268 if (parseOptionalImportType(Lex.getKind(), IK))
11270 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11275 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11280 return error(Lex.getLoc(),
"expected gv flag type");
11294bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11302 auto ParseRest = [
this](
unsigned int &Val) {
11306 return parseFlag(Val);
11311 switch (Lex.getKind()) {
11312 case lltok::kw_readonly:
11313 if (ParseRest(Flag))
11317 case lltok::kw_writeonly:
11318 if (ParseRest(Flag))
11323 if (ParseRest(Flag))
11328 if (ParseRest(Flag))
11333 return error(Lex.getLoc(),
"expected gvar flag type");
11341bool LLParser::parseModuleReference(StringRef &ModulePath) {
11348 unsigned ModuleID = Lex.getUIntVal();
11349 auto I = ModuleIdMap.find(ModuleID);
11351 assert(
I != ModuleIdMap.end());
11352 ModulePath =
I->second;
11358bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11361 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11365 GVId = Lex.getUIntVal();
11367 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11369 VI = NumberedValueInfos[GVId];
11386bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11390 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11402 SmallVector<uint8_t> Versions;
11405 if (parseAllocType(V))
11410 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11414 std::vector<MIBInfo> MIBs;
11415 if (parseMemProfs(MIBs))
11418 Allocs.push_back({Versions, MIBs});
11435bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11439 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11445 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11454 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11460 SmallVector<unsigned> StackIdIndices;
11465 if (parseUInt64(StackId))
11467 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11488bool LLParser::parseAllocType(uint8_t &
AllocType) {
11489 switch (Lex.getKind()) {
11496 case lltok::kw_cold:
11499 case lltok::kw_hot:
11503 return error(Lex.getLoc(),
"invalid alloc type");
11516bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11520 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11524 IdToIndexMapType IdToIndexMap;
11527 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11534 LocTy Loc = Lex.getLoc();
11536 if (parseGVReference(VI, GVId))
11540 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11546 SmallVector<unsigned> Clones;
11549 if (parseUInt32(V))
11555 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11561 SmallVector<unsigned> StackIdIndices;
11566 if (parseUInt64(StackId))
11568 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11579 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11580 Callsites.push_back({
VI, Clones, StackIdIndices});
11588 for (
auto I : IdToIndexMap) {
11589 auto &Infos = ForwardRefValueInfos[
I.first];
11590 for (
auto P :
I.second) {
11592 "Forward referenced ValueInfo expected to be empty");
11593 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11597 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(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool 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)
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isAggregateType() const
Return true if the type is an aggregate type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
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.