72 "Can't read textual IR with a Context that discards named Values");
74 return ParseTopLevelEntities() || ValidateEndOfModule() ||
80 restoreParsingState(Slots);
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
87 return Error(Lex.
getLoc(),
"expected end of string");
93 restoreParsingState(Slots);
107 void LLParser::restoreParsingState(
const SlotMapping *Slots) {
114 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
115 for (
const auto &
I : Slots->
Types)
116 NumberedTypes.insert(
117 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
122 bool LLParser::ValidateEndOfModule() {
126 for (
const auto &RAG : ForwardRefAttrGroups) {
127 Value *V = RAG.first;
128 const std::vector<unsigned> &
Attrs = RAG.second;
131 for (
const auto &Attr : Attrs)
132 B.
merge(NumberedAttrBuilders[Attr]);
134 if (
Function *Fn = dyn_cast<Function>(V)) {
143 if (FnAttrs.hasAlignmentAttr()) {
144 Fn->setAlignment(FnAttrs.getAlignment());
150 Fn->setAttributes(AS);
151 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
158 CI->setAttributes(AS);
159 }
else if (
InvokeInst *II = dyn_cast<InvokeInst>(V)) {
166 II->setAttributes(AS);
167 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
178 if (!ForwardRefBlockAddresses.empty())
179 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
180 "expected function name in blockaddress");
182 for (
const auto &NT : NumberedTypes)
183 if (NT.second.second.isValid())
184 return Error(NT.second.second,
185 "use of undefined type '%" +
Twine(NT.first) +
"'");
187 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
188 NamedTypes.begin(),
E = NamedTypes.end();
I !=
E; ++
I)
189 if (
I->second.second.isValid())
190 return Error(
I->second.second,
191 "use of undefined type named '" +
I->getKey() +
"'");
193 if (!ForwardRefComdats.empty())
194 return Error(ForwardRefComdats.begin()->second,
195 "use of undefined comdat '$" +
196 ForwardRefComdats.begin()->first +
"'");
198 if (!ForwardRefVals.empty())
199 return Error(ForwardRefVals.begin()->second.second,
200 "use of undefined value '@" + ForwardRefVals.begin()->first +
203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
206 Twine(ForwardRefValIDs.begin()->first) +
"'");
208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
211 Twine(ForwardRefMDNodes.begin()->first) +
"'");
214 for (
auto &
N : NumberedMetadata) {
215 if (
N.second && !
N.second->isResolved())
216 N.second->resolveCycles();
219 for (
auto *Inst : InstsWithTBAATag) {
221 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
223 if (MD != UpgradedMD)
242 if (UpgradeDebugInfo)
255 for (
const auto &
I : NamedTypes)
256 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
257 for (
const auto &
I : NumberedTypes)
258 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
264 bool LLParser::ValidateEndOfIndex() {
268 if (!ForwardRefValueInfos.empty())
269 return Error(ForwardRefValueInfos.begin()->second.front().second,
270 "use of undefined summary '^" +
271 Twine(ForwardRefValueInfos.begin()->first) +
"'");
273 if (!ForwardRefAliasees.empty())
274 return Error(ForwardRefAliasees.begin()->second.front().second,
275 "use of undefined summary '^" +
276 Twine(ForwardRefAliasees.begin()->first) +
"'");
278 if (!ForwardRefTypeIds.empty())
279 return Error(ForwardRefTypeIds.begin()->second.front().second,
280 "use of undefined type id summary '^" +
281 Twine(ForwardRefTypeIds.begin()->first) +
"'");
290 bool LLParser::ParseTopLevelEntities() {
298 if (ParseSummaryEntry())
302 if (ParseSourceFileName())
313 default:
return TokError(
"expected top-level entity");
320 if (ParseSourceFileName())
329 case lltok::exclaim:
if (ParseStandaloneMetadata())
return true;
break;
331 if (ParseSummaryEntry())
338 if (ParseUseListOrderBB())
347 bool LLParser::ParseModuleAsm() {
353 ParseStringConstant(AsmStr))
return true;
362 bool LLParser::ParseTargetDefinition() {
366 default:
return TokError(
"unknown target property");
369 if (ParseToken(
lltok::equal,
"expected '=' after target triple") ||
370 ParseStringConstant(Str))
376 if (ParseToken(
lltok::equal,
"expected '=' after target datalayout") ||
377 ParseStringConstant(Str))
379 if (DataLayoutStr.
empty())
387 bool LLParser::ParseSourceFileName() {
390 if (ParseToken(
lltok::equal,
"expected '=' after source_filename") ||
391 ParseStringConstant(SourceFileName))
402 bool LLParser::ParseDepLibs() {
405 if (ParseToken(
lltok::equal,
"expected '=' after deplibs") ||
414 if (ParseStringConstant(Str))
return true;
422 bool LLParser::ParseUnnamedType() {
427 if (ParseToken(
lltok::equal,
"expected '=' after name") ||
432 if (ParseStructDefinition(TypeLoc,
"",
433 NumberedTypes[TypeID], Result))
return true;
435 if (!isa<StructType>(Result)) {
436 std::pair<Type*, LocTy> &Entry = NumberedTypes[
TypeID];
438 return Error(TypeLoc,
"non-struct types may not be recursive");
439 Entry.first = Result;
440 Entry.second =
SMLoc();
448 bool LLParser::ParseNamedType() {
453 if (ParseToken(
lltok::equal,
"expected '=' after name") ||
458 if (ParseStructDefinition(NameLoc, Name,
459 NamedTypes[Name], Result))
return true;
461 if (!isa<StructType>(Result)) {
462 std::pair<Type*, LocTy> &Entry = NamedTypes[
Name];
464 return Error(NameLoc,
"non-struct types may not be recursive");
465 Entry.first = Result;
466 Entry.second =
SMLoc();
474 bool LLParser::ParseDeclare() {
478 std::vector<std::pair<unsigned, MDNode *>> MDs;
482 if (ParseMetadataAttachment(MDK, N))
484 MDs.push_back({MDK, N});
488 if (ParseFunctionHeader(F,
false))
497 bool LLParser::ParseDefine() {
502 return ParseFunctionHeader(F,
true) ||
503 ParseOptionalFunctionMetadata(*F) ||
504 ParseFunctionBody(*F);
510 bool LLParser::ParseGlobalType(
bool &IsConstant) {
517 return TokError(
"expected 'global' or 'constant'");
523 bool LLParser::ParseOptionalUnnamedAddr(
543 bool LLParser::ParseUnnamedGlobal() {
544 unsigned VarID = NumberedVals.size();
551 return Error(Lex.
getLoc(),
"variable expected to be numbered '%" +
555 if (ParseToken(
lltok::equal,
"expected '=' after name"))
560 unsigned Linkage,
Visibility, DLLStorageClass;
564 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
566 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
570 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
571 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
573 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
574 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
582 bool LLParser::ParseNamedGlobal() {
589 unsigned Linkage,
Visibility, DLLStorageClass;
593 if (ParseToken(
lltok::equal,
"expected '=' in global variable") ||
594 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
596 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
600 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
601 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
603 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
604 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
607 bool LLParser::parseComdat() {
617 return TokError(
"expected comdat type");
622 return TokError(
"unknown selection kind");
644 if (I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
645 return Error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
648 if (I != ComdatSymTab.
end())
661 if (ParseStringConstant(Str))
return true;
668 bool LLParser::ParseMDNodeID(
MDNode *&Result) {
672 if (ParseUInt32(MID))
676 if (NumberedMetadata.count(MID)) {
677 Result = NumberedMetadata[MID];
682 auto &FwdRef = ForwardRefMDNodes[MID];
685 Result = FwdRef.first.
get();
686 NumberedMetadata[MID].reset(Result);
692 bool LLParser::ParseNamedMetadata() {
711 if (ParseDIExpression(N,
false))
720 return ParseToken(
lltok::rbrace,
"expected end of metadata node");
725 bool LLParser::ParseStandaloneMetadata() {
728 unsigned MetadataID = 0;
731 if (ParseUInt32(MetadataID) ||
737 return TokError(
"unexpected type in metadata definition");
741 if (ParseSpecializedMDNode(Init, IsDistinct))
744 ParseMDTuple(Init, IsDistinct))
748 auto FI = ForwardRefMDNodes.find(MetadataID);
749 if (FI != ForwardRefMDNodes.end()) {
750 FI->second.first->replaceAllUsesWith(Init);
751 ForwardRefMDNodes.erase(FI);
753 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
755 if (NumberedMetadata.count(MetadataID))
756 return TokError(
"Metadata id is already used");
757 NumberedMetadata[MetadataID].reset(Init);
764 bool LLParser::SkipModuleSummaryEntry() {
772 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
774 if (ParseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
775 ParseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
779 unsigned NumOpenParen = 1;
789 return TokError(
"found end of file while parsing summary entry");
795 }
while (NumOpenParen > 0);
801 bool LLParser::ParseSummaryEntry() {
815 return SkipModuleSummaryEntry();
819 return ParseGVEntry(SummaryID);
821 return ParseModuleEntry(SummaryID);
823 return ParseTypeIdEntry(SummaryID);
826 return Error(Lex.
getLoc(),
"unexpected summary kind");
855 bool LLParser::parseIndirectSymbol(
const std::string &
Name,
LocTy NameLoc,
857 unsigned DLLStorageClass,
bool DSOLocal,
872 return Error(NameLoc,
"invalid linkage type for alias");
875 return Error(NameLoc,
876 "symbol with local linkage must have default visibility");
881 ParseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
890 if (ParseGlobalTypeAndValue(Aliasee))
898 return Error(AliaseeLoc,
"invalid aliasee");
905 return Error(AliaseeLoc,
"An alias or ifunc must have pointer type");
906 unsigned AddrSpace = PTy->getAddressSpace();
908 if (IsAlias && Ty != PTy->getElementType())
911 "explicit pointee type doesn't match operand's pointee type");
913 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
916 "explicit pointee type should be a function type");
925 if (!ForwardRefVals.erase(
Name))
926 return Error(NameLoc,
"redefinition of global '@" +
Name +
"'");
929 auto I = ForwardRefValIDs.find(NumberedVals.size());
930 if (
I != ForwardRefValIDs.end()) {
931 GVal =
I->second.first;
932 ForwardRefValIDs.erase(
I);
937 std::unique_ptr<GlobalIndirectSymbol> GA;
946 GA->setThreadLocalMode(
TLM);
949 GA->setUnnamedAddr(UnnamedAddr);
953 NumberedVals.push_back(GA.get());
957 if (GVal->
getType() != GA->getType())
960 "forward reference and definition of alias have different types");
973 assert(GA->getName() ==
Name &&
"Should not be a name conflict!");
994 bool LLParser::ParseGlobal(
const std::string &
Name,
LocTy NameLoc,
995 unsigned Linkage,
bool HasLinkage,
996 unsigned Visibility,
unsigned DLLStorageClass,
1000 return Error(NameLoc,
1001 "symbol with local linkage must have default visibility");
1004 bool IsConstant, IsExternallyInitialized;
1005 LocTy IsExternallyInitializedLoc;
1009 if (ParseOptionalAddrSpace(AddrSpace) ||
1011 IsExternallyInitialized,
1012 &IsExternallyInitializedLoc) ||
1013 ParseGlobalType(IsConstant) ||
1014 ParseType(Ty, TyLoc))
1023 if (ParseGlobalValue(Ty, Init))
1028 return Error(TyLoc,
"invalid type for global variable");
1033 if (!
Name.empty()) {
1036 if (!ForwardRefVals.erase(
Name))
1037 return Error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1040 auto I = ForwardRefValIDs.find(NumberedVals.size());
1041 if (
I != ForwardRefValIDs.end()) {
1042 GVal =
I->second.first;
1043 ForwardRefValIDs.erase(
I);
1055 "forward reference and definition of global have different types");
1057 GV = cast<GlobalVariable>(GVal);
1064 NumberedVals.push_back(GV);
1089 if (ParseOptionalAlignment(Alignment))
return true;
1092 if (ParseGlobalObjectMetadataAttachment(*GV))
1096 if (parseOptionalComdat(
Name, C))
1101 return TokError(
"unknown global variable property!");
1107 std::vector<unsigned> FwdRefAttrGrps;
1108 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1112 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1120 bool LLParser::ParseUnnamedAttrGrp() {
1126 return TokError(
"expected attribute group id");
1129 std::vector<unsigned> unused;
1135 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused,
true,
1137 ParseToken(
lltok::rbrace,
"expected end of attribute group"))
1140 if (!NumberedAttrBuilders[VarID].hasAttributes())
1141 return Error(AttrGrpLoc,
"attribute group has no attributes");
1148 bool LLParser::ParseFnAttributeValuePairs(
AttrBuilder &
B,
1149 std::vector<unsigned> &FwdRefAttrGrps,
1150 bool inAttrGrp,
LocTy &BuiltinLoc) {
1151 bool HaveError =
false;
1158 BuiltinLoc = Lex.
getLoc();
1161 if (!inAttrGrp)
return HaveError;
1162 return Error(Lex.
getLoc(),
"unterminated attribute group");
1174 "cannot have an attribute group reference in an attribute group");
1177 if (inAttrGrp)
break;
1180 FwdRefAttrGrps.push_back(AttrGrpNum);
1185 if (ParseStringAttribute(B))
1199 ParseUInt32(Alignment))
1202 if (ParseOptionalAlignment(Alignment))
1213 ParseUInt32(Alignment))
1216 if (ParseOptionalStackAlignment(Alignment))
1223 unsigned ElemSizeArg;
1226 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1239 B.
addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
break;
1289 "invalid use of attribute on a function");
1305 "invalid use of parameter-only attribute on a function");
1318 const std::string &
Name) {
1335 Error(Loc,
"global variable reference must have pointer type");
1346 auto I = ForwardRefVals.find(
Name);
1347 if (
I != ForwardRefVals.end())
1348 Val =
I->second.first;
1353 if (Val->
getType() == Ty)
return Val;
1354 Error(Loc,
"'@" +
Name +
"' defined with type '" +
1361 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1368 Error(Loc,
"global variable reference must have pointer type");
1372 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[
ID] :
nullptr;
1377 auto I = ForwardRefValIDs.find(ID);
1378 if (
I != ForwardRefValIDs.end())
1379 Val =
I->second.first;
1384 if (Val->
getType() == Ty)
return Val;
1385 Error(Loc,
"'@" +
Twine(ID) +
"' defined with type '" +
1392 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1404 if (I != ComdatSymTab.
end())
1409 ForwardRefComdats[
Name] = Loc;
1419 bool LLParser::ParseToken(
lltok::Kind T,
const char *ErrMsg) {
1421 return TokError(ErrMsg);
1428 bool LLParser::ParseStringConstant(std::string &Result) {
1430 return TokError(
"expected string constant");
1438 bool LLParser::ParseUInt32(
uint32_t &Val) {
1440 return TokError(
"expected integer");
1442 if (Val64 !=
unsigned(Val64))
1443 return TokError(
"expected 32-bit integer (too large)");
1451 bool LLParser::ParseUInt64(uint64_t &Val) {
1453 return TokError(
"expected integer");
1466 return TokError(
"expected localdynamic, initialexec or localexec");
1494 return ParseTLSModel(TLM) ||
1495 ParseToken(
lltok::rparen,
"expected ')' after thread local model");
1503 bool LLParser::ParseOptionalAddrSpace(
unsigned &AddrSpace) {
1507 return ParseToken(
lltok::lparen,
"expected '(' in address space") ||
1508 ParseUInt32(AddrSpace) ||
1515 bool LLParser::ParseStringAttribute(
AttrBuilder &B) {
1519 if (EatIfPresent(
lltok::equal) && ParseStringConstant(Val))
1526 bool LLParser::ParseOptionalParamAttrs(
AttrBuilder &B) {
1527 bool HaveError =
false;
1537 if (ParseStringAttribute(B))
1543 if (ParseOptionalAlignment(Alignment))
1611 HaveError |=
Error(Lex.
getLoc(),
"invalid use of function-only attribute");
1620 bool LLParser::ParseOptionalReturnAttrs(
AttrBuilder &B) {
1621 bool HaveError =
false;
1631 if (ParseStringAttribute(B))
1651 if (ParseOptionalAlignment(Alignment))
1671 HaveError |=
Error(Lex.
getLoc(),
"invalid use of parameter-only attribute");
1707 HaveError |=
Error(Lex.
getLoc(),
"invalid use of function-only attribute");
1712 HaveError |=
Error(Lex.
getLoc(),
"invalid use of attribute on return type");
1763 bool LLParser::ParseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
1764 unsigned &Visibility,
1765 unsigned &DLLStorageClass,
1770 ParseOptionalDSOLocal(DSOLocal);
1771 ParseOptionalVisibility(Visibility);
1772 ParseOptionalDLLStorageClass(DLLStorageClass);
1775 return Error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
1781 void LLParser::ParseOptionalDSOLocal(
bool &DSOLocal) {
1803 void LLParser::ParseOptionalVisibility(
unsigned &Res) {
1826 void LLParser::ParseOptionalDLLStorageClass(
unsigned &Res) {
1883 bool LLParser::ParseOptionalCallingConv(
unsigned &CC) {
1927 return ParseUInt32(CC);
1937 bool LLParser::ParseMetadataAttachment(
unsigned &
Kind,
MDNode *&MD) {
1944 return ParseMDNode(MD);
1949 bool LLParser::ParseInstructionMetadata(
Instruction &Inst) {
1952 return TokError(
"expected metadata after comma");
1956 if (ParseMetadataAttachment(MDK, N))
1961 InstsWithTBAATag.push_back(&Inst);
1970 bool LLParser::ParseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
1973 if (ParseMetadataAttachment(MDK, N))
1982 bool LLParser::ParseOptionalFunctionMetadata(
Function &
F) {
1984 if (ParseGlobalObjectMetadataAttachment(F))
1992 bool LLParser::ParseOptionalAlignment(
unsigned &Alignment) {
1997 if (ParseUInt32(Alignment))
return true;
1999 return Error(AlignLoc,
"alignment is not a power of two");
2001 return Error(AlignLoc,
"huge alignments are not supported yet");
2010 bool LLParser::ParseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2017 if (!EatIfPresent(AttrKind))
2021 return Error(ParenLoc,
"expected '('");
2023 if (ParseUInt64(Bytes))
return true;
2026 return Error(ParenLoc,
"expected ')'");
2028 return Error(DerefLoc,
"dereferenceable bytes must be non-zero");
2038 bool LLParser::ParseOptionalCommaAlign(
unsigned &Alignment,
2039 bool &AteExtraComma) {
2040 AteExtraComma =
false;
2044 AteExtraComma =
true;
2049 return Error(Lex.
getLoc(),
"expected metadata or 'align'");
2051 if (ParseOptionalAlignment(Alignment))
return true;
2063 bool LLParser::ParseOptionalCommaAddrSpace(
unsigned &AddrSpace,
2065 bool &AteExtraComma) {
2066 AteExtraComma =
false;
2070 AteExtraComma =
true;
2076 return Error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2078 if (ParseOptionalAddrSpace(AddrSpace))
2085 bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2089 auto StartParen = Lex.
getLoc();
2091 return Error(StartParen,
"expected '('");
2093 if (ParseUInt32(BaseSizeArg))
2097 auto HowManyAt = Lex.
getLoc();
2099 if (ParseUInt32(HowMany))
2101 if (HowMany == BaseSizeArg)
2102 return Error(HowManyAt,
2103 "'allocsize' indices can't refer to the same parameter");
2104 HowManyArg = HowMany;
2108 auto EndParen = Lex.
getLoc();
2110 return Error(EndParen,
"expected ')'");
2124 return ParseScope(SSID) || ParseOrdering(Ordering);
2134 auto StartParenAt = Lex.
getLoc();
2136 return Error(StartParenAt,
"Expected '(' in syncscope");
2139 auto SSNAt = Lex.
getLoc();
2140 if (ParseStringConstant(SSN))
2141 return Error(SSNAt,
"Expected synchronization scope name");
2143 auto EndParenAt = Lex.
getLoc();
2145 return Error(EndParenAt,
"Expected ')' in syncscope");
2159 default:
return TokError(
"Expected ordering on atomic instruction");
2178 bool LLParser::ParseOptionalStackAlignment(
unsigned &Alignment) {
2184 return Error(ParenLoc,
"expected '('");
2186 if (ParseUInt32(Alignment))
return true;
2189 return Error(ParenLoc,
"expected ')'");
2191 return Error(AlignLoc,
"stack alignment is not a power of two");
2205 bool &AteExtraComma) {
2206 AteExtraComma =
false;
2209 return TokError(
"expected ',' as start of index list");
2213 if (Indices.
empty())
return TokError(
"expected index");
2214 AteExtraComma =
true;
2218 if (ParseUInt32(Idx))
return true;
2230 bool LLParser::ParseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2234 return TokError(Msg);
2242 if (ParseAnonStructType(Result,
false))
2248 if (ParseArrayVectorType(Result,
false))
2255 if (ParseAnonStructType(Result,
true) ||
2256 ParseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2258 }
else if (ParseArrayVectorType(Result,
true))
2263 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.
getStrVal()];
2269 Entry.second = Lex.
getLoc();
2271 Result = Entry.first;
2278 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.
getUIntVal()];
2284 Entry.second = Lex.
getLoc();
2286 Result = Entry.first;
2297 if (!AllowVoid && Result->
isVoidTy())
2298 return Error(TypeLoc,
"void type only allowed for function results");
2304 return TokError(
"basic block pointers are invalid");
2306 return TokError(
"pointers to void are invalid - use i8* instead");
2308 return TokError(
"pointer to this type is invalid");
2316 return TokError(
"basic block pointers are invalid");
2318 return TokError(
"pointers to void are invalid; use i8* instead");
2320 return TokError(
"pointer to this type is invalid");
2322 if (ParseOptionalAddrSpace(AddrSpace) ||
2323 ParseToken(
lltok::star,
"expected '*' in address space"))
2332 if (ParseFunctionType(Result))
2345 PerFunctionState &PFS,
bool IsMustTailCall,
2346 bool InVarArgsFunc) {
2352 if (!ArgList.
empty() &&
2353 ParseToken(
lltok::comma,
"expected ',' in argument list"))
2358 const char *Msg =
"unexpected ellipsis in argument list for ";
2359 if (!IsMustTailCall)
2360 return TokError(
Twine(Msg) +
"non-musttail call");
2362 return TokError(
Twine(Msg) +
"musttail call in non-varargs function");
2364 return ParseToken(
lltok::rparen,
"expected ')' at end of argument list");
2369 Type *ArgTy =
nullptr;
2372 if (ParseType(ArgTy, ArgLoc))
2376 if (ParseMetadataAsValue(V, PFS))
2380 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2387 if (IsMustTailCall && InVarArgsFunc)
2388 return TokError(
"expected '...' at end of argument list for musttail call " 2389 "in varargs function");
2404 bool LLParser::ParseOptionalOperandBundles(
2412 if (!BundleList.
empty() &&
2413 ParseToken(
lltok::comma,
"expected ',' in input list"))
2417 if (ParseStringConstant(Tag))
2420 if (ParseToken(
lltok::lparen,
"expected '(' in operand bundle"))
2423 std::vector<Value *> Inputs;
2426 if (!Inputs.empty() &&
2427 ParseToken(
lltok::comma,
"expected ',' in input list"))
2431 Value *Input =
nullptr;
2432 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2434 Inputs.push_back(Input);
2437 BundleList.
emplace_back(std::move(Tag), std::move(Inputs));
2442 if (BundleList.
empty())
2443 return Error(BeginLoc,
"operand bundle set must not be empty");
2471 Type *ArgTy =
nullptr;
2475 if (ParseType(ArgTy) ||
2476 ParseOptionalParamAttrs(Attrs))
return true;
2479 return Error(TypeLoc,
"argument can not have void type");
2487 return Error(TypeLoc,
"invalid type for function argument");
2502 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs))
return true;
2505 return Error(TypeLoc,
"argument can not have void type");
2515 return Error(TypeLoc,
"invalid type for function argument");
2523 return ParseToken(
lltok::rparen,
"expected ')' at end of argument list");
2528 bool LLParser::ParseFunctionType(
Type *&Result) {
2532 return TokError(
"invalid function return type");
2536 if (ParseArgumentList(ArgList, isVarArg))
2540 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
2541 if (!ArgList[i].
Name.empty())
2542 return Error(ArgList[i].Loc,
"argument name invalid in function type");
2543 if (ArgList[i].
Attrs.hasAttributes())
2544 return Error(ArgList[i].Loc,
2545 "argument attributes invalid in function type");
2549 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
2558 bool LLParser::ParseAnonStructType(
Type *&Result,
bool Packed) {
2560 if (ParseStructBody(Elts))
return true;
2568 std::pair<Type*, LocTy> &Entry,
2571 if (Entry.first && !Entry.second.isValid())
2572 return Error(TypeLoc,
"redefinition of type");
2578 Entry.second =
SMLoc();
2583 ResultTy = Entry.first;
2595 return Error(TypeLoc,
"forward references to non-struct type");
2599 return ParseArrayVectorType(ResultTy,
true);
2600 return ParseType(ResultTy);
2604 Entry.second =
SMLoc();
2610 StructType *STy = cast<StructType>(Entry.first);
2613 if (ParseStructBody(Body) ||
2614 (isPacked && ParseToken(
lltok::greater,
"expected '>' in packed struct")))
2638 if (ParseType(Ty))
return true;
2642 return Error(EltTyLoc,
"invalid element type for struct");
2646 if (ParseType(Ty))
return true;
2649 return Error(EltTyLoc,
"invalid element type for struct");
2654 return ParseToken(
lltok::rbrace,
"expected '}' at end of struct");
2662 bool LLParser::ParseArrayVectorType(
Type *&Result,
bool isVector) {
2665 return TokError(
"expected number in address space");
2671 if (ParseToken(
lltok::kw_x,
"expected 'x' after element count"))
2675 Type *EltTy =
nullptr;
2676 if (ParseType(EltTy))
return true;
2679 "expected end of sequential type"))
2684 return Error(SizeLoc,
"zero element vector is illegal");
2685 if ((
unsigned)Size != Size)
2686 return Error(SizeLoc,
"size too large for vector");
2688 return Error(TypeLoc,
"invalid vector element type");
2692 return Error(TypeLoc,
"invalid array element type");
2709 NumberedVals.push_back(&A);
2712 LLParser::PerFunctionState::~PerFunctionState() {
2715 for (
const auto &
P : ForwardRefVals) {
2716 if (isa<BasicBlock>(
P.second.first))
2718 P.second.first->replaceAllUsesWith(
2720 P.second.first->deleteValue();
2723 for (
const auto &
P : ForwardRefValIDs) {
2724 if (isa<BasicBlock>(
P.second.first))
2726 P.second.first->replaceAllUsesWith(
2728 P.second.first->deleteValue();
2732 bool LLParser::PerFunctionState::FinishFunction() {
2733 if (!ForwardRefVals.empty())
2734 return P.Error(ForwardRefVals.begin()->second.second,
2735 "use of undefined value '%" + ForwardRefVals.begin()->first +
2737 if (!ForwardRefValIDs.empty())
2738 return P.Error(ForwardRefValIDs.begin()->second.second,
2739 "use of undefined value '%" +
2740 Twine(ForwardRefValIDs.begin()->first) +
"'");
2748 if (IsCall && isa<PointerType>(Ty)) {
2751 if (Val->
getType() == TyInProgAS)
2760 Value *LLParser::PerFunctionState::GetVal(
const std::string &
Name,
Type *Ty,
2761 LocTy Loc,
bool IsCall) {
2763 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
2768 auto I = ForwardRefVals.find(
Name);
2769 if (
I != ForwardRefVals.end())
2770 Val =
I->second.first;
2778 P.Error(Loc,
"'%" +
Name +
"' is not a basic block");
2780 P.Error(Loc,
"'%" +
Name +
"' defined with type '" +
2787 P.Error(Loc,
"invalid use of a non-first-class type");
2799 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
2803 Value *LLParser::PerFunctionState::GetVal(
unsigned ID,
Type *Ty,
LocTy Loc,
2806 Value *Val = ID < NumberedVals.size() ? NumberedVals[
ID] :
nullptr;
2811 auto I = ForwardRefValIDs.find(ID);
2812 if (
I != ForwardRefValIDs.end())
2813 Val =
I->second.first;
2821 P.Error(Loc,
"'%" +
Twine(ID) +
"' is not a basic block");
2823 P.Error(Loc,
"'%" +
Twine(ID) +
"' defined with type '" +
2829 P.Error(Loc,
"invalid use of a non-first-class type");
2841 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
2847 bool LLParser::PerFunctionState::SetInstName(
int NameID,
2848 const std::string &NameStr,
2852 if (NameID != -1 || !NameStr.empty())
2853 return P.Error(NameLoc,
"instructions returning void cannot have a name");
2859 if (NameStr.empty()) {
2862 NameID = NumberedVals.size();
2864 if (
unsigned(NameID) != NumberedVals.size())
2865 return P.Error(NameLoc,
"instruction expected to be numbered '%" +
2866 Twine(NumberedVals.size()) +
"'");
2868 auto FI = ForwardRefValIDs.find(NameID);
2869 if (FI != ForwardRefValIDs.end()) {
2870 Value *Sentinel = FI->second.first;
2872 return P.Error(NameLoc,
"instruction forward referenced with type '" +
2877 ForwardRefValIDs.erase(FI);
2880 NumberedVals.push_back(Inst);
2885 auto FI = ForwardRefVals.find(NameStr);
2886 if (FI != ForwardRefVals.end()) {
2887 Value *Sentinel = FI->second.first;
2889 return P.Error(NameLoc,
"instruction forward referenced with type '" +
2894 ForwardRefVals.erase(FI);
2900 if (Inst->
getName() != NameStr)
2901 return P.Error(NameLoc,
"multiple definition of local value named '" +
2908 BasicBlock *LLParser::PerFunctionState::GetBB(
const std::string &
Name,
2910 return dyn_cast_or_null<BasicBlock>(
2914 BasicBlock *LLParser::PerFunctionState::GetBB(
unsigned ID,
LocTy Loc) {
2915 return dyn_cast_or_null<BasicBlock>(
2922 BasicBlock *LLParser::PerFunctionState::DefineBB(
const std::string &
Name,
2926 BB = GetBB(NumberedVals.size(), Loc);
2928 BB = GetBB(
Name, Loc);
2929 if (!BB)
return nullptr;
2933 F.getBasicBlockList().splice(
F.end(),
F.getBasicBlockList(), BB);
2937 ForwardRefValIDs.erase(NumberedVals.size());
2938 NumberedVals.push_back(BB);
2941 ForwardRefVals.erase(
Name);
2957 bool LLParser::ParseValID(
ValID &ID, PerFunctionState *PFS) {
2960 default:
return TokError(
"expected value token");
3002 if (ParseGlobalValueVector(Elts) ||
3003 ParseToken(
lltok::rbrace,
"expected end of struct constant"))
3009 Elts.
size() *
sizeof(Elts[0]));
3021 if (ParseGlobalValueVector(Elts) ||
3023 ParseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3027 if (isPackedStruct) {
3030 Elts.
size() *
sizeof(Elts[0]));
3037 return Error(ID.
Loc,
"constant vector must not be empty");
3039 if (!Elts[0]->
getType()->isIntegerTy() &&
3040 !Elts[0]->getType()->isFloatingPointTy() &&
3041 !Elts[0]->getType()->isPointerTy())
3042 return Error(FirstEltLoc,
3043 "vector elements must have integer, pointer or floating point type");
3046 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3047 if (Elts[i]->
getType() != Elts[0]->getType())
3048 return Error(FirstEltLoc,
3049 "vector element #" +
Twine(i) +
3060 if (ParseGlobalValueVector(Elts) ||
3072 if (!Elts[0]->
getType()->isFirstClassType())
3073 return Error(FirstEltLoc,
"invalid array element type: " +
3079 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3080 if (Elts[i]->
getType() != Elts[0]->getType())
3081 return Error(FirstEltLoc,
3082 "array element #" +
Twine(i) +
3101 bool HasSideEffect, AlignStack, AsmDialect;
3106 ParseStringConstant(ID.
StrVal) ||
3107 ParseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3112 (
unsigned(AsmDialect)<<2);
3123 if (ParseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3125 ParseToken(
lltok::comma,
"expected comma in block address expression")||
3126 ParseValID(Label) ||
3127 ParseToken(
lltok::rparen,
"expected ')' in block address expression"))
3131 return Error(Fn.
Loc,
"expected function name in blockaddress");
3133 return Error(Label.
Loc,
"expected basic block name in blockaddress");
3138 if (Fn.
UIntVal < NumberedVals.size())
3139 GV = NumberedVals[Fn.
UIntVal];
3140 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3146 if (!isa<Function>(GV))
3147 return Error(Fn.
Loc,
"expected function name in blockaddress");
3148 F = cast<Function>(GV);
3150 return Error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3156 ForwardRefBlockAddresses.insert(std::make_pair(
3158 std::map<ValID, GlobalValue *>()))
3159 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
3172 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3174 BB = BlockAddressPFS->GetBB(Label.
UIntVal, Label.
Loc);
3176 BB = BlockAddressPFS->GetBB(Label.
StrVal, Label.
Loc);
3178 return Error(Label.
Loc,
"referenced value is not a basic block");
3181 return Error(Label.
Loc,
"cannot take address of numeric label after " 3182 "the function is defined");
3183 BB = dyn_cast_or_null<BasicBlock>(
3186 return Error(Label.
Loc,
"referenced value is not a basic block");
3208 Type *DestTy =
nullptr;
3211 if (ParseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
3212 ParseGlobalTypeAndValue(SrcVal) ||
3213 ParseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
3214 ParseType(DestTy) ||
3215 ParseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
3218 return Error(ID.
Loc,
"invalid cast opcode for cast from '" +
3230 if (ParseToken(
lltok::lparen,
"expected '(' in extractvalue constantexpr")||
3231 ParseGlobalTypeAndValue(Val) ||
3232 ParseIndexList(Indices) ||
3233 ParseToken(
lltok::rparen,
"expected ')' in extractvalue constantexpr"))
3237 return Error(ID.
Loc,
"extractvalue operand must be aggregate type");
3239 return Error(ID.
Loc,
"invalid indices for extractvalue");
3248 if (ParseToken(
lltok::lparen,
"expected '(' in insertvalue constantexpr")||
3249 ParseGlobalTypeAndValue(Val0) ||
3250 ParseToken(
lltok::comma,
"expected comma in insertvalue constantexpr")||
3251 ParseGlobalTypeAndValue(Val1) ||
3252 ParseIndexList(Indices) ||
3253 ParseToken(
lltok::rparen,
"expected ')' in insertvalue constantexpr"))
3256 return Error(ID.
Loc,
"insertvalue operand must be aggregate type");
3260 return Error(ID.
Loc,
"invalid indices for insertvalue");
3261 if (IndexedType != Val1->
getType())
3262 return Error(ID.
Loc,
"insertvalue operand and field disagree in type: '" +
3275 if (ParseCmpPredicate(PredVal, Opc) ||
3276 ParseToken(
lltok::lparen,
"expected '(' in compare constantexpr") ||
3277 ParseGlobalTypeAndValue(Val0) ||
3278 ParseToken(
lltok::comma,
"expected comma in compare constantexpr") ||
3279 ParseGlobalTypeAndValue(Val1) ||
3280 ParseToken(
lltok::rparen,
"expected ')' in compare constantexpr"))
3284 return Error(ID.
Loc,
"compare operands must have the same type");
3288 if (Opc == Instruction::FCmp) {
3290 return Error(ID.
Loc,
"fcmp requires floating point operands");
3293 assert(Opc == Instruction::ICmp &&
"Unexpected opcode for CmpInst!");
3296 return Error(ID.
Loc,
"icmp requires pointer or integer operands");
3327 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3335 }
else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3336 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3340 if (ParseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
3341 ParseGlobalTypeAndValue(Val0) ||
3342 ParseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
3343 ParseGlobalTypeAndValue(Val1) ||
3344 ParseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
3347 return Error(ID.
Loc,
"operands of constexpr must have same type");
3350 return Error(ModifierLoc,
"nuw only applies to integer operations");
3352 return Error(ModifierLoc,
"nsw only applies to integer operations");
3357 case Instruction::Sub:
3358 case Instruction::Mul:
3359 case Instruction::UDiv:
3360 case Instruction::SDiv:
3361 case Instruction::URem:
3362 case Instruction::SRem:
3363 case Instruction::Shl:
3364 case Instruction::AShr:
3365 case Instruction::LShr:
3367 return Error(ID.
Loc,
"constexpr requires integer operands");
3369 case Instruction::FAdd:
3370 case Instruction::FSub:
3371 case Instruction::FMul:
3372 case Instruction::FDiv:
3373 case Instruction::FRem:
3375 return Error(ID.
Loc,
"constexpr requires fp operands");
3396 if (ParseToken(
lltok::lparen,
"expected '(' in logical constantexpr") ||
3397 ParseGlobalTypeAndValue(Val0) ||
3398 ParseToken(
lltok::comma,
"expected comma in logical constantexpr") ||
3399 ParseGlobalTypeAndValue(Val1) ||
3400 ParseToken(
lltok::rparen,
"expected ')' in logical constantexpr"))
3403 return Error(ID.
Loc,
"operands of constexpr must have same type");
3406 "constexpr requires integer or integer vector operands");
3419 bool InBounds =
false;
3423 if (Opc == Instruction::GetElementPtr)
3426 if (ParseToken(
lltok::lparen,
"expected '(' in constantexpr"))
3430 if (Opc == Instruction::GetElementPtr) {
3431 if (ParseType(Ty) ||
3432 ParseToken(
lltok::comma,
"expected comma after getelementptr's type"))
3437 if (ParseGlobalValueVector(
3438 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp :
nullptr) ||
3442 if (Opc == Instruction::GetElementPtr) {
3443 if (Elts.
size() == 0 ||
3444 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3445 return Error(ID.
Loc,
"base of getelementptr must be a pointer");
3448 auto *BasePointerType = cast<PointerType>(BaseType->
getScalarType());
3449 if (Ty != BasePointerType->getElementType())
3452 "explicit pointee type doesn't match operand's pointee type");
3459 Type *ValTy = Val->getType();
3461 return Error(ID.
Loc,
"getelementptr index must be an integer");
3464 if (GEPWidth && (ValNumEl != GEPWidth))
3467 "getelementptr vector index has a wrong number of elements");
3470 GEPWidth = ValNumEl;
3475 if (!Indices.empty() && !Ty->
isSized(&Visited))
3476 return Error(ID.
Loc,
"base element of getelementptr must be sized");
3479 return Error(ID.
Loc,
"invalid getelementptr indices");
3482 if (*InRangeOp == 0)
3484 "inrange keyword may not appear on pointer operand");
3489 InBounds, InRangeOp);
3491 if (Elts.
size() != 3)
3492 return Error(ID.
Loc,
"expected three operands to select");
3497 }
else if (Opc == Instruction::ShuffleVector) {
3498 if (Elts.
size() != 3)
3499 return Error(ID.
Loc,
"expected three operands to shufflevector");
3501 return Error(ID.
Loc,
"invalid operands to shufflevector");
3504 }
else if (Opc == Instruction::ExtractElement) {
3505 if (Elts.
size() != 2)
3506 return Error(ID.
Loc,
"expected two operands to extractelement");
3508 return Error(ID.
Loc,
"invalid extractelement operands");
3511 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
3512 if (Elts.
size() != 3)
3513 return Error(ID.
Loc,
"expected three operands to insertelement");
3515 return Error(ID.
Loc,
"invalid insertelement operands");
3534 bool Parsed = ParseValID(ID) ||
3535 ConvertValIDToValue(Ty, ID, V,
nullptr,
false);
3536 if (V && !(C = dyn_cast<Constant>(V)))
3537 return Error(ID.
Loc,
"global values must be constants");
3541 bool LLParser::ParseGlobalTypeAndValue(
Constant *&V) {
3543 return ParseType(Ty) ||
3544 ParseGlobalValue(Ty, V);
3547 bool LLParser::parseOptionalComdat(
StringRef GlobalName,
Comdat *&C) {
3556 return TokError(
"expected comdat variable");
3559 if (ParseToken(
lltok::rparen,
"expected ')' after comdat var"))
3562 if (GlobalName.
empty())
3563 return TokError(
"comdat cannot be unnamed");
3564 C = getComdat(GlobalName, KwLoc);
3584 *InRangeOp = Elts.
size();
3587 if (ParseGlobalTypeAndValue(C))
return true;
3594 bool LLParser::ParseMDTuple(
MDNode *&MD,
bool IsDistinct) {
3596 if (ParseMDNodeVector(Elts))
3607 bool LLParser::ParseMDNode(
MDNode *&
N) {
3609 return ParseSpecializedMDNode(N);
3615 bool LLParser::ParseMDNodeTail(
MDNode *&N) {
3618 return ParseMDTuple(N);
3621 return ParseMDNodeID(N);
3627 template <
class FieldTy>
struct MDFieldImpl {
3628 typedef MDFieldImpl ImplTy;
3632 void assign(FieldTy Val) {
3634 this->Val = std::move(Val);
3637 explicit MDFieldImpl(FieldTy
Default)
3638 : Val(std::move(Default)), Seen(
false) {}
3645 template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
3646 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3657 void assign(FieldTypeA A) {
3659 this->A = std::move(A);
3663 void assign(FieldTypeB B) {
3665 this->B = std::move(B);
3669 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3670 : A(std::move(DefaultA)),
B(std::move(DefaultB)), Seen(
false),
3671 WhatIs(IsInvalid) {}
3674 struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
3678 : ImplTy(
Default), Max(Max) {}
3681 struct LineField :
public MDUnsignedField {
3682 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3685 struct ColumnField :
public MDUnsignedField {
3686 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3689 struct DwarfTagField :
public MDUnsignedField {
3695 struct DwarfMacinfoTypeField :
public MDUnsignedField {
3701 struct DwarfAttEncodingField :
public MDUnsignedField {
3705 struct DwarfVirtualityField :
public MDUnsignedField {
3709 struct DwarfLangField :
public MDUnsignedField {
3713 struct DwarfCCField :
public MDUnsignedField {
3717 struct EmissionKindField :
public MDUnsignedField {
3721 struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
3722 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3725 struct MDSignedField :
public MDFieldImpl<int64_t> {
3729 MDSignedField(int64_t
Default = 0)
3731 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
3732 : ImplTy(Default), Min(Min), Max(Max) {}
3735 struct MDBoolField :
public MDFieldImpl<bool> {
3739 struct MDField :
public MDFieldImpl<Metadata *> {
3742 MDField(
bool AllowNull =
true) : ImplTy(
nullptr), AllowNull(AllowNull) {}
3745 struct MDConstant :
public MDFieldImpl<ConstantAsMetadata *> {
3746 MDConstant() : ImplTy(
nullptr) {}
3749 struct MDStringField :
public MDFieldImpl<MDString *> {
3751 MDStringField(
bool AllowEmpty =
true)
3752 : ImplTy(
nullptr), AllowEmpty(AllowEmpty) {}
3755 struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
3759 struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
3763 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3764 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
3765 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
3767 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
3768 bool AllowNull =
true)
3769 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3771 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
3772 bool isMDField()
const {
return WhatIs == IsTypeB; }
3773 int64_t getMDSignedValue()
const {
3774 assert(isMDSignedField() &&
"Wrong field type");
3777 Metadata *getMDFieldValue()
const {
3778 assert(isMDField() &&
"Wrong field type");
3783 struct MDSignedOrUnsignedField
3784 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3785 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3787 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
3788 bool isMDUnsignedField()
const {
return WhatIs == IsTypeB; }
3789 int64_t getMDSignedValue()
const {
3790 assert(isMDSignedField() &&
"Wrong field type");
3793 uint64_t getMDUnsignedValue()
const {
3794 assert(isMDUnsignedField() &&
"Wrong field type");
3805 MDUnsignedField &Result) {
3806 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
3807 return TokError(
"expected unsigned integer");
3809 auto &U = Lex.getAPSIntVal();
3810 if (U.ugt(Result.Max))
3811 return TokError(
"value for '" + Name +
"' too large, limit is " +
3813 Result.assign(U.getZExtValue());
3814 assert(Result.Val <= Result.Max &&
"Expected value in range");
3820 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, LineField &Result) {
3821 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3824 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, ColumnField &Result) {
3825 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3829 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, DwarfTagField &Result) {
3831 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3834 return TokError(
"expected DWARF tag");
3838 return TokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
3839 assert(Tag <= Result.Max &&
"Expected valid DWARF tag");
3848 DwarfMacinfoTypeField &Result) {
3850 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3853 return TokError(
"expected DWARF macinfo type");
3858 "invalid DWARF macinfo type" +
Twine(
" '") + Lex.getStrVal() +
"'");
3859 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
3861 Result.assign(Macinfo);
3868 DwarfVirtualityField &Result) {
3870 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3873 return TokError(
"expected DWARF virtuality code");
3877 return TokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
3878 Lex.getStrVal() +
"'");
3879 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
3880 Result.assign(Virtuality);
3886 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, DwarfLangField &Result) {
3888 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3891 return TokError(
"expected DWARF language");
3895 return TokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
3897 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
3898 Result.assign(Lang);
3904 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, DwarfCCField &Result) {
3906 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3909 return TokError(
"expected DWARF calling convention");
3913 return TokError(
"invalid DWARF calling convention" +
Twine(
" '") + Lex.getStrVal() +
3915 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
3922 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, EmissionKindField &Result) {
3924 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3927 return TokError(
"expected emission kind");
3931 return TokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
3933 assert(*
Kind <= Result.Max &&
"Expected valid emission kind");
3934 Result.assign(*
Kind);
3941 DwarfAttEncodingField &Result) {
3943 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3946 return TokError(
"expected DWARF type attribute encoding");
3950 return TokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
3951 Lex.getStrVal() +
"'");
3952 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
3953 Result.assign(Encoding);
3963 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, DIFlagField &Result) {
3967 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3969 bool Res = ParseUInt32(TempVal);
3975 return TokError(
"expected debug info flag");
3979 return TokError(
Twine(
"invalid debug info flag flag '") +
3980 Lex.getStrVal() +
"'");
3994 Result.assign(Combined);
4000 MDSignedField &Result) {
4002 return TokError(
"expected signed integer");
4004 auto &S = Lex.getAPSIntVal();
4006 return TokError(
"value for '" + Name +
"' too small, limit is " +
4009 return TokError(
"value for '" + Name +
"' too large, limit is " +
4011 Result.assign(S.getExtValue());
4012 assert(Result.Val >= Result.Min &&
"Expected value in range");
4013 assert(Result.Val <= Result.Max &&
"Expected value in range");
4019 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, MDBoolField &Result) {
4020 switch (Lex.getKind()) {
4022 return TokError(
"expected 'true' or 'false'");
4024 Result.assign(
true);
4027 Result.assign(
false);
4035 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, MDField &Result) {
4037 if (!Result.AllowNull)
4038 return TokError(
"'" + Name +
"' cannot be null");
4040 Result.assign(
nullptr);
4045 if (ParseMetadata(MD,
nullptr))
4054 MDSignedOrMDField &Result) {
4057 MDSignedField Res = Result.A;
4058 if (!ParseMDField(Loc, Name, Res)) {
4066 MDField Res = Result.B;
4067 if (!ParseMDField(Loc, Name, Res)) {
4077 MDSignedOrUnsignedField &Result) {
4081 if (Lex.getAPSIntVal().isSigned()) {
4082 MDSignedField Res = Result.A;
4083 if (ParseMDField(Loc, Name, Res))
4089 MDUnsignedField Res = Result.B;
4090 if (ParseMDField(Loc, Name, Res))
4097 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, MDStringField &Result) {
4098 LocTy ValueLoc = Lex.getLoc();
4100 if (ParseStringConstant(S))
4103 if (!Result.AllowEmpty && S.empty())
4104 return Error(ValueLoc,
"'" + Name +
"' cannot be empty");
4111 bool LLParser::ParseMDField(
LocTy Loc,
StringRef Name, MDFieldList &Result) {
4113 if (ParseMDNodeVector(MDs))
4116 Result.assign(std::move(MDs));
4122 ChecksumKindField &Result) {
4128 "invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
"'");
4130 Result.assign(*CSKind);
4137 template <
class ParserTy>
4138 bool LLParser::ParseMDFieldsImplBody(ParserTy
parseField) {
4141 return TokError(
"expected field label here");
4150 template <
class ParserTy>
4151 bool LLParser::ParseMDFieldsImpl(ParserTy
parseField,
LocTy &ClosingLoc) {
4161 ClosingLoc = Lex.getLoc();
4165 template <
class FieldTy>
4166 bool LLParser::ParseMDField(
StringRef Name, FieldTy &Result) {
4168 return TokError(
"field '" + Name +
"' cannot be specified more than once");
4170 LocTy Loc = Lex.getLoc();
4172 return ParseMDField(Loc, Name, Result);
4175 bool LLParser::ParseSpecializedMDNode(
MDNode *&N,
bool IsDistinct) {
4178 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 4179 if (Lex.getStrVal() == #CLASS) \ 4180 return Parse##CLASS(N, IsDistinct); 4181 #include "llvm/IR/Metadata.def" 4183 return TokError(
"expected metadata type");
4186 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 4187 #define NOP_FIELD(NAME, TYPE, INIT) 4188 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 4190 return Error(ClosingLoc, "missing required field '" #NAME "'"); 4191 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 4192 if (Lex.getStrVal() == #NAME) \ 4193 return ParseMDField(#NAME, NAME); 4194 #define PARSE_MD_FIELDS() \ 4195 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 4198 if (ParseMDFieldsImpl([&]() -> bool { \ 4199 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 4200 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \ 4203 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 4205 #define GET_OR_DISTINCT(CLASS, ARGS) \ 4206 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 4210 bool LLParser::ParseDILocation(
MDNode *&Result,
bool IsDistinct) {
4211 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4212 OPTIONAL(line, LineField, ); \ 4213 OPTIONAL(column, ColumnField, ); \ 4214 REQUIRED(scope, MDField, ( false)); \ 4215 OPTIONAL(inlinedAt, MDField, ); 4217 #undef VISIT_MD_FIELDS 4226 bool LLParser::ParseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
4227 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4228 REQUIRED(tag, DwarfTagField, ); \ 4229 OPTIONAL(header, MDStringField, ); \ 4230 OPTIONAL(operands, MDFieldList, ); 4232 #undef VISIT_MD_FIELDS 4235 (
Context, tag.Val, header.Val, operands.Val));
4242 bool LLParser::ParseDISubrange(
MDNode *&Result,
bool IsDistinct) {
4243 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4244 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 4245 OPTIONAL(lowerBound, MDSignedField, ); 4247 #undef VISIT_MD_FIELDS 4249 if (
count.isMDSignedField())
4252 else if (
count.isMDField())
4263 bool LLParser::ParseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
4264 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4265 REQUIRED(name, MDStringField, ); \ 4266 REQUIRED(value, MDSignedOrUnsignedField, ); \ 4267 OPTIONAL(isUnsigned, MDBoolField, (false)); 4269 #undef VISIT_MD_FIELDS 4271 if (isUnsigned.Val && value.isMDSignedField())
4272 return TokError(
"unsigned enumerator with negative value");
4274 int64_t
Value = value.isMDSignedField()
4275 ? value.getMDSignedValue()
4276 :
static_cast<int64_t
>(value.getMDUnsignedValue());
4285 bool LLParser::ParseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
4286 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4287 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 4288 OPTIONAL(name, MDStringField, ); \ 4289 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4290 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4291 OPTIONAL(encoding, DwarfAttEncodingField, ); 4293 #undef VISIT_MD_FIELDS 4296 align.Val, encoding.Val));
4305 bool LLParser::ParseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
4306 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4307 REQUIRED(tag, DwarfTagField, ); \ 4308 OPTIONAL(name, MDStringField, ); \ 4309 OPTIONAL(file, MDField, ); \ 4310 OPTIONAL(line, LineField, ); \ 4311 OPTIONAL(scope, MDField, ); \ 4312 REQUIRED(baseType, MDField, ); \ 4313 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4314 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4315 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4316 OPTIONAL(flags, DIFlagField, ); \ 4317 OPTIONAL(extraData, MDField, ); \ 4318 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); 4320 #undef VISIT_MD_FIELDS 4323 if (dwarfAddressSpace.Val != UINT32_MAX)
4324 DWARFAddressSpace = dwarfAddressSpace.Val;
4328 scope.Val, baseType.Val,
size.Val, align.Val,
4329 offset.Val, DWARFAddressSpace, flags.Val,
4334 bool LLParser::ParseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
4335 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4336 REQUIRED(tag, DwarfTagField, ); \ 4337 OPTIONAL(name, MDStringField, ); \ 4338 OPTIONAL(file, MDField, ); \ 4339 OPTIONAL(line, LineField, ); \ 4340 OPTIONAL(scope, MDField, ); \ 4341 OPTIONAL(baseType, MDField, ); \ 4342 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4343 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4344 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4345 OPTIONAL(flags, DIFlagField, ); \ 4346 OPTIONAL(elements, MDField, ); \ 4347 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4348 OPTIONAL(vtableHolder, MDField, ); \ 4349 OPTIONAL(templateParams, MDField, ); \ 4350 OPTIONAL(identifier, MDStringField, ); \ 4351 OPTIONAL(discriminator, MDField, ); 4353 #undef VISIT_MD_FIELDS 4359 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val,
4360 elements.Val, runtimeLang.Val, vtableHolder.Val,
4361 templateParams.Val, discriminator.Val)) {
4370 (
Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
4371 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4372 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4373 discriminator.Val));
4377 bool LLParser::ParseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
4378 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4379 OPTIONAL(flags, DIFlagField, ); \ 4380 OPTIONAL(cc, DwarfCCField, ); \ 4381 REQUIRED(types, MDField, ); 4383 #undef VISIT_MD_FIELDS 4386 (
Context, flags.Val, cc.Val, types.Val));
4395 bool LLParser::ParseDIFile(
MDNode *&Result,
bool IsDistinct) {
4399 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4400 REQUIRED(filename, MDStringField, ); \ 4401 REQUIRED(directory, MDStringField, ); \ 4402 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 4403 OPTIONAL(checksum, MDStringField, ); \ 4404 OPTIONAL(source, MDStringField, ); 4406 #undef VISIT_MD_FIELDS 4409 if (checksumkind.Seen && checksum.Seen)
4410 OptChecksum.
emplace(checksumkind.Val, checksum.Val);
4411 else if (checksumkind.Seen || checksum.Seen)
4412 return Lex.Error(
"'checksumkind' and 'checksum' must be provided together");
4416 OptSource = source.Val;
4418 OptChecksum, OptSource));
4428 bool LLParser::ParseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
4430 return Lex.Error(
"missing 'distinct', required for !DICompileUnit");
4432 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4433 REQUIRED(language, DwarfLangField, ); \ 4434 REQUIRED(file, MDField, ( false)); \ 4435 OPTIONAL(producer, MDStringField, ); \ 4436 OPTIONAL(isOptimized, MDBoolField, ); \ 4437 OPTIONAL(flags, MDStringField, ); \ 4438 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4439 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4440 OPTIONAL(emissionKind, EmissionKindField, ); \ 4441 OPTIONAL(enums, MDField, ); \ 4442 OPTIONAL(retainedTypes, MDField, ); \ 4443 OPTIONAL(globals, MDField, ); \ 4444 OPTIONAL(imports, MDField, ); \ 4445 OPTIONAL(macros, MDField, ); \ 4446 OPTIONAL(dwoId, MDUnsignedField, ); \ 4447 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4448 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 4449 OPTIONAL(gnuPubnames, MDBoolField, = false); 4451 #undef VISIT_MD_FIELDS 4454 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
4455 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4456 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
4457 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
4469 bool LLParser::ParseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
4470 auto Loc = Lex.getLoc();
4471 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4472 OPTIONAL(scope, MDField, ); \ 4473 OPTIONAL(name, MDStringField, ); \ 4474 OPTIONAL(linkageName, MDStringField, ); \ 4475 OPTIONAL(file, MDField, ); \ 4476 OPTIONAL(line, LineField, ); \ 4477 OPTIONAL(type, MDField, ); \ 4478 OPTIONAL(isLocal, MDBoolField, ); \ 4479 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4480 OPTIONAL(scopeLine, LineField, ); \ 4481 OPTIONAL(containingType, MDField, ); \ 4482 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4483 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4484 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4485 OPTIONAL(flags, DIFlagField, ); \ 4486 OPTIONAL(isOptimized, MDBoolField, ); \ 4487 OPTIONAL(unit, MDField, ); \ 4488 OPTIONAL(templateParams, MDField, ); \ 4489 OPTIONAL(declaration, MDField, ); \ 4490 OPTIONAL(retainedNodes, MDField, ); \ 4491 OPTIONAL(thrownTypes, MDField, ); 4493 #undef VISIT_MD_FIELDS 4495 if (isDefinition.Val && !IsDistinct)
4498 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4503 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4504 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4505 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4506 declaration.Val, retainedNodes.Val, thrownTypes.Val));
4512 bool LLParser::ParseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
4513 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4514 REQUIRED(scope, MDField, ( false)); \ 4515 OPTIONAL(file, MDField, ); \ 4516 OPTIONAL(line, LineField, ); \ 4517 OPTIONAL(column, ColumnField, ); 4519 #undef VISIT_MD_FIELDS 4528 bool LLParser::ParseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
4529 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4530 REQUIRED(scope, MDField, ( false)); \ 4531 OPTIONAL(file, MDField, ); \ 4532 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 4534 #undef VISIT_MD_FIELDS 4537 (
Context, scope.Val,
file.Val, discriminator.Val));
4543 bool LLParser::ParseDINamespace(
MDNode *&Result,
bool IsDistinct) {
4544 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4545 REQUIRED(scope, MDField, ); \ 4546 OPTIONAL(name, MDStringField, ); \ 4547 OPTIONAL(exportSymbols, MDBoolField, ); 4549 #undef VISIT_MD_FIELDS 4552 (
Context, scope.Val,
name.Val, exportSymbols.Val));
4558 bool LLParser::ParseDIMacro(
MDNode *&Result,
bool IsDistinct) {
4559 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4560 REQUIRED(type, DwarfMacinfoTypeField, ); \ 4561 OPTIONAL(line, LineField, ); \ 4562 REQUIRED(name, MDStringField, ); \ 4563 OPTIONAL(value, MDStringField, ); 4565 #undef VISIT_MD_FIELDS 4574 bool LLParser::ParseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
4575 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4576 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 4577 OPTIONAL(line, LineField, ); \ 4578 REQUIRED(file, MDField, ); \ 4579 OPTIONAL(nodes, MDField, ); 4581 #undef VISIT_MD_FIELDS 4591 bool LLParser::ParseDIModule(
MDNode *&Result,
bool IsDistinct) {
4592 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4593 REQUIRED(scope, MDField, ); \ 4594 REQUIRED(name, MDStringField, ); \ 4595 OPTIONAL(configMacros, MDStringField, ); \ 4596 OPTIONAL(includePath, MDStringField, ); \ 4597 OPTIONAL(isysroot, MDStringField, ); 4599 #undef VISIT_MD_FIELDS 4602 configMacros.Val, includePath.Val, isysroot.Val));
4608 bool LLParser::ParseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
4609 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4610 OPTIONAL(name, MDStringField, ); \ 4611 REQUIRED(type, MDField, ); 4613 #undef VISIT_MD_FIELDS 4623 bool LLParser::ParseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
4624 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4625 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 4626 OPTIONAL(name, MDStringField, ); \ 4627 OPTIONAL(type, MDField, ); \ 4628 REQUIRED(value, MDField, ); 4630 #undef VISIT_MD_FIELDS 4641 bool LLParser::ParseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
4642 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4643 REQUIRED(name, MDStringField, ( false)); \ 4644 OPTIONAL(scope, MDField, ); \ 4645 OPTIONAL(linkageName, MDStringField, ); \ 4646 OPTIONAL(file, MDField, ); \ 4647 OPTIONAL(line, LineField, ); \ 4648 OPTIONAL(type, MDField, ); \ 4649 OPTIONAL(isLocal, MDBoolField, ); \ 4650 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4651 OPTIONAL(declaration, MDField, ); \ 4652 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 4654 #undef VISIT_MD_FIELDS 4658 file.Val, line.Val,
type.Val, isLocal.Val,
4659 isDefinition.Val, declaration.Val, align.Val));
4670 bool LLParser::ParseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
4671 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4672 REQUIRED(scope, MDField, ( false)); \ 4673 OPTIONAL(name, MDStringField, ); \ 4674 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 4675 OPTIONAL(file, MDField, ); \ 4676 OPTIONAL(line, LineField, ); \ 4677 OPTIONAL(type, MDField, ); \ 4678 OPTIONAL(flags, DIFlagField, ); \ 4679 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 4681 #undef VISIT_MD_FIELDS 4685 type.Val, arg.Val, flags.Val, align.Val));
4691 bool LLParser::ParseDILabel(
MDNode *&Result,
bool IsDistinct) {
4692 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4693 REQUIRED(scope, MDField, ( false)); \ 4694 REQUIRED(name, MDStringField, ); \ 4695 REQUIRED(file, MDField, ); \ 4696 REQUIRED(line, LineField, ); 4698 #undef VISIT_MD_FIELDS 4707 bool LLParser::ParseDIExpression(
MDNode *&Result,
bool IsDistinct) {
4723 return TokError(
Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
4726 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
4727 return TokError(
"expected unsigned integer");
4729 auto &U = Lex.getAPSIntVal();
4745 bool LLParser::ParseDIGlobalVariableExpression(
MDNode *&Result,
4747 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4748 REQUIRED(var, MDField, ); \ 4749 REQUIRED(expr, MDField, ); 4751 #undef VISIT_MD_FIELDS 4761 bool LLParser::ParseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
4762 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4763 OPTIONAL(name, MDStringField, ); \ 4764 OPTIONAL(file, MDField, ); \ 4765 OPTIONAL(line, LineField, ); \ 4766 OPTIONAL(setter, MDStringField, ); \ 4767 OPTIONAL(getter, MDStringField, ); \ 4768 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 4769 OPTIONAL(type, MDField, ); 4771 #undef VISIT_MD_FIELDS 4782 bool LLParser::ParseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
4783 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4784 REQUIRED(tag, DwarfTagField, ); \ 4785 REQUIRED(scope, MDField, ); \ 4786 OPTIONAL(entity, MDField, ); \ 4787 OPTIONAL(file, MDField, ); \ 4788 OPTIONAL(line, LineField, ); \ 4789 OPTIONAL(name, MDStringField, ); 4791 #undef VISIT_MD_FIELDS 4795 (
Context, tag.Val, scope.Val, entity.Val,
file.Val, line.Val,
name.Val));
4799 #undef PARSE_MD_FIELD 4801 #undef REQUIRE_FIELD 4802 #undef DECLARE_FIELD 4811 bool LLParser::ParseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
4814 if (ParseMetadata(MD, &PFS))
4825 bool LLParser::ParseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
4826 PerFunctionState *PFS) {
4829 if (ParseType(Ty, TypeMsg, Loc))
4832 return Error(Loc,
"invalid metadata-value-metadata roundtrip");
4835 if (ParseValue(Ty, V, PFS))
4850 bool LLParser::ParseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
4853 if (ParseSpecializedMDNode(N))
4862 return ParseValueAsMetadata(MD,
"expected metadata operand", PFS);
4872 if (ParseMDString(S))
4882 if (ParseMDNodeTail(N))
4892 bool LLParser::ConvertValIDToValue(
Type *Ty,
ValID &ID,
Value *&V,
4893 PerFunctionState *PFS,
bool IsCall) {
4895 return Error(ID.
Loc,
"functions are not values, refer to them as pointers");
4899 if (!PFS)
return Error(ID.
Loc,
"invalid use of function-local name");
4900 V = PFS->GetVal(ID.
UIntVal, Ty, ID.
Loc, IsCall);
4901 return V ==
nullptr;
4903 if (!PFS)
return Error(ID.
Loc,
"invalid use of function-local name");
4904 V = PFS->GetVal(ID.
StrVal, Ty, ID.
Loc, IsCall);
4905 return V ==
nullptr;
4908 return Error(ID.
Loc,
"invalid type for inline asm constraint string");
4915 V = GetGlobalVal(ID.
StrVal, Ty, ID.
Loc);
4916 return V ==
nullptr;
4919 return V ==
nullptr;
4922 return Error(ID.
Loc,
"integer constant must have integer type");
4929 return Error(ID.
Loc,
"floating point constant invalid for type");
4945 return Error(ID.
Loc,
"floating point constant does not have type '" +
4951 return Error(ID.
Loc,
"null must be a pointer type");
4957 return Error(ID.
Loc,
"invalid type for undef constant");
4961 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4962 return Error(ID.
Loc,
"invalid empty array initializer");
4968 return Error(ID.
Loc,
"invalid type for null constant");
4973 return Error(ID.
Loc,
"invalid type for none constant");
4978 return Error(ID.
Loc,
"constant expression type mismatch");
4987 "initializer with struct type has wrong # elements");
4989 return Error(ID.
Loc,
"packed'ness of initializer and type don't match");
4992 for (
unsigned i = 0, e = ID.
UIntVal; i != e; ++i)
4995 " of struct initializer doesn't match struct element type");
5000 return Error(ID.
Loc,
"constant expression type mismatch");
5006 bool LLParser::parseConstantValue(
Type *Ty,
Constant *&C) {
5009 auto Loc = Lex.getLoc();
5010 if (ParseValID(ID,
nullptr))
5020 if (ConvertValIDToValue(Ty, ID, V,
nullptr,
false))
5022 assert(isa<Constant>(V) &&
"Expected a constant value");
5023 C = cast<Constant>(V);
5030 return Error(Loc,
"expected a constant value");
5034 bool LLParser::ParseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
5037 return ParseValID(ID, PFS) ||
5038 ConvertValIDToValue(Ty, ID, V, PFS,
false);
5041 bool LLParser::ParseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
5043 return ParseType(Ty) ||
5044 ParseValue(Ty, V, PFS);
5048 PerFunctionState &PFS) {
5051 if (ParseTypeAndValue(V, PFS))
return true;
5052 if (!isa<BasicBlock>(V))
5053 return Error(Loc,
"expected a basic block");
5054 BB = cast<BasicBlock>(V);
5063 bool LLParser::ParseFunctionHeader(
Function *&Fn,
bool isDefine) {
5065 LocTy LinkageLoc = Lex.getLoc();
5068 unsigned DLLStorageClass;
5073 Type *RetType =
nullptr;
5074 LocTy RetTypeLoc = Lex.getLoc();
5075 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5077 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5078 ParseType(RetType, RetTypeLoc,
true ))
5087 return Error(LinkageLoc,
"invalid linkage for function definition");
5097 return Error(LinkageLoc,
"invalid linkage for function declaration");
5101 return Error(LinkageLoc,
"invalid function linkage type");
5105 return Error(LinkageLoc,
5106 "symbol with local linkage must have default visibility");
5109 return Error(RetTypeLoc,
"invalid function return type");
5111 LocTy NameLoc = Lex.getLoc();
5113 std::string FunctionName;
5115 FunctionName = Lex.getStrVal();
5117 unsigned NameID = Lex.getUIntVal();
5119 if (NameID != NumberedVals.size())
5120 return TokError(
"function expected to be numbered '%" +
5121 Twine(NumberedVals.size()) +
"'");
5123 return TokError(
"expected function name");
5129 return TokError(
"expected '(' in function argument list");
5134 std::vector<unsigned> FwdRefAttrGrps;
5145 if (ParseArgumentList(ArgList, isVarArg) ||
5146 ParseOptionalUnnamedAddr(UnnamedAddr) ||
5147 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
5150 ParseStringConstant(Section)) ||
5151 parseOptionalComdat(FunctionName, C) ||
5152 ParseOptionalAlignment(Alignment) ||
5154 ParseStringConstant(GC)) ||
5156 ParseGlobalTypeAndValue(Prefix)) ||
5158 ParseGlobalTypeAndValue(Prologue)) ||
5160 ParseGlobalTypeAndValue(PersonalityFn)))
5163 if (FuncAttrs.
contains(Attribute::Builtin))
5164 return Error(BuiltinLoc,
"'builtin' attribute not valid on function");
5174 std::vector<Type*> ParamTypeList;
5177 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
5178 ParamTypeList.push_back(ArgList[i].Ty);
5187 return Error(RetTypeLoc,
"functions with 'sret' argument must return void");
5194 if (!FunctionName.empty()) {
5197 auto FRVI = ForwardRefVals.find(FunctionName);
5198 if (FRVI != ForwardRefVals.end()) {
5199 Fn = M->getFunction(FunctionName);
5201 return Error(FRVI->second.second,
"invalid forward reference to " 5202 "function as global value!");
5204 return Error(FRVI->second.second,
"invalid forward reference to " 5205 "function '" + FunctionName +
"' with wrong type!");
5207 ForwardRefVals.erase(FRVI);
5208 }
else if ((Fn = M->getFunction(FunctionName))) {
5210 return Error(NameLoc,
"invalid redefinition of function '" +
5211 FunctionName +
"'");
5212 }
else if (M->getNamedValue(FunctionName)) {
5213 return Error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
5219 auto I = ForwardRefValIDs.find(NumberedVals.size());
5220 if (
I != ForwardRefValIDs.end()) {
5221 Fn = cast<Function>(
I->second.first);
5223 return Error(NameLoc,
"type of definition and forward reference of '@" +
5224 Twine(NumberedVals.size()) +
"' disagree");
5225 ForwardRefValIDs.erase(
I);
5232 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5234 if (FunctionName.empty())
5235 NumberedVals.push_back(Fn);
5248 if (!GC.empty()) Fn->
setGC(GC);
5251 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5255 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i, ++ArgIt) {
5257 if (ArgList[i].Name.
empty())
continue;
5260 ArgIt->
setName(ArgList[i].Name);
5262 if (ArgIt->
getName() != ArgList[i].Name)
5263 return Error(ArgList[i].Loc,
"redefinition of argument '%" +
5264 ArgList[i].Name +
"'");
5272 if (FunctionName.empty()) {
5274 ID.
UIntVal = NumberedVals.size() - 1;
5277 ID.
StrVal = FunctionName;
5279 auto Blocks = ForwardRefBlockAddresses.find(ID);
5280 if (Blocks != ForwardRefBlockAddresses.end())
5281 return Error(Blocks->first.Loc,
5282 "cannot take blockaddress inside a declaration");
5286 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5296 auto Blocks =
P.ForwardRefBlockAddresses.find(ID);
5297 if (Blocks ==
P.ForwardRefBlockAddresses.end())
5300 for (
const auto &
I : Blocks->second) {
5301 const ValID &BBID =
I.first;
5305 "Expected local id or name");
5312 return P.Error(BBID.
Loc,
"referenced value is not a basic block");
5318 P.ForwardRefBlockAddresses.erase(Blocks);
5324 bool LLParser::ParseFunctionBody(
Function &Fn) {
5326 return TokError(
"expected '{' in function body");
5330 if (!Fn.
hasName()) FunctionNumber = NumberedVals.size()-1;
5332 PerFunctionState PFS(*
this, Fn, FunctionNumber);
5336 if (PFS.resolveForwardRefBlockAddresses())
5342 return TokError(
"function body requires at least one basic block");
5346 if (ParseBasicBlock(PFS))
return true;
5349 if (ParseUseListOrder(&PFS))
5356 return PFS.FinishFunction();
5361 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5364 LocTy NameLoc = Lex.getLoc();
5366 Name = Lex.getStrVal();
5370 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
5372 return Error(NameLoc,
5373 "unable to create block named '" + Name +
"'");
5375 std::string NameStr;
5382 LocTy NameLoc = Lex.getLoc();
5387 NameID = Lex.getUIntVal();
5389 if (ParseToken(
lltok::equal,
"expected '=' after instruction id"))
5392 NameStr = Lex.getStrVal();
5394 if (ParseToken(
lltok::equal,
"expected '=' after instruction name"))
5398 switch (ParseInstruction(Inst, BB, PFS)) {
5400 case InstError:
return true;
5407 if (ParseInstructionMetadata(*Inst))
5410 case InstExtraComma:
5415 if (ParseInstructionMetadata(*Inst))
5421 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst))
return true;
5422 }
while (!isa<TerminatorInst>(Inst));
5434 PerFunctionState &PFS) {
5437 return TokError(
"found end of file when expecting more instructions");
5438 LocTy Loc = Lex.getLoc();
5439 unsigned KeywordVal = Lex.getUIntVal();
5443 default:
return Error(Loc,
"expected instruction opcode");
5466 if (ParseArithmetic(Inst, PFS, KeywordVal, 1))
return true;
5468 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
5469 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
5478 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5492 if (ParseArithmetic(Inst, PFS, KeywordVal, 1))
return true;
5493 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
5498 case lltok::kw_srem:
return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5501 case lltok::kw_xor:
return ParseLogical(Inst, PFS, KeywordVal);
5505 int Res = ParseCompare(Inst, PFS, KeywordVal);
5554 bool LLParser::ParseCmpPredicate(
unsigned &
P,
unsigned Opc) {
5555 if (Opc == Instruction::FCmp) {
5556 switch (Lex.getKind()) {
5557 default:
return TokError(
"expected fcmp predicate (e.g. 'oeq')");
5576 switch (Lex.getKind()) {
5577 default:
return TokError(
"expected icmp predicate (e.g. 'eq')");
5602 PerFunctionState &PFS) {
5603 SMLoc TypeLoc = Lex.getLoc();
5605 if (ParseType(Ty,
true ))
return true;
5607 Type *ResType = PFS.getFunction().getReturnType();
5611 return Error(TypeLoc,
"value doesn't match function result type '" +
5619 if (ParseValue(Ty, RV, PFS))
return true;
5622 return Error(TypeLoc,
"value doesn't match function result type '" +
5632 bool LLParser::ParseBr(
Instruction *&Inst, PerFunctionState &PFS) {
5636 if (ParseTypeAndValue(Op0, Loc, PFS))
return true;
5638 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5644 return Error(Loc,
"branch condition must have 'i1' type");
5646 if (ParseToken(
lltok::comma,
"expected ',' after branch condition") ||
5647 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5648 ParseToken(
lltok::comma,
"expected ',' after true destination") ||
5649 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5661 bool LLParser::ParseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
5662 LocTy CondLoc, BBLoc;
5665 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5666 ParseToken(
lltok::comma,
"expected ',' after switch condition") ||
5667 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5672 return Error(CondLoc,
"switch condition must have integer type");
5681 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5682 ParseToken(
lltok::comma,
"expected ',' after case value") ||
5683 ParseTypeAndBasicBlock(DestBB, PFS))
5686 if (!SeenCases.
insert(Constant).second)
5687 return Error(CondLoc,
"duplicate case value in switch");
5688 if (!isa<ConstantInt>(Constant))
5689 return Error(CondLoc,
"case value is not a constant integer");
5691 Table.
push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5697 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
5698 SI->
addCase(Table[i].first, Table[i].second);
5706 bool LLParser::ParseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
5709 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5710 ParseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
5715 return Error(AddrLoc,
"indirectbr address must have pointer type");
5722 if (ParseTypeAndBasicBlock(DestBB, PFS))
5727 if (ParseTypeAndBasicBlock(DestBB, PFS))
5733 if (ParseToken(
lltok::rsquare,
"expected ']' at end of block list"))
5737 for (
unsigned i = 0, e = DestList.
size(); i != e; ++i)
5746 bool LLParser::ParseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
5747 LocTy CallLoc = Lex.getLoc();
5749 std::vector<unsigned> FwdRefAttrGrps;
5752 Type *RetType =
nullptr;
5759 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5760 ParseType(RetType, RetTypeLoc,
true ) ||
5761 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5762 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
5764 ParseOptionalOperandBundles(BundleList, PFS) ||
5766 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5768 ParseTypeAndBasicBlock(UnwindBB, PFS))
5777 std::vector<Type*> ParamTypes;
5778 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
5779 ParamTypes.push_back(ArgList[i].V->getType());
5782 return Error(RetTypeLoc,
"Invalid result type for LLVM function");
5803 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
5804 Type *ExpectedTy =
nullptr;
5808 return Error(ArgList[i].Loc,
"too many arguments specified");
5811 if (ExpectedTy && ExpectedTy != ArgList[i].V->
getType())
5812 return Error(ArgList[i].Loc,
"argument is not of expected type '" +
5819 return Error(CallLoc,
"not enough parameters specified for call");
5822 return Error(CallLoc,
"invoke instructions may not have an alignment");
5833 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5840 bool LLParser::ParseResume(
Instruction *&Inst, PerFunctionState &PFS) {
5842 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5851 PerFunctionState &PFS) {
5852 if (ParseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
5857 if (!Args.
empty() &&
5858 ParseToken(
lltok::comma,
"expected ',' in argument list"))
5863 Type *ArgTy =
nullptr;
5864 if (ParseType(ArgTy, ArgLoc))
5869 if (ParseMetadataAsValue(V, PFS))
5872 if (ParseValue(ArgTy, V, PFS))
5884 bool LLParser::ParseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
5885 Value *CleanupPad =
nullptr;
5887 if (ParseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
5902 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5913 bool LLParser::ParseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
5914 Value *CatchPad =
nullptr;
5916 if (ParseToken(
lltok::kw_from,
"expected 'from' after catchret"))
5923 if (ParseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
5924 ParseTypeAndBasicBlock(BB, PFS))
5933 bool LLParser::ParseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
5941 return TokError(
"expected scope value for catchswitch");
5946 if (ParseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
5952 if (ParseTypeAndBasicBlock(DestBB, PFS))
5957 if (ParseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
5961 "expected 'unwind' after catchswitch scope"))
5969 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5983 bool LLParser::ParseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
5984 Value *CatchSwitch =
nullptr;
5990 return TokError(
"expected scope value for catchpad");
5996 if (ParseExceptionArgs(Args, PFS))
6005 bool LLParser::ParseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
6006 Value *ParentPad =
nullptr;
6013 return TokError(
"expected scope value for cleanuppad");
6019 if (ParseExceptionArgs(Args, PFS))
6035 bool LLParser::ParseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
6038 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6039 ParseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
6040 ParseValue(LHS->
getType(), RHS, PFS))
6044 switch (OperandType) {
6055 return Error(Loc,
"invalid operand type for instruction");
6063 bool LLParser::ParseLogical(
Instruction *&Inst, PerFunctionState &PFS,
6066 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6067 ParseToken(
lltok::comma,
"expected ',' in logical operation") ||
6068 ParseValue(LHS->
getType(), RHS, PFS))
6072 return Error(Loc,
"instruction requires integer or integer vector operands");
6081 bool LLParser::ParseCompare(
Instruction *&Inst, PerFunctionState &PFS,
6087 if (ParseCmpPredicate(Pred, Opc) ||
6088 ParseTypeAndValue(LHS, Loc, PFS) ||
6089 ParseToken(
lltok::comma,
"expected ',' after compare value") ||
6090 ParseValue(LHS->
getType(), RHS, PFS))
6093 if (Opc == Instruction::FCmp) {
6095 return Error(Loc,
"fcmp requires floating point operands");
6098 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
6101 return Error(Loc,
"icmp requires integer operands");
6114 bool LLParser::ParseCast(
Instruction *&Inst, PerFunctionState &PFS,
6118 Type *DestTy =
nullptr;
6119 if (ParseTypeAndValue(Op, Loc, PFS) ||
6120 ParseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
6126 return Error(Loc,
"invalid cast opcode for cast from '" +
6136 bool LLParser::ParseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
6138 Value *Op0, *Op1, *Op2;
6139 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6140 ParseToken(
lltok::comma,
"expected ',' after select condition") ||
6141 ParseTypeAndValue(Op1, PFS) ||
6142 ParseToken(
lltok::comma,
"expected ',' after select value") ||
6143 ParseTypeAndValue(Op2, PFS))
6147 return Error(Loc, Reason);
6155 bool LLParser::ParseVA_Arg(
Instruction *&Inst, PerFunctionState &PFS) {
6157 Type *EltTy =
nullptr;
6159 if (ParseTypeAndValue(Op, PFS) ||
6160 ParseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
6161 ParseType(EltTy, TypeLoc))
6165 return Error(TypeLoc,
"va_arg requires operand with first class type");
6173 bool LLParser::ParseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
6176 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6177 ParseToken(
lltok::comma,
"expected ',' after extract value") ||
6178 ParseTypeAndValue(Op1, PFS))
6182 return Error(Loc,
"invalid extractelement operands");
6190 bool LLParser::ParseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
6192 Value *Op0, *Op1, *Op2;
6193 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6194 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
6195 ParseTypeAndValue(Op1, PFS) ||
6196 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
6197 ParseTypeAndValue(Op2, PFS))
6201 return Error(Loc,
"invalid insertelement operands");
6209 bool LLParser::ParseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
6211 Value *Op0, *Op1, *Op2;
6212 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6213 ParseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
6214 ParseTypeAndValue(Op1, PFS) ||
6215 ParseToken(
lltok::comma,
"expected ',' after shuffle value") ||
6216 ParseTypeAndValue(Op2, PFS))
6220 return Error(Loc,
"invalid shufflevector operands");
6228 int LLParser::ParsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
6232 if (ParseType(Ty, TypeLoc) ||
6234 ParseValue(Ty, Op0, PFS) ||
6235 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
6240 bool AteExtraComma =
false;
6244 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6250 AteExtraComma =
true;
6254 if (ParseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
6255 ParseValue(Ty, Op0, PFS) ||
6256 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
6263 return Error(TypeLoc,
"phi node must have first class type");
6266 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
6267 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
6269 return AteExtraComma ? InstExtraComma : InstNormal;
6278 bool LLParser::ParseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
6281 if (ParseType(Ty, TyLoc))
6294 return TokError(
"expected 'catch' or 'filter' clause type");
6298 if (ParseTypeAndValue(V, VLoc, PFS))
6304 if (isa<ArrayType>(V->
getType()))
6305 Error(VLoc,
"'catch' clause has an invalid type");
6307 if (!isa<ArrayType>(V->
getType()))
6308 Error(VLoc,
"'filter' clause has an invalid type");
6313 return Error(VLoc,
"clause argument must be a constant");
6317 Inst = LP.release();
6330 bool LLParser::ParseCall(
Instruction *&Inst, PerFunctionState &PFS,
6333 std::vector<unsigned> FwdRefAttrGrps;
6336 Type *RetType =
nullptr;
6341 LocTy CallLoc = Lex.getLoc();
6345 "expected 'tail call', 'musttail call', or 'notail call'"))
6350 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6351 ParseType(RetType, RetTypeLoc,
true ) ||
6352 ParseValID(CalleeID) ||
6354 PFS.getFunction().isVarArg()) ||
6355 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
6356 ParseOptionalOperandBundles(BundleList, PFS))
6360 return Error(CallLoc,
"fast-math-flags specified for call without " 6361 "floating-point scalar or vector return type");
6369 std::vector<Type*> ParamTypes;
6370 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
6371 ParamTypes.push_back(ArgList[i].V->getType());
6374 return Error(RetTypeLoc,
"Invalid result type for LLVM function");
6396 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
6397 Type *ExpectedTy =
nullptr;
6401 return Error(ArgList[i].Loc,
"too many arguments specified");
6404 if (ExpectedTy && ExpectedTy != ArgList[i].V->
getType())
6405 return Error(ArgList[i].Loc,
"argument is not of expected type '" +
6412 return Error(CallLoc,
"not enough parameters specified for call");
6415 return Error(CallLoc,
"call instructions may not have an alignment");
6428 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6440 int LLParser::ParseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
6442 LocTy SizeLoc, TyLoc, ASLoc;
6443 unsigned Alignment = 0;
6444 unsigned AddrSpace = 0;
6450 if (ParseType(Ty, TyLoc))
return true;
6453 return Error(TyLoc,
"invalid type for alloca");
6455 bool AteExtraComma =
false;
6458 if (ParseOptionalAlignment(Alignment))
6460 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6463 ASLoc = Lex.getLoc();
6464 if (ParseOptionalAddrSpace(AddrSpace))
6467 AteExtraComma =
true;
6469 if (ParseTypeAndValue(Size, SizeLoc, PFS))
6473 if (ParseOptionalAlignment(Alignment))
6475 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6478 ASLoc = Lex.getLoc();
6479 if (ParseOptionalAddrSpace(AddrSpace))
6482 AteExtraComma =
true;
6489 return Error(SizeLoc,
"element count must have integer type");
6495 return AteExtraComma ? InstExtraComma : InstNormal;
6502 int LLParser::ParseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
6504 unsigned Alignment = 0;
6505 bool AteExtraComma =
false;
6522 LocTy ExplicitTypeLoc = Lex.getLoc();
6523 if (ParseType(Ty) ||
6524 ParseToken(
lltok::comma,
"expected comma after load's type") ||
6525 ParseTypeAndValue(Val, Loc, PFS) ||
6526 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6527 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6531 return Error(Loc,
"load operand must be a pointer to a first class type");
6532 if (isAtomic && !Alignment)
6533 return Error(Loc,
"atomic load must have explicit non-zero alignment");
6536 return Error(Loc,
"atomic load cannot use Release ordering");
6538 if (Ty != cast<PointerType>(Val->
getType())->getElementType())
6539 return Error(ExplicitTypeLoc,
6540 "explicit pointee type doesn't match operand's pointee type");
6542 Inst =
new LoadInst(Ty, Val,
"", isVolatile, Alignment, Ordering, SSID);
6543 return AteExtraComma ? InstExtraComma : InstNormal;
6551 int LLParser::ParseStore(
Instruction *&Inst, PerFunctionState &PFS) {
6553 unsigned Alignment = 0;
6554 bool AteExtraComma =
false;
6570 if (ParseTypeAndValue(Val, Loc, PFS) ||
6571 ParseToken(
lltok::comma,
"expected ',' after store operand") ||
6572 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6573 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6574 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6578 return Error(PtrLoc,
"store operand must be a pointer");
6580 return Error(Loc,
"store operand must be a first class value");
6581 if (cast<PointerType>(Ptr->
getType())->getElementType() != Val->
getType())
6582 return Error(Loc,
"stored value and pointer type do not match");
6583 if (isAtomic && !Alignment)
6584 return Error(Loc,
"atomic store must have explicit non-zero alignment");
6587 return Error(Loc,
"atomic store cannot use Acquire ordering");
6589 Inst =
new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
6590 return AteExtraComma ? InstExtraComma : InstNormal;
6596 int LLParser::ParseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
6598 bool AteExtraComma =
false;
6611 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6612 ParseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
6613 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6614 ParseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
6615 ParseTypeAndValue(New, NewLoc, PFS) ||
6616 ParseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
6617 ParseOrdering(FailureOrdering))
6622 return TokError(
"cmpxchg cannot be unordered");
6624 return TokError(
"cmpxchg failure argument shall be no stronger than the " 6625 "success argument");
6629 "cmpxchg failure ordering cannot include release semantics");
6631 return Error(PtrLoc,
"cmpxchg operand must be a pointer");
6632 if (cast<PointerType>(Ptr->
getType())->getElementType() != Cmp->
getType())
6633 return Error(CmpLoc,
"compare value and pointer type do not match");
6634 if (cast<PointerType>(Ptr->
getType())->getElementType() != New->
getType())
6635 return Error(NewLoc,
"new value and pointer type do not match");
6637 return Error(NewLoc,
"cmpxchg operand must be a first class value");
6639 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
6643 return AteExtraComma ? InstExtraComma : InstNormal;
6649 int LLParser::ParseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
6651 bool AteExtraComma =
false;
6660 switch (Lex.getKind()) {
6661 default:
return TokError(
"expected binary operation in atomicrmw");
6676 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6677 ParseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
6678 ParseTypeAndValue(Val, ValLoc, PFS) ||
6679 ParseScopeAndOrdering(
true , SSID, Ordering))
6683 return TokError(
"atomicrmw cannot be unordered");
6685 return Error(PtrLoc,
"atomicrmw operand must be a pointer");
6686 if (cast<PointerType>(Ptr->
getType())->getElementType() != Val->
getType())
6687 return Error(ValLoc,
"atomicrmw value and pointer type do not match");
6689 return Error(ValLoc,
"atomicrmw operand must be an integer");
6691 if (Size < 8 || (Size & (Size - 1)))
6692 return Error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized" 6699 return AteExtraComma ? InstExtraComma : InstNormal;
6704 int LLParser::ParseFence(
Instruction *&Inst, PerFunctionState &PFS) {
6707 if (ParseScopeAndOrdering(
true , SSID, Ordering))
6711 return TokError(
"fence cannot be unordered");
6713 return TokError(
"fence cannot be monotonic");
6721 int LLParser::ParseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
6723 Value *Val =
nullptr;
6729 LocTy ExplicitTypeLoc = Lex.getLoc();
6730 if (ParseType(Ty) ||
6731 ParseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
6732 ParseTypeAndValue(Ptr, Loc, PFS))
6737 if (!BasePointerType)
6738 return Error(Loc,
"base of getelementptr must be a pointer");
6741 return Error(ExplicitTypeLoc,
6742 "explicit pointee type doesn't match operand's pointee type");
6745 bool AteExtraComma =
false;
6753 AteExtraComma =
true;
6756 if (ParseTypeAndValue(Val, EltLoc, PFS))
return true;
6758 return Error(EltLoc,
"getelementptr index must be an integer");
6762 if (GEPWidth && GEPWidth != ValNumEl)
6763 return Error(EltLoc,
6764 "getelementptr vector index has a wrong number of elements");
6765 GEPWidth = ValNumEl;
6772 return Error(Loc,
"base element of getelementptr must be sized");
6775 return Error(Loc,
"invalid getelementptr indices");
6778 cast<GetElementPtrInst>(Inst)->setIsInBounds(
true);
6779 return AteExtraComma ? InstExtraComma : InstNormal;
6784 int LLParser::ParseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
6788 if (ParseTypeAndValue(Val, Loc, PFS) ||
6789 ParseIndexList(Indices, AteExtraComma))
6793 return Error(Loc,
"extractvalue operand must be aggregate type");
6796 return Error(Loc,
"invalid indices for extractvalue");
6798 return AteExtraComma ? InstExtraComma : InstNormal;
6803 int LLParser::ParseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
6807 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6808 ParseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
6809 ParseTypeAndValue(Val1, Loc1, PFS) ||
6810 ParseIndexList(Indices, AteExtraComma))
6814 return Error(Loc0,
"insertvalue operand must be aggregate type");
6818 return Error(Loc0,
"invalid indices for insertvalue");
6819 if (IndexedType != Val1->
getType())
6820 return Error(Loc1,
"insertvalue operand and field disagree in type: '" +
6824 return AteExtraComma ? InstExtraComma : InstNormal;
6851 if (ParseMetadata(MD,
nullptr))
6856 return ParseToken(
lltok::rbrace,
"expected end of metadata node");
6865 return Error(Loc,
"value has no uses");
6867 unsigned NumUses = 0;
6869 for (
const Use &U : V->
uses()) {
6870 if (++NumUses > Indexes.
size())
6872 Order[&U] = Indexes[NumUses - 1];
6875 return Error(Loc,
"value only has one use");
6876 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
6889 SMLoc Loc = Lex.getLoc();
6893 return Lex.Error(
"expected non-empty list of uselistorder indexes");
6900 bool IsOrdered =
true;
6901 assert(Indexes.
empty() &&
"Expected empty order vector");
6904 if (ParseUInt32(Index))
6908 Offset += Index - Indexes.
size();
6910 IsOrdered &= Index == Indexes.
size();
6918 if (Indexes.
size() < 2)
6919 return Error(Loc,
"expected >= 2 uselistorder indexes");
6920 if (Offset != 0 || Max >= Indexes.
size())
6921 return Error(Loc,
"expected distinct uselistorder indexes in range [0, size)");
6923 return Error(Loc,
"expected uselistorder indexes to change the order");
6930 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6931 SMLoc Loc = Lex.getLoc();
6937 if (ParseTypeAndValue(V, PFS) ||
6938 ParseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
6939 ParseUseListOrderIndexes(Indexes))
6942 return sortUseListOrder(V, Indexes, Loc);
6947 bool LLParser::ParseUseListOrderBB() {
6949 SMLoc Loc = Lex.getLoc();
6954 if (ParseValID(Fn) ||
6955 ParseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
6956 ParseValID(Label) ||
6957 ParseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
6958 ParseUseListOrderIndexes(Indexes))
6964 GV = M->getNamedValue(Fn.
StrVal);
6966 GV = Fn.
UIntVal < NumberedVals.size() ? NumberedVals[Fn.
UIntVal] :
nullptr;
6968 return Error(Fn.
Loc,
"expected function name in uselistorder_bb");
6970 return Error(Fn.
Loc,
"invalid function forward reference in uselistorder_bb");
6973 return Error(Fn.
Loc,
"expected function name in uselistorder_bb");
6974 if (
F->isDeclaration())
6975 return Error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
6979 return Error(Label.
Loc,
"invalid numeric label in uselistorder_bb");
6981 return Error(Label.
Loc,
"expected basic block name in uselistorder_bb");
6982 Value *V =
F->getValueSymbolTable()->lookup(Label.
StrVal);
6984 return Error(Label.
Loc,
"invalid basic block in uselistorder_bb");
6985 if (!isa<BasicBlock>(V))
6986 return Error(Label.
Loc,
"expected basic block in uselistorder_bb");
6988 return sortUseListOrder(V, Indexes, Loc);
6994 bool LLParser::ParseModuleEntry(
unsigned ID) {
7003 ParseStringConstant(Path) ||
7011 if (ParseUInt32(Hash[0]) || ParseToken(
lltok::comma,
"expected ',' here") ||
7012 ParseUInt32(Hash[1]) || ParseToken(
lltok::comma,
"expected ',' here") ||
7013 ParseUInt32(Hash[2]) || ParseToken(
lltok::comma,
"expected ',' here") ||
7014 ParseUInt32(Hash[3]) || ParseToken(
lltok::comma,
"expected ',' here") ||
7015 ParseUInt32(Hash[4]))
7022 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7023 ModuleIdMap[
ID] = ModuleEntry->first();
7030 bool LLParser::ParseTypeIdEntry(
unsigned ID) {
7039 ParseStringConstant(Name))
7044 ParseTypeIdSummary(TIS) || ParseToken(
lltok::rparen,
"expected ')' here"))
7049 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7050 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7051 for (
auto TIDRef : FwdRefTIDs->second) {
7053 "Forward referenced type id GUID expected to be 0");
7056 ForwardRefTypeIds.erase(FwdRefTIDs);
7068 ParseTypeTestResolution(TIS.
TTRes))
7073 if (ParseOptionalWpdResolutions(TIS.
WPDRes))
7097 switch (Lex.getKind()) {
7114 return Error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
7126 switch (Lex.getKind()) {
7141 if (ParseToken(
lltok::colon,
"expected ':'") || ParseUInt32(Val))
7154 return Error(Lex.getLoc(),
"expected optional TypeTestResolution field");
7167 bool LLParser::ParseOptionalWpdResolutions(
7168 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7179 ParseToken(
lltok::colon,
"expected ':' here") || ParseUInt64(Offset) ||
7180 ParseToken(
lltok::comma,
"expected ',' here") || ParseWpdRes(WPDRes) ||
7183 WPDResMap[
Offset] = WPDRes;
7208 switch (Lex.getKind()) {
7219 return Error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
7225 switch (Lex.getKind()) {
7233 if (ParseOptionalResByArg(WPDRes.
ResByArg))
7237 return Error(Lex.getLoc(),
7238 "expected optional WholeProgramDevirtResolution field");
7255 bool LLParser::ParseOptionalResByArg(
7264 std::vector<uint64_t>
Args;
7265 if (ParseArgs(Args) || ParseToken(
lltok::comma,
"expected ',' here") ||
7274 switch (Lex.getKind()) {
7288 return Error(Lex.getLoc(),
7289 "unexpected WholeProgramDevirtResolution::ByArg kind");
7295 switch (Lex.getKind()) {
7299 ParseUInt64(ByArg.
Info))
7305 ParseUInt32(ByArg.
Byte))
7311 ParseUInt32(ByArg.
Bit))
7315 return Error(Lex.getLoc(),
7316 "expected optional whole program devirt field");
7323 ResByArg[
Args] = ByArg;
7334 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7342 if (ParseUInt64(Val))
7344 Args.push_back(Val);
7354 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
7358 void LLParser::AddGlobalValueToIndex(
7360 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7365 VI = Index->getOrInsertValueInfo(GUID);
7369 auto *GV = M->getNamedValue(Name);
7371 VI = Index->getOrInsertValueInfo(GV);
7375 "Need a source_filename to compute GUID for local");
7378 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7384 Index->addGlobalValueSummary(VI, std::move(Summary));
7387 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7388 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7389 for (
auto VIRef : FwdRefVIs->second) {
7390 assert(*VIRef.first == EmptyVI &&
7391 "Forward referenced ValueInfo expected to be empty");
7394 ForwardRefValueInfos.erase(FwdRefVIs);
7398 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7399 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7400 for (
auto AliaseeRef : FwdRefAliasees->second) {
7401 assert(!AliaseeRef.first->hasAliasee() &&
7402 "Forward referencing alias already has aliasee");
7405 ForwardRefAliasees.erase(FwdRefAliasees);
7409 if (ID == NumberedValueInfos.size())
7410 NumberedValueInfos.push_back(VI);
7413 if (ID > NumberedValueInfos.size())
7414 NumberedValueInfos.resize(ID + 1);
7415 NumberedValueInfos[
ID] =
VI;
7423 bool LLParser::ParseGVEntry(
unsigned ID) {
7433 switch (Lex.getKind()) {
7437 ParseStringConstant(Name))
7443 if (ParseToken(
lltok::colon,
"expected ':' here") || ParseUInt64(GUID))
7447 return Error(Lex.getLoc(),
"expected name or guid tag");
7473 switch (Lex.getKind()) {
7475 if (ParseFunctionSummary(Name, GUID, ID))
7479 if (ParseVariableSummary(Name, GUID, ID))
7483 if (ParseAliasSummary(Name, GUID, ID))
7487 return Error(Lex.getLoc(),
"expected summary type");
7513 std::vector<FunctionSummary::EdgeTy> Calls;
7515 std::vector<ValueInfo> Refs;
7520 ParseModuleReference(ModulePath) ||
7521 ParseToken(
lltok::comma,
"expected ',' here") || ParseGVFlags(GVFlags) ||
7524 ParseToken(
lltok::colon,
"expected ':' here") || ParseUInt32(InstCount))
7529 switch (Lex.getKind()) {
7531 if (ParseOptionalFFlags(FFlags))
7535 if (ParseOptionalCalls(Calls))
7539 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7543 if (ParseOptionalRefs(Refs))
7547 return Error(Lex.getLoc(),
"expected optional function summary field");
7554 auto FS = llvm::make_unique<FunctionSummary>(
7555 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
7562 FS->setModulePath(ModulePath);
7582 std::vector<ValueInfo> Refs;
7585 ParseModuleReference(ModulePath) ||
7586 ParseToken(
lltok::comma,
"expected ',' here") || ParseGVFlags(GVFlags))
7591 if (ParseOptionalRefs(Refs))
7598 auto GS = llvm::make_unique<GlobalVarSummary>(GVFlags, std::move(Refs));
7600 GS->setModulePath(ModulePath);
7614 LocTy Loc = Lex.getLoc();
7623 ParseModuleReference(ModulePath) ||
7624 ParseToken(
lltok::comma,
"expected ',' here") || ParseGVFlags(GVFlags) ||
7632 if (ParseGVReference(AliaseeVI, GVId))
7638 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7640 AS->setModulePath(ModulePath);
7643 if (AliaseeVI == EmptyVI) {
7644 auto FwdRef = ForwardRefAliasees.insert(
7645 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7646 FwdRef.first->second.push_back(std::make_pair(
AS.get(), Loc));
7658 bool LLParser::ParseFlag(
unsigned &Val) {
7659 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
7660 return TokError(
"expected integer");
7661 Val = (
unsigned)Lex.getAPSIntVal().getBoolValue();
7674 if (ParseToken(
lltok::colon,
"expected ':' in funcFlags") |
7680 switch (Lex.getKind()) {
7683 if (ParseToken(
lltok::colon,
"expected ':'") || ParseFlag(Val))
7689 if (ParseToken(
lltok::colon,
"expected ':'") || ParseFlag(Val))
7695 if (ParseToken(
lltok::colon,
"expected ':'") || ParseFlag(Val))
7701 if (ParseToken(
lltok::colon,
"expected ':'") || ParseFlag(Val))
7706 return Error(Lex.getLoc(),
"expected function flag type");
7720 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
7724 if (ParseToken(
lltok::colon,
"expected ':' in calls") |
7728 IdToIndexMapType IdToIndexMap;
7737 LocTy Loc = Lex.getLoc();
7739 if (ParseGVReference(VI, GVId))
7747 if (ParseToken(
lltok::colon,
"expected ':'") || ParseHotness(Hotness))
7751 ParseToken(
lltok::colon,
"expected ':'") || ParseUInt32(RelBF))
7759 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
7768 for (
auto I : IdToIndexMap) {
7769 for (
auto P :
I.second) {
7770 assert(Calls[P.first].first == EmptyVI &&
7771 "Forward referenced ValueInfo expected to be empty");
7772 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7773 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7774 FwdRef.first->second.push_back(
7775 std::make_pair(&Calls[P.first].first, P.second));
7788 switch (Lex.getKind()) {
7805 return Error(Lex.getLoc(),
"invalid call edge hotness");
7813 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
7821 IdToIndexMapType IdToIndexMap;
7825 LocTy Loc = Lex.getLoc();
7827 if (ParseGVReference(VI, GVId))
7834 IdToIndexMap[GVId].push_back(std::make_pair(Refs.size(), Loc));
7840 for (
auto I : IdToIndexMap) {
7841 for (
auto P :
I.second) {
7842 assert(Refs[P.first] == EmptyVI &&
7843 "Forward referenced ValueInfo expected to be empty");
7844 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7845 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7846 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
7860 bool LLParser::ParseOptionalTypeIdInfo(
7870 switch (Lex.getKind()) {
7872 if (ParseTypeTests(TypeIdInfo.
TypeTests))
7896 return Error(Lex.getLoc(),
"invalid typeIdInfo list type");
7900 if (ParseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
7909 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
7917 IdToIndexMapType IdToIndexMap;
7921 unsigned ID = Lex.getUIntVal();
7922 LocTy Loc = Lex.getLoc();
7926 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
7928 }
else if (ParseUInt64(GUID))
7930 TypeTests.push_back(GUID);
7935 for (
auto I : IdToIndexMap) {
7936 for (
auto P :
I.second) {
7937 assert(TypeTests[P.first] == 0 &&
7938 "Forward referenced type id GUID expected to be 0");
7939 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
7940 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
7941 FwdRef.first->second.push_back(
7942 std::make_pair(&TypeTests[P.first], P.second));
7946 if (ParseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
7954 bool LLParser::ParseVFuncIdList(
7955 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
7963 IdToIndexMapType IdToIndexMap;
7966 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
7968 VFuncIdList.push_back(VFuncId);
7976 for (
auto I : IdToIndexMap) {
7977 for (
auto P :
I.second) {
7978 assert(VFuncIdList[P.first].GUID == 0 &&
7979 "Forward referenced type id GUID expected to be 0");
7980 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
7981 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
7982 FwdRef.first->second.push_back(
7983 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
7992 bool LLParser::ParseConstVCallList(
7994 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8002 IdToIndexMapType IdToIndexMap;
8005 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8007 ConstVCallList.push_back(ConstVCall);
8015 for (
auto I : IdToIndexMap) {
8016 for (
auto P :
I.second) {
8017 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8018 "Forward referenced type id GUID expected to be 0");
8019 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8020 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8021 FwdRef.first->second.push_back(
8022 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8032 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
8033 if (ParseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index) ||
8035 ParseArgs(ConstVCall.
Args))
8045 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
8055 unsigned ID = Lex.getUIntVal();
8056 LocTy Loc = Lex.getLoc();
8060 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
8064 ParseUInt64(VFuncId.
GUID))
8070 ParseUInt64(VFuncId.
Offset) ||
8093 assert(HasLinkage &&
"Linkage not optional in summary entry");
8099 "expected 'notEligibleToImport' here") ||
8100 ParseToken(
lltok::colon,
"expected ':' here") || ParseFlag(Flag))
8106 ParseToken(
lltok::colon,
"expected ':' here") || ParseFlag(Flag))
8112 ParseToken(
lltok::colon,
"expected ':' here") || ParseFlag(Flag))
8124 bool LLParser::ParseModuleReference(
StringRef &ModulePath) {
8131 unsigned ModuleID = Lex.getUIntVal();
8132 auto I = ModuleIdMap.find(ModuleID);
8134 assert(
I != ModuleIdMap.end());
8135 ModulePath =
I->second;
8141 bool LLParser::ParseGVReference(
ValueInfo &
VI,
unsigned &GVId) {
8145 GVId = Lex.getUIntVal();
8148 if (GVId < NumberedValueInfos.size()) {
8149 assert(NumberedValueInfos[GVId] != EmptyVI);
8150 VI = NumberedValueInfos[GVId];
void setVisibility(VisibilityTypes V)
void sortUseList(Compare Cmp)
Sort the use-list.
void push_back(const T &Elt)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
static ConstantInt * getFalse(LLVMContext &Context)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
iterator_range< use_iterator > uses()
Calling convention used for AMDPAL shader stage before geometry shader if geometry is in use...
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Special purpose, only applies to global arrays.
uint64_t getZExtValue() const
Get zero extended value.
*p = old <signed v ? old : v
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
void UpgradeSectionAttributes(Module &M)
C - The default llvm calling convention, compatible with C.
bool isMetadataTy() const
Return true if this is 'metadata'.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Compute iterated dominance frontiers using a linear time algorithm.
unsigned Linkage
The linkage type of the associated global value.
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static ResumeInst * Create(Value *Exn, Instruction *InsertBefore=nullptr)
An instruction for ordering other memory operations.
Same, but only replaced by something equivalent.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
static MDString * get(LLVMContext &Context, StringRef Str)
Unsatisfiable type (i.e. no global has this type metadata)
ARM_AAPCS - ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Available for inspection, not emission.
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void addOperand(MDNode *M)
This class represents a function call, abstracting a target machine's calling convention.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID...
void setGC(std::string Str)
void emplace(ArgTypes &&... Args)
Create a new object by constructing it in place with the given arguments.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
The two locations do not alias at all.
*p = old <unsigned v ? old : v
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
0 1 0 0 True if ordered and less than
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
uint64_t Info
Additional information for the resolution:
Like Internal, but omit from symbol table.
iterator find(StringRef Key)
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
*p = old >unsigned v ? old : v
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
Externally visible function.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
LLVMContext & getContext() const
All values hold a context through their type.
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do not have all constant integer arguments.
void setDataLayout(StringRef Desc)
Set the data layout.
1 1 1 0 True if unordered or not equal
void deleteValue()
Delete a pointer to a generic Value.
The data referenced by the COMDAT must be the same size.
AttrBuilder & addDereferenceableAttr(uint64_t Bytes)
This turns the number of dereferenceable bytes into the form used internally in Attribute.
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
const fltSemantics & getSemantics() const
param_iterator param_end() const
An instruction for reading from memory.
void setIgnoreColonInIdentifiers(bool val)
ELFYAML::ELF_STV Visibility
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
bool isVectorTy() const
True if this is an instance of VectorType.
const APFloat & getAPFloatVal() const
static bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy, const std::string &Name)
void setAlignment(unsigned Align)
unsigned getVirtuality(StringRef VirtualityString)
*p = old >signed v ? old : v
Virtual constant propagation.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair...
ARM_APCS - ARM Procedure Calling Standard calling convention (obsolete, but still used on some target...
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
static Optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
unsigned getBitWidth() const
Return the number of bits in the APInt.
static bool isLocalLinkage(LinkageTypes Linkage)
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Calling convention used for Mesa/AMDPAL pixel shaders.
const AliasListType & getAliasList() const
Get the Module's list of aliases (constant).
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
X86_INTR - x86 hardware interrupt context.
bool Run()
Run: module ::= toplevelentity*.
1 0 0 1 True if unordered or equal
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
static Type * getTokenTy(LLVMContext &C)
bool hasAttributes() const
Return true if the builder has IR-level attributes.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool hasAlignmentAttr() const
Return true if the builder has an alignment attribute.
SPIR_FUNC - Calling convention for SPIR non-kernel device functions.
AttrBuilder & addDereferenceableOrNullAttr(uint64_t Bytes)
This turns the number of dereferenceable_or_null bytes into the form used internally in Attribute...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module...
bool isStrongerThan(AtomicOrdering ao, AtomicOrdering other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice, which is based on C++'s definition.
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
Class to represent struct types.
APSInt extOrTrunc(uint32_t width) const
A Use represents the edge between a Value definition and its users.
Intel_OCL_BI - Calling conventions for Intel OpenCL built-ins.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
PTX_Device - Call to a PTX device function.
bool isIntegerTy() const
True if this is an instance of IntegerType.
void setThreadLocalMode(ThreadLocalMode Val)
static 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...
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
AttrBuilder & addAllocSizeAttr(unsigned ElemSizeArg, const Optional< unsigned > &NumElemsArg)
This turns one (or two) ints into the form used internally in Attribute.
0 1 0 1 True if ordered and less than or equal
Just do a regular virtual call.
The linker may choose any COMDAT.
void setName(const Twine &Name)
Change the name of the value.
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Calling convention used by HipHop Virtual Machine (HHVM) to perform calls to and from translation cac...
static const unsigned MaximumAlignment
void setDLLStorageClass(DLLStorageClassTypes C)
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
AtomicOrdering
Atomic ordering for LLVM's memory model.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction...
static 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. ...
Uniform return value optimization.
llvm::Optional< Function * > remangleIntrinsicFunction(Function *F)
SPIR_KERNEL - Calling convention for SPIR kernel functions.
Class to represent function types.
static Type * getLabelTy(LLVMContext &C)
Type * getType() const
All values are typed, get the type of this value.
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value. ...
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
AttributeList removeAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &AttrsToRemove) const
Remove the specified attributes at the specified index from this attribute list.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Class to represent array types.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
This instruction compares its operands according to the predicate given to the constructor.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
void setComdat(Comdat *C)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
unsigned getUIntVal() const
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static bool Verify(FunctionType *Ty, StringRef Constraints)
Verify - This static method can be used by the parser to check to see if the specified constraint str...
An instruction for storing to memory.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static const fltSemantics & IEEEdouble() LLVM_READNONE
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void setBody(ArrayRef< Type *> Elements, bool isPacked=false)
Specify a body for an opaque identified type.
amdgpu Simplify well known AMD library false Value * Callee
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
Class to represent pointers.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Flag
These should be considered private to the implementation of the MCInstrDesc class.
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isVoidTy() const
Return true if this is 'void'.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
ExternalWeak linkage description.
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Return a temporary node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
void setCallingConv(CallingConv::ID CC)
const char * getPointer() const
Same, but only replaced by something equivalent.
No other Module may specify this COMDAT.
bool isLabelTy() const
Return true if this is 'label'.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
X86_ThisCall - Similar to X86_StdCall.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
The instances of the Type class are immutable: once they are created, they are never changed...
PowerPC Reduce CR logical Operation
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
X86_FastCall - 'fast' analog of X86_StdCall.
size_t size() const
size - Get the array size.
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Calling convention used for AVR signal routines.
Resume the propagation of an exception.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const APSInt & getAPSIntVal() const
unsigned getCallingConvention(StringRef LanguageString)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata *> MDs)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
std::vector< uint64_t > Args
bool isPointerTy() const
True if this is an instance of PointerType.
Indirect Branch Instruction.
void setExternallyInitialized(bool Val)
unsigned getOperationEncoding(StringRef OperationEncodingString)
uint64_t getAlignment() const
Retrieve the alignment attribute, if it exists.
StringMap< Type * > NamedTypes
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Class to accumulate and hold information about a callee.
Calling convention used for AMDPAL vertex shader if tessellation is in use.
static bool isValidLinkage(LinkageTypes L)
static bool isValidVariableType(Module *M, Type *Ty, Value *Val, bool IsCall)
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
param_iterator param_begin() const
A pair of DIGlobalVariable and DIExpression.
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
void splice(iterator where, iplist_impl &L2)
Single element (last example in "Short Inline Bit Vectors")
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
DLLStorageClassTypes
Storage classes of global values for PE targets.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Constant * get(StructType *T, ArrayRef< Constant *> V)
0 1 1 1 True if ordered (no nans)
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
ChecksumKind
Which algorithm (e.g.
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
The data referenced by the COMDAT must be the same.
All type identifier related information.
void setTailCallKind(TailCallKind TCK)
std::vector< GlobalValue * > GlobalValues
void setConstant(bool Val)
lltok::Kind getKind() const
unsigned getLanguage(StringRef LanguageString)
dot regions Print regions of function to dot file(with no function bodies)"
1 1 1 1 Always true (always folded)
std::map< unsigned, Type * > Types
ARM_AAPCS_VFP - Same as ARM_AAPCS, but uses hard floating point ABI.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static bool isAtomic(Instruction *I)
static wasm::ValType getType(const TargetRegisterClass *RC)
1 1 0 1 True if unordered, less than, or equal
Fast - This calling convention attempts to make calls as fast as possible (e.g.
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, Instruction *InsertBefore=nullptr)
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
const IFuncListType & getIFuncList() const
Get the Module's list of ifuncs (constant).
An imported module (C++ using directive or similar).
unsigned getTag(StringRef TagString)
An "identifier" for a virtual function.
void setCallingConv(CallingConv::ID CC)
Struct that holds a reference to a particular GUID in a global value summary.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Return a distinct node.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
global_iterator global_end()
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
0 0 1 0 True if ordered and greater than
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
const InstListType & getInstList() const
Return the underlying instruction list container.
std::vector< VFuncId > TypeCheckedLoadVCalls
static const fltSemantics & IEEEsingle() LLVM_READNONE
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
void setSelectionKind(SelectionKind Val)
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
static const fltSemantics & IEEEhalf() LLVM_READNONE
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value *> Args=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
AttrBuilder & removeAttribute(Attribute::AttrKind Val)
Remove an attribute from the builder.
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
1 1 0 0 True if unordered or less than
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Keep one copy of function when linking (inline)
Module.h This file contains the declarations for the Module class.
enum llvm::ValID::@311 Kind
Register calling convention used for parameters transfer optimization.
bool isVector(MCInstrInfo const &MCII, MCInst const &MCI)
Type::subtype_iterator param_iterator
Single implementation devirtualization.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
bool isAggregateType() const
Return true if the type is an aggregate type.
unsigned getProgramAddressSpace() const
#define GET_OR_DISTINCT(CLASS, ARGS)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
The linker will choose the largest COMDAT.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
static ConstantInt * getTrue(LLVMContext &Context)
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setLinkage(LinkageTypes LT)
std::string SingleImplName
enum llvm::TypeTestResolution::Kind TheKind
ValueSymbolTable * getValueSymbolTable()
getSymbolTable() - Return the symbol table if any, otherwise nullptr.
DebugEmissionKind getEmissionKind() const
unsigned getVectorNumElements() const
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
This file contains constants used for implementing Dwarf debug support.
static DIFlags getFlag(StringRef Flag)
void push_back(pointer val)
A specification for a virtual function call with all constant integer arguments.
static bool isWeak(const MCSymbolELF &Sym)
Calling convention used for Mesa/AMDPAL compute shaders.
LinkageTypes
An enumeration for the kinds of linkage for global values.
A (clang) module that has been imported by the compile unit.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
void setWeak(bool IsWeak)
Calling convention for AMDGPU code object kernels.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
void setAttributes(AttributeSet A)
Set attribute list for this global.
Generic tagged DWARF-like metadata node.
This struct contains the mappings from the slot numbers to unnamed metadata nodes, global values and types.
A utility class that uses RAII to save and restore the value of a variable.
FunctionNumber(functionNumber)
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value *> Args, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
const std::string & getStrVal() const
Used for AVR interrupt routines.
Type array for a subprogram.
Test a byte array (first example)
static std::string getTypeString(Type *T)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Function to be accessible from DLL.
Calling convention used for Mesa/AMDPAL geometry shaders.
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
unsigned getNumUses() const
This method computes the number of uses of this Value.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
OperandType
Operands are tagged with one of the values of this enum.
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument, "this"), where the key is the argument vector.
bool isFunctionTy() const
True if this is an instance of FunctionType.
ValID - Represents a reference of a definition of some sort with no type.
pointer data()
Return a pointer to the vector's buffer, even if empty().
iterator_range< typename GraphTraits< GraphType >::nodes_iterator > nodes(const GraphType &G)
void setUnnamedAddr(UnnamedAddr Val)
void emplace_back(ArgTypes &&... Args)
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
static Type * getIndexedType(Type *Ty, ArrayRef< Value *> IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
LLVM_NODISCARD bool empty() const
unsigned greater or equal
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors") ...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit...
bool isTokenTy() const
Return true if this is 'token'.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void setSourceFileName(StringRef Name)
Set the module's original source file name.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
StringRef getName() const
Return a constant reference to the value's name.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Remove the specified attribute at the specified index from this attribute list.
void setPrologueData(Constant *PrologueData)
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
Deduce function attributes
std::unique_ptr< Constant *[]> ConstantStructElts
0 1 1 0 True if ordered and operands are unequal
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
void setTargetTriple(StringRef T)
Set the target triple.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
MSP430_INTR - Calling convention used for MSP430 interrupt routines.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Function attribute flags.
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Inlined bit vector ("Short Inline Bit Vectors")
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
1 0 1 0 True if unordered or greater than
PTX_Kernel - Call to a PTX kernel.
Value * lookup(StringRef Name) const
This method finds the value with the given Name in the the symbol table.
Function to be imported from DLL.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
unsigned getMacinfo(StringRef MacinfoString)
AttributeList addAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &B) const
Add attributes to the attribute set at the given index.
void addDestination(BasicBlock *Dest)
Add a destination.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
AttrBuilder & merge(const AttrBuilder &B)
Add the attributes from the builder.
Synchronized with respect to all concurrently executing threads.
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator)
Build a DICompositeType with the given ODR identifier.
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore=nullptr)
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
0 0 0 1 True if ordered and equal
LLVM Value Representation.
Calling convention used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (ve...
1 0 1 1 True if unordered, greater than, or equal
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Just do a regular virtual call.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Lightweight error class with error context and mandatory checking.
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, Instruction *InsertBefore=nullptr)
AttributeSet getFnAttributes() const
The function attributes are returned.
unsigned getAttributeEncoding(StringRef EncodingString)
AttrBuilder & addStackAlignmentAttr(unsigned Align)
This turns an int stack alignment (which must be a power of 2) into the form used internally in Attri...
This file provides utility classes that use RAII to save and restore values.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
#define PARSE_MD_FIELDS()
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
HHVM calling convention for invoking C/C++ helpers.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
AttrBuilder & addAlignmentAttr(unsigned Align)
This turns an int alignment (which must be a power of 2) into the form used internally in Attribute...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
void setPersonalityFn(Constant *Fn)
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool isVolatile(Instruction *Inst)
Represents a location in source code.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
0 0 1 1 True if ordered and greater than or equal
unsigned ReturnDoesNotAlias
Calling convention used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
The C convention as implemented on Windows/x86-64 and AArch64.
static IntegerType * getInt8Ty(LLVMContext &C)
void setSection(StringRef S)
Change the section for this global.
static 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 Constant * get(ArrayRef< Constant *> V)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Type * getElementType() const
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
0 0 0 0 Always false (always folded)
Unique return value optimization.
bool isArrayTy() const
True if this is an instance of ArrayType.
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
an instruction to allocate memory on the stack
Basic type, like 'int' or 'float'.
static bool parseField(amd_kernel_code_t &C, MCAsmParser &MCParser, raw_ostream &Err)
void setPrefixData(Constant *PrefixData)
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with all constant integer arguments.
static 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...