1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the parser class for .ll files.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/AsmParser/LLParser.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/ModRef.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
57 static std::string getTypeString(Type *T) {
59 raw_string_ostream Tmp(Result);
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run(bool UpgradeDebugInfo,
66 DataLayoutCallbackTy DataLayoutCallback) {
70 if (Context.shouldDiscardValueNames())
73 "Can't read textual IR with a Context that discards named Values");
76 if (parseTargetDefinitions(DataLayoutCallback))
80 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
84 bool LLParser::parseStandaloneConstantValue(Constant *&C,
85 const SlotMapping *Slots) {
86 restoreParsingState(Slots);
90 if (parseType(Ty) || parseConstantValue(Ty, C))
92 if (Lex.getKind() != lltok::Eof)
93 return error(Lex.getLoc(), "expected end of string");
97 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
98 const SlotMapping *Slots) {
99 restoreParsingState(Slots);
103 SMLoc Start = Lex.getLoc();
107 SMLoc End = Lex.getLoc();
108 Read = End.getPointer() - Start.getPointer();
113 void LLParser::restoreParsingState(const SlotMapping *Slots) {
116 NumberedVals = Slots->GlobalValues;
117 NumberedMetadata = Slots->MetadataNodes;
118 for (const auto &I : Slots->NamedTypes)
120 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
121 for (const auto &I : Slots->Types)
122 NumberedTypes.insert(
123 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
126 /// validateEndOfModule - Do final validity and basic correctness checks at the
127 /// end of the module.
128 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
131 // Handle any function attribute group forward references.
132 for (const auto &RAG : ForwardRefAttrGroups) {
133 Value *V = RAG.first;
134 const std::vector<unsigned> &Attrs = RAG.second;
135 AttrBuilder B(Context);
137 for (const auto &Attr : Attrs) {
138 auto R = NumberedAttrBuilders.find(Attr);
139 if (R != NumberedAttrBuilders.end())
143 if (Function *Fn = dyn_cast<Function>(V)) {
144 AttributeList AS = Fn->getAttributes();
145 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
146 AS = AS.removeFnAttributes(Context);
150 // If the alignment was parsed as an attribute, move to the alignment
152 if (MaybeAlign A = FnAttrs.getAlignment()) {
153 Fn->setAlignment(*A);
154 FnAttrs.removeAttribute(Attribute::Alignment);
157 AS = AS.addFnAttributes(Context, FnAttrs);
158 Fn->setAttributes(AS);
159 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
160 AttributeList AS = CI->getAttributes();
161 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
162 AS = AS.removeFnAttributes(Context);
164 AS = AS.addFnAttributes(Context, FnAttrs);
165 CI->setAttributes(AS);
166 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AttributeList AS = II->getAttributes();
168 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
169 AS = AS.removeFnAttributes(Context);
171 AS = AS.addFnAttributes(Context, FnAttrs);
172 II->setAttributes(AS);
173 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
174 AttributeList AS = CBI->getAttributes();
175 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
176 AS = AS.removeFnAttributes(Context);
178 AS = AS.addFnAttributes(Context, FnAttrs);
179 CBI->setAttributes(AS);
180 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
181 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
183 GV->setAttributes(AttributeSet::get(Context,Attrs));
185 llvm_unreachable("invalid object with forward attribute group reference");
189 // If there are entries in ForwardRefBlockAddresses at this point, the
190 // function was never defined.
191 if (!ForwardRefBlockAddresses.empty())
192 return error(ForwardRefBlockAddresses.begin()->first.Loc,
193 "expected function name in blockaddress");
195 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
196 GlobalValue *FwdRef) {
197 GlobalValue *GV = nullptr;
198 if (GVRef.Kind == ValID::t_GlobalName) {
199 GV = M->getNamedValue(GVRef.StrVal);
200 } else if (GVRef.UIntVal < NumberedVals.size()) {
201 GV = dyn_cast<GlobalValue>(NumberedVals[GVRef.UIntVal]);
205 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
206 "' referenced by dso_local_equivalent");
208 if (!GV->getValueType()->isFunctionTy())
209 return error(GVRef.Loc,
210 "expected a function, alias to function, or ifunc "
211 "in dso_local_equivalent");
213 auto *Equiv = DSOLocalEquivalent::get(GV);
214 FwdRef->replaceAllUsesWith(Equiv);
215 FwdRef->eraseFromParent();
219 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
220 // point, they are references after the function was defined. Resolve those
222 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
223 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
226 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
227 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
230 ForwardRefDSOLocalEquivalentIDs.clear();
231 ForwardRefDSOLocalEquivalentNames.clear();
233 for (const auto &NT : NumberedTypes)
234 if (NT.second.second.isValid())
235 return error(NT.second.second,
236 "use of undefined type '%" + Twine(NT.first) + "'");
238 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
239 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
240 if (I->second.second.isValid())
241 return error(I->second.second,
242 "use of undefined type named '" + I->getKey() + "'");
244 if (!ForwardRefComdats.empty())
245 return error(ForwardRefComdats.begin()->second,
246 "use of undefined comdat '$" +
247 ForwardRefComdats.begin()->first + "'");
249 if (!ForwardRefVals.empty())
250 return error(ForwardRefVals.begin()->second.second,
251 "use of undefined value '@" + ForwardRefVals.begin()->first +
254 if (!ForwardRefValIDs.empty())
255 return error(ForwardRefValIDs.begin()->second.second,
256 "use of undefined value '@" +
257 Twine(ForwardRefValIDs.begin()->first) + "'");
259 if (!ForwardRefMDNodes.empty())
260 return error(ForwardRefMDNodes.begin()->second.second,
261 "use of undefined metadata '!" +
262 Twine(ForwardRefMDNodes.begin()->first) + "'");
264 // Resolve metadata cycles.
265 for (auto &N : NumberedMetadata) {
266 if (N.second && !N.second->isResolved())
267 N.second->resolveCycles();
270 for (auto *Inst : InstsWithTBAATag) {
271 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
272 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
273 auto *UpgradedMD = UpgradeTBAANode(*MD);
274 if (MD != UpgradedMD)
275 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
278 // Look for intrinsic functions and CallInst that need to be upgraded. We use
279 // make_early_inc_range here because we may remove some functions.
280 for (Function &F : llvm::make_early_inc_range(*M))
281 UpgradeCallsToIntrinsic(&F);
283 if (UpgradeDebugInfo)
284 llvm::UpgradeDebugInfo(*M);
286 UpgradeModuleFlags(*M);
287 UpgradeSectionAttributes(*M);
291 // Initialize the slot mapping.
292 // Because by this point we've parsed and validated everything, we can "steal"
293 // the mapping from LLParser as it doesn't need it anymore.
294 Slots->GlobalValues = std::move(NumberedVals);
295 Slots->MetadataNodes = std::move(NumberedMetadata);
296 for (const auto &I : NamedTypes)
297 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
298 for (const auto &I : NumberedTypes)
299 Slots->Types.insert(std::make_pair(I.first, I.second.first));
304 /// Do final validity and basic correctness checks at the end of the index.
305 bool LLParser::validateEndOfIndex() {
309 if (!ForwardRefValueInfos.empty())
310 return error(ForwardRefValueInfos.begin()->second.front().second,
311 "use of undefined summary '^" +
312 Twine(ForwardRefValueInfos.begin()->first) + "'");
314 if (!ForwardRefAliasees.empty())
315 return error(ForwardRefAliasees.begin()->second.front().second,
316 "use of undefined summary '^" +
317 Twine(ForwardRefAliasees.begin()->first) + "'");
319 if (!ForwardRefTypeIds.empty())
320 return error(ForwardRefTypeIds.begin()->second.front().second,
321 "use of undefined type id summary '^" +
322 Twine(ForwardRefTypeIds.begin()->first) + "'");
327 //===----------------------------------------------------------------------===//
328 // Top-Level Entities
329 //===----------------------------------------------------------------------===//
331 bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
332 // Delay parsing of the data layout string until the target triple is known.
333 // Then, pass both the the target triple and the tentative data layout string
334 // to DataLayoutCallback, allowing to override the DL string.
335 // This enables importing modules with invalid DL strings.
336 std::string TentativeDLStr = M->getDataLayoutStr();
341 switch (Lex.getKind()) {
342 case lltok::kw_target:
343 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
346 case lltok::kw_source_filename:
347 if (parseSourceFileName())
354 // Run the override callback to potentially change the data layout string, and
355 // parse the data layout string.
356 if (auto LayoutOverride =
357 DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
358 TentativeDLStr = *LayoutOverride;
361 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
363 return error(DLStrLoc, toString(MaybeDL.takeError()));
364 M->setDataLayout(MaybeDL.get());
368 bool LLParser::parseTopLevelEntities() {
369 // If there is no Module, then parse just the summary index entries.
372 switch (Lex.getKind()) {
375 case lltok::SummaryID:
376 if (parseSummaryEntry())
379 case lltok::kw_source_filename:
380 if (parseSourceFileName())
384 // Skip everything else
390 switch (Lex.getKind()) {
392 return tokError("expected top-level entity");
393 case lltok::Eof: return false;
394 case lltok::kw_declare:
398 case lltok::kw_define:
402 case lltok::kw_module:
403 if (parseModuleAsm())
406 case lltok::LocalVarID:
407 if (parseUnnamedType())
410 case lltok::LocalVar:
411 if (parseNamedType())
414 case lltok::GlobalID:
415 if (parseUnnamedGlobal())
418 case lltok::GlobalVar:
419 if (parseNamedGlobal())
422 case lltok::ComdatVar: if (parseComdat()) return true; break;
424 if (parseStandaloneMetadata())
427 case lltok::SummaryID:
428 if (parseSummaryEntry())
431 case lltok::MetadataVar:
432 if (parseNamedMetadata())
435 case lltok::kw_attributes:
436 if (parseUnnamedAttrGrp())
439 case lltok::kw_uselistorder:
440 if (parseUseListOrder())
443 case lltok::kw_uselistorder_bb:
444 if (parseUseListOrderBB())
452 /// ::= 'module' 'asm' STRINGCONSTANT
453 bool LLParser::parseModuleAsm() {
454 assert(Lex.getKind() == lltok::kw_module);
458 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
459 parseStringConstant(AsmStr))
462 M->appendModuleInlineAsm(AsmStr);
467 /// ::= 'target' 'triple' '=' STRINGCONSTANT
468 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
469 bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
471 assert(Lex.getKind() == lltok::kw_target);
475 return tokError("unknown target property");
476 case lltok::kw_triple:
478 if (parseToken(lltok::equal, "expected '=' after target triple") ||
479 parseStringConstant(Str))
481 M->setTargetTriple(Str);
483 case lltok::kw_datalayout:
485 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
487 DLStrLoc = Lex.getLoc();
488 if (parseStringConstant(TentativeDLStr))
495 /// ::= 'source_filename' '=' STRINGCONSTANT
496 bool LLParser::parseSourceFileName() {
497 assert(Lex.getKind() == lltok::kw_source_filename);
499 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
500 parseStringConstant(SourceFileName))
503 M->setSourceFileName(SourceFileName);
507 /// parseUnnamedType:
508 /// ::= LocalVarID '=' 'type' type
509 bool LLParser::parseUnnamedType() {
510 LocTy TypeLoc = Lex.getLoc();
511 unsigned TypeID = Lex.getUIntVal();
512 Lex.Lex(); // eat LocalVarID;
514 if (parseToken(lltok::equal, "expected '=' after name") ||
515 parseToken(lltok::kw_type, "expected 'type' after '='"))
518 Type *Result = nullptr;
519 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
522 if (!isa<StructType>(Result)) {
523 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
525 return error(TypeLoc, "non-struct types may not be recursive");
526 Entry.first = Result;
527 Entry.second = SMLoc();
534 /// ::= LocalVar '=' 'type' type
535 bool LLParser::parseNamedType() {
536 std::string Name = Lex.getStrVal();
537 LocTy NameLoc = Lex.getLoc();
538 Lex.Lex(); // eat LocalVar.
540 if (parseToken(lltok::equal, "expected '=' after name") ||
541 parseToken(lltok::kw_type, "expected 'type' after name"))
544 Type *Result = nullptr;
545 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
548 if (!isa<StructType>(Result)) {
549 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
551 return error(NameLoc, "non-struct types may not be recursive");
552 Entry.first = Result;
553 Entry.second = SMLoc();
560 /// ::= 'declare' FunctionHeader
561 bool LLParser::parseDeclare() {
562 assert(Lex.getKind() == lltok::kw_declare);
565 std::vector<std::pair<unsigned, MDNode *>> MDs;
566 while (Lex.getKind() == lltok::MetadataVar) {
569 if (parseMetadataAttachment(MDK, N))
571 MDs.push_back({MDK, N});
575 if (parseFunctionHeader(F, false))
578 F->addMetadata(MD.first, *MD.second);
583 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
584 bool LLParser::parseDefine() {
585 assert(Lex.getKind() == lltok::kw_define);
589 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
590 parseFunctionBody(*F);
596 bool LLParser::parseGlobalType(bool &IsConstant) {
597 if (Lex.getKind() == lltok::kw_constant)
599 else if (Lex.getKind() == lltok::kw_global)
603 return tokError("expected 'global' or 'constant'");
609 bool LLParser::parseOptionalUnnamedAddr(
610 GlobalVariable::UnnamedAddr &UnnamedAddr) {
611 if (EatIfPresent(lltok::kw_unnamed_addr))
612 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
613 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
614 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
616 UnnamedAddr = GlobalValue::UnnamedAddr::None;
620 /// parseUnnamedGlobal:
621 /// OptionalVisibility (ALIAS | IFUNC) ...
622 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
623 /// OptionalDLLStorageClass
624 /// ... -> global variable
625 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
626 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
627 /// OptionalVisibility
628 /// OptionalDLLStorageClass
629 /// ... -> global variable
630 bool LLParser::parseUnnamedGlobal() {
631 unsigned VarID = NumberedVals.size();
633 LocTy NameLoc = Lex.getLoc();
635 // Handle the GlobalID form.
636 if (Lex.getKind() == lltok::GlobalID) {
637 if (Lex.getUIntVal() != VarID)
638 return error(Lex.getLoc(),
639 "variable expected to be numbered '%" + Twine(VarID) + "'");
640 Lex.Lex(); // eat GlobalID;
642 if (parseToken(lltok::equal, "expected '=' after name"))
647 unsigned Linkage, Visibility, DLLStorageClass;
649 GlobalVariable::ThreadLocalMode TLM;
650 GlobalVariable::UnnamedAddr UnnamedAddr;
651 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
653 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
656 switch (Lex.getKind()) {
658 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
659 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
660 case lltok::kw_alias:
661 case lltok::kw_ifunc:
662 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
663 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
667 /// parseNamedGlobal:
668 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
669 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
670 /// OptionalVisibility OptionalDLLStorageClass
671 /// ... -> global variable
672 bool LLParser::parseNamedGlobal() {
673 assert(Lex.getKind() == lltok::GlobalVar);
674 LocTy NameLoc = Lex.getLoc();
675 std::string Name = Lex.getStrVal();
679 unsigned Linkage, Visibility, DLLStorageClass;
681 GlobalVariable::ThreadLocalMode TLM;
682 GlobalVariable::UnnamedAddr UnnamedAddr;
683 if (parseToken(lltok::equal, "expected '=' in global variable") ||
684 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
686 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
689 switch (Lex.getKind()) {
691 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
692 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
693 case lltok::kw_alias:
694 case lltok::kw_ifunc:
695 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
696 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
700 bool LLParser::parseComdat() {
701 assert(Lex.getKind() == lltok::ComdatVar);
702 std::string Name = Lex.getStrVal();
703 LocTy NameLoc = Lex.getLoc();
706 if (parseToken(lltok::equal, "expected '=' here"))
709 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
710 return tokError("expected comdat type");
712 Comdat::SelectionKind SK;
713 switch (Lex.getKind()) {
715 return tokError("unknown selection kind");
719 case lltok::kw_exactmatch:
720 SK = Comdat::ExactMatch;
722 case lltok::kw_largest:
723 SK = Comdat::Largest;
725 case lltok::kw_nodeduplicate:
726 SK = Comdat::NoDeduplicate;
728 case lltok::kw_samesize:
729 SK = Comdat::SameSize;
734 // See if the comdat was forward referenced, if so, use the comdat.
735 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
736 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
737 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
738 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
741 if (I != ComdatSymTab.end())
744 C = M->getOrInsertComdat(Name);
745 C->setSelectionKind(SK);
751 // ::= '!' STRINGCONSTANT
752 bool LLParser::parseMDString(MDString *&Result) {
754 if (parseStringConstant(Str))
756 Result = MDString::get(Context, Str);
761 // ::= '!' MDNodeNumber
762 bool LLParser::parseMDNodeID(MDNode *&Result) {
763 // !{ ..., !42, ... }
764 LocTy IDLoc = Lex.getLoc();
766 if (parseUInt32(MID))
769 // If not a forward reference, just return it now.
770 if (NumberedMetadata.count(MID)) {
771 Result = NumberedMetadata[MID];
775 // Otherwise, create MDNode forward reference.
776 auto &FwdRef = ForwardRefMDNodes[MID];
777 FwdRef = std::make_pair(MDTuple::getTemporary(Context, std::nullopt), IDLoc);
779 Result = FwdRef.first.get();
780 NumberedMetadata[MID].reset(Result);
784 /// parseNamedMetadata:
785 /// !foo = !{ !1, !2 }
786 bool LLParser::parseNamedMetadata() {
787 assert(Lex.getKind() == lltok::MetadataVar);
788 std::string Name = Lex.getStrVal();
791 if (parseToken(lltok::equal, "expected '=' here") ||
792 parseToken(lltok::exclaim, "Expected '!' here") ||
793 parseToken(lltok::lbrace, "Expected '{' here"))
796 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
797 if (Lex.getKind() != lltok::rbrace)
800 // parse DIExpressions inline as a special case. They are still MDNodes,
801 // so they can still appear in named metadata. Remove this logic if they
802 // become plain Metadata.
803 if (Lex.getKind() == lltok::MetadataVar &&
804 Lex.getStrVal() == "DIExpression") {
805 if (parseDIExpression(N, /*IsDistinct=*/false))
807 // DIArgLists should only appear inline in a function, as they may
808 // contain LocalAsMetadata arguments which require a function context.
809 } else if (Lex.getKind() == lltok::MetadataVar &&
810 Lex.getStrVal() == "DIArgList") {
811 return tokError("found DIArgList outside of function");
812 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
817 } while (EatIfPresent(lltok::comma));
819 return parseToken(lltok::rbrace, "expected end of metadata node");
822 /// parseStandaloneMetadata:
824 bool LLParser::parseStandaloneMetadata() {
825 assert(Lex.getKind() == lltok::exclaim);
827 unsigned MetadataID = 0;
830 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
833 // Detect common error, from old metadata syntax.
834 if (Lex.getKind() == lltok::Type)
835 return tokError("unexpected type in metadata definition");
837 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
838 if (Lex.getKind() == lltok::MetadataVar) {
839 if (parseSpecializedMDNode(Init, IsDistinct))
841 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
842 parseMDTuple(Init, IsDistinct))
845 // See if this was forward referenced, if so, handle it.
846 auto FI = ForwardRefMDNodes.find(MetadataID);
847 if (FI != ForwardRefMDNodes.end()) {
848 auto *ToReplace = FI->second.first.get();
849 // DIAssignID has its own special forward-reference "replacement" for
850 // attachments (the temporary attachments are never actually attached).
851 if (isa<DIAssignID>(Init)) {
852 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
853 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
854 "Inst unexpectedly already has DIAssignID attachment");
855 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
859 ToReplace->replaceAllUsesWith(Init);
860 ForwardRefMDNodes.erase(FI);
862 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
864 if (NumberedMetadata.count(MetadataID))
865 return tokError("Metadata id is already used");
866 NumberedMetadata[MetadataID].reset(Init);
872 // Skips a single module summary entry.
873 bool LLParser::skipModuleSummaryEntry() {
874 // Each module summary entry consists of a tag for the entry
875 // type, followed by a colon, then the fields which may be surrounded by
876 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
877 // support is in place we will look for the tokens corresponding to the
879 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
880 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
881 Lex.getKind() != lltok::kw_blockcount)
883 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
884 "start of summary entry");
885 if (Lex.getKind() == lltok::kw_flags)
886 return parseSummaryIndexFlags();
887 if (Lex.getKind() == lltok::kw_blockcount)
888 return parseBlockCount();
890 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
891 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
893 // Now walk through the parenthesized entry, until the number of open
894 // parentheses goes back down to 0 (the first '(' was parsed above).
895 unsigned NumOpenParen = 1;
897 switch (Lex.getKind()) {
905 return tokError("found end of file while parsing summary entry");
907 // Skip everything in between parentheses.
911 } while (NumOpenParen > 0);
916 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
917 bool LLParser::parseSummaryEntry() {
918 assert(Lex.getKind() == lltok::SummaryID);
919 unsigned SummaryID = Lex.getUIntVal();
921 // For summary entries, colons should be treated as distinct tokens,
922 // not an indication of the end of a label token.
923 Lex.setIgnoreColonInIdentifiers(true);
926 if (parseToken(lltok::equal, "expected '=' here"))
929 // If we don't have an index object, skip the summary entry.
931 return skipModuleSummaryEntry();
934 switch (Lex.getKind()) {
936 result = parseGVEntry(SummaryID);
938 case lltok::kw_module:
939 result = parseModuleEntry(SummaryID);
941 case lltok::kw_typeid:
942 result = parseTypeIdEntry(SummaryID);
944 case lltok::kw_typeidCompatibleVTable:
945 result = parseTypeIdCompatibleVtableEntry(SummaryID);
947 case lltok::kw_flags:
948 result = parseSummaryIndexFlags();
950 case lltok::kw_blockcount:
951 result = parseBlockCount();
954 result = error(Lex.getLoc(), "unexpected summary kind");
957 Lex.setIgnoreColonInIdentifiers(false);
961 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
962 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
963 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
965 static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
966 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
967 (GlobalValue::DLLStorageClassTypes)S == GlobalValue::DefaultStorageClass;
970 // If there was an explicit dso_local, update GV. In the absence of an explicit
971 // dso_local we keep the default value.
972 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
974 GV.setDSOLocal(true);
977 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
979 std::string ErrString;
980 raw_string_ostream ErrOS(ErrString);
981 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
985 /// parseAliasOrIFunc:
986 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
987 /// OptionalVisibility OptionalDLLStorageClass
988 /// OptionalThreadLocal OptionalUnnamedAddr
989 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
991 /// AliaseeOrResolver
995 /// ::= ',' 'partition' StringConstant
997 /// Everything through OptionalUnnamedAddr has already been parsed.
999 bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc,
1000 unsigned L, unsigned Visibility,
1001 unsigned DLLStorageClass, bool DSOLocal,
1002 GlobalVariable::ThreadLocalMode TLM,
1003 GlobalVariable::UnnamedAddr UnnamedAddr) {
1005 if (Lex.getKind() == lltok::kw_alias)
1007 else if (Lex.getKind() == lltok::kw_ifunc)
1010 llvm_unreachable("Not an alias or ifunc!");
1013 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
1015 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1016 return error(NameLoc, "invalid linkage type for alias");
1018 if (!isValidVisibilityForLinkage(Visibility, L))
1019 return error(NameLoc,
1020 "symbol with local linkage must have default visibility");
1022 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1023 return error(NameLoc,
1024 "symbol with local linkage cannot have a DLL storage class");
1027 LocTy ExplicitTypeLoc = Lex.getLoc();
1028 if (parseType(Ty) ||
1029 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1033 LocTy AliaseeLoc = Lex.getLoc();
1034 if (Lex.getKind() != lltok::kw_bitcast &&
1035 Lex.getKind() != lltok::kw_getelementptr &&
1036 Lex.getKind() != lltok::kw_addrspacecast &&
1037 Lex.getKind() != lltok::kw_inttoptr) {
1038 if (parseGlobalTypeAndValue(Aliasee))
1041 // The bitcast dest type is not present, it is implied by the dest type.
1043 if (parseValID(ID, /*PFS=*/nullptr))
1045 if (ID.Kind != ValID::t_Constant)
1046 return error(AliaseeLoc, "invalid aliasee");
1047 Aliasee = ID.ConstantVal;
1050 Type *AliaseeType = Aliasee->getType();
1051 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1053 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1054 unsigned AddrSpace = PTy->getAddressSpace();
1057 if (!PTy->isOpaqueOrPointeeTypeMatches(Ty))
1060 typeComparisonErrorMessage(
1061 "explicit pointee type doesn't match operand's pointee type", Ty,
1062 PTy->getNonOpaquePointerElementType()));
1064 if (!PTy->isOpaque() &&
1065 !PTy->getNonOpaquePointerElementType()->isFunctionTy())
1066 return error(ExplicitTypeLoc,
1067 "explicit pointee type should be a function type");
1070 GlobalValue *GVal = nullptr;
1072 // See if the alias was forward referenced, if so, prepare to replace the
1073 // forward reference.
1074 if (!Name.empty()) {
1075 auto I = ForwardRefVals.find(Name);
1076 if (I != ForwardRefVals.end()) {
1077 GVal = I->second.first;
1078 ForwardRefVals.erase(Name);
1079 } else if (M->getNamedValue(Name)) {
1080 return error(NameLoc, "redefinition of global '@" + Name + "'");
1083 auto I = ForwardRefValIDs.find(NumberedVals.size());
1084 if (I != ForwardRefValIDs.end()) {
1085 GVal = I->second.first;
1086 ForwardRefValIDs.erase(I);
1090 // Okay, create the alias/ifunc but do not insert it into the module yet.
1091 std::unique_ptr<GlobalAlias> GA;
1092 std::unique_ptr<GlobalIFunc> GI;
1095 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1096 (GlobalValue::LinkageTypes)Linkage, Name,
1097 Aliasee, /*Parent*/ nullptr));
1100 GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1101 (GlobalValue::LinkageTypes)Linkage, Name,
1102 Aliasee, /*Parent*/ nullptr));
1105 GV->setThreadLocalMode(TLM);
1106 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1107 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1108 GV->setUnnamedAddr(UnnamedAddr);
1109 maybeSetDSOLocal(DSOLocal, *GV);
1111 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1112 // Now parse them if there are any.
1113 while (Lex.getKind() == lltok::comma) {
1116 if (Lex.getKind() == lltok::kw_partition) {
1118 GV->setPartition(Lex.getStrVal());
1119 if (parseToken(lltok::StringConstant, "expected partition string"))
1122 return tokError("unknown alias or ifunc property!");
1127 NumberedVals.push_back(GV);
1130 // Verify that types agree.
1131 if (GVal->getType() != GV->getType())
1134 "forward reference and definition of alias have different types");
1136 // If they agree, just RAUW the old value with the alias and remove the
1137 // forward ref info.
1138 GVal->replaceAllUsesWith(GV);
1139 GVal->eraseFromParent();
1142 // Insert into the module, we know its name won't collide now.
1144 M->insertAlias(GA.release());
1146 M->insertIFunc(GI.release());
1147 assert(GV->getName() == Name && "Should not be a name conflict!");
1152 static bool isSanitizer(lltok::Kind Kind) {
1154 case lltok::kw_no_sanitize_address:
1155 case lltok::kw_no_sanitize_hwaddress:
1156 case lltok::kw_sanitize_memtag:
1157 case lltok::kw_sanitize_address_dyninit:
1164 bool LLParser::parseSanitizer(GlobalVariable *GV) {
1165 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1166 SanitizerMetadata Meta;
1167 if (GV->hasSanitizerMetadata())
1168 Meta = GV->getSanitizerMetadata();
1170 switch (Lex.getKind()) {
1171 case lltok::kw_no_sanitize_address:
1172 Meta.NoAddress = true;
1174 case lltok::kw_no_sanitize_hwaddress:
1175 Meta.NoHWAddress = true;
1177 case lltok::kw_sanitize_memtag:
1180 case lltok::kw_sanitize_address_dyninit:
1181 Meta.IsDynInit = true;
1184 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1186 GV->setSanitizerMetadata(Meta);
1192 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1193 /// OptionalVisibility OptionalDLLStorageClass
1194 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1195 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1196 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1197 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1198 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1199 /// Const OptionalAttrs
1201 /// Everything up to and including OptionalUnnamedAddr has been parsed
1204 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1205 unsigned Linkage, bool HasLinkage,
1206 unsigned Visibility, unsigned DLLStorageClass,
1207 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1208 GlobalVariable::UnnamedAddr UnnamedAddr) {
1209 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1210 return error(NameLoc,
1211 "symbol with local linkage must have default visibility");
1213 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1214 return error(NameLoc,
1215 "symbol with local linkage cannot have a DLL storage class");
1218 bool IsConstant, IsExternallyInitialized;
1219 LocTy IsExternallyInitializedLoc;
1223 if (parseOptionalAddrSpace(AddrSpace) ||
1224 parseOptionalToken(lltok::kw_externally_initialized,
1225 IsExternallyInitialized,
1226 &IsExternallyInitializedLoc) ||
1227 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1230 // If the linkage is specified and is external, then no initializer is
1232 Constant *Init = nullptr;
1234 !GlobalValue::isValidDeclarationLinkage(
1235 (GlobalValue::LinkageTypes)Linkage)) {
1236 if (parseGlobalValue(Ty, Init))
1240 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1241 return error(TyLoc, "invalid type for global variable");
1243 GlobalValue *GVal = nullptr;
1245 // See if the global was forward referenced, if so, use the global.
1246 if (!Name.empty()) {
1247 auto I = ForwardRefVals.find(Name);
1248 if (I != ForwardRefVals.end()) {
1249 GVal = I->second.first;
1250 ForwardRefVals.erase(I);
1251 } else if (M->getNamedValue(Name)) {
1252 return error(NameLoc, "redefinition of global '@" + Name + "'");
1255 auto I = ForwardRefValIDs.find(NumberedVals.size());
1256 if (I != ForwardRefValIDs.end()) {
1257 GVal = I->second.first;
1258 ForwardRefValIDs.erase(I);
1262 GlobalVariable *GV = new GlobalVariable(
1263 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1264 GlobalVariable::NotThreadLocal, AddrSpace);
1267 NumberedVals.push_back(GV);
1269 // Set the parsed properties on the global.
1271 GV->setInitializer(Init);
1272 GV->setConstant(IsConstant);
1273 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1274 maybeSetDSOLocal(DSOLocal, *GV);
1275 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1276 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1277 GV->setExternallyInitialized(IsExternallyInitialized);
1278 GV->setThreadLocalMode(TLM);
1279 GV->setUnnamedAddr(UnnamedAddr);
1282 if (GVal->getAddressSpace() != AddrSpace)
1285 "forward reference and definition of global have different types");
1287 GVal->replaceAllUsesWith(GV);
1288 GVal->eraseFromParent();
1291 // parse attributes on the global.
1292 while (Lex.getKind() == lltok::comma) {
1295 if (Lex.getKind() == lltok::kw_section) {
1297 GV->setSection(Lex.getStrVal());
1298 if (parseToken(lltok::StringConstant, "expected global section string"))
1300 } else if (Lex.getKind() == lltok::kw_partition) {
1302 GV->setPartition(Lex.getStrVal());
1303 if (parseToken(lltok::StringConstant, "expected partition string"))
1305 } else if (Lex.getKind() == lltok::kw_align) {
1306 MaybeAlign Alignment;
1307 if (parseOptionalAlignment(Alignment))
1310 GV->setAlignment(*Alignment);
1311 } else if (Lex.getKind() == lltok::MetadataVar) {
1312 if (parseGlobalObjectMetadataAttachment(*GV))
1314 } else if (isSanitizer(Lex.getKind())) {
1315 if (parseSanitizer(GV))
1319 if (parseOptionalComdat(Name, C))
1324 return tokError("unknown global variable property!");
1328 AttrBuilder Attrs(M->getContext());
1330 std::vector<unsigned> FwdRefAttrGrps;
1331 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1333 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1334 GV->setAttributes(AttributeSet::get(Context, Attrs));
1335 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1341 /// parseUnnamedAttrGrp
1342 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1343 bool LLParser::parseUnnamedAttrGrp() {
1344 assert(Lex.getKind() == lltok::kw_attributes);
1345 LocTy AttrGrpLoc = Lex.getLoc();
1348 if (Lex.getKind() != lltok::AttrGrpID)
1349 return tokError("expected attribute group id");
1351 unsigned VarID = Lex.getUIntVal();
1352 std::vector<unsigned> unused;
1356 if (parseToken(lltok::equal, "expected '=' here") ||
1357 parseToken(lltok::lbrace, "expected '{' here"))
1360 auto R = NumberedAttrBuilders.find(VarID);
1361 if (R == NumberedAttrBuilders.end())
1362 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1364 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1365 parseToken(lltok::rbrace, "expected end of attribute group"))
1368 if (!R->second.hasAttributes())
1369 return error(AttrGrpLoc, "attribute group has no attributes");
1374 static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
1376 #define GET_ATTR_NAMES
1377 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1378 case lltok::kw_##DISPLAY_NAME: \
1379 return Attribute::ENUM_NAME;
1380 #include "llvm/IR/Attributes.inc"
1382 return Attribute::None;
1386 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1388 if (Attribute::isTypeAttrKind(Attr))
1389 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1392 case Attribute::Alignment: {
1393 MaybeAlign Alignment;
1397 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1399 Alignment = Align(Value);
1401 if (parseOptionalAlignment(Alignment, true))
1404 B.addAlignmentAttr(Alignment);
1407 case Attribute::StackAlignment: {
1411 if (parseToken(lltok::equal, "expected '=' here") ||
1412 parseUInt32(Alignment))
1415 if (parseOptionalStackAlignment(Alignment))
1418 B.addStackAlignmentAttr(Alignment);
1421 case Attribute::AllocSize: {
1422 unsigned ElemSizeArg;
1423 std::optional<unsigned> NumElemsArg;
1424 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1426 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1429 case Attribute::VScaleRange: {
1430 unsigned MinValue, MaxValue;
1431 if (parseVScaleRangeArguments(MinValue, MaxValue))
1433 B.addVScaleRangeAttr(MinValue,
1434 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1437 case Attribute::Dereferenceable: {
1439 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1441 B.addDereferenceableAttr(Bytes);
1444 case Attribute::DereferenceableOrNull: {
1446 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1448 B.addDereferenceableOrNullAttr(Bytes);
1451 case Attribute::UWTable: {
1453 if (parseOptionalUWTableKind(Kind))
1455 B.addUWTableAttr(Kind);
1458 case Attribute::AllocKind: {
1459 AllocFnKind Kind = AllocFnKind::Unknown;
1460 if (parseAllocKind(Kind))
1462 B.addAllocKindAttr(Kind);
1465 case Attribute::Memory: {
1466 std::optional<MemoryEffects> ME = parseMemoryAttr();
1469 B.addMemoryAttr(*ME);
1472 case Attribute::NoFPClass: {
1473 if (FPClassTest NoFPClass =
1474 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1475 B.addNoFPClassAttr(NoFPClass);
1482 B.addAttribute(Attr);
1488 static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind) {
1490 case lltok::kw_readnone:
1491 ME &= MemoryEffects::none();
1493 case lltok::kw_readonly:
1494 ME &= MemoryEffects::readOnly();
1496 case lltok::kw_writeonly:
1497 ME &= MemoryEffects::writeOnly();
1499 case lltok::kw_argmemonly:
1500 ME &= MemoryEffects::argMemOnly();
1502 case lltok::kw_inaccessiblememonly:
1503 ME &= MemoryEffects::inaccessibleMemOnly();
1505 case lltok::kw_inaccessiblemem_or_argmemonly:
1506 ME &= MemoryEffects::inaccessibleOrArgMemOnly();
1513 /// parseFnAttributeValuePairs
1514 /// ::= <attr> | <attr> '=' <value>
1515 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1516 std::vector<unsigned> &FwdRefAttrGrps,
1517 bool InAttrGrp, LocTy &BuiltinLoc) {
1518 bool HaveError = false;
1522 MemoryEffects ME = MemoryEffects::unknown();
1524 lltok::Kind Token = Lex.getKind();
1525 if (Token == lltok::rbrace)
1528 if (Token == lltok::StringConstant) {
1529 if (parseStringAttribute(B))
1534 if (Token == lltok::AttrGrpID) {
1535 // Allow a function to reference an attribute group:
1537 // define void @foo() #1 { ... }
1541 "cannot have an attribute group reference in an attribute group");
1543 // Save the reference to the attribute group. We'll fill it in later.
1544 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1550 SMLoc Loc = Lex.getLoc();
1551 if (Token == lltok::kw_builtin)
1554 if (upgradeMemoryAttr(ME, Token)) {
1559 Attribute::AttrKind Attr = tokenToAttribute(Token);
1560 if (Attr == Attribute::None) {
1563 return error(Lex.getLoc(), "unterminated attribute group");
1566 if (parseEnumAttribute(Attr, B, InAttrGrp))
1569 // As a hack, we allow function alignment to be initially parsed as an
1570 // attribute on a function declaration/definition or added to an attribute
1571 // group and later moved to the alignment field.
1572 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1573 HaveError |= error(Loc, "this attribute does not apply to functions");
1576 if (ME != MemoryEffects::unknown())
1577 B.addMemoryAttr(ME);
1581 //===----------------------------------------------------------------------===//
1582 // GlobalValue Reference/Resolution Routines.
1583 //===----------------------------------------------------------------------===//
1585 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
1586 // For opaque pointers, the used global type does not matter. We will later
1587 // RAUW it with a global/function of the correct type.
1588 if (PTy->isOpaque())
1589 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1590 GlobalValue::ExternalWeakLinkage, nullptr, "",
1591 nullptr, GlobalVariable::NotThreadLocal,
1592 PTy->getAddressSpace());
1594 Type *ElemTy = PTy->getNonOpaquePointerElementType();
1595 if (auto *FT = dyn_cast<FunctionType>(ElemTy))
1596 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1597 PTy->getAddressSpace(), "", M);
1599 return new GlobalVariable(
1600 *M, ElemTy, false, GlobalValue::ExternalWeakLinkage, nullptr, "",
1601 nullptr, GlobalVariable::NotThreadLocal, PTy->getAddressSpace());
1604 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1606 Type *ValTy = Val->getType();
1609 if (Ty->isLabelTy())
1610 error(Loc, "'" + Name + "' is not a basic block");
1612 error(Loc, "'" + Name + "' defined with type '" +
1613 getTypeString(Val->getType()) + "' but expected '" +
1614 getTypeString(Ty) + "'");
1618 /// getGlobalVal - Get a value with the specified name or ID, creating a
1619 /// forward reference record if needed. This can return null if the value
1620 /// exists but does not have the right type.
1621 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1623 PointerType *PTy = dyn_cast<PointerType>(Ty);
1625 error(Loc, "global variable reference must have pointer type");
1629 // Look this name up in the normal function symbol table.
1631 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1633 // If this is a forward reference for the value, see if we already created a
1634 // forward ref record.
1636 auto I = ForwardRefVals.find(Name);
1637 if (I != ForwardRefVals.end())
1638 Val = I->second.first;
1641 // If we have the value in the symbol table or fwd-ref table, return it.
1643 return cast_or_null<GlobalValue>(
1644 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1646 // Otherwise, create a new forward reference for this value and remember it.
1647 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1648 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1652 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1653 PointerType *PTy = dyn_cast<PointerType>(Ty);
1655 error(Loc, "global variable reference must have pointer type");
1659 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1661 // If this is a forward reference for the value, see if we already created a
1662 // forward ref record.
1664 auto I = ForwardRefValIDs.find(ID);
1665 if (I != ForwardRefValIDs.end())
1666 Val = I->second.first;
1669 // If we have the value in the symbol table or fwd-ref table, return it.
1671 return cast_or_null<GlobalValue>(
1672 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1674 // Otherwise, create a new forward reference for this value and remember it.
1675 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1676 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1680 //===----------------------------------------------------------------------===//
1681 // Comdat Reference/Resolution Routines.
1682 //===----------------------------------------------------------------------===//
1684 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1685 // Look this name up in the comdat symbol table.
1686 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1687 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1688 if (I != ComdatSymTab.end())
1691 // Otherwise, create a new forward reference for this value and remember it.
1692 Comdat *C = M->getOrInsertComdat(Name);
1693 ForwardRefComdats[Name] = Loc;
1697 //===----------------------------------------------------------------------===//
1699 //===----------------------------------------------------------------------===//
1701 /// parseToken - If the current token has the specified kind, eat it and return
1702 /// success. Otherwise, emit the specified error and return failure.
1703 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1704 if (Lex.getKind() != T)
1705 return tokError(ErrMsg);
1710 /// parseStringConstant
1711 /// ::= StringConstant
1712 bool LLParser::parseStringConstant(std::string &Result) {
1713 if (Lex.getKind() != lltok::StringConstant)
1714 return tokError("expected string constant");
1715 Result = Lex.getStrVal();
1722 bool LLParser::parseUInt32(uint32_t &Val) {
1723 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1724 return tokError("expected integer");
1725 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1726 if (Val64 != unsigned(Val64))
1727 return tokError("expected 32-bit integer (too large)");
1735 bool LLParser::parseUInt64(uint64_t &Val) {
1736 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1737 return tokError("expected integer");
1738 Val = Lex.getAPSIntVal().getLimitedValue();
1744 /// := 'localdynamic'
1745 /// := 'initialexec'
1747 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1748 switch (Lex.getKind()) {
1750 return tokError("expected localdynamic, initialexec or localexec");
1751 case lltok::kw_localdynamic:
1752 TLM = GlobalVariable::LocalDynamicTLSModel;
1754 case lltok::kw_initialexec:
1755 TLM = GlobalVariable::InitialExecTLSModel;
1757 case lltok::kw_localexec:
1758 TLM = GlobalVariable::LocalExecTLSModel;
1766 /// parseOptionalThreadLocal
1768 /// := 'thread_local'
1769 /// := 'thread_local' '(' tlsmodel ')'
1770 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1771 TLM = GlobalVariable::NotThreadLocal;
1772 if (!EatIfPresent(lltok::kw_thread_local))
1775 TLM = GlobalVariable::GeneralDynamicTLSModel;
1776 if (Lex.getKind() == lltok::lparen) {
1778 return parseTLSModel(TLM) ||
1779 parseToken(lltok::rparen, "expected ')' after thread local model");
1784 /// parseOptionalAddrSpace
1786 /// := 'addrspace' '(' uint32 ')'
1787 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1788 AddrSpace = DefaultAS;
1789 if (!EatIfPresent(lltok::kw_addrspace))
1792 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1793 if (Lex.getKind() == lltok::StringConstant) {
1794 auto AddrSpaceStr = Lex.getStrVal();
1795 if (AddrSpaceStr == "A") {
1796 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1797 } else if (AddrSpaceStr == "G") {
1798 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1799 } else if (AddrSpaceStr == "P") {
1800 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1802 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1807 if (Lex.getKind() != lltok::APSInt)
1808 return tokError("expected integer or string constant");
1809 SMLoc Loc = Lex.getLoc();
1810 if (parseUInt32(AddrSpace))
1812 if (!isUInt<24>(AddrSpace))
1813 return error(Loc, "invalid address space, must be a 24-bit integer");
1817 return parseToken(lltok::lparen, "expected '(' in address space") ||
1818 ParseAddrspaceValue(AddrSpace) ||
1819 parseToken(lltok::rparen, "expected ')' in address space");
1822 /// parseStringAttribute
1823 /// := StringConstant
1824 /// := StringConstant '=' StringConstant
1825 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1826 std::string Attr = Lex.getStrVal();
1829 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1831 B.addAttribute(Attr, Val);
1835 /// Parse a potentially empty list of parameter or return attributes.
1836 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1837 bool HaveError = false;
1842 lltok::Kind Token = Lex.getKind();
1843 if (Token == lltok::StringConstant) {
1844 if (parseStringAttribute(B))
1849 SMLoc Loc = Lex.getLoc();
1850 Attribute::AttrKind Attr = tokenToAttribute(Token);
1851 if (Attr == Attribute::None)
1854 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1857 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1858 HaveError |= error(Loc, "this attribute does not apply to parameters");
1859 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1860 HaveError |= error(Loc, "this attribute does not apply to return values");
1864 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1869 return GlobalValue::ExternalLinkage;
1870 case lltok::kw_private:
1871 return GlobalValue::PrivateLinkage;
1872 case lltok::kw_internal:
1873 return GlobalValue::InternalLinkage;
1874 case lltok::kw_weak:
1875 return GlobalValue::WeakAnyLinkage;
1876 case lltok::kw_weak_odr:
1877 return GlobalValue::WeakODRLinkage;
1878 case lltok::kw_linkonce:
1879 return GlobalValue::LinkOnceAnyLinkage;
1880 case lltok::kw_linkonce_odr:
1881 return GlobalValue::LinkOnceODRLinkage;
1882 case lltok::kw_available_externally:
1883 return GlobalValue::AvailableExternallyLinkage;
1884 case lltok::kw_appending:
1885 return GlobalValue::AppendingLinkage;
1886 case lltok::kw_common:
1887 return GlobalValue::CommonLinkage;
1888 case lltok::kw_extern_weak:
1889 return GlobalValue::ExternalWeakLinkage;
1890 case lltok::kw_external:
1891 return GlobalValue::ExternalLinkage;
1895 /// parseOptionalLinkage
1902 /// ::= 'linkonce_odr'
1903 /// ::= 'available_externally'
1906 /// ::= 'extern_weak'
1908 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1909 unsigned &Visibility,
1910 unsigned &DLLStorageClass, bool &DSOLocal) {
1911 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1914 parseOptionalDSOLocal(DSOLocal);
1915 parseOptionalVisibility(Visibility);
1916 parseOptionalDLLStorageClass(DLLStorageClass);
1918 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1919 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1925 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1926 switch (Lex.getKind()) {
1930 case lltok::kw_dso_local:
1934 case lltok::kw_dso_preemptable:
1941 /// parseOptionalVisibility
1947 void LLParser::parseOptionalVisibility(unsigned &Res) {
1948 switch (Lex.getKind()) {
1950 Res = GlobalValue::DefaultVisibility;
1952 case lltok::kw_default:
1953 Res = GlobalValue::DefaultVisibility;
1955 case lltok::kw_hidden:
1956 Res = GlobalValue::HiddenVisibility;
1958 case lltok::kw_protected:
1959 Res = GlobalValue::ProtectedVisibility;
1965 /// parseOptionalDLLStorageClass
1970 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1971 switch (Lex.getKind()) {
1973 Res = GlobalValue::DefaultStorageClass;
1975 case lltok::kw_dllimport:
1976 Res = GlobalValue::DLLImportStorageClass;
1978 case lltok::kw_dllexport:
1979 Res = GlobalValue::DLLExportStorageClass;
1985 /// parseOptionalCallingConv
1989 /// ::= 'intel_ocl_bicc'
1991 /// ::= 'cfguard_checkcc'
1992 /// ::= 'x86_stdcallcc'
1993 /// ::= 'x86_fastcallcc'
1994 /// ::= 'x86_thiscallcc'
1995 /// ::= 'x86_vectorcallcc'
1996 /// ::= 'arm_apcscc'
1997 /// ::= 'arm_aapcscc'
1998 /// ::= 'arm_aapcs_vfpcc'
1999 /// ::= 'aarch64_vector_pcs'
2000 /// ::= 'aarch64_sve_vector_pcs'
2001 /// ::= 'aarch64_sme_preservemost_from_x0'
2002 /// ::= 'aarch64_sme_preservemost_from_x2'
2003 /// ::= 'msp430_intrcc'
2004 /// ::= 'avr_intrcc'
2005 /// ::= 'avr_signalcc'
2006 /// ::= 'ptx_kernel'
2007 /// ::= 'ptx_device'
2009 /// ::= 'spir_kernel'
2010 /// ::= 'x86_64_sysvcc'
2012 /// ::= 'webkit_jscc'
2014 /// ::= 'preserve_mostcc'
2015 /// ::= 'preserve_allcc'
2018 /// ::= 'swifttailcc'
2019 /// ::= 'x86_intrcc'
2022 /// ::= 'cxx_fast_tlscc'
2030 /// ::= 'amdgpu_cs_chain'
2031 /// ::= 'amdgpu_cs_chain_preserve'
2032 /// ::= 'amdgpu_kernel'
2036 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2037 switch (Lex.getKind()) {
2038 default: CC = CallingConv::C; return false;
2039 case lltok::kw_ccc: CC = CallingConv::C; break;
2040 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2041 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2042 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
2043 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
2044 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
2045 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
2046 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
2047 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
2048 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
2049 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
2050 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
2051 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
2052 case lltok::kw_aarch64_sve_vector_pcs:
2053 CC = CallingConv::AArch64_SVE_VectorCall;
2055 case lltok::kw_aarch64_sme_preservemost_from_x0:
2056 CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0;
2058 case lltok::kw_aarch64_sme_preservemost_from_x2:
2059 CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2;
2061 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
2062 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
2063 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
2064 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
2065 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
2066 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
2067 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
2068 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
2069 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
2070 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2071 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
2072 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2073 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
2074 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
2075 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2076 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2077 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
2078 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
2079 case lltok::kw_hhvmcc:
2080 CC = CallingConv::DUMMY_HHVM;
2082 case lltok::kw_hhvm_ccc:
2083 CC = CallingConv::DUMMY_HHVM_C;
2085 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
2086 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
2087 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
2088 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
2089 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2090 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2091 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2092 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2093 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2094 case lltok::kw_amdgpu_cs_chain:
2095 CC = CallingConv::AMDGPU_CS_Chain;
2097 case lltok::kw_amdgpu_cs_chain_preserve:
2098 CC = CallingConv::AMDGPU_CS_ChainPreserve;
2100 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
2101 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2102 case lltok::kw_cc: {
2104 return parseUInt32(CC);
2112 /// parseMetadataAttachment
2114 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2115 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2117 std::string Name = Lex.getStrVal();
2118 Kind = M->getMDKindID(Name);
2121 return parseMDNode(MD);
2124 /// parseInstructionMetadata
2125 /// ::= !dbg !42 (',' !dbg !57)*
2126 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2128 if (Lex.getKind() != lltok::MetadataVar)
2129 return tokError("expected metadata after comma");
2133 if (parseMetadataAttachment(MDK, N))
2136 if (MDK == LLVMContext::MD_DIAssignID)
2137 TempDIAssignIDAttachments[N].push_back(&Inst);
2139 Inst.setMetadata(MDK, N);
2141 if (MDK == LLVMContext::MD_tbaa)
2142 InstsWithTBAATag.push_back(&Inst);
2144 // If this is the end of the list, we're done.
2145 } while (EatIfPresent(lltok::comma));
2149 /// parseGlobalObjectMetadataAttachment
2151 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2154 if (parseMetadataAttachment(MDK, N))
2157 GO.addMetadata(MDK, *N);
2161 /// parseOptionalFunctionMetadata
2163 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2164 while (Lex.getKind() == lltok::MetadataVar)
2165 if (parseGlobalObjectMetadataAttachment(F))
2170 /// parseOptionalAlignment
2173 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2174 Alignment = std::nullopt;
2175 if (!EatIfPresent(lltok::kw_align))
2177 LocTy AlignLoc = Lex.getLoc();
2180 LocTy ParenLoc = Lex.getLoc();
2181 bool HaveParens = false;
2183 if (EatIfPresent(lltok::lparen))
2187 if (parseUInt64(Value))
2190 if (HaveParens && !EatIfPresent(lltok::rparen))
2191 return error(ParenLoc, "expected ')'");
2193 if (!isPowerOf2_64(Value))
2194 return error(AlignLoc, "alignment is not a power of two");
2195 if (Value > Value::MaximumAlignment)
2196 return error(AlignLoc, "huge alignments are not supported yet");
2197 Alignment = Align(Value);
2201 /// parseOptionalDerefAttrBytes
2203 /// ::= AttrKind '(' 4 ')'
2205 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2206 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2208 assert((AttrKind == lltok::kw_dereferenceable ||
2209 AttrKind == lltok::kw_dereferenceable_or_null) &&
2213 if (!EatIfPresent(AttrKind))
2215 LocTy ParenLoc = Lex.getLoc();
2216 if (!EatIfPresent(lltok::lparen))
2217 return error(ParenLoc, "expected '('");
2218 LocTy DerefLoc = Lex.getLoc();
2219 if (parseUInt64(Bytes))
2221 ParenLoc = Lex.getLoc();
2222 if (!EatIfPresent(lltok::rparen))
2223 return error(ParenLoc, "expected ')'");
2225 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2229 bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2231 Kind = UWTableKind::Default;
2232 if (!EatIfPresent(lltok::lparen))
2234 LocTy KindLoc = Lex.getLoc();
2235 if (Lex.getKind() == lltok::kw_sync)
2236 Kind = UWTableKind::Sync;
2237 else if (Lex.getKind() == lltok::kw_async)
2238 Kind = UWTableKind::Async;
2240 return error(KindLoc, "expected unwind table kind");
2242 return parseToken(lltok::rparen, "expected ')'");
2245 bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2247 LocTy ParenLoc = Lex.getLoc();
2248 if (!EatIfPresent(lltok::lparen))
2249 return error(ParenLoc, "expected '('");
2250 LocTy KindLoc = Lex.getLoc();
2252 if (parseStringConstant(Arg))
2253 return error(KindLoc, "expected allockind value");
2254 for (StringRef A : llvm::split(Arg, ",")) {
2256 Kind |= AllocFnKind::Alloc;
2257 } else if (A == "realloc") {
2258 Kind |= AllocFnKind::Realloc;
2259 } else if (A == "free") {
2260 Kind |= AllocFnKind::Free;
2261 } else if (A == "uninitialized") {
2262 Kind |= AllocFnKind::Uninitialized;
2263 } else if (A == "zeroed") {
2264 Kind |= AllocFnKind::Zeroed;
2265 } else if (A == "aligned") {
2266 Kind |= AllocFnKind::Aligned;
2268 return error(KindLoc, Twine("unknown allockind ") + A);
2271 ParenLoc = Lex.getLoc();
2272 if (!EatIfPresent(lltok::rparen))
2273 return error(ParenLoc, "expected ')'");
2274 if (Kind == AllocFnKind::Unknown)
2275 return error(KindLoc, "expected allockind value");
2279 static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2281 case lltok::kw_argmem:
2282 return IRMemLocation::ArgMem;
2283 case lltok::kw_inaccessiblemem:
2284 return IRMemLocation::InaccessibleMem;
2286 return std::nullopt;
2290 static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2292 case lltok::kw_none:
2293 return ModRefInfo::NoModRef;
2294 case lltok::kw_read:
2295 return ModRefInfo::Ref;
2296 case lltok::kw_write:
2297 return ModRefInfo::Mod;
2298 case lltok::kw_readwrite:
2299 return ModRefInfo::ModRef;
2301 return std::nullopt;
2305 std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2306 MemoryEffects ME = MemoryEffects::none();
2308 // We use syntax like memory(argmem: read), so the colon should not be
2309 // interpreted as a label terminator.
2310 Lex.setIgnoreColonInIdentifiers(true);
2311 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2314 if (!EatIfPresent(lltok::lparen)) {
2315 tokError("expected '('");
2316 return std::nullopt;
2319 bool SeenLoc = false;
2321 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2324 if (!EatIfPresent(lltok::colon)) {
2325 tokError("expected ':' after location");
2326 return std::nullopt;
2330 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2333 tokError("expected memory location (argmem, inaccessiblemem) "
2334 "or access kind (none, read, write, readwrite)");
2336 tokError("expected access kind (none, read, write, readwrite)");
2337 return std::nullopt;
2343 ME = ME.getWithModRef(*Loc, *MR);
2346 tokError("default access kind must be specified first");
2347 return std::nullopt;
2349 ME = MemoryEffects(*MR);
2352 if (EatIfPresent(lltok::rparen))
2354 } while (EatIfPresent(lltok::comma));
2356 tokError("unterminated memory attribute");
2357 return std::nullopt;
2360 static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2366 case lltok::kw_snan:
2368 case lltok::kw_qnan:
2372 case lltok::kw_ninf:
2374 case lltok::kw_pinf:
2376 case lltok::kw_norm:
2378 case lltok::kw_nnorm:
2380 case lltok::kw_pnorm:
2384 case lltok::kw_nsub:
2385 return fcNegSubnormal;
2386 case lltok::kw_psub:
2387 return fcPosSubnormal;
2388 case lltok::kw_zero:
2390 case lltok::kw_nzero:
2392 case lltok::kw_pzero:
2399 unsigned LLParser::parseNoFPClassAttr() {
2400 unsigned Mask = fcNone;
2403 if (!EatIfPresent(lltok::lparen)) {
2404 tokError("expected '('");
2410 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2411 if (TestMask != 0) {
2413 // TODO: Disallow overlapping masks to avoid copy paste errors
2414 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2415 !parseUInt64(Value)) {
2416 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2417 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2421 if (!EatIfPresent(lltok::rparen)) {
2422 error(Lex.getLoc(), "expected ')'");
2428 error(Lex.getLoc(), "expected nofpclass test mask");
2433 if (EatIfPresent(lltok::rparen))
2437 llvm_unreachable("unterminated nofpclass attribute");
2440 /// parseOptionalCommaAlign
2444 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2446 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2447 bool &AteExtraComma) {
2448 AteExtraComma = false;
2449 while (EatIfPresent(lltok::comma)) {
2450 // Metadata at the end is an early exit.
2451 if (Lex.getKind() == lltok::MetadataVar) {
2452 AteExtraComma = true;
2456 if (Lex.getKind() != lltok::kw_align)
2457 return error(Lex.getLoc(), "expected metadata or 'align'");
2459 if (parseOptionalAlignment(Alignment))
2466 /// parseOptionalCommaAddrSpace
2468 /// ::= ',' addrspace(1)
2470 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2472 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2473 bool &AteExtraComma) {
2474 AteExtraComma = false;
2475 while (EatIfPresent(lltok::comma)) {
2476 // Metadata at the end is an early exit.
2477 if (Lex.getKind() == lltok::MetadataVar) {
2478 AteExtraComma = true;
2483 if (Lex.getKind() != lltok::kw_addrspace)
2484 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2486 if (parseOptionalAddrSpace(AddrSpace))
2493 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2494 std::optional<unsigned> &HowManyArg) {
2497 auto StartParen = Lex.getLoc();
2498 if (!EatIfPresent(lltok::lparen))
2499 return error(StartParen, "expected '('");
2501 if (parseUInt32(BaseSizeArg))
2504 if (EatIfPresent(lltok::comma)) {
2505 auto HowManyAt = Lex.getLoc();
2507 if (parseUInt32(HowMany))
2509 if (HowMany == BaseSizeArg)
2510 return error(HowManyAt,
2511 "'allocsize' indices can't refer to the same parameter");
2512 HowManyArg = HowMany;
2514 HowManyArg = std::nullopt;
2516 auto EndParen = Lex.getLoc();
2517 if (!EatIfPresent(lltok::rparen))
2518 return error(EndParen, "expected ')'");
2522 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2523 unsigned &MaxValue) {
2526 auto StartParen = Lex.getLoc();
2527 if (!EatIfPresent(lltok::lparen))
2528 return error(StartParen, "expected '('");
2530 if (parseUInt32(MinValue))
2533 if (EatIfPresent(lltok::comma)) {
2534 if (parseUInt32(MaxValue))
2537 MaxValue = MinValue;
2539 auto EndParen = Lex.getLoc();
2540 if (!EatIfPresent(lltok::rparen))
2541 return error(EndParen, "expected ')'");
2545 /// parseScopeAndOrdering
2546 /// if isAtomic: ::= SyncScope? AtomicOrdering
2549 /// This sets Scope and Ordering to the parsed values.
2550 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2551 AtomicOrdering &Ordering) {
2555 return parseScope(SSID) || parseOrdering(Ordering);
2559 /// ::= syncscope("singlethread" | "<target scope>")?
2561 /// This sets synchronization scope ID to the ID of the parsed value.
2562 bool LLParser::parseScope(SyncScope::ID &SSID) {
2563 SSID = SyncScope::System;
2564 if (EatIfPresent(lltok::kw_syncscope)) {
2565 auto StartParenAt = Lex.getLoc();
2566 if (!EatIfPresent(lltok::lparen))
2567 return error(StartParenAt, "Expected '(' in syncscope");
2570 auto SSNAt = Lex.getLoc();
2571 if (parseStringConstant(SSN))
2572 return error(SSNAt, "Expected synchronization scope name");
2574 auto EndParenAt = Lex.getLoc();
2575 if (!EatIfPresent(lltok::rparen))
2576 return error(EndParenAt, "Expected ')' in syncscope");
2578 SSID = Context.getOrInsertSyncScopeID(SSN);
2585 /// ::= AtomicOrdering
2587 /// This sets Ordering to the parsed value.
2588 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2589 switch (Lex.getKind()) {
2591 return tokError("Expected ordering on atomic instruction");
2592 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2593 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2594 // Not specified yet:
2595 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2596 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2597 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2598 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2599 case lltok::kw_seq_cst:
2600 Ordering = AtomicOrdering::SequentiallyConsistent;
2607 /// parseOptionalStackAlignment
2609 /// ::= 'alignstack' '(' 4 ')'
2610 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2612 if (!EatIfPresent(lltok::kw_alignstack))
2614 LocTy ParenLoc = Lex.getLoc();
2615 if (!EatIfPresent(lltok::lparen))
2616 return error(ParenLoc, "expected '('");
2617 LocTy AlignLoc = Lex.getLoc();
2618 if (parseUInt32(Alignment))
2620 ParenLoc = Lex.getLoc();
2621 if (!EatIfPresent(lltok::rparen))
2622 return error(ParenLoc, "expected ')'");
2623 if (!isPowerOf2_32(Alignment))
2624 return error(AlignLoc, "stack alignment is not a power of two");
2628 /// parseIndexList - This parses the index list for an insert/extractvalue
2629 /// instruction. This sets AteExtraComma in the case where we eat an extra
2630 /// comma at the end of the line and find that it is followed by metadata.
2631 /// Clients that don't allow metadata can call the version of this function that
2632 /// only takes one argument.
2635 /// ::= (',' uint32)+
2637 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2638 bool &AteExtraComma) {
2639 AteExtraComma = false;
2641 if (Lex.getKind() != lltok::comma)
2642 return tokError("expected ',' as start of index list");
2644 while (EatIfPresent(lltok::comma)) {
2645 if (Lex.getKind() == lltok::MetadataVar) {
2646 if (Indices.empty())
2647 return tokError("expected index");
2648 AteExtraComma = true;
2652 if (parseUInt32(Idx))
2654 Indices.push_back(Idx);
2660 //===----------------------------------------------------------------------===//
2662 //===----------------------------------------------------------------------===//
2664 /// parseType - parse a type.
2665 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2666 SMLoc TypeLoc = Lex.getLoc();
2667 switch (Lex.getKind()) {
2669 return tokError(Msg);
2671 // Type ::= 'float' | 'void' (etc)
2672 Result = Lex.getTyVal();
2675 // Handle "ptr" opaque pointer type.
2677 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2678 if (Result->isPointerTy()) {
2680 if (parseOptionalAddrSpace(AddrSpace))
2682 Result = PointerType::get(getContext(), AddrSpace);
2684 // Give a nice error for 'ptr*'.
2685 if (Lex.getKind() == lltok::star)
2686 return tokError("ptr* is invalid - use ptr instead");
2688 // Fall through to parsing the type suffixes only if this 'ptr' is a
2689 // function return. Otherwise, return success, implicitly rejecting other
2691 if (Lex.getKind() != lltok::lparen)
2695 case lltok::kw_target: {
2696 // Type ::= TargetExtType
2697 if (parseTargetExtType(Result))
2702 // Type ::= StructType
2703 if (parseAnonStructType(Result, false))
2706 case lltok::lsquare:
2707 // Type ::= '[' ... ']'
2708 Lex.Lex(); // eat the lsquare.
2709 if (parseArrayVectorType(Result, false))
2712 case lltok::less: // Either vector or packed struct.
2713 // Type ::= '<' ... '>'
2715 if (Lex.getKind() == lltok::lbrace) {
2716 if (parseAnonStructType(Result, true) ||
2717 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2719 } else if (parseArrayVectorType(Result, true))
2722 case lltok::LocalVar: {
2724 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2726 // If the type hasn't been defined yet, create a forward definition and
2727 // remember where that forward def'n was seen (in case it never is defined).
2729 Entry.first = StructType::create(Context, Lex.getStrVal());
2730 Entry.second = Lex.getLoc();
2732 Result = Entry.first;
2737 case lltok::LocalVarID: {
2739 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2741 // If the type hasn't been defined yet, create a forward definition and
2742 // remember where that forward def'n was seen (in case it never is defined).
2744 Entry.first = StructType::create(Context);
2745 Entry.second = Lex.getLoc();
2747 Result = Entry.first;
2753 // parse the type suffixes.
2755 switch (Lex.getKind()) {
2758 if (!AllowVoid && Result->isVoidTy())
2759 return error(TypeLoc, "void type only allowed for function results");
2762 // Type ::= Type '*'
2764 if (Result->isLabelTy())
2765 return tokError("basic block pointers are invalid");
2766 if (Result->isVoidTy())
2767 return tokError("pointers to void are invalid - use i8* instead");
2768 if (!PointerType::isValidElementType(Result))
2769 return tokError("pointer to this type is invalid");
2770 Result = PointerType::getUnqual(Result);
2774 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2775 case lltok::kw_addrspace: {
2776 if (Result->isLabelTy())
2777 return tokError("basic block pointers are invalid");
2778 if (Result->isVoidTy())
2779 return tokError("pointers to void are invalid; use i8* instead");
2780 if (!PointerType::isValidElementType(Result))
2781 return tokError("pointer to this type is invalid");
2783 if (parseOptionalAddrSpace(AddrSpace) ||
2784 parseToken(lltok::star, "expected '*' in address space"))
2787 Result = PointerType::get(Result, AddrSpace);
2791 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2793 if (parseFunctionType(Result))
2800 /// parseParameterList
2802 /// ::= '(' Arg (',' Arg)* ')'
2804 /// ::= Type OptionalAttributes Value OptionalAttributes
2805 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2806 PerFunctionState &PFS, bool IsMustTailCall,
2807 bool InVarArgsFunc) {
2808 if (parseToken(lltok::lparen, "expected '(' in call"))
2811 while (Lex.getKind() != lltok::rparen) {
2812 // If this isn't the first argument, we need a comma.
2813 if (!ArgList.empty() &&
2814 parseToken(lltok::comma, "expected ',' in argument list"))
2817 // parse an ellipsis if this is a musttail call in a variadic function.
2818 if (Lex.getKind() == lltok::dotdotdot) {
2819 const char *Msg = "unexpected ellipsis in argument list for ";
2820 if (!IsMustTailCall)
2821 return tokError(Twine(Msg) + "non-musttail call");
2823 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2824 Lex.Lex(); // Lex the '...', it is purely for readability.
2825 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2828 // parse the argument.
2830 Type *ArgTy = nullptr;
2832 if (parseType(ArgTy, ArgLoc))
2835 AttrBuilder ArgAttrs(M->getContext());
2837 if (ArgTy->isMetadataTy()) {
2838 if (parseMetadataAsValue(V, PFS))
2841 // Otherwise, handle normal operands.
2842 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2845 ArgList.push_back(ParamInfo(
2846 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2849 if (IsMustTailCall && InVarArgsFunc)
2850 return tokError("expected '...' at end of argument list for musttail call "
2851 "in varargs function");
2853 Lex.Lex(); // Lex the ')'.
2857 /// parseRequiredTypeAttr
2858 /// ::= attrname(<ty>)
2859 bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2860 Attribute::AttrKind AttrKind) {
2862 if (!EatIfPresent(AttrToken))
2864 if (!EatIfPresent(lltok::lparen))
2865 return error(Lex.getLoc(), "expected '('");
2868 if (!EatIfPresent(lltok::rparen))
2869 return error(Lex.getLoc(), "expected ')'");
2871 B.addTypeAttr(AttrKind, Ty);
2875 /// parseOptionalOperandBundles
2877 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2880 /// ::= bundle-tag '(' ')'
2881 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2883 /// bundle-tag ::= String Constant
2884 bool LLParser::parseOptionalOperandBundles(
2885 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2886 LocTy BeginLoc = Lex.getLoc();
2887 if (!EatIfPresent(lltok::lsquare))
2890 while (Lex.getKind() != lltok::rsquare) {
2891 // If this isn't the first operand bundle, we need a comma.
2892 if (!BundleList.empty() &&
2893 parseToken(lltok::comma, "expected ',' in input list"))
2897 if (parseStringConstant(Tag))
2900 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2903 std::vector<Value *> Inputs;
2904 while (Lex.getKind() != lltok::rparen) {
2905 // If this isn't the first input, we need a comma.
2906 if (!Inputs.empty() &&
2907 parseToken(lltok::comma, "expected ',' in input list"))
2911 Value *Input = nullptr;
2912 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2914 Inputs.push_back(Input);
2917 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2919 Lex.Lex(); // Lex the ')'.
2922 if (BundleList.empty())
2923 return error(BeginLoc, "operand bundle set must not be empty");
2925 Lex.Lex(); // Lex the ']'.
2929 /// parseArgumentList - parse the argument list for a function type or function
2931 /// ::= '(' ArgTypeListI ')'
2935 /// ::= ArgTypeList ',' '...'
2936 /// ::= ArgType (',' ArgType)*
2938 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2940 unsigned CurValID = 0;
2942 assert(Lex.getKind() == lltok::lparen);
2943 Lex.Lex(); // eat the (.
2945 if (Lex.getKind() == lltok::rparen) {
2947 } else if (Lex.getKind() == lltok::dotdotdot) {
2951 LocTy TypeLoc = Lex.getLoc();
2952 Type *ArgTy = nullptr;
2953 AttrBuilder Attrs(M->getContext());
2956 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2959 if (ArgTy->isVoidTy())
2960 return error(TypeLoc, "argument can not have void type");
2962 if (Lex.getKind() == lltok::LocalVar) {
2963 Name = Lex.getStrVal();
2965 } else if (Lex.getKind() == lltok::LocalVarID) {
2966 if (Lex.getUIntVal() != CurValID)
2967 return error(TypeLoc, "argument expected to be numbered '%" +
2968 Twine(CurValID) + "'");
2973 if (!FunctionType::isValidArgumentType(ArgTy))
2974 return error(TypeLoc, "invalid type for function argument");
2976 ArgList.emplace_back(TypeLoc, ArgTy,
2977 AttributeSet::get(ArgTy->getContext(), Attrs),
2980 while (EatIfPresent(lltok::comma)) {
2981 // Handle ... at end of arg list.
2982 if (EatIfPresent(lltok::dotdotdot)) {
2987 // Otherwise must be an argument type.
2988 TypeLoc = Lex.getLoc();
2989 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2992 if (ArgTy->isVoidTy())
2993 return error(TypeLoc, "argument can not have void type");
2995 if (Lex.getKind() == lltok::LocalVar) {
2996 Name = Lex.getStrVal();
2999 if (Lex.getKind() == lltok::LocalVarID) {
3000 if (Lex.getUIntVal() != CurValID)
3001 return error(TypeLoc, "argument expected to be numbered '%" +
3002 Twine(CurValID) + "'");
3009 if (!ArgTy->isFirstClassType())
3010 return error(TypeLoc, "invalid type for function argument");
3012 ArgList.emplace_back(TypeLoc, ArgTy,
3013 AttributeSet::get(ArgTy->getContext(), Attrs),
3018 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3021 /// parseFunctionType
3022 /// ::= Type ArgumentList OptionalAttrs
3023 bool LLParser::parseFunctionType(Type *&Result) {
3024 assert(Lex.getKind() == lltok::lparen);
3026 if (!FunctionType::isValidReturnType(Result))
3027 return tokError("invalid function return type");
3029 SmallVector<ArgInfo, 8> ArgList;
3031 if (parseArgumentList(ArgList, IsVarArg))
3034 // Reject names on the arguments lists.
3035 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3036 if (!ArgList[i].Name.empty())
3037 return error(ArgList[i].Loc, "argument name invalid in function type");
3038 if (ArgList[i].Attrs.hasAttributes())
3039 return error(ArgList[i].Loc,
3040 "argument attributes invalid in function type");
3043 SmallVector<Type*, 16> ArgListTy;
3044 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3045 ArgListTy.push_back(ArgList[i].Ty);
3047 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3051 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
3053 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3054 SmallVector<Type*, 8> Elts;
3055 if (parseStructBody(Elts))
3058 Result = StructType::get(Context, Elts, Packed);
3062 /// parseStructDefinition - parse a struct in a 'type' definition.
3063 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3064 std::pair<Type *, LocTy> &Entry,
3066 // If the type was already defined, diagnose the redefinition.
3067 if (Entry.first && !Entry.second.isValid())
3068 return error(TypeLoc, "redefinition of type");
3070 // If we have opaque, just return without filling in the definition for the
3071 // struct. This counts as a definition as far as the .ll file goes.
3072 if (EatIfPresent(lltok::kw_opaque)) {
3073 // This type is being defined, so clear the location to indicate this.
3074 Entry.second = SMLoc();
3076 // If this type number has never been uttered, create it.
3078 Entry.first = StructType::create(Context, Name);
3079 ResultTy = Entry.first;
3083 // If the type starts with '<', then it is either a packed struct or a vector.
3084 bool isPacked = EatIfPresent(lltok::less);
3086 // If we don't have a struct, then we have a random type alias, which we
3087 // accept for compatibility with old files. These types are not allowed to be
3088 // forward referenced and not allowed to be recursive.
3089 if (Lex.getKind() != lltok::lbrace) {
3091 return error(TypeLoc, "forward references to non-struct type");
3095 return parseArrayVectorType(ResultTy, true);
3096 return parseType(ResultTy);
3099 // This type is being defined, so clear the location to indicate this.
3100 Entry.second = SMLoc();
3102 // If this type number has never been uttered, create it.
3104 Entry.first = StructType::create(Context, Name);
3106 StructType *STy = cast<StructType>(Entry.first);
3108 SmallVector<Type*, 8> Body;
3109 if (parseStructBody(Body) ||
3110 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3113 STy->setBody(Body, isPacked);
3118 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3121 /// ::= '{' Type (',' Type)* '}'
3122 /// ::= '<' '{' '}' '>'
3123 /// ::= '<' '{' Type (',' Type)* '}' '>'
3124 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3125 assert(Lex.getKind() == lltok::lbrace);
3126 Lex.Lex(); // Consume the '{'
3128 // Handle the empty struct.
3129 if (EatIfPresent(lltok::rbrace))
3132 LocTy EltTyLoc = Lex.getLoc();
3138 if (!StructType::isValidElementType(Ty))
3139 return error(EltTyLoc, "invalid element type for struct");
3141 while (EatIfPresent(lltok::comma)) {
3142 EltTyLoc = Lex.getLoc();
3146 if (!StructType::isValidElementType(Ty))
3147 return error(EltTyLoc, "invalid element type for struct");
3152 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3155 /// parseArrayVectorType - parse an array or vector type, assuming the first
3156 /// token has already been consumed.
3158 /// ::= '[' APSINTVAL 'x' Types ']'
3159 /// ::= '<' APSINTVAL 'x' Types '>'
3160 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3161 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3162 bool Scalable = false;
3164 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3165 Lex.Lex(); // consume the 'vscale'
3166 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3172 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3173 Lex.getAPSIntVal().getBitWidth() > 64)
3174 return tokError("expected number in address space");
3176 LocTy SizeLoc = Lex.getLoc();
3177 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3180 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3183 LocTy TypeLoc = Lex.getLoc();
3184 Type *EltTy = nullptr;
3185 if (parseType(EltTy))
3188 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3189 "expected end of sequential type"))
3194 return error(SizeLoc, "zero element vector is illegal");
3195 if ((unsigned)Size != Size)
3196 return error(SizeLoc, "size too large for vector");
3197 if (!VectorType::isValidElementType(EltTy))
3198 return error(TypeLoc, "invalid vector element type");
3199 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3201 if (!ArrayType::isValidElementType(EltTy))
3202 return error(TypeLoc, "invalid array element type");
3203 Result = ArrayType::get(EltTy, Size);
3208 /// parseTargetExtType - handle target extension type syntax
3210 /// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3212 /// TargetExtTypeParams
3214 /// ::= ',' Type TargetExtTypeParams
3216 /// TargetExtIntParams
3218 /// ::= ',' uint32 TargetExtIntParams
3219 bool LLParser::parseTargetExtType(Type *&Result) {
3220 Lex.Lex(); // Eat the 'target' keyword.
3222 // Get the mandatory type name.
3223 std::string TypeName;
3224 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3225 parseStringConstant(TypeName))
3228 // Parse all of the integer and type parameters at the same time; the use of
3229 // SeenInt will allow us to catch cases where type parameters follow integer
3231 SmallVector<Type *> TypeParams;
3232 SmallVector<unsigned> IntParams;
3233 bool SeenInt = false;
3234 while (Lex.getKind() == lltok::comma) {
3235 Lex.Lex(); // Eat the comma.
3237 if (Lex.getKind() == lltok::APSInt) {
3240 if (parseUInt32(IntVal))
3242 IntParams.push_back(IntVal);
3243 } else if (SeenInt) {
3244 // The only other kind of parameter we support is type parameters, which
3245 // must precede the integer parameters. This is therefore an error.
3246 return tokError("expected uint32 param");
3249 if (parseType(TypeParam, /*AllowVoid=*/true))
3251 TypeParams.push_back(TypeParam);
3255 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3258 Result = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
3262 //===----------------------------------------------------------------------===//
3263 // Function Semantic Analysis.
3264 //===----------------------------------------------------------------------===//
3266 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3268 : P(p), F(f), FunctionNumber(functionNumber) {
3270 // Insert unnamed arguments into the NumberedVals list.
3271 for (Argument &A : F.args())
3273 NumberedVals.push_back(&A);
3276 LLParser::PerFunctionState::~PerFunctionState() {
3277 // If there were any forward referenced non-basicblock values, delete them.
3279 for (const auto &P : ForwardRefVals) {
3280 if (isa<BasicBlock>(P.second.first))
3282 P.second.first->replaceAllUsesWith(
3283 UndefValue::get(P.second.first->getType()));
3284 P.second.first->deleteValue();
3287 for (const auto &P : ForwardRefValIDs) {
3288 if (isa<BasicBlock>(P.second.first))
3290 P.second.first->replaceAllUsesWith(
3291 UndefValue::get(P.second.first->getType()));
3292 P.second.first->deleteValue();
3296 bool LLParser::PerFunctionState::finishFunction() {
3297 if (!ForwardRefVals.empty())
3298 return P.error(ForwardRefVals.begin()->second.second,
3299 "use of undefined value '%" + ForwardRefVals.begin()->first +
3301 if (!ForwardRefValIDs.empty())
3302 return P.error(ForwardRefValIDs.begin()->second.second,
3303 "use of undefined value '%" +
3304 Twine(ForwardRefValIDs.begin()->first) + "'");
3308 /// getVal - Get a value with the specified name or ID, creating a
3309 /// forward reference record if needed. This can return null if the value
3310 /// exists but does not have the right type.
3311 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3313 // Look this name up in the normal function symbol table.
3314 Value *Val = F.getValueSymbolTable()->lookup(Name);
3316 // If this is a forward reference for the value, see if we already created a
3317 // forward ref record.
3319 auto I = ForwardRefVals.find(Name);
3320 if (I != ForwardRefVals.end())
3321 Val = I->second.first;
3324 // If we have the value in the symbol table or fwd-ref table, return it.
3326 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3328 // Don't make placeholders with invalid type.
3329 if (!Ty->isFirstClassType()) {
3330 P.error(Loc, "invalid use of a non-first-class type");
3334 // Otherwise, create a new forward reference for this value and remember it.
3336 if (Ty->isLabelTy()) {
3337 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3339 FwdVal = new Argument(Ty, Name);
3341 if (FwdVal->getName() != Name) {
3342 P.error(Loc, "name is too long which can result in name collisions, "
3343 "consider making the name shorter or "
3344 "increasing -non-global-value-max-name-size");
3348 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3352 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3353 // Look this name up in the normal function symbol table.
3354 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3356 // If this is a forward reference for the value, see if we already created a
3357 // forward ref record.
3359 auto I = ForwardRefValIDs.find(ID);
3360 if (I != ForwardRefValIDs.end())
3361 Val = I->second.first;
3364 // If we have the value in the symbol table or fwd-ref table, return it.
3366 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3368 if (!Ty->isFirstClassType()) {
3369 P.error(Loc, "invalid use of a non-first-class type");
3373 // Otherwise, create a new forward reference for this value and remember it.
3375 if (Ty->isLabelTy()) {
3376 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3378 FwdVal = new Argument(Ty);
3381 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3385 /// setInstName - After an instruction is parsed and inserted into its
3386 /// basic block, this installs its name.
3387 bool LLParser::PerFunctionState::setInstName(int NameID,
3388 const std::string &NameStr,
3389 LocTy NameLoc, Instruction *Inst) {
3390 // If this instruction has void type, it cannot have a name or ID specified.
3391 if (Inst->getType()->isVoidTy()) {
3392 if (NameID != -1 || !NameStr.empty())
3393 return P.error(NameLoc, "instructions returning void cannot have a name");
3397 // If this was a numbered instruction, verify that the instruction is the
3398 // expected value and resolve any forward references.
3399 if (NameStr.empty()) {
3400 // If neither a name nor an ID was specified, just use the next ID.
3402 NameID = NumberedVals.size();
3404 if (unsigned(NameID) != NumberedVals.size())
3405 return P.error(NameLoc, "instruction expected to be numbered '%" +
3406 Twine(NumberedVals.size()) + "'");
3408 auto FI = ForwardRefValIDs.find(NameID);
3409 if (FI != ForwardRefValIDs.end()) {
3410 Value *Sentinel = FI->second.first;
3411 if (Sentinel->getType() != Inst->getType())
3412 return P.error(NameLoc, "instruction forward referenced with type '" +
3413 getTypeString(FI->second.first->getType()) +
3416 Sentinel->replaceAllUsesWith(Inst);
3417 Sentinel->deleteValue();
3418 ForwardRefValIDs.erase(FI);
3421 NumberedVals.push_back(Inst);
3425 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3426 auto FI = ForwardRefVals.find(NameStr);
3427 if (FI != ForwardRefVals.end()) {
3428 Value *Sentinel = FI->second.first;
3429 if (Sentinel->getType() != Inst->getType())
3430 return P.error(NameLoc, "instruction forward referenced with type '" +
3431 getTypeString(FI->second.first->getType()) +
3434 Sentinel->replaceAllUsesWith(Inst);
3435 Sentinel->deleteValue();
3436 ForwardRefVals.erase(FI);
3439 // Set the name on the instruction.
3440 Inst->setName(NameStr);
3442 if (Inst->getName() != NameStr)
3443 return P.error(NameLoc, "multiple definition of local value named '" +
3448 /// getBB - Get a basic block with the specified name or ID, creating a
3449 /// forward reference record if needed.
3450 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3452 return dyn_cast_or_null<BasicBlock>(
3453 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3456 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3457 return dyn_cast_or_null<BasicBlock>(
3458 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3461 /// defineBB - Define the specified basic block, which is either named or
3462 /// unnamed. If there is an error, this returns null otherwise it returns
3463 /// the block being defined.
3464 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3465 int NameID, LocTy Loc) {
3468 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3469 P.error(Loc, "label expected to be numbered '" +
3470 Twine(NumberedVals.size()) + "'");
3473 BB = getBB(NumberedVals.size(), Loc);
3475 P.error(Loc, "unable to create block numbered '" +
3476 Twine(NumberedVals.size()) + "'");
3480 BB = getBB(Name, Loc);
3482 P.error(Loc, "unable to create block named '" + Name + "'");
3487 // Move the block to the end of the function. Forward ref'd blocks are
3488 // inserted wherever they happen to be referenced.
3489 F.splice(F.end(), &F, BB->getIterator());
3491 // Remove the block from forward ref sets.
3493 ForwardRefValIDs.erase(NumberedVals.size());
3494 NumberedVals.push_back(BB);
3496 // BB forward references are already in the function symbol table.
3497 ForwardRefVals.erase(Name);
3503 //===----------------------------------------------------------------------===//
3505 //===----------------------------------------------------------------------===//
3507 /// parseValID - parse an abstract value that doesn't necessarily have a
3508 /// type implied. For example, if we parse "4" we don't know what integer type
3509 /// it has. The value will later be combined with its type and checked for
3510 /// basic correctness. PFS is used to convert function-local operands of
3511 /// metadata (since metadata operands are not just parsed here but also
3512 /// converted to values). PFS can be null when we are not parsing metadata
3513 /// values inside a function.
3514 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3515 ID.Loc = Lex.getLoc();
3516 switch (Lex.getKind()) {
3518 return tokError("expected value token");
3519 case lltok::GlobalID: // @42
3520 ID.UIntVal = Lex.getUIntVal();
3521 ID.Kind = ValID::t_GlobalID;
3523 case lltok::GlobalVar: // @foo
3524 ID.StrVal = Lex.getStrVal();
3525 ID.Kind = ValID::t_GlobalName;
3527 case lltok::LocalVarID: // %42
3528 ID.UIntVal = Lex.getUIntVal();
3529 ID.Kind = ValID::t_LocalID;
3531 case lltok::LocalVar: // %foo
3532 ID.StrVal = Lex.getStrVal();
3533 ID.Kind = ValID::t_LocalName;
3536 ID.APSIntVal = Lex.getAPSIntVal();
3537 ID.Kind = ValID::t_APSInt;
3539 case lltok::APFloat:
3540 ID.APFloatVal = Lex.getAPFloatVal();
3541 ID.Kind = ValID::t_APFloat;
3543 case lltok::kw_true:
3544 ID.ConstantVal = ConstantInt::getTrue(Context);
3545 ID.Kind = ValID::t_Constant;
3547 case lltok::kw_false:
3548 ID.ConstantVal = ConstantInt::getFalse(Context);
3549 ID.Kind = ValID::t_Constant;
3551 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3552 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3553 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3554 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3555 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3557 case lltok::lbrace: {
3558 // ValID ::= '{' ConstVector '}'
3560 SmallVector<Constant*, 16> Elts;
3561 if (parseGlobalValueVector(Elts) ||
3562 parseToken(lltok::rbrace, "expected end of struct constant"))
3565 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3566 ID.UIntVal = Elts.size();
3567 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3568 Elts.size() * sizeof(Elts[0]));
3569 ID.Kind = ValID::t_ConstantStruct;
3573 // ValID ::= '<' ConstVector '>' --> Vector.
3574 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3576 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3578 SmallVector<Constant*, 16> Elts;
3579 LocTy FirstEltLoc = Lex.getLoc();
3580 if (parseGlobalValueVector(Elts) ||
3582 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3583 parseToken(lltok::greater, "expected end of constant"))
3586 if (isPackedStruct) {
3587 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3588 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3589 Elts.size() * sizeof(Elts[0]));
3590 ID.UIntVal = Elts.size();
3591 ID.Kind = ValID::t_PackedConstantStruct;
3596 return error(ID.Loc, "constant vector must not be empty");
3598 if (!Elts[0]->getType()->isIntegerTy() &&
3599 !Elts[0]->getType()->isFloatingPointTy() &&
3600 !Elts[0]->getType()->isPointerTy())
3603 "vector elements must have integer, pointer or floating point type");
3605 // Verify that all the vector elements have the same type.
3606 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3607 if (Elts[i]->getType() != Elts[0]->getType())
3608 return error(FirstEltLoc, "vector element #" + Twine(i) +
3609 " is not of type '" +
3610 getTypeString(Elts[0]->getType()));
3612 ID.ConstantVal = ConstantVector::get(Elts);
3613 ID.Kind = ValID::t_Constant;
3616 case lltok::lsquare: { // Array Constant
3618 SmallVector<Constant*, 16> Elts;
3619 LocTy FirstEltLoc = Lex.getLoc();
3620 if (parseGlobalValueVector(Elts) ||
3621 parseToken(lltok::rsquare, "expected end of array constant"))
3624 // Handle empty element.
3626 // Use undef instead of an array because it's inconvenient to determine
3627 // the element type at this point, there being no elements to examine.
3628 ID.Kind = ValID::t_EmptyArray;
3632 if (!Elts[0]->getType()->isFirstClassType())
3633 return error(FirstEltLoc, "invalid array element type: " +
3634 getTypeString(Elts[0]->getType()));
3636 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3638 // Verify all elements are correct type!
3639 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3640 if (Elts[i]->getType() != Elts[0]->getType())
3641 return error(FirstEltLoc, "array element #" + Twine(i) +
3642 " is not of type '" +
3643 getTypeString(Elts[0]->getType()));
3646 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3647 ID.Kind = ValID::t_Constant;
3650 case lltok::kw_c: // c "foo"
3652 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3654 if (parseToken(lltok::StringConstant, "expected string"))
3656 ID.Kind = ValID::t_Constant;
3659 case lltok::kw_asm: {
3660 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3662 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3664 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3665 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3666 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3667 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3668 parseStringConstant(ID.StrVal) ||
3669 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3670 parseToken(lltok::StringConstant, "expected constraint string"))
3672 ID.StrVal2 = Lex.getStrVal();
3673 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3674 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3675 ID.Kind = ValID::t_InlineAsm;
3679 case lltok::kw_blockaddress: {
3680 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3685 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3686 parseValID(Fn, PFS) ||
3687 parseToken(lltok::comma,
3688 "expected comma in block address expression") ||
3689 parseValID(Label, PFS) ||
3690 parseToken(lltok::rparen, "expected ')' in block address expression"))
3693 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3694 return error(Fn.Loc, "expected function name in blockaddress");
3695 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3696 return error(Label.Loc, "expected basic block name in blockaddress");
3698 // Try to find the function (but skip it if it's forward-referenced).
3699 GlobalValue *GV = nullptr;
3700 if (Fn.Kind == ValID::t_GlobalID) {
3701 if (Fn.UIntVal < NumberedVals.size())
3702 GV = NumberedVals[Fn.UIntVal];
3703 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3704 GV = M->getNamedValue(Fn.StrVal);
3706 Function *F = nullptr;
3708 // Confirm that it's actually a function with a definition.
3709 if (!isa<Function>(GV))
3710 return error(Fn.Loc, "expected function name in blockaddress");
3711 F = cast<Function>(GV);
3712 if (F->isDeclaration())
3713 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3717 // Make a global variable as a placeholder for this reference.
3718 GlobalValue *&FwdRef =
3719 ForwardRefBlockAddresses.insert(std::make_pair(
3721 std::map<ValID, GlobalValue *>()))
3722 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3727 // If we know the type that the blockaddress is being assigned to,
3728 // we can use the address space of that type.
3729 if (!ExpectedTy->isPointerTy())
3730 return error(ID.Loc,
3731 "type of blockaddress must be a pointer and not '" +
3732 getTypeString(ExpectedTy) + "'");
3733 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3735 // Otherwise, we default the address space of the current function.
3736 FwdDeclAS = PFS->getFunction().getAddressSpace();
3738 llvm_unreachable("Unknown address space for blockaddress");
3740 FwdRef = new GlobalVariable(
3741 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3742 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3745 ID.ConstantVal = FwdRef;
3746 ID.Kind = ValID::t_Constant;
3750 // We found the function; now find the basic block. Don't use PFS, since we
3751 // might be inside a constant expression.
3753 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3754 if (Label.Kind == ValID::t_LocalID)
3755 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3757 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3759 return error(Label.Loc, "referenced value is not a basic block");
3761 if (Label.Kind == ValID::t_LocalID)
3762 return error(Label.Loc, "cannot take address of numeric label after "
3763 "the function is defined");
3764 BB = dyn_cast_or_null<BasicBlock>(
3765 F->getValueSymbolTable()->lookup(Label.StrVal));
3767 return error(Label.Loc, "referenced value is not a basic block");
3770 ID.ConstantVal = BlockAddress::get(F, BB);
3771 ID.Kind = ValID::t_Constant;
3775 case lltok::kw_dso_local_equivalent: {
3776 // ValID ::= 'dso_local_equivalent' @foo
3781 if (parseValID(Fn, PFS))
3784 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3785 return error(Fn.Loc,
3786 "expected global value name in dso_local_equivalent");
3788 // Try to find the function (but skip it if it's forward-referenced).
3789 GlobalValue *GV = nullptr;
3790 if (Fn.Kind == ValID::t_GlobalID) {
3791 if (Fn.UIntVal < NumberedVals.size())
3792 GV = NumberedVals[Fn.UIntVal];
3793 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3794 GV = M->getNamedValue(Fn.StrVal);
3798 // Make a placeholder global variable as a placeholder for this reference.
3799 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
3800 ? ForwardRefDSOLocalEquivalentIDs
3801 : ForwardRefDSOLocalEquivalentNames;
3802 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;
3804 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3805 GlobalValue::InternalLinkage, nullptr, "",
3806 nullptr, GlobalValue::NotThreadLocal);
3809 ID.ConstantVal = FwdRef;
3810 ID.Kind = ValID::t_Constant;
3814 if (!GV->getValueType()->isFunctionTy())
3815 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3816 "in dso_local_equivalent");
3818 ID.ConstantVal = DSOLocalEquivalent::get(GV);
3819 ID.Kind = ValID::t_Constant;
3823 case lltok::kw_no_cfi: {
3824 // ValID ::= 'no_cfi' @foo
3827 if (parseValID(ID, PFS))
3830 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
3831 return error(ID.Loc, "expected global value name in no_cfi");
3837 case lltok::kw_trunc:
3838 case lltok::kw_zext:
3839 case lltok::kw_sext:
3840 case lltok::kw_fptrunc:
3841 case lltok::kw_fpext:
3842 case lltok::kw_bitcast:
3843 case lltok::kw_addrspacecast:
3844 case lltok::kw_uitofp:
3845 case lltok::kw_sitofp:
3846 case lltok::kw_fptoui:
3847 case lltok::kw_fptosi:
3848 case lltok::kw_inttoptr:
3849 case lltok::kw_ptrtoint: {
3850 unsigned Opc = Lex.getUIntVal();
3851 Type *DestTy = nullptr;
3854 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3855 parseGlobalTypeAndValue(SrcVal) ||
3856 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3857 parseType(DestTy) ||
3858 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3860 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3861 return error(ID.Loc, "invalid cast opcode for cast from '" +
3862 getTypeString(SrcVal->getType()) + "' to '" +
3863 getTypeString(DestTy) + "'");
3864 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3866 ID.Kind = ValID::t_Constant;
3869 case lltok::kw_extractvalue:
3870 return error(ID.Loc, "extractvalue constexprs are no longer supported");
3871 case lltok::kw_insertvalue:
3872 return error(ID.Loc, "insertvalue constexprs are no longer supported");
3873 case lltok::kw_udiv:
3874 return error(ID.Loc, "udiv constexprs are no longer supported");
3875 case lltok::kw_sdiv:
3876 return error(ID.Loc, "sdiv constexprs are no longer supported");
3877 case lltok::kw_urem:
3878 return error(ID.Loc, "urem constexprs are no longer supported");
3879 case lltok::kw_srem:
3880 return error(ID.Loc, "srem constexprs are no longer supported");
3881 case lltok::kw_fadd:
3882 return error(ID.Loc, "fadd constexprs are no longer supported");
3883 case lltok::kw_fsub:
3884 return error(ID.Loc, "fsub constexprs are no longer supported");
3885 case lltok::kw_fmul:
3886 return error(ID.Loc, "fmul constexprs are no longer supported");
3887 case lltok::kw_fdiv:
3888 return error(ID.Loc, "fdiv constexprs are no longer supported");
3889 case lltok::kw_frem:
3890 return error(ID.Loc, "frem constexprs are no longer supported");
3891 case lltok::kw_fneg:
3892 return error(ID.Loc, "fneg constexprs are no longer supported");
3893 case lltok::kw_select:
3894 return error(ID.Loc, "select constexprs are no longer supported");
3895 case lltok::kw_icmp:
3896 case lltok::kw_fcmp: {
3897 unsigned PredVal, Opc = Lex.getUIntVal();
3898 Constant *Val0, *Val1;
3900 if (parseCmpPredicate(PredVal, Opc) ||
3901 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3902 parseGlobalTypeAndValue(Val0) ||
3903 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3904 parseGlobalTypeAndValue(Val1) ||
3905 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3908 if (Val0->getType() != Val1->getType())
3909 return error(ID.Loc, "compare operands must have the same type");
3911 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3913 if (Opc == Instruction::FCmp) {
3914 if (!Val0->getType()->isFPOrFPVectorTy())
3915 return error(ID.Loc, "fcmp requires floating point operands");
3916 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3918 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3919 if (!Val0->getType()->isIntOrIntVectorTy() &&
3920 !Val0->getType()->isPtrOrPtrVectorTy())
3921 return error(ID.Loc, "icmp requires pointer or integer operands");
3922 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3924 ID.Kind = ValID::t_Constant;
3928 // Binary Operators.
3933 case lltok::kw_lshr:
3934 case lltok::kw_ashr: {
3938 unsigned Opc = Lex.getUIntVal();
3939 Constant *Val0, *Val1;
3941 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3942 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3943 if (EatIfPresent(lltok::kw_nuw))
3945 if (EatIfPresent(lltok::kw_nsw)) {
3947 if (EatIfPresent(lltok::kw_nuw))
3950 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3951 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3952 if (EatIfPresent(lltok::kw_exact))
3955 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3956 parseGlobalTypeAndValue(Val0) ||
3957 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3958 parseGlobalTypeAndValue(Val1) ||
3959 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3961 if (Val0->getType() != Val1->getType())
3962 return error(ID.Loc, "operands of constexpr must have same type");
3963 // Check that the type is valid for the operator.
3965 case Instruction::Add:
3966 case Instruction::Sub:
3967 case Instruction::Mul:
3968 case Instruction::UDiv:
3969 case Instruction::SDiv:
3970 case Instruction::URem:
3971 case Instruction::SRem:
3972 case Instruction::Shl:
3973 case Instruction::AShr:
3974 case Instruction::LShr:
3975 if (!Val0->getType()->isIntOrIntVectorTy())
3976 return error(ID.Loc, "constexpr requires integer operands");
3978 case Instruction::FAdd:
3979 case Instruction::FSub:
3980 case Instruction::FMul:
3981 case Instruction::FDiv:
3982 case Instruction::FRem:
3983 if (!Val0->getType()->isFPOrFPVectorTy())
3984 return error(ID.Loc, "constexpr requires fp operands");
3986 default: llvm_unreachable("Unknown binary operator!");
3989 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3990 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3991 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3992 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3994 ID.Kind = ValID::t_Constant;
3998 // Logical Operations
4001 case lltok::kw_xor: {
4002 unsigned Opc = Lex.getUIntVal();
4003 Constant *Val0, *Val1;
4005 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
4006 parseGlobalTypeAndValue(Val0) ||
4007 parseToken(lltok::comma, "expected comma in logical constantexpr") ||
4008 parseGlobalTypeAndValue(Val1) ||
4009 parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
4011 if (Val0->getType() != Val1->getType())
4012 return error(ID.Loc, "operands of constexpr must have same type");
4013 if (!Val0->getType()->isIntOrIntVectorTy())
4014 return error(ID.Loc,
4015 "constexpr requires integer or integer vector operands");
4016 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
4017 ID.Kind = ValID::t_Constant;
4021 case lltok::kw_getelementptr:
4022 case lltok::kw_shufflevector:
4023 case lltok::kw_insertelement:
4024 case lltok::kw_extractelement: {
4025 unsigned Opc = Lex.getUIntVal();
4026 SmallVector<Constant*, 16> Elts;
4027 bool InBounds = false;
4031 if (Opc == Instruction::GetElementPtr)
4032 InBounds = EatIfPresent(lltok::kw_inbounds);
4034 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4037 LocTy ExplicitTypeLoc = Lex.getLoc();
4038 if (Opc == Instruction::GetElementPtr) {
4039 if (parseType(Ty) ||
4040 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4044 std::optional<unsigned> InRangeOp;
4045 if (parseGlobalValueVector(
4046 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
4047 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4050 if (Opc == Instruction::GetElementPtr) {
4051 if (Elts.size() == 0 ||
4052 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4053 return error(ID.Loc, "base of getelementptr must be a pointer");
4055 Type *BaseType = Elts[0]->getType();
4056 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
4057 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
4060 typeComparisonErrorMessage(
4061 "explicit pointee type doesn't match operand's pointee type",
4062 Ty, BasePointerType->getNonOpaquePointerElementType()));
4066 BaseType->isVectorTy()
4067 ? cast<FixedVectorType>(BaseType)->getNumElements()
4070 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4071 for (Constant *Val : Indices) {
4072 Type *ValTy = Val->getType();
4073 if (!ValTy->isIntOrIntVectorTy())
4074 return error(ID.Loc, "getelementptr index must be an integer");
4075 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4076 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4077 if (GEPWidth && (ValNumEl != GEPWidth))
4080 "getelementptr vector index has a wrong number of elements");
4081 // GEPWidth may have been unknown because the base is a scalar,
4082 // but it is known now.
4083 GEPWidth = ValNumEl;
4087 SmallPtrSet<Type*, 4> Visited;
4088 if (!Indices.empty() && !Ty->isSized(&Visited))
4089 return error(ID.Loc, "base element of getelementptr must be sized");
4091 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4092 return error(ID.Loc, "invalid getelementptr indices");
4095 if (*InRangeOp == 0)
4096 return error(ID.Loc,
4097 "inrange keyword may not appear on pointer operand");
4101 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
4102 InBounds, InRangeOp);
4103 } else if (Opc == Instruction::ShuffleVector) {
4104 if (Elts.size() != 3)
4105 return error(ID.Loc, "expected three operands to shufflevector");
4106 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4107 return error(ID.Loc, "invalid operands to shufflevector");
4108 SmallVector<int, 16> Mask;
4109 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
4110 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4111 } else if (Opc == Instruction::ExtractElement) {
4112 if (Elts.size() != 2)
4113 return error(ID.Loc, "expected two operands to extractelement");
4114 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4115 return error(ID.Loc, "invalid extractelement operands");
4116 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4118 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4119 if (Elts.size() != 3)
4120 return error(ID.Loc, "expected three operands to insertelement");
4121 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4122 return error(ID.Loc, "invalid insertelement operands");
4124 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4127 ID.Kind = ValID::t_Constant;
4136 /// parseGlobalValue - parse a global value with the specified type.
4137 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4141 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4142 convertValIDToValue(Ty, ID, V, nullptr);
4143 if (V && !(C = dyn_cast<Constant>(V)))
4144 return error(ID.Loc, "global values must be constants");
4148 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4150 return parseType(Ty) || parseGlobalValue(Ty, V);
4153 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4156 LocTy KwLoc = Lex.getLoc();
4157 if (!EatIfPresent(lltok::kw_comdat))
4160 if (EatIfPresent(lltok::lparen)) {
4161 if (Lex.getKind() != lltok::ComdatVar)
4162 return tokError("expected comdat variable");
4163 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4165 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4168 if (GlobalName.empty())
4169 return tokError("comdat cannot be unnamed");
4170 C = getComdat(std::string(GlobalName), KwLoc);
4176 /// parseGlobalValueVector
4178 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
4179 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
4180 std::optional<unsigned> *InRangeOp) {
4182 if (Lex.getKind() == lltok::rbrace ||
4183 Lex.getKind() == lltok::rsquare ||
4184 Lex.getKind() == lltok::greater ||
4185 Lex.getKind() == lltok::rparen)
4189 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
4190 *InRangeOp = Elts.size();
4193 if (parseGlobalTypeAndValue(C))
4196 } while (EatIfPresent(lltok::comma));
4201 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4202 SmallVector<Metadata *, 16> Elts;
4203 if (parseMDNodeVector(Elts))
4206 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4213 /// ::= !DILocation(...)
4214 bool LLParser::parseMDNode(MDNode *&N) {
4215 if (Lex.getKind() == lltok::MetadataVar)
4216 return parseSpecializedMDNode(N);
4218 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4221 bool LLParser::parseMDNodeTail(MDNode *&N) {
4223 if (Lex.getKind() == lltok::lbrace)
4224 return parseMDTuple(N);
4227 return parseMDNodeID(N);
4232 /// Structure to represent an optional metadata field.
4233 template <class FieldTy> struct MDFieldImpl {
4234 typedef MDFieldImpl ImplTy;
4238 void assign(FieldTy Val) {
4240 this->Val = std::move(Val);
4243 explicit MDFieldImpl(FieldTy Default)
4244 : Val(std::move(Default)), Seen(false) {}
4247 /// Structure to represent an optional metadata field that
4248 /// can be of either type (A or B) and encapsulates the
4249 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4250 /// to reimplement the specifics for representing each Field.
4251 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4252 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4263 void assign(FieldTypeA A) {
4265 this->A = std::move(A);
4269 void assign(FieldTypeB B) {
4271 this->B = std::move(B);
4275 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4276 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4277 WhatIs(IsInvalid) {}
4280 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4283 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4284 : ImplTy(Default), Max(Max) {}
4287 struct LineField : public MDUnsignedField {
4288 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4291 struct ColumnField : public MDUnsignedField {
4292 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4295 struct DwarfTagField : public MDUnsignedField {
4296 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4297 DwarfTagField(dwarf::Tag DefaultTag)
4298 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4301 struct DwarfMacinfoTypeField : public MDUnsignedField {
4302 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4303 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4304 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4307 struct DwarfAttEncodingField : public MDUnsignedField {
4308 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4311 struct DwarfVirtualityField : public MDUnsignedField {
4312 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4315 struct DwarfLangField : public MDUnsignedField {
4316 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4319 struct DwarfCCField : public MDUnsignedField {
4320 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4323 struct EmissionKindField : public MDUnsignedField {
4324 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4327 struct NameTableKindField : public MDUnsignedField {
4328 NameTableKindField()
4331 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4334 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4335 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4338 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4339 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4342 struct MDAPSIntField : public MDFieldImpl<APSInt> {
4343 MDAPSIntField() : ImplTy(APSInt()) {}
4346 struct MDSignedField : public MDFieldImpl<int64_t> {
4347 int64_t Min = INT64_MIN;
4348 int64_t Max = INT64_MAX;
4350 MDSignedField(int64_t Default = 0)
4351 : ImplTy(Default) {}
4352 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4353 : ImplTy(Default), Min(Min), Max(Max) {}
4356 struct MDBoolField : public MDFieldImpl<bool> {
4357 MDBoolField(bool Default = false) : ImplTy(Default) {}
4360 struct MDField : public MDFieldImpl<Metadata *> {
4363 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4366 struct MDStringField : public MDFieldImpl<MDString *> {
4368 MDStringField(bool AllowEmpty = true)
4369 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4372 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4373 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4376 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4377 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4380 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4381 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4382 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4384 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4385 bool AllowNull = true)
4386 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4388 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4389 bool isMDField() const { return WhatIs == IsTypeB; }
4390 int64_t getMDSignedValue() const {
4391 assert(isMDSignedField() && "Wrong field type");
4394 Metadata *getMDFieldValue() const {
4395 assert(isMDField() && "Wrong field type");
4400 } // end anonymous namespace
4405 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4406 if (Lex.getKind() != lltok::APSInt)
4407 return tokError("expected integer");
4409 Result.assign(Lex.getAPSIntVal());
4415 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4416 MDUnsignedField &Result) {
4417 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4418 return tokError("expected unsigned integer");
4420 auto &U = Lex.getAPSIntVal();
4421 if (U.ugt(Result.Max))
4422 return tokError("value for '" + Name + "' too large, limit is " +
4424 Result.assign(U.getZExtValue());
4425 assert(Result.Val <= Result.Max && "Expected value in range");
4431 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4432 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4435 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4436 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4440 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4441 if (Lex.getKind() == lltok::APSInt)
4442 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4444 if (Lex.getKind() != lltok::DwarfTag)
4445 return tokError("expected DWARF tag");
4447 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4448 if (Tag == dwarf::DW_TAG_invalid)
4449 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4450 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4458 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4459 DwarfMacinfoTypeField &Result) {
4460 if (Lex.getKind() == lltok::APSInt)
4461 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4463 if (Lex.getKind() != lltok::DwarfMacinfo)
4464 return tokError("expected DWARF macinfo type");
4466 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4467 if (Macinfo == dwarf::DW_MACINFO_invalid)
4468 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4469 Lex.getStrVal() + "'");
4470 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4472 Result.assign(Macinfo);
4478 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4479 DwarfVirtualityField &Result) {
4480 if (Lex.getKind() == lltok::APSInt)
4481 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4483 if (Lex.getKind() != lltok::DwarfVirtuality)
4484 return tokError("expected DWARF virtuality code");
4486 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4487 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4488 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4489 Lex.getStrVal() + "'");
4490 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4491 Result.assign(Virtuality);
4497 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4498 if (Lex.getKind() == lltok::APSInt)
4499 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4501 if (Lex.getKind() != lltok::DwarfLang)
4502 return tokError("expected DWARF language");
4504 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4506 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4508 assert(Lang <= Result.Max && "Expected valid DWARF language");
4509 Result.assign(Lang);
4515 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4516 if (Lex.getKind() == lltok::APSInt)
4517 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4519 if (Lex.getKind() != lltok::DwarfCC)
4520 return tokError("expected DWARF calling convention");
4522 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4524 return tokError("invalid DWARF calling convention" + Twine(" '") +
4525 Lex.getStrVal() + "'");
4526 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4533 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4534 EmissionKindField &Result) {
4535 if (Lex.getKind() == lltok::APSInt)
4536 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4538 if (Lex.getKind() != lltok::EmissionKind)
4539 return tokError("expected emission kind");
4541 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4543 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4545 assert(*Kind <= Result.Max && "Expected valid emission kind");
4546 Result.assign(*Kind);
4552 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4553 NameTableKindField &Result) {
4554 if (Lex.getKind() == lltok::APSInt)
4555 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4557 if (Lex.getKind() != lltok::NameTableKind)
4558 return tokError("expected nameTable kind");
4560 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4562 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4564 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4565 Result.assign((unsigned)*Kind);
4571 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4572 DwarfAttEncodingField &Result) {
4573 if (Lex.getKind() == lltok::APSInt)
4574 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4576 if (Lex.getKind() != lltok::DwarfAttEncoding)
4577 return tokError("expected DWARF type attribute encoding");
4579 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4581 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4582 Lex.getStrVal() + "'");
4583 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4584 Result.assign(Encoding);
4591 /// ::= DIFlagVector
4592 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4594 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4596 // parser for a single flag.
4597 auto parseFlag = [&](DINode::DIFlags &Val) {
4598 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4599 uint32_t TempVal = static_cast<uint32_t>(Val);
4600 bool Res = parseUInt32(TempVal);
4601 Val = static_cast<DINode::DIFlags>(TempVal);
4605 if (Lex.getKind() != lltok::DIFlag)
4606 return tokError("expected debug info flag");
4608 Val = DINode::getFlag(Lex.getStrVal());
4610 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4616 // parse the flags and combine them together.
4617 DINode::DIFlags Combined = DINode::FlagZero;
4619 DINode::DIFlags Val;
4623 } while (EatIfPresent(lltok::bar));
4625 Result.assign(Combined);
4631 /// ::= DISPFlagVector
4632 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4634 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4636 // parser for a single flag.
4637 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4638 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4639 uint32_t TempVal = static_cast<uint32_t>(Val);
4640 bool Res = parseUInt32(TempVal);
4641 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4645 if (Lex.getKind() != lltok::DISPFlag)
4646 return tokError("expected debug info flag");
4648 Val = DISubprogram::getFlag(Lex.getStrVal());
4650 return tokError(Twine("invalid subprogram debug info flag '") +
4651 Lex.getStrVal() + "'");
4656 // parse the flags and combine them together.
4657 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4659 DISubprogram::DISPFlags Val;
4663 } while (EatIfPresent(lltok::bar));
4665 Result.assign(Combined);
4670 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4671 if (Lex.getKind() != lltok::APSInt)
4672 return tokError("expected signed integer");
4674 auto &S = Lex.getAPSIntVal();
4676 return tokError("value for '" + Name + "' too small, limit is " +
4679 return tokError("value for '" + Name + "' too large, limit is " +
4681 Result.assign(S.getExtValue());
4682 assert(Result.Val >= Result.Min && "Expected value in range");
4683 assert(Result.Val <= Result.Max && "Expected value in range");
4689 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4690 switch (Lex.getKind()) {
4692 return tokError("expected 'true' or 'false'");
4693 case lltok::kw_true:
4694 Result.assign(true);
4696 case lltok::kw_false:
4697 Result.assign(false);
4705 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4706 if (Lex.getKind() == lltok::kw_null) {
4707 if (!Result.AllowNull)
4708 return tokError("'" + Name + "' cannot be null");
4710 Result.assign(nullptr);
4715 if (parseMetadata(MD, nullptr))
4723 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4724 MDSignedOrMDField &Result) {
4725 // Try to parse a signed int.
4726 if (Lex.getKind() == lltok::APSInt) {
4727 MDSignedField Res = Result.A;
4728 if (!parseMDField(Loc, Name, Res)) {
4735 // Otherwise, try to parse as an MDField.
4736 MDField Res = Result.B;
4737 if (!parseMDField(Loc, Name, Res)) {
4746 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4747 LocTy ValueLoc = Lex.getLoc();
4749 if (parseStringConstant(S))
4752 if (!Result.AllowEmpty && S.empty())
4753 return error(ValueLoc, "'" + Name + "' cannot be empty");
4755 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4760 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4761 SmallVector<Metadata *, 4> MDs;
4762 if (parseMDNodeVector(MDs))
4765 Result.assign(std::move(MDs));
4770 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4771 ChecksumKindField &Result) {
4772 std::optional<DIFile::ChecksumKind> CSKind =
4773 DIFile::getChecksumKind(Lex.getStrVal());
4775 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4776 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4779 Result.assign(*CSKind);
4784 } // end namespace llvm
4786 template <class ParserTy>
4787 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4789 if (Lex.getKind() != lltok::LabelStr)
4790 return tokError("expected field label here");
4794 } while (EatIfPresent(lltok::comma));
4799 template <class ParserTy>
4800 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4801 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4804 if (parseToken(lltok::lparen, "expected '(' here"))
4806 if (Lex.getKind() != lltok::rparen)
4807 if (parseMDFieldsImplBody(ParseField))
4810 ClosingLoc = Lex.getLoc();
4811 return parseToken(lltok::rparen, "expected ')' here");
4814 template <class FieldTy>
4815 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4817 return tokError("field '" + Name + "' cannot be specified more than once");
4819 LocTy Loc = Lex.getLoc();
4821 return parseMDField(Loc, Name, Result);
4824 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4825 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4827 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4828 if (Lex.getStrVal() == #CLASS) \
4829 return parse##CLASS(N, IsDistinct);
4830 #include "llvm/IR/Metadata.def"
4832 return tokError("expected metadata type");
4835 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4836 #define NOP_FIELD(NAME, TYPE, INIT)
4837 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4839 return error(ClosingLoc, "missing required field '" #NAME "'");
4840 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4841 if (Lex.getStrVal() == #NAME) \
4842 return parseMDField(#NAME, NAME);
4843 #define PARSE_MD_FIELDS() \
4844 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4847 if (parseMDFieldsImpl( \
4849 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4850 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4855 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4857 #define GET_OR_DISTINCT(CLASS, ARGS) \
4858 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4860 /// parseDILocationFields:
4861 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4862 /// isImplicitCode: true)
4863 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4864 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4865 OPTIONAL(line, LineField, ); \
4866 OPTIONAL(column, ColumnField, ); \
4867 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4868 OPTIONAL(inlinedAt, MDField, ); \
4869 OPTIONAL(isImplicitCode, MDBoolField, (false));
4871 #undef VISIT_MD_FIELDS
4874 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4875 inlinedAt.Val, isImplicitCode.Val));
4879 /// parseDIAssignID:
4880 /// ::= distinct !DIAssignID()
4881 bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
4883 return Lex.Error("missing 'distinct', required for !DIAssignID()");
4887 // Now eat the parens.
4888 if (parseToken(lltok::lparen, "expected '(' here"))
4890 if (parseToken(lltok::rparen, "expected ')' here"))
4893 Result = DIAssignID::getDistinct(Context);
4897 /// parseGenericDINode:
4898 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4899 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4900 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4901 REQUIRED(tag, DwarfTagField, ); \
4902 OPTIONAL(header, MDStringField, ); \
4903 OPTIONAL(operands, MDFieldList, );
4905 #undef VISIT_MD_FIELDS
4907 Result = GET_OR_DISTINCT(GenericDINode,
4908 (Context, tag.Val, header.Val, operands.Val));
4912 /// parseDISubrange:
4913 /// ::= !DISubrange(count: 30, lowerBound: 2)
4914 /// ::= !DISubrange(count: !node, lowerBound: 2)
4915 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4916 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4917 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4918 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4919 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4920 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4921 OPTIONAL(stride, MDSignedOrMDField, );
4923 #undef VISIT_MD_FIELDS
4925 Metadata *Count = nullptr;
4926 Metadata *LowerBound = nullptr;
4927 Metadata *UpperBound = nullptr;
4928 Metadata *Stride = nullptr;
4930 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4931 if (Bound.isMDSignedField())
4932 return ConstantAsMetadata::get(ConstantInt::getSigned(
4933 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4934 if (Bound.isMDField())
4935 return Bound.getMDFieldValue();
4939 Count = convToMetadata(count);
4940 LowerBound = convToMetadata(lowerBound);
4941 UpperBound = convToMetadata(upperBound);
4942 Stride = convToMetadata(stride);
4944 Result = GET_OR_DISTINCT(DISubrange,
4945 (Context, Count, LowerBound, UpperBound, Stride));
4950 /// parseDIGenericSubrange:
4951 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4953 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4954 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4955 OPTIONAL(count, MDSignedOrMDField, ); \
4956 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4957 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4958 OPTIONAL(stride, MDSignedOrMDField, );
4960 #undef VISIT_MD_FIELDS
4962 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4963 if (Bound.isMDSignedField())
4964 return DIExpression::get(
4965 Context, {dwarf::DW_OP_consts,
4966 static_cast<uint64_t>(Bound.getMDSignedValue())});
4967 if (Bound.isMDField())
4968 return Bound.getMDFieldValue();
4972 Metadata *Count = ConvToMetadata(count);
4973 Metadata *LowerBound = ConvToMetadata(lowerBound);
4974 Metadata *UpperBound = ConvToMetadata(upperBound);
4975 Metadata *Stride = ConvToMetadata(stride);
4977 Result = GET_OR_DISTINCT(DIGenericSubrange,
4978 (Context, Count, LowerBound, UpperBound, Stride));
4983 /// parseDIEnumerator:
4984 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4985 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4986 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4987 REQUIRED(name, MDStringField, ); \
4988 REQUIRED(value, MDAPSIntField, ); \
4989 OPTIONAL(isUnsigned, MDBoolField, (false));
4991 #undef VISIT_MD_FIELDS
4993 if (isUnsigned.Val && value.Val.isNegative())
4994 return tokError("unsigned enumerator with negative value");
4996 APSInt Value(value.Val);
4997 // Add a leading zero so that unsigned values with the msb set are not
4998 // mistaken for negative values when used for signed enumerators.
4999 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5000 Value = Value.zext(Value.getBitWidth() + 1);
5003 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5008 /// parseDIBasicType:
5009 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5010 /// encoding: DW_ATE_encoding, flags: 0)
5011 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5012 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5013 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5014 OPTIONAL(name, MDStringField, ); \
5015 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5016 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5017 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5018 OPTIONAL(flags, DIFlagField, );
5020 #undef VISIT_MD_FIELDS
5022 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
5023 align.Val, encoding.Val, flags.Val));
5027 /// parseDIStringType:
5028 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5029 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5030 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5031 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5032 OPTIONAL(name, MDStringField, ); \
5033 OPTIONAL(stringLength, MDField, ); \
5034 OPTIONAL(stringLengthExpression, MDField, ); \
5035 OPTIONAL(stringLocationExpression, MDField, ); \
5036 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5037 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5038 OPTIONAL(encoding, DwarfAttEncodingField, );
5040 #undef VISIT_MD_FIELDS
5042 Result = GET_OR_DISTINCT(
5044 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5045 stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
5049 /// parseDIDerivedType:
5050 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5051 /// line: 7, scope: !1, baseType: !2, size: 32,
5052 /// align: 32, offset: 0, flags: 0, extraData: !3,
5053 /// dwarfAddressSpace: 3)
5054 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5055 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5056 REQUIRED(tag, DwarfTagField, ); \
5057 OPTIONAL(name, MDStringField, ); \
5058 OPTIONAL(file, MDField, ); \
5059 OPTIONAL(line, LineField, ); \
5060 OPTIONAL(scope, MDField, ); \
5061 REQUIRED(baseType, MDField, ); \
5062 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5063 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5064 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5065 OPTIONAL(flags, DIFlagField, ); \
5066 OPTIONAL(extraData, MDField, ); \
5067 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5068 OPTIONAL(annotations, MDField, );
5070 #undef VISIT_MD_FIELDS
5072 std::optional<unsigned> DWARFAddressSpace;
5073 if (dwarfAddressSpace.Val != UINT32_MAX)
5074 DWARFAddressSpace = dwarfAddressSpace.Val;
5076 Result = GET_OR_DISTINCT(DIDerivedType,
5077 (Context, tag.Val, name.Val, file.Val, line.Val,
5078 scope.Val, baseType.Val, size.Val, align.Val,
5079 offset.Val, DWARFAddressSpace, flags.Val,
5080 extraData.Val, annotations.Val));
5084 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5085 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5086 REQUIRED(tag, DwarfTagField, ); \
5087 OPTIONAL(name, MDStringField, ); \
5088 OPTIONAL(file, MDField, ); \
5089 OPTIONAL(line, LineField, ); \
5090 OPTIONAL(scope, MDField, ); \
5091 OPTIONAL(baseType, MDField, ); \
5092 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5093 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5094 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5095 OPTIONAL(flags, DIFlagField, ); \
5096 OPTIONAL(elements, MDField, ); \
5097 OPTIONAL(runtimeLang, DwarfLangField, ); \
5098 OPTIONAL(vtableHolder, MDField, ); \
5099 OPTIONAL(templateParams, MDField, ); \
5100 OPTIONAL(identifier, MDStringField, ); \
5101 OPTIONAL(discriminator, MDField, ); \
5102 OPTIONAL(dataLocation, MDField, ); \
5103 OPTIONAL(associated, MDField, ); \
5104 OPTIONAL(allocated, MDField, ); \
5105 OPTIONAL(rank, MDSignedOrMDField, ); \
5106 OPTIONAL(annotations, MDField, );
5108 #undef VISIT_MD_FIELDS
5110 Metadata *Rank = nullptr;
5111 if (rank.isMDSignedField())
5112 Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
5113 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5114 else if (rank.isMDField())
5115 Rank = rank.getMDFieldValue();
5117 // If this has an identifier try to build an ODR type.
5119 if (auto *CT = DICompositeType::buildODRType(
5120 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5121 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
5122 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5123 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5124 Rank, annotations.Val)) {
5129 // Create a new node, and save it in the context if it belongs in the type
5131 Result = GET_OR_DISTINCT(
5133 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5134 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5135 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5136 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5141 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5142 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5143 OPTIONAL(flags, DIFlagField, ); \
5144 OPTIONAL(cc, DwarfCCField, ); \
5145 REQUIRED(types, MDField, );
5147 #undef VISIT_MD_FIELDS
5149 Result = GET_OR_DISTINCT(DISubroutineType,
5150 (Context, flags.Val, cc.Val, types.Val));
5154 /// parseDIFileType:
5155 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5156 /// checksumkind: CSK_MD5,
5157 /// checksum: "000102030405060708090a0b0c0d0e0f",
5158 /// source: "source file contents")
5159 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5160 // The default constructed value for checksumkind is required, but will never
5161 // be used, as the parser checks if the field was actually Seen before using
5163 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5164 REQUIRED(filename, MDStringField, ); \
5165 REQUIRED(directory, MDStringField, ); \
5166 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5167 OPTIONAL(checksum, MDStringField, ); \
5168 OPTIONAL(source, MDStringField, );
5170 #undef VISIT_MD_FIELDS
5172 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5173 if (checksumkind.Seen && checksum.Seen)
5174 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5175 else if (checksumkind.Seen || checksum.Seen)
5176 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
5178 MDString *Source = nullptr;
5180 Source = source.Val;
5181 Result = GET_OR_DISTINCT(
5182 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5186 /// parseDICompileUnit:
5187 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5188 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5189 /// splitDebugFilename: "abc.debug",
5190 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5191 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5192 /// sysroot: "/", sdk: "MacOSX.sdk")
5193 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5195 return Lex.Error("missing 'distinct', required for !DICompileUnit");
5197 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5198 REQUIRED(language, DwarfLangField, ); \
5199 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5200 OPTIONAL(producer, MDStringField, ); \
5201 OPTIONAL(isOptimized, MDBoolField, ); \
5202 OPTIONAL(flags, MDStringField, ); \
5203 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5204 OPTIONAL(splitDebugFilename, MDStringField, ); \
5205 OPTIONAL(emissionKind, EmissionKindField, ); \
5206 OPTIONAL(enums, MDField, ); \
5207 OPTIONAL(retainedTypes, MDField, ); \
5208 OPTIONAL(globals, MDField, ); \
5209 OPTIONAL(imports, MDField, ); \
5210 OPTIONAL(macros, MDField, ); \
5211 OPTIONAL(dwoId, MDUnsignedField, ); \
5212 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5213 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5214 OPTIONAL(nameTableKind, NameTableKindField, ); \
5215 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5216 OPTIONAL(sysroot, MDStringField, ); \
5217 OPTIONAL(sdk, MDStringField, );
5219 #undef VISIT_MD_FIELDS
5221 Result = DICompileUnit::getDistinct(
5222 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5223 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5224 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5225 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5226 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5230 /// parseDISubprogram:
5231 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5232 /// file: !1, line: 7, type: !2, isLocal: false,
5233 /// isDefinition: true, scopeLine: 8, containingType: !3,
5234 /// virtuality: DW_VIRTUALTIY_pure_virtual,
5235 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5236 /// spFlags: 10, isOptimized: false, templateParams: !4,
5237 /// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5238 /// annotations: !8)
5239 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5240 auto Loc = Lex.getLoc();
5241 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5242 OPTIONAL(scope, MDField, ); \
5243 OPTIONAL(name, MDStringField, ); \
5244 OPTIONAL(linkageName, MDStringField, ); \
5245 OPTIONAL(file, MDField, ); \
5246 OPTIONAL(line, LineField, ); \
5247 OPTIONAL(type, MDField, ); \
5248 OPTIONAL(isLocal, MDBoolField, ); \
5249 OPTIONAL(isDefinition, MDBoolField, (true)); \
5250 OPTIONAL(scopeLine, LineField, ); \
5251 OPTIONAL(containingType, MDField, ); \
5252 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5253 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5254 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5255 OPTIONAL(flags, DIFlagField, ); \
5256 OPTIONAL(spFlags, DISPFlagField, ); \
5257 OPTIONAL(isOptimized, MDBoolField, ); \
5258 OPTIONAL(unit, MDField, ); \
5259 OPTIONAL(templateParams, MDField, ); \
5260 OPTIONAL(declaration, MDField, ); \
5261 OPTIONAL(retainedNodes, MDField, ); \
5262 OPTIONAL(thrownTypes, MDField, ); \
5263 OPTIONAL(annotations, MDField, ); \
5264 OPTIONAL(targetFuncName, MDStringField, );
5266 #undef VISIT_MD_FIELDS
5268 // An explicit spFlags field takes precedence over individual fields in
5269 // older IR versions.
5270 DISubprogram::DISPFlags SPFlags =
5271 spFlags.Seen ? spFlags.Val
5272 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5273 isOptimized.Val, virtuality.Val);
5274 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5277 "missing 'distinct', required for !DISubprogram that is a Definition");
5278 Result = GET_OR_DISTINCT(
5280 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5281 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5282 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5283 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5284 targetFuncName.Val));
5288 /// parseDILexicalBlock:
5289 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5290 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5291 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5292 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5293 OPTIONAL(file, MDField, ); \
5294 OPTIONAL(line, LineField, ); \
5295 OPTIONAL(column, ColumnField, );
5297 #undef VISIT_MD_FIELDS
5299 Result = GET_OR_DISTINCT(
5300 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5304 /// parseDILexicalBlockFile:
5305 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5306 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5307 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5308 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5309 OPTIONAL(file, MDField, ); \
5310 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5312 #undef VISIT_MD_FIELDS
5314 Result = GET_OR_DISTINCT(DILexicalBlockFile,
5315 (Context, scope.Val, file.Val, discriminator.Val));
5319 /// parseDICommonBlock:
5320 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5321 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5322 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5323 REQUIRED(scope, MDField, ); \
5324 OPTIONAL(declaration, MDField, ); \
5325 OPTIONAL(name, MDStringField, ); \
5326 OPTIONAL(file, MDField, ); \
5327 OPTIONAL(line, LineField, );
5329 #undef VISIT_MD_FIELDS
5331 Result = GET_OR_DISTINCT(DICommonBlock,
5332 (Context, scope.Val, declaration.Val, name.Val,
5333 file.Val, line.Val));
5337 /// parseDINamespace:
5338 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5339 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5340 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5341 REQUIRED(scope, MDField, ); \
5342 OPTIONAL(name, MDStringField, ); \
5343 OPTIONAL(exportSymbols, MDBoolField, );
5345 #undef VISIT_MD_FIELDS
5347 Result = GET_OR_DISTINCT(DINamespace,
5348 (Context, scope.Val, name.Val, exportSymbols.Val));
5353 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5355 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5356 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5357 REQUIRED(type, DwarfMacinfoTypeField, ); \
5358 OPTIONAL(line, LineField, ); \
5359 REQUIRED(name, MDStringField, ); \
5360 OPTIONAL(value, MDStringField, );
5362 #undef VISIT_MD_FIELDS
5364 Result = GET_OR_DISTINCT(DIMacro,
5365 (Context, type.Val, line.Val, name.Val, value.Val));
5369 /// parseDIMacroFile:
5370 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5371 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5372 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5373 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5374 OPTIONAL(line, LineField, ); \
5375 REQUIRED(file, MDField, ); \
5376 OPTIONAL(nodes, MDField, );
5378 #undef VISIT_MD_FIELDS
5380 Result = GET_OR_DISTINCT(DIMacroFile,
5381 (Context, type.Val, line.Val, file.Val, nodes.Val));
5386 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5387 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5388 /// file: !1, line: 4, isDecl: false)
5389 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5390 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5391 REQUIRED(scope, MDField, ); \
5392 REQUIRED(name, MDStringField, ); \
5393 OPTIONAL(configMacros, MDStringField, ); \
5394 OPTIONAL(includePath, MDStringField, ); \
5395 OPTIONAL(apinotes, MDStringField, ); \
5396 OPTIONAL(file, MDField, ); \
5397 OPTIONAL(line, LineField, ); \
5398 OPTIONAL(isDecl, MDBoolField, );
5400 #undef VISIT_MD_FIELDS
5402 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5403 configMacros.Val, includePath.Val,
5404 apinotes.Val, line.Val, isDecl.Val));
5408 /// parseDITemplateTypeParameter:
5409 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5410 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5411 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5412 OPTIONAL(name, MDStringField, ); \
5413 REQUIRED(type, MDField, ); \
5414 OPTIONAL(defaulted, MDBoolField, );
5416 #undef VISIT_MD_FIELDS
5418 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5419 (Context, name.Val, type.Val, defaulted.Val));
5423 /// parseDITemplateValueParameter:
5424 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5425 /// name: "V", type: !1, defaulted: false,
5427 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5428 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5429 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5430 OPTIONAL(name, MDStringField, ); \
5431 OPTIONAL(type, MDField, ); \
5432 OPTIONAL(defaulted, MDBoolField, ); \
5433 REQUIRED(value, MDField, );
5436 #undef VISIT_MD_FIELDS
5438 Result = GET_OR_DISTINCT(
5439 DITemplateValueParameter,
5440 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5444 /// parseDIGlobalVariable:
5445 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5446 /// file: !1, line: 7, type: !2, isLocal: false,
5447 /// isDefinition: true, templateParams: !3,
5448 /// declaration: !4, align: 8)
5449 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5450 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5451 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5452 OPTIONAL(scope, MDField, ); \
5453 OPTIONAL(linkageName, MDStringField, ); \
5454 OPTIONAL(file, MDField, ); \
5455 OPTIONAL(line, LineField, ); \
5456 OPTIONAL(type, MDField, ); \
5457 OPTIONAL(isLocal, MDBoolField, ); \
5458 OPTIONAL(isDefinition, MDBoolField, (true)); \
5459 OPTIONAL(templateParams, MDField, ); \
5460 OPTIONAL(declaration, MDField, ); \
5461 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5462 OPTIONAL(annotations, MDField, );
5464 #undef VISIT_MD_FIELDS
5467 GET_OR_DISTINCT(DIGlobalVariable,
5468 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5469 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5470 declaration.Val, templateParams.Val, align.Val,
5475 /// parseDILocalVariable:
5476 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5477 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5479 /// ::= !DILocalVariable(scope: !0, name: "foo",
5480 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5482 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5483 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5484 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5485 OPTIONAL(name, MDStringField, ); \
5486 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5487 OPTIONAL(file, MDField, ); \
5488 OPTIONAL(line, LineField, ); \
5489 OPTIONAL(type, MDField, ); \
5490 OPTIONAL(flags, DIFlagField, ); \
5491 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5492 OPTIONAL(annotations, MDField, );
5494 #undef VISIT_MD_FIELDS
5496 Result = GET_OR_DISTINCT(DILocalVariable,
5497 (Context, scope.Val, name.Val, file.Val, line.Val,
5498 type.Val, arg.Val, flags.Val, align.Val,
5504 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5505 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5506 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5507 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5508 REQUIRED(name, MDStringField, ); \
5509 REQUIRED(file, MDField, ); \
5510 REQUIRED(line, LineField, );
5512 #undef VISIT_MD_FIELDS
5514 Result = GET_OR_DISTINCT(DILabel,
5515 (Context, scope.Val, name.Val, file.Val, line.Val));
5519 /// parseDIExpression:
5520 /// ::= !DIExpression(0, 7, -1)
5521 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5522 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5525 if (parseToken(lltok::lparen, "expected '(' here"))
5528 SmallVector<uint64_t, 8> Elements;
5529 if (Lex.getKind() != lltok::rparen)
5531 if (Lex.getKind() == lltok::DwarfOp) {
5532 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5534 Elements.push_back(Op);
5537 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5540 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5541 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5543 Elements.push_back(Op);
5546 return tokError(Twine("invalid DWARF attribute encoding '") +
5547 Lex.getStrVal() + "'");
5550 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5551 return tokError("expected unsigned integer");
5553 auto &U = Lex.getAPSIntVal();
5554 if (U.ugt(UINT64_MAX))
5555 return tokError("element too large, limit is " + Twine(UINT64_MAX));
5556 Elements.push_back(U.getZExtValue());
5558 } while (EatIfPresent(lltok::comma));
5560 if (parseToken(lltok::rparen, "expected ')' here"))
5563 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5567 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5568 return parseDIArgList(Result, IsDistinct, nullptr);
5571 /// ::= !DIArgList(i32 7, i64 %0)
5572 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5573 PerFunctionState *PFS) {
5574 assert(PFS && "Expected valid function state");
5575 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5578 if (parseToken(lltok::lparen, "expected '(' here"))
5581 SmallVector<ValueAsMetadata *, 4> Args;
5582 if (Lex.getKind() != lltok::rparen)
5585 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5587 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5588 } while (EatIfPresent(lltok::comma));
5590 if (parseToken(lltok::rparen, "expected ')' here"))
5593 Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5597 /// parseDIGlobalVariableExpression:
5598 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5599 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5601 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5602 REQUIRED(var, MDField, ); \
5603 REQUIRED(expr, MDField, );
5605 #undef VISIT_MD_FIELDS
5608 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5612 /// parseDIObjCProperty:
5613 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5614 /// getter: "getFoo", attributes: 7, type: !2)
5615 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5616 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5617 OPTIONAL(name, MDStringField, ); \
5618 OPTIONAL(file, MDField, ); \
5619 OPTIONAL(line, LineField, ); \
5620 OPTIONAL(setter, MDStringField, ); \
5621 OPTIONAL(getter, MDStringField, ); \
5622 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5623 OPTIONAL(type, MDField, );
5625 #undef VISIT_MD_FIELDS
5627 Result = GET_OR_DISTINCT(DIObjCProperty,
5628 (Context, name.Val, file.Val, line.Val, setter.Val,
5629 getter.Val, attributes.Val, type.Val));
5633 /// parseDIImportedEntity:
5634 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5635 /// line: 7, name: "foo", elements: !2)
5636 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5637 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5638 REQUIRED(tag, DwarfTagField, ); \
5639 REQUIRED(scope, MDField, ); \
5640 OPTIONAL(entity, MDField, ); \
5641 OPTIONAL(file, MDField, ); \
5642 OPTIONAL(line, LineField, ); \
5643 OPTIONAL(name, MDStringField, ); \
5644 OPTIONAL(elements, MDField, );
5646 #undef VISIT_MD_FIELDS
5648 Result = GET_OR_DISTINCT(DIImportedEntity,
5649 (Context, tag.Val, scope.Val, entity.Val, file.Val,
5650 line.Val, name.Val, elements.Val));
5654 #undef PARSE_MD_FIELD
5656 #undef REQUIRE_FIELD
5657 #undef DECLARE_FIELD
5659 /// parseMetadataAsValue
5660 /// ::= metadata i32 %local
5661 /// ::= metadata i32 @global
5662 /// ::= metadata i32 7
5664 /// ::= metadata !{...}
5665 /// ::= metadata !"string"
5666 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5667 // Note: the type 'metadata' has already been parsed.
5669 if (parseMetadata(MD, &PFS))
5672 V = MetadataAsValue::get(Context, MD);
5676 /// parseValueAsMetadata
5680 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5681 PerFunctionState *PFS) {
5684 if (parseType(Ty, TypeMsg, Loc))
5686 if (Ty->isMetadataTy())
5687 return error(Loc, "invalid metadata-value-metadata roundtrip");
5690 if (parseValue(Ty, V, PFS))
5693 MD = ValueAsMetadata::get(V);
5704 /// ::= !DILocation(...)
5705 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5706 if (Lex.getKind() == lltok::MetadataVar) {
5708 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5709 // so parsing this requires a Function State.
5710 if (Lex.getStrVal() == "DIArgList") {
5711 if (parseDIArgList(N, false, PFS))
5713 } else if (parseSpecializedMDNode(N)) {
5722 if (Lex.getKind() != lltok::exclaim)
5723 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5726 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5730 // ::= '!' STRINGCONSTANT
5731 if (Lex.getKind() == lltok::StringConstant) {
5733 if (parseMDString(S))
5743 if (parseMDNodeTail(N))
5749 //===----------------------------------------------------------------------===//
5750 // Function Parsing.
5751 //===----------------------------------------------------------------------===//
5753 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5754 PerFunctionState *PFS) {
5755 if (Ty->isFunctionTy())
5756 return error(ID.Loc, "functions are not values, refer to them as pointers");
5759 case ValID::t_LocalID:
5761 return error(ID.Loc, "invalid use of function-local name");
5762 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
5763 return V == nullptr;
5764 case ValID::t_LocalName:
5766 return error(ID.Loc, "invalid use of function-local name");
5767 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
5768 return V == nullptr;
5769 case ValID::t_InlineAsm: {
5771 return error(ID.Loc, "invalid type for inline asm constraint string");
5772 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
5773 return error(ID.Loc, toString(std::move(Err)));
5775 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5776 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5779 case ValID::t_GlobalName:
5780 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
5782 V = NoCFIValue::get(cast<GlobalValue>(V));
5783 return V == nullptr;
5784 case ValID::t_GlobalID:
5785 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
5787 V = NoCFIValue::get(cast<GlobalValue>(V));
5788 return V == nullptr;
5789 case ValID::t_APSInt:
5790 if (!Ty->isIntegerTy())
5791 return error(ID.Loc, "integer constant must have integer type");
5792 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5793 V = ConstantInt::get(Context, ID.APSIntVal);
5795 case ValID::t_APFloat:
5796 if (!Ty->isFloatingPointTy() ||
5797 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5798 return error(ID.Loc, "floating point constant invalid for type");
5800 // The lexer has no type info, so builds all half, bfloat, float, and double
5801 // FP constants as double. Fix this here. Long double does not need this.
5802 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5803 // Check for signaling before potentially converting and losing that info.
5804 bool IsSNAN = ID.APFloatVal.isSignaling();
5807 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5809 else if (Ty->isBFloatTy())
5810 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5812 else if (Ty->isFloatTy())
5813 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5816 // The convert call above may quiet an SNaN, so manufacture another
5817 // SNaN. The bitcast works because the payload (significand) parameter
5818 // is truncated to fit.
5819 APInt Payload = ID.APFloatVal.bitcastToAPInt();
5820 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5821 ID.APFloatVal.isNegative(), &Payload);
5824 V = ConstantFP::get(Context, ID.APFloatVal);
5826 if (V->getType() != Ty)
5827 return error(ID.Loc, "floating point constant does not have type '" +
5828 getTypeString(Ty) + "'");
5832 if (!Ty->isPointerTy())
5833 return error(ID.Loc, "null must be a pointer type");
5834 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5836 case ValID::t_Undef:
5837 // FIXME: LabelTy should not be a first-class type.
5838 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5839 return error(ID.Loc, "invalid type for undef constant");
5840 V = UndefValue::get(Ty);
5842 case ValID::t_EmptyArray:
5843 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5844 return error(ID.Loc, "invalid empty array initializer");
5845 V = UndefValue::get(Ty);
5848 // FIXME: LabelTy should not be a first-class type.
5849 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5850 return error(ID.Loc, "invalid type for null constant");
5851 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
5852 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
5853 return error(ID.Loc, "invalid type for null constant");
5854 V = Constant::getNullValue(Ty);
5857 if (!Ty->isTokenTy())
5858 return error(ID.Loc, "invalid type for none constant");
5859 V = Constant::getNullValue(Ty);
5861 case ValID::t_Poison:
5862 // FIXME: LabelTy should not be a first-class type.
5863 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5864 return error(ID.Loc, "invalid type for poison constant");
5865 V = PoisonValue::get(Ty);
5867 case ValID::t_Constant:
5868 if (ID.ConstantVal->getType() != Ty)
5869 return error(ID.Loc, "constant expression type mismatch: got type '" +
5870 getTypeString(ID.ConstantVal->getType()) +
5871 "' but expected '" + getTypeString(Ty) + "'");
5874 case ValID::t_ConstantStruct:
5875 case ValID::t_PackedConstantStruct:
5876 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5877 if (ST->getNumElements() != ID.UIntVal)
5878 return error(ID.Loc,
5879 "initializer with struct type has wrong # elements");
5880 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5881 return error(ID.Loc, "packed'ness of initializer and type don't match");
5883 // Verify that the elements are compatible with the structtype.
5884 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5885 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5888 "element " + Twine(i) +
5889 " of struct initializer doesn't match struct element type");
5891 V = ConstantStruct::get(
5892 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5894 return error(ID.Loc, "constant expression type mismatch");
5897 llvm_unreachable("Invalid ValID");
5900 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5903 auto Loc = Lex.getLoc();
5904 if (parseValID(ID, /*PFS=*/nullptr))
5907 case ValID::t_APSInt:
5908 case ValID::t_APFloat:
5909 case ValID::t_Undef:
5910 case ValID::t_Constant:
5911 case ValID::t_ConstantStruct:
5912 case ValID::t_PackedConstantStruct: {
5914 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
5916 assert(isa<Constant>(V) && "Expected a constant value");
5917 C = cast<Constant>(V);
5921 C = Constant::getNullValue(Ty);
5924 return error(Loc, "expected a constant value");
5928 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5931 return parseValID(ID, PFS, Ty) ||
5932 convertValIDToValue(Ty, ID, V, PFS);
5935 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5937 return parseType(Ty) || parseValue(Ty, V, PFS);
5940 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5941 PerFunctionState &PFS) {
5944 if (parseTypeAndValue(V, PFS))
5946 if (!isa<BasicBlock>(V))
5947 return error(Loc, "expected a basic block");
5948 BB = cast<BasicBlock>(V);
5953 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5954 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5955 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5956 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5957 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5958 // parse the linkage.
5959 LocTy LinkageLoc = Lex.getLoc();
5961 unsigned Visibility;
5962 unsigned DLLStorageClass;
5964 AttrBuilder RetAttrs(M->getContext());
5967 Type *RetType = nullptr;
5968 LocTy RetTypeLoc = Lex.getLoc();
5969 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5971 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5972 parseType(RetType, RetTypeLoc, true /*void allowed*/))
5975 // Verify that the linkage is ok.
5976 switch ((GlobalValue::LinkageTypes)Linkage) {
5977 case GlobalValue::ExternalLinkage:
5978 break; // always ok.
5979 case GlobalValue::ExternalWeakLinkage:
5981 return error(LinkageLoc, "invalid linkage for function definition");
5983 case GlobalValue::PrivateLinkage:
5984 case GlobalValue::InternalLinkage:
5985 case GlobalValue::AvailableExternallyLinkage:
5986 case GlobalValue::LinkOnceAnyLinkage:
5987 case GlobalValue::LinkOnceODRLinkage:
5988 case GlobalValue::WeakAnyLinkage:
5989 case GlobalValue::WeakODRLinkage:
5991 return error(LinkageLoc, "invalid linkage for function declaration");
5993 case GlobalValue::AppendingLinkage:
5994 case GlobalValue::CommonLinkage:
5995 return error(LinkageLoc, "invalid function linkage type");
5998 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5999 return error(LinkageLoc,
6000 "symbol with local linkage must have default visibility");
6002 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6003 return error(LinkageLoc,
6004 "symbol with local linkage cannot have a DLL storage class");
6006 if (!FunctionType::isValidReturnType(RetType))
6007 return error(RetTypeLoc, "invalid function return type");
6009 LocTy NameLoc = Lex.getLoc();
6011 std::string FunctionName;
6012 if (Lex.getKind() == lltok::GlobalVar) {
6013 FunctionName = Lex.getStrVal();
6014 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6015 unsigned NameID = Lex.getUIntVal();
6017 if (NameID != NumberedVals.size())
6018 return tokError("function expected to be numbered '%" +
6019 Twine(NumberedVals.size()) + "'");
6021 return tokError("expected function name");
6026 if (Lex.getKind() != lltok::lparen)
6027 return tokError("expected '(' in function argument list");
6029 SmallVector<ArgInfo, 8> ArgList;
6031 AttrBuilder FuncAttrs(M->getContext());
6032 std::vector<unsigned> FwdRefAttrGrps;
6034 std::string Section;
6035 std::string Partition;
6036 MaybeAlign Alignment;
6038 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
6039 unsigned AddrSpace = 0;
6040 Constant *Prefix = nullptr;
6041 Constant *Prologue = nullptr;
6042 Constant *PersonalityFn = nullptr;
6045 if (parseArgumentList(ArgList, IsVarArg) ||
6046 parseOptionalUnnamedAddr(UnnamedAddr) ||
6047 parseOptionalProgramAddrSpace(AddrSpace) ||
6048 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6050 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6051 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6052 parseOptionalComdat(FunctionName, C) ||
6053 parseOptionalAlignment(Alignment) ||
6054 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6055 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6056 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6057 (EatIfPresent(lltok::kw_personality) &&
6058 parseGlobalTypeAndValue(PersonalityFn)))
6061 if (FuncAttrs.contains(Attribute::Builtin))
6062 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6064 // If the alignment was parsed as an attribute, move to the alignment field.
6065 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6067 FuncAttrs.removeAttribute(Attribute::Alignment);
6070 // Okay, if we got here, the function is syntactically valid. Convert types
6071 // and do semantic checks.
6072 std::vector<Type*> ParamTypeList;
6073 SmallVector<AttributeSet, 8> Attrs;
6075 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6076 ParamTypeList.push_back(ArgList[i].Ty);
6077 Attrs.push_back(ArgList[i].Attrs);
6081 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6082 AttributeSet::get(Context, RetAttrs), Attrs);
6084 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6085 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6087 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6088 PointerType *PFT = PointerType::get(FT, AddrSpace);
6091 GlobalValue *FwdFn = nullptr;
6092 if (!FunctionName.empty()) {
6093 // If this was a definition of a forward reference, remove the definition
6094 // from the forward reference table and fill in the forward ref.
6095 auto FRVI = ForwardRefVals.find(FunctionName);
6096 if (FRVI != ForwardRefVals.end()) {
6097 FwdFn = FRVI->second.first;
6098 if (!FwdFn->getType()->isOpaque() &&
6099 !FwdFn->getType()->getNonOpaquePointerElementType()->isFunctionTy())
6100 return error(FRVI->second.second, "invalid forward reference to "
6101 "function as global value!");
6102 if (FwdFn->getType() != PFT)
6103 return error(FRVI->second.second,
6104 "invalid forward reference to "
6107 "' with wrong type: "
6109 getTypeString(PFT) + "' but was '" +
6110 getTypeString(FwdFn->getType()) + "'");
6111 ForwardRefVals.erase(FRVI);
6112 } else if ((Fn = M->getFunction(FunctionName))) {
6113 // Reject redefinitions.
6114 return error(NameLoc,
6115 "invalid redefinition of function '" + FunctionName + "'");
6116 } else if (M->getNamedValue(FunctionName)) {
6117 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6121 // If this is a definition of a forward referenced function, make sure the
6123 auto I = ForwardRefValIDs.find(NumberedVals.size());
6124 if (I != ForwardRefValIDs.end()) {
6125 FwdFn = I->second.first;
6126 if (FwdFn->getType() != PFT)
6127 return error(NameLoc, "type of definition and forward reference of '@" +
6128 Twine(NumberedVals.size()) +
6131 getTypeString(PFT) + "' but was '" +
6132 getTypeString(FwdFn->getType()) + "'");
6133 ForwardRefValIDs.erase(I);
6137 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
6140 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6142 if (FunctionName.empty())
6143 NumberedVals.push_back(Fn);
6145 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
6146 maybeSetDSOLocal(DSOLocal, *Fn);
6147 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
6148 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
6149 Fn->setCallingConv(CC);
6150 Fn->setAttributes(PAL);
6151 Fn->setUnnamedAddr(UnnamedAddr);
6153 Fn->setAlignment(*Alignment);
6154 Fn->setSection(Section);
6155 Fn->setPartition(Partition);
6157 Fn->setPersonalityFn(PersonalityFn);
6158 if (!GC.empty()) Fn->setGC(GC);
6159 Fn->setPrefixData(Prefix);
6160 Fn->setPrologueData(Prologue);
6161 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6163 // Add all of the arguments we parsed to the function.
6164 Function::arg_iterator ArgIt = Fn->arg_begin();
6165 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6166 // If the argument has a name, insert it into the argument symbol table.
6167 if (ArgList[i].Name.empty()) continue;
6169 // Set the name, if it conflicted, it will be auto-renamed.
6170 ArgIt->setName(ArgList[i].Name);
6172 if (ArgIt->getName() != ArgList[i].Name)
6173 return error(ArgList[i].Loc,
6174 "redefinition of argument '%" + ArgList[i].Name + "'");
6178 FwdFn->replaceAllUsesWith(Fn);
6179 FwdFn->eraseFromParent();
6185 // Check the declaration has no block address forward references.
6187 if (FunctionName.empty()) {
6188 ID.Kind = ValID::t_GlobalID;
6189 ID.UIntVal = NumberedVals.size() - 1;
6191 ID.Kind = ValID::t_GlobalName;
6192 ID.StrVal = FunctionName;
6194 auto Blocks = ForwardRefBlockAddresses.find(ID);
6195 if (Blocks != ForwardRefBlockAddresses.end())
6196 return error(Blocks->first.Loc,
6197 "cannot take blockaddress inside a declaration");
6201 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6203 if (FunctionNumber == -1) {
6204 ID.Kind = ValID::t_GlobalName;
6205 ID.StrVal = std::string(F.getName());
6207 ID.Kind = ValID::t_GlobalID;
6208 ID.UIntVal = FunctionNumber;
6211 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6212 if (Blocks == P.ForwardRefBlockAddresses.end())
6215 for (const auto &I : Blocks->second) {
6216 const ValID &BBID = I.first;
6217 GlobalValue *GV = I.second;
6219 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6220 "Expected local id or name");
6222 if (BBID.Kind == ValID::t_LocalName)
6223 BB = getBB(BBID.StrVal, BBID.Loc);
6225 BB = getBB(BBID.UIntVal, BBID.Loc);
6227 return P.error(BBID.Loc, "referenced value is not a basic block");
6229 Value *ResolvedVal = BlockAddress::get(&F, BB);
6230 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6234 GV->replaceAllUsesWith(ResolvedVal);
6235 GV->eraseFromParent();
6238 P.ForwardRefBlockAddresses.erase(Blocks);
6242 /// parseFunctionBody
6243 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6244 bool LLParser::parseFunctionBody(Function &Fn) {
6245 if (Lex.getKind() != lltok::lbrace)
6246 return tokError("expected '{' in function body");
6247 Lex.Lex(); // eat the {.
6249 int FunctionNumber = -1;
6250 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
6252 PerFunctionState PFS(*this, Fn, FunctionNumber);
6254 // Resolve block addresses and allow basic blocks to be forward-declared
6255 // within this function.
6256 if (PFS.resolveForwardRefBlockAddresses())
6258 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6260 // We need at least one basic block.
6261 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6262 return tokError("function body requires at least one basic block");
6264 while (Lex.getKind() != lltok::rbrace &&
6265 Lex.getKind() != lltok::kw_uselistorder)
6266 if (parseBasicBlock(PFS))
6269 while (Lex.getKind() != lltok::rbrace)
6270 if (parseUseListOrder(&PFS))
6276 // Verify function is ok.
6277 return PFS.finishFunction();
6281 /// ::= (LabelStr|LabelID)? Instruction*
6282 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6283 // If this basic block starts out with a name, remember it.
6286 LocTy NameLoc = Lex.getLoc();
6287 if (Lex.getKind() == lltok::LabelStr) {
6288 Name = Lex.getStrVal();
6290 } else if (Lex.getKind() == lltok::LabelID) {
6291 NameID = Lex.getUIntVal();
6295 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6299 std::string NameStr;
6301 // parse the instructions in this block until we get a terminator.
6304 // This instruction may have three possibilities for a name: a) none
6305 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6306 LocTy NameLoc = Lex.getLoc();
6310 if (Lex.getKind() == lltok::LocalVarID) {
6311 NameID = Lex.getUIntVal();
6313 if (parseToken(lltok::equal, "expected '=' after instruction id"))
6315 } else if (Lex.getKind() == lltok::LocalVar) {
6316 NameStr = Lex.getStrVal();
6318 if (parseToken(lltok::equal, "expected '=' after instruction name"))
6322 switch (parseInstruction(Inst, BB, PFS)) {
6324 llvm_unreachable("Unknown parseInstruction result!");
6325 case InstError: return true;
6327 Inst->insertInto(BB, BB->end());
6329 // With a normal result, we check to see if the instruction is followed by
6330 // a comma and metadata.
6331 if (EatIfPresent(lltok::comma))
6332 if (parseInstructionMetadata(*Inst))
6335 case InstExtraComma:
6336 Inst->insertInto(BB, BB->end());
6338 // If the instruction parser ate an extra comma at the end of it, it
6339 // *must* be followed by metadata.
6340 if (parseInstructionMetadata(*Inst))
6345 // Set the name on the instruction.
6346 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6348 } while (!Inst->isTerminator());
6353 //===----------------------------------------------------------------------===//
6354 // Instruction Parsing.
6355 //===----------------------------------------------------------------------===//
6357 /// parseInstruction - parse one of the many different instructions.
6359 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6360 PerFunctionState &PFS) {
6361 lltok::Kind Token = Lex.getKind();
6362 if (Token == lltok::Eof)
6363 return tokError("found end of file when expecting more instructions");
6364 LocTy Loc = Lex.getLoc();
6365 unsigned KeywordVal = Lex.getUIntVal();
6366 Lex.Lex(); // Eat the keyword.
6370 return error(Loc, "expected instruction opcode");
6371 // Terminator Instructions.
6372 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6374 return parseRet(Inst, BB, PFS);
6376 return parseBr(Inst, PFS);
6377 case lltok::kw_switch:
6378 return parseSwitch(Inst, PFS);
6379 case lltok::kw_indirectbr:
6380 return parseIndirectBr(Inst, PFS);
6381 case lltok::kw_invoke:
6382 return parseInvoke(Inst, PFS);
6383 case lltok::kw_resume:
6384 return parseResume(Inst, PFS);
6385 case lltok::kw_cleanupret:
6386 return parseCleanupRet(Inst, PFS);
6387 case lltok::kw_catchret:
6388 return parseCatchRet(Inst, PFS);
6389 case lltok::kw_catchswitch:
6390 return parseCatchSwitch(Inst, PFS);
6391 case lltok::kw_catchpad:
6392 return parseCatchPad(Inst, PFS);
6393 case lltok::kw_cleanuppad:
6394 return parseCleanupPad(Inst, PFS);
6395 case lltok::kw_callbr:
6396 return parseCallBr(Inst, PFS);
6398 case lltok::kw_fneg: {
6399 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6400 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6404 Inst->setFastMathFlags(FMF);
6407 // Binary Operators.
6411 case lltok::kw_shl: {
6412 bool NUW = EatIfPresent(lltok::kw_nuw);
6413 bool NSW = EatIfPresent(lltok::kw_nsw);
6414 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6416 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6419 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6420 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6423 case lltok::kw_fadd:
6424 case lltok::kw_fsub:
6425 case lltok::kw_fmul:
6426 case lltok::kw_fdiv:
6427 case lltok::kw_frem: {
6428 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6429 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6433 Inst->setFastMathFlags(FMF);
6437 case lltok::kw_sdiv:
6438 case lltok::kw_udiv:
6439 case lltok::kw_lshr:
6440 case lltok::kw_ashr: {
6441 bool Exact = EatIfPresent(lltok::kw_exact);
6443 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6445 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6449 case lltok::kw_urem:
6450 case lltok::kw_srem:
6451 return parseArithmetic(Inst, PFS, KeywordVal,
6456 return parseLogical(Inst, PFS, KeywordVal);
6457 case lltok::kw_icmp:
6458 return parseCompare(Inst, PFS, KeywordVal);
6459 case lltok::kw_fcmp: {
6460 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6461 int Res = parseCompare(Inst, PFS, KeywordVal);
6465 Inst->setFastMathFlags(FMF);
6470 case lltok::kw_trunc:
6471 case lltok::kw_zext:
6472 case lltok::kw_sext:
6473 case lltok::kw_fptrunc:
6474 case lltok::kw_fpext:
6475 case lltok::kw_bitcast:
6476 case lltok::kw_addrspacecast:
6477 case lltok::kw_uitofp:
6478 case lltok::kw_sitofp:
6479 case lltok::kw_fptoui:
6480 case lltok::kw_fptosi:
6481 case lltok::kw_inttoptr:
6482 case lltok::kw_ptrtoint:
6483 return parseCast(Inst, PFS, KeywordVal);
6485 case lltok::kw_select: {
6486 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6487 int Res = parseSelect(Inst, PFS);
6491 if (!isa<FPMathOperator>(Inst))
6492 return error(Loc, "fast-math-flags specified for select without "
6493 "floating-point scalar or vector return type");
6494 Inst->setFastMathFlags(FMF);
6498 case lltok::kw_va_arg:
6499 return parseVAArg(Inst, PFS);
6500 case lltok::kw_extractelement:
6501 return parseExtractElement(Inst, PFS);
6502 case lltok::kw_insertelement:
6503 return parseInsertElement(Inst, PFS);
6504 case lltok::kw_shufflevector:
6505 return parseShuffleVector(Inst, PFS);
6506 case lltok::kw_phi: {
6507 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6508 int Res = parsePHI(Inst, PFS);
6512 if (!isa<FPMathOperator>(Inst))
6513 return error(Loc, "fast-math-flags specified for phi without "
6514 "floating-point scalar or vector return type");
6515 Inst->setFastMathFlags(FMF);
6519 case lltok::kw_landingpad:
6520 return parseLandingPad(Inst, PFS);
6521 case lltok::kw_freeze:
6522 return parseFreeze(Inst, PFS);
6524 case lltok::kw_call:
6525 return parseCall(Inst, PFS, CallInst::TCK_None);
6526 case lltok::kw_tail:
6527 return parseCall(Inst, PFS, CallInst::TCK_Tail);
6528 case lltok::kw_musttail:
6529 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6530 case lltok::kw_notail:
6531 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6533 case lltok::kw_alloca:
6534 return parseAlloc(Inst, PFS);
6535 case lltok::kw_load:
6536 return parseLoad(Inst, PFS);
6537 case lltok::kw_store:
6538 return parseStore(Inst, PFS);
6539 case lltok::kw_cmpxchg:
6540 return parseCmpXchg(Inst, PFS);
6541 case lltok::kw_atomicrmw:
6542 return parseAtomicRMW(Inst, PFS);
6543 case lltok::kw_fence:
6544 return parseFence(Inst, PFS);
6545 case lltok::kw_getelementptr:
6546 return parseGetElementPtr(Inst, PFS);
6547 case lltok::kw_extractvalue:
6548 return parseExtractValue(Inst, PFS);
6549 case lltok::kw_insertvalue:
6550 return parseInsertValue(Inst, PFS);
6554 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6555 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6556 if (Opc == Instruction::FCmp) {
6557 switch (Lex.getKind()) {
6559 return tokError("expected fcmp predicate (e.g. 'oeq')");
6560 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6561 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6562 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6563 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6564 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6565 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6566 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6567 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6568 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6569 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6570 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6571 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6572 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6573 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6574 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6575 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6578 switch (Lex.getKind()) {
6580 return tokError("expected icmp predicate (e.g. 'eq')");
6581 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
6582 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
6583 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6584 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6585 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6586 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6587 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6588 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6589 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6590 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6597 //===----------------------------------------------------------------------===//
6598 // Terminator Instructions.
6599 //===----------------------------------------------------------------------===//
6601 /// parseRet - parse a return instruction.
6602 /// ::= 'ret' void (',' !dbg, !1)*
6603 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6604 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6605 PerFunctionState &PFS) {
6606 SMLoc TypeLoc = Lex.getLoc();
6608 if (parseType(Ty, true /*void allowed*/))
6611 Type *ResType = PFS.getFunction().getReturnType();
6613 if (Ty->isVoidTy()) {
6614 if (!ResType->isVoidTy())
6615 return error(TypeLoc, "value doesn't match function result type '" +
6616 getTypeString(ResType) + "'");
6618 Inst = ReturnInst::Create(Context);
6623 if (parseValue(Ty, RV, PFS))
6626 if (ResType != RV->getType())
6627 return error(TypeLoc, "value doesn't match function result type '" +
6628 getTypeString(ResType) + "'");
6630 Inst = ReturnInst::Create(Context, RV);
6635 /// ::= 'br' TypeAndValue
6636 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6637 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6640 BasicBlock *Op1, *Op2;
6641 if (parseTypeAndValue(Op0, Loc, PFS))
6644 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6645 Inst = BranchInst::Create(BB);
6649 if (Op0->getType() != Type::getInt1Ty(Context))
6650 return error(Loc, "branch condition must have 'i1' type");
6652 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6653 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6654 parseToken(lltok::comma, "expected ',' after true destination") ||
6655 parseTypeAndBasicBlock(Op2, Loc2, PFS))
6658 Inst = BranchInst::Create(Op1, Op2, Op0);
6664 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6666 /// ::= (TypeAndValue ',' TypeAndValue)*
6667 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6668 LocTy CondLoc, BBLoc;
6670 BasicBlock *DefaultBB;
6671 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6672 parseToken(lltok::comma, "expected ',' after switch condition") ||
6673 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6674 parseToken(lltok::lsquare, "expected '[' with switch table"))
6677 if (!Cond->getType()->isIntegerTy())
6678 return error(CondLoc, "switch condition must have integer type");
6680 // parse the jump table pairs.
6681 SmallPtrSet<Value*, 32> SeenCases;
6682 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6683 while (Lex.getKind() != lltok::rsquare) {
6687 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6688 parseToken(lltok::comma, "expected ',' after case value") ||
6689 parseTypeAndBasicBlock(DestBB, PFS))
6692 if (!SeenCases.insert(Constant).second)
6693 return error(CondLoc, "duplicate case value in switch");
6694 if (!isa<ConstantInt>(Constant))
6695 return error(CondLoc, "case value is not a constant integer");
6697 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6700 Lex.Lex(); // Eat the ']'.
6702 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6703 for (unsigned i = 0, e = Table.size(); i != e; ++i)
6704 SI->addCase(Table[i].first, Table[i].second);
6711 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6712 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6715 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6716 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6717 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6720 if (!Address->getType()->isPointerTy())
6721 return error(AddrLoc, "indirectbr address must have pointer type");
6723 // parse the destination list.
6724 SmallVector<BasicBlock*, 16> DestList;
6726 if (Lex.getKind() != lltok::rsquare) {
6728 if (parseTypeAndBasicBlock(DestBB, PFS))
6730 DestList.push_back(DestBB);
6732 while (EatIfPresent(lltok::comma)) {
6733 if (parseTypeAndBasicBlock(DestBB, PFS))
6735 DestList.push_back(DestBB);
6739 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6742 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6743 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6744 IBI->addDestination(DestList[i]);
6749 // If RetType is a non-function pointer type, then this is the short syntax
6750 // for the call, which means that RetType is just the return type. Infer the
6751 // rest of the function argument types from the arguments that are present.
6752 bool LLParser::resolveFunctionType(Type *RetType,
6753 const SmallVector<ParamInfo, 16> &ArgList,
6754 FunctionType *&FuncTy) {
6755 FuncTy = dyn_cast<FunctionType>(RetType);
6757 // Pull out the types of all of the arguments...
6758 std::vector<Type*> ParamTypes;
6759 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6760 ParamTypes.push_back(ArgList[i].V->getType());
6762 if (!FunctionType::isValidReturnType(RetType))
6765 FuncTy = FunctionType::get(RetType, ParamTypes, false);
6771 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6772 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6773 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6774 LocTy CallLoc = Lex.getLoc();
6775 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6776 std::vector<unsigned> FwdRefAttrGrps;
6779 unsigned InvokeAddrSpace;
6780 Type *RetType = nullptr;
6783 SmallVector<ParamInfo, 16> ArgList;
6784 SmallVector<OperandBundleDef, 2> BundleList;
6786 BasicBlock *NormalBB, *UnwindBB;
6787 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6788 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6789 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6790 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6791 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6793 parseOptionalOperandBundles(BundleList, PFS) ||
6794 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6795 parseTypeAndBasicBlock(NormalBB, PFS) ||
6796 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6797 parseTypeAndBasicBlock(UnwindBB, PFS))
6800 // If RetType is a non-function pointer type, then this is the short syntax
6801 // for the call, which means that RetType is just the return type. Infer the
6802 // rest of the function argument types from the arguments that are present.
6804 if (resolveFunctionType(RetType, ArgList, Ty))
6805 return error(RetTypeLoc, "Invalid result type for LLVM function");
6809 // Look up the callee.
6811 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6815 // Set up the Attribute for the function.
6816 SmallVector<Value *, 8> Args;
6817 SmallVector<AttributeSet, 8> ArgAttrs;
6819 // Loop through FunctionType's arguments and ensure they are specified
6820 // correctly. Also, gather any parameter attributes.
6821 FunctionType::param_iterator I = Ty->param_begin();
6822 FunctionType::param_iterator E = Ty->param_end();
6823 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6824 Type *ExpectedTy = nullptr;
6827 } else if (!Ty->isVarArg()) {
6828 return error(ArgList[i].Loc, "too many arguments specified");
6831 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6832 return error(ArgList[i].Loc, "argument is not of expected type '" +
6833 getTypeString(ExpectedTy) + "'");
6834 Args.push_back(ArgList[i].V);
6835 ArgAttrs.push_back(ArgList[i].Attrs);
6839 return error(CallLoc, "not enough parameters specified for call");
6841 // Finish off the Attribute and check them
6843 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6844 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6847 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6848 II->setCallingConv(CC);
6849 II->setAttributes(PAL);
6850 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6856 /// ::= 'resume' TypeAndValue
6857 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6858 Value *Exn; LocTy ExnLoc;
6859 if (parseTypeAndValue(Exn, ExnLoc, PFS))
6862 ResumeInst *RI = ResumeInst::Create(Exn);
6867 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6868 PerFunctionState &PFS) {
6869 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6872 while (Lex.getKind() != lltok::rsquare) {
6873 // If this isn't the first argument, we need a comma.
6874 if (!Args.empty() &&
6875 parseToken(lltok::comma, "expected ',' in argument list"))
6878 // parse the argument.
6880 Type *ArgTy = nullptr;
6881 if (parseType(ArgTy, ArgLoc))
6885 if (ArgTy->isMetadataTy()) {
6886 if (parseMetadataAsValue(V, PFS))
6889 if (parseValue(ArgTy, V, PFS))
6895 Lex.Lex(); // Lex the ']'.
6900 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6901 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6902 Value *CleanupPad = nullptr;
6904 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6907 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6910 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6913 BasicBlock *UnwindBB = nullptr;
6914 if (Lex.getKind() == lltok::kw_to) {
6916 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6919 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6924 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6929 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6930 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6931 Value *CatchPad = nullptr;
6933 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6936 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6940 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6941 parseTypeAndBasicBlock(BB, PFS))
6944 Inst = CatchReturnInst::Create(CatchPad, BB);
6948 /// parseCatchSwitch
6949 /// ::= 'catchswitch' within Parent
6950 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6953 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6956 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6957 Lex.getKind() != lltok::LocalVarID)
6958 return tokError("expected scope value for catchswitch");
6960 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6963 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6966 SmallVector<BasicBlock *, 32> Table;
6969 if (parseTypeAndBasicBlock(DestBB, PFS))
6971 Table.push_back(DestBB);
6972 } while (EatIfPresent(lltok::comma));
6974 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6977 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6980 BasicBlock *UnwindBB = nullptr;
6981 if (EatIfPresent(lltok::kw_to)) {
6982 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6985 if (parseTypeAndBasicBlock(UnwindBB, PFS))
6990 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6991 for (BasicBlock *DestBB : Table)
6992 CatchSwitch->addHandler(DestBB);
6998 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6999 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7000 Value *CatchSwitch = nullptr;
7002 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7005 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7006 return tokError("expected scope value for catchpad");
7008 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7011 SmallVector<Value *, 8> Args;
7012 if (parseExceptionArgs(Args, PFS))
7015 Inst = CatchPadInst::Create(CatchSwitch, Args);
7020 /// ::= 'cleanuppad' within Parent ParamList
7021 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7022 Value *ParentPad = nullptr;
7024 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7027 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7028 Lex.getKind() != lltok::LocalVarID)
7029 return tokError("expected scope value for cleanuppad");
7031 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7034 SmallVector<Value *, 8> Args;
7035 if (parseExceptionArgs(Args, PFS))
7038 Inst = CleanupPadInst::Create(ParentPad, Args);
7042 //===----------------------------------------------------------------------===//
7044 //===----------------------------------------------------------------------===//
7047 /// ::= UnaryOp TypeAndValue ',' Value
7049 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7050 /// operand is allowed.
7051 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7052 unsigned Opc, bool IsFP) {
7053 LocTy Loc; Value *LHS;
7054 if (parseTypeAndValue(LHS, Loc, PFS))
7057 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7058 : LHS->getType()->isIntOrIntVectorTy();
7061 return error(Loc, "invalid operand type for instruction");
7063 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
7068 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7069 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7070 /// '[' LabelList ']'
7071 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7072 LocTy CallLoc = Lex.getLoc();
7073 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7074 std::vector<unsigned> FwdRefAttrGrps;
7077 Type *RetType = nullptr;
7080 SmallVector<ParamInfo, 16> ArgList;
7081 SmallVector<OperandBundleDef, 2> BundleList;
7083 BasicBlock *DefaultDest;
7084 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7085 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7086 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7087 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7089 parseOptionalOperandBundles(BundleList, PFS) ||
7090 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7091 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7092 parseToken(lltok::lsquare, "expected '[' in callbr"))
7095 // parse the destination list.
7096 SmallVector<BasicBlock *, 16> IndirectDests;
7098 if (Lex.getKind() != lltok::rsquare) {
7100 if (parseTypeAndBasicBlock(DestBB, PFS))
7102 IndirectDests.push_back(DestBB);
7104 while (EatIfPresent(lltok::comma)) {
7105 if (parseTypeAndBasicBlock(DestBB, PFS))
7107 IndirectDests.push_back(DestBB);
7111 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7114 // If RetType is a non-function pointer type, then this is the short syntax
7115 // for the call, which means that RetType is just the return type. Infer the
7116 // rest of the function argument types from the arguments that are present.
7118 if (resolveFunctionType(RetType, ArgList, Ty))
7119 return error(RetTypeLoc, "Invalid result type for LLVM function");
7123 // Look up the callee.
7125 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
7128 // Set up the Attribute for the function.
7129 SmallVector<Value *, 8> Args;
7130 SmallVector<AttributeSet, 8> ArgAttrs;
7132 // Loop through FunctionType's arguments and ensure they are specified
7133 // correctly. Also, gather any parameter attributes.
7134 FunctionType::param_iterator I = Ty->param_begin();
7135 FunctionType::param_iterator E = Ty->param_end();
7136 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7137 Type *ExpectedTy = nullptr;
7140 } else if (!Ty->isVarArg()) {
7141 return error(ArgList[i].Loc, "too many arguments specified");
7144 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7145 return error(ArgList[i].Loc, "argument is not of expected type '" +
7146 getTypeString(ExpectedTy) + "'");
7147 Args.push_back(ArgList[i].V);
7148 ArgAttrs.push_back(ArgList[i].Attrs);
7152 return error(CallLoc, "not enough parameters specified for call");
7154 // Finish off the Attribute and check them
7156 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7157 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7160 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
7162 CBI->setCallingConv(CC);
7163 CBI->setAttributes(PAL);
7164 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7169 //===----------------------------------------------------------------------===//
7170 // Binary Operators.
7171 //===----------------------------------------------------------------------===//
7174 /// ::= ArithmeticOps TypeAndValue ',' Value
7176 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7177 /// operand is allowed.
7178 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
7179 unsigned Opc, bool IsFP) {
7180 LocTy Loc; Value *LHS, *RHS;
7181 if (parseTypeAndValue(LHS, Loc, PFS) ||
7182 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
7183 parseValue(LHS->getType(), RHS, PFS))
7186 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7187 : LHS->getType()->isIntOrIntVectorTy();
7190 return error(Loc, "invalid operand type for instruction");
7192 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7197 /// ::= ArithmeticOps TypeAndValue ',' Value {
7198 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
7200 LocTy Loc; Value *LHS, *RHS;
7201 if (parseTypeAndValue(LHS, Loc, PFS) ||
7202 parseToken(lltok::comma, "expected ',' in logical operation") ||
7203 parseValue(LHS->getType(), RHS, PFS))
7206 if (!LHS->getType()->isIntOrIntVectorTy())
7208 "instruction requires integer or integer vector operands");
7210 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7215 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
7216 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
7217 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7219 // parse the integer/fp comparison predicate.
7223 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7224 parseToken(lltok::comma, "expected ',' after compare value") ||
7225 parseValue(LHS->getType(), RHS, PFS))
7228 if (Opc == Instruction::FCmp) {
7229 if (!LHS->getType()->isFPOrFPVectorTy())
7230 return error(Loc, "fcmp requires floating point operands");
7231 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7233 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7234 if (!LHS->getType()->isIntOrIntVectorTy() &&
7235 !LHS->getType()->isPtrOrPtrVectorTy())
7236 return error(Loc, "icmp requires integer operands");
7237 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7242 //===----------------------------------------------------------------------===//
7243 // Other Instructions.
7244 //===----------------------------------------------------------------------===//
7247 /// ::= CastOpc TypeAndValue 'to' Type
7248 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7252 Type *DestTy = nullptr;
7253 if (parseTypeAndValue(Op, Loc, PFS) ||
7254 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7258 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
7259 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
7260 return error(Loc, "invalid cast opcode for cast from '" +
7261 getTypeString(Op->getType()) + "' to '" +
7262 getTypeString(DestTy) + "'");
7264 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7269 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7270 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7272 Value *Op0, *Op1, *Op2;
7273 if (parseTypeAndValue(Op0, Loc, PFS) ||
7274 parseToken(lltok::comma, "expected ',' after select condition") ||
7275 parseTypeAndValue(Op1, PFS) ||
7276 parseToken(lltok::comma, "expected ',' after select value") ||
7277 parseTypeAndValue(Op2, PFS))
7280 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7281 return error(Loc, Reason);
7283 Inst = SelectInst::Create(Op0, Op1, Op2);
7288 /// ::= 'va_arg' TypeAndValue ',' Type
7289 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7291 Type *EltTy = nullptr;
7293 if (parseTypeAndValue(Op, PFS) ||
7294 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7295 parseType(EltTy, TypeLoc))
7298 if (!EltTy->isFirstClassType())
7299 return error(TypeLoc, "va_arg requires operand with first class type");
7301 Inst = new VAArgInst(Op, EltTy);
7305 /// parseExtractElement
7306 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
7307 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7310 if (parseTypeAndValue(Op0, Loc, PFS) ||
7311 parseToken(lltok::comma, "expected ',' after extract value") ||
7312 parseTypeAndValue(Op1, PFS))
7315 if (!ExtractElementInst::isValidOperands(Op0, Op1))
7316 return error(Loc, "invalid extractelement operands");
7318 Inst = ExtractElementInst::Create(Op0, Op1);
7322 /// parseInsertElement
7323 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7324 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7326 Value *Op0, *Op1, *Op2;
7327 if (parseTypeAndValue(Op0, Loc, PFS) ||
7328 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7329 parseTypeAndValue(Op1, PFS) ||
7330 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7331 parseTypeAndValue(Op2, PFS))
7334 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7335 return error(Loc, "invalid insertelement operands");
7337 Inst = InsertElementInst::Create(Op0, Op1, Op2);
7341 /// parseShuffleVector
7342 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7343 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7345 Value *Op0, *Op1, *Op2;
7346 if (parseTypeAndValue(Op0, Loc, PFS) ||
7347 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7348 parseTypeAndValue(Op1, PFS) ||
7349 parseToken(lltok::comma, "expected ',' after shuffle value") ||
7350 parseTypeAndValue(Op2, PFS))
7353 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7354 return error(Loc, "invalid shufflevector operands");
7356 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7361 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7362 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7363 Type *Ty = nullptr; LocTy TypeLoc;
7366 if (parseType(Ty, TypeLoc))
7369 if (!Ty->isFirstClassType())
7370 return error(TypeLoc, "phi node must have first class type");
7373 bool AteExtraComma = false;
7374 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
7378 if (Lex.getKind() != lltok::lsquare)
7381 } else if (!EatIfPresent(lltok::comma))
7384 if (Lex.getKind() == lltok::MetadataVar) {
7385 AteExtraComma = true;
7389 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7390 parseValue(Ty, Op0, PFS) ||
7391 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7392 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7393 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7396 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7399 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7400 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7401 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7403 return AteExtraComma ? InstExtraComma : InstNormal;
7407 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7409 /// ::= 'catch' TypeAndValue
7411 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7412 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7413 Type *Ty = nullptr; LocTy TyLoc;
7415 if (parseType(Ty, TyLoc))
7418 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7419 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7421 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7422 LandingPadInst::ClauseType CT;
7423 if (EatIfPresent(lltok::kw_catch))
7424 CT = LandingPadInst::Catch;
7425 else if (EatIfPresent(lltok::kw_filter))
7426 CT = LandingPadInst::Filter;
7428 return tokError("expected 'catch' or 'filter' clause type");
7432 if (parseTypeAndValue(V, VLoc, PFS))
7435 // A 'catch' type expects a non-array constant. A filter clause expects an
7437 if (CT == LandingPadInst::Catch) {
7438 if (isa<ArrayType>(V->getType()))
7439 error(VLoc, "'catch' clause has an invalid type");
7441 if (!isa<ArrayType>(V->getType()))
7442 error(VLoc, "'filter' clause has an invalid type");
7445 Constant *CV = dyn_cast<Constant>(V);
7447 return error(VLoc, "clause argument must be a constant");
7451 Inst = LP.release();
7456 /// ::= 'freeze' Type Value
7457 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7460 if (parseTypeAndValue(Op, Loc, PFS))
7463 Inst = new FreezeInst(Op);
7468 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7469 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7470 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7471 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7472 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7473 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7474 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7475 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7476 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7477 CallInst::TailCallKind TCK) {
7478 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7479 std::vector<unsigned> FwdRefAttrGrps;
7481 unsigned CallAddrSpace;
7483 Type *RetType = nullptr;
7486 SmallVector<ParamInfo, 16> ArgList;
7487 SmallVector<OperandBundleDef, 2> BundleList;
7488 LocTy CallLoc = Lex.getLoc();
7490 if (TCK != CallInst::TCK_None &&
7491 parseToken(lltok::kw_call,
7492 "expected 'tail call', 'musttail call', or 'notail call'"))
7495 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7497 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7498 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7499 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7500 parseValID(CalleeID, &PFS) ||
7501 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7502 PFS.getFunction().isVarArg()) ||
7503 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7504 parseOptionalOperandBundles(BundleList, PFS))
7507 // If RetType is a non-function pointer type, then this is the short syntax
7508 // for the call, which means that RetType is just the return type. Infer the
7509 // rest of the function argument types from the arguments that are present.
7511 if (resolveFunctionType(RetType, ArgList, Ty))
7512 return error(RetTypeLoc, "Invalid result type for LLVM function");
7516 // Look up the callee.
7518 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7522 // Set up the Attribute for the function.
7523 SmallVector<AttributeSet, 8> Attrs;
7525 SmallVector<Value*, 8> Args;
7527 // Loop through FunctionType's arguments and ensure they are specified
7528 // correctly. Also, gather any parameter attributes.
7529 FunctionType::param_iterator I = Ty->param_begin();
7530 FunctionType::param_iterator E = Ty->param_end();
7531 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7532 Type *ExpectedTy = nullptr;
7535 } else if (!Ty->isVarArg()) {
7536 return error(ArgList[i].Loc, "too many arguments specified");
7539 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7540 return error(ArgList[i].Loc, "argument is not of expected type '" +
7541 getTypeString(ExpectedTy) + "'");
7542 Args.push_back(ArgList[i].V);
7543 Attrs.push_back(ArgList[i].Attrs);
7547 return error(CallLoc, "not enough parameters specified for call");
7549 // Finish off the Attribute and check them
7551 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7552 AttributeSet::get(Context, RetAttrs), Attrs);
7554 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7555 CI->setTailCallKind(TCK);
7556 CI->setCallingConv(CC);
7558 if (!isa<FPMathOperator>(CI)) {
7560 return error(CallLoc, "fast-math-flags specified for call without "
7561 "floating-point scalar or vector return type");
7563 CI->setFastMathFlags(FMF);
7565 CI->setAttributes(PAL);
7566 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7571 //===----------------------------------------------------------------------===//
7572 // Memory Instructions.
7573 //===----------------------------------------------------------------------===//
7576 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7577 /// (',' 'align' i32)? (',', 'addrspace(n))?
7578 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7579 Value *Size = nullptr;
7580 LocTy SizeLoc, TyLoc, ASLoc;
7581 MaybeAlign Alignment;
7582 unsigned AddrSpace = 0;
7585 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7586 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7588 if (parseType(Ty, TyLoc))
7591 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7592 return error(TyLoc, "invalid type for alloca");
7594 bool AteExtraComma = false;
7595 if (EatIfPresent(lltok::comma)) {
7596 if (Lex.getKind() == lltok::kw_align) {
7597 if (parseOptionalAlignment(Alignment))
7599 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7601 } else if (Lex.getKind() == lltok::kw_addrspace) {
7602 ASLoc = Lex.getLoc();
7603 if (parseOptionalAddrSpace(AddrSpace))
7605 } else if (Lex.getKind() == lltok::MetadataVar) {
7606 AteExtraComma = true;
7608 if (parseTypeAndValue(Size, SizeLoc, PFS))
7610 if (EatIfPresent(lltok::comma)) {
7611 if (Lex.getKind() == lltok::kw_align) {
7612 if (parseOptionalAlignment(Alignment))
7614 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7616 } else if (Lex.getKind() == lltok::kw_addrspace) {
7617 ASLoc = Lex.getLoc();
7618 if (parseOptionalAddrSpace(AddrSpace))
7620 } else if (Lex.getKind() == lltok::MetadataVar) {
7621 AteExtraComma = true;
7627 if (Size && !Size->getType()->isIntegerTy())
7628 return error(SizeLoc, "element count must have integer type");
7630 SmallPtrSet<Type *, 4> Visited;
7631 if (!Alignment && !Ty->isSized(&Visited))
7632 return error(TyLoc, "Cannot allocate unsized type");
7634 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7635 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7636 AI->setUsedWithInAlloca(IsInAlloca);
7637 AI->setSwiftError(IsSwiftError);
7639 return AteExtraComma ? InstExtraComma : InstNormal;
7643 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7644 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7645 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7646 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7647 Value *Val; LocTy Loc;
7648 MaybeAlign Alignment;
7649 bool AteExtraComma = false;
7650 bool isAtomic = false;
7651 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7652 SyncScope::ID SSID = SyncScope::System;
7654 if (Lex.getKind() == lltok::kw_atomic) {
7659 bool isVolatile = false;
7660 if (Lex.getKind() == lltok::kw_volatile) {
7666 LocTy ExplicitTypeLoc = Lex.getLoc();
7667 if (parseType(Ty) ||
7668 parseToken(lltok::comma, "expected comma after load's type") ||
7669 parseTypeAndValue(Val, Loc, PFS) ||
7670 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7671 parseOptionalCommaAlign(Alignment, AteExtraComma))
7674 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7675 return error(Loc, "load operand must be a pointer to a first class type");
7676 if (isAtomic && !Alignment)
7677 return error(Loc, "atomic load must have explicit non-zero alignment");
7678 if (Ordering == AtomicOrdering::Release ||
7679 Ordering == AtomicOrdering::AcquireRelease)
7680 return error(Loc, "atomic load cannot use Release ordering");
7682 if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
7685 typeComparisonErrorMessage(
7686 "explicit pointee type doesn't match operand's pointee type", Ty,
7687 Val->getType()->getNonOpaquePointerElementType()));
7689 SmallPtrSet<Type *, 4> Visited;
7690 if (!Alignment && !Ty->isSized(&Visited))
7691 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7693 Alignment = M->getDataLayout().getABITypeAlign(Ty);
7694 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7695 return AteExtraComma ? InstExtraComma : InstNormal;
7700 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7701 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7702 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7703 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7704 Value *Val, *Ptr; LocTy Loc, PtrLoc;
7705 MaybeAlign Alignment;
7706 bool AteExtraComma = false;
7707 bool isAtomic = false;
7708 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7709 SyncScope::ID SSID = SyncScope::System;
7711 if (Lex.getKind() == lltok::kw_atomic) {
7716 bool isVolatile = false;
7717 if (Lex.getKind() == lltok::kw_volatile) {
7722 if (parseTypeAndValue(Val, Loc, PFS) ||
7723 parseToken(lltok::comma, "expected ',' after store operand") ||
7724 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7725 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7726 parseOptionalCommaAlign(Alignment, AteExtraComma))
7729 if (!Ptr->getType()->isPointerTy())
7730 return error(PtrLoc, "store operand must be a pointer");
7731 if (!Val->getType()->isFirstClassType())
7732 return error(Loc, "store operand must be a first class value");
7733 if (!cast<PointerType>(Ptr->getType())
7734 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7735 return error(Loc, "stored value and pointer type do not match");
7736 if (isAtomic && !Alignment)
7737 return error(Loc, "atomic store must have explicit non-zero alignment");
7738 if (Ordering == AtomicOrdering::Acquire ||
7739 Ordering == AtomicOrdering::AcquireRelease)
7740 return error(Loc, "atomic store cannot use Acquire ordering");
7741 SmallPtrSet<Type *, 4> Visited;
7742 if (!Alignment && !Val->getType()->isSized(&Visited))
7743 return error(Loc, "storing unsized types is not allowed");
7745 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7747 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7748 return AteExtraComma ? InstExtraComma : InstNormal;
7752 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7753 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7755 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7756 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7757 bool AteExtraComma = false;
7758 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7759 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7760 SyncScope::ID SSID = SyncScope::System;
7761 bool isVolatile = false;
7762 bool isWeak = false;
7763 MaybeAlign Alignment;
7765 if (EatIfPresent(lltok::kw_weak))
7768 if (EatIfPresent(lltok::kw_volatile))
7771 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7772 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7773 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7774 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7775 parseTypeAndValue(New, NewLoc, PFS) ||
7776 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7777 parseOrdering(FailureOrdering) ||
7778 parseOptionalCommaAlign(Alignment, AteExtraComma))
7781 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7782 return tokError("invalid cmpxchg success ordering");
7783 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7784 return tokError("invalid cmpxchg failure ordering");
7785 if (!Ptr->getType()->isPointerTy())
7786 return error(PtrLoc, "cmpxchg operand must be a pointer");
7787 if (!cast<PointerType>(Ptr->getType())
7788 ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
7789 return error(CmpLoc, "compare value and pointer type do not match");
7790 if (!cast<PointerType>(Ptr->getType())
7791 ->isOpaqueOrPointeeTypeMatches(New->getType()))
7792 return error(NewLoc, "new value and pointer type do not match");
7793 if (Cmp->getType() != New->getType())
7794 return error(NewLoc, "compare value and new value type do not match");
7795 if (!New->getType()->isFirstClassType())
7796 return error(NewLoc, "cmpxchg operand must be a first class value");
7798 const Align DefaultAlignment(
7799 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7802 AtomicCmpXchgInst *CXI =
7803 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
7804 SuccessOrdering, FailureOrdering, SSID);
7805 CXI->setVolatile(isVolatile);
7806 CXI->setWeak(isWeak);
7809 return AteExtraComma ? InstExtraComma : InstNormal;
7813 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7814 /// 'singlethread'? AtomicOrdering
7815 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7816 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7817 bool AteExtraComma = false;
7818 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7819 SyncScope::ID SSID = SyncScope::System;
7820 bool isVolatile = false;
7822 AtomicRMWInst::BinOp Operation;
7823 MaybeAlign Alignment;
7825 if (EatIfPresent(lltok::kw_volatile))
7828 switch (Lex.getKind()) {
7830 return tokError("expected binary operation in atomicrmw");
7831 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7832 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7833 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7834 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7835 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7836 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7837 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7838 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7839 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7840 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7841 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7842 case lltok::kw_uinc_wrap:
7843 Operation = AtomicRMWInst::UIncWrap;
7845 case lltok::kw_udec_wrap:
7846 Operation = AtomicRMWInst::UDecWrap;
7848 case lltok::kw_fadd:
7849 Operation = AtomicRMWInst::FAdd;
7852 case lltok::kw_fsub:
7853 Operation = AtomicRMWInst::FSub;
7856 case lltok::kw_fmax:
7857 Operation = AtomicRMWInst::FMax;
7860 case lltok::kw_fmin:
7861 Operation = AtomicRMWInst::FMin;
7865 Lex.Lex(); // Eat the operation.
7867 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7868 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7869 parseTypeAndValue(Val, ValLoc, PFS) ||
7870 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7871 parseOptionalCommaAlign(Alignment, AteExtraComma))
7874 if (Ordering == AtomicOrdering::Unordered)
7875 return tokError("atomicrmw cannot be unordered");
7876 if (!Ptr->getType()->isPointerTy())
7877 return error(PtrLoc, "atomicrmw operand must be a pointer");
7878 if (!cast<PointerType>(Ptr->getType())
7879 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7880 return error(ValLoc, "atomicrmw value and pointer type do not match");
7882 if (Operation == AtomicRMWInst::Xchg) {
7883 if (!Val->getType()->isIntegerTy() &&
7884 !Val->getType()->isFloatingPointTy() &&
7885 !Val->getType()->isPointerTy()) {
7888 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7889 " operand must be an integer, floating point, or pointer type");
7892 if (!Val->getType()->isFloatingPointTy()) {
7893 return error(ValLoc, "atomicrmw " +
7894 AtomicRMWInst::getOperationName(Operation) +
7895 " operand must be a floating point type");
7898 if (!Val->getType()->isIntegerTy()) {
7899 return error(ValLoc, "atomicrmw " +
7900 AtomicRMWInst::getOperationName(Operation) +
7901 " operand must be an integer");
7906 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
7908 if (Size < 8 || (Size & (Size - 1)))
7909 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7911 const Align DefaultAlignment(
7912 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7914 AtomicRMWInst *RMWI =
7915 new AtomicRMWInst(Operation, Ptr, Val,
7916 Alignment.value_or(DefaultAlignment), Ordering, SSID);
7917 RMWI->setVolatile(isVolatile);
7919 return AteExtraComma ? InstExtraComma : InstNormal;
7923 /// ::= 'fence' 'singlethread'? AtomicOrdering
7924 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7925 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7926 SyncScope::ID SSID = SyncScope::System;
7927 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7930 if (Ordering == AtomicOrdering::Unordered)
7931 return tokError("fence cannot be unordered");
7932 if (Ordering == AtomicOrdering::Monotonic)
7933 return tokError("fence cannot be monotonic");
7935 Inst = new FenceInst(Context, Ordering, SSID);
7939 /// parseGetElementPtr
7940 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7941 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7942 Value *Ptr = nullptr;
7943 Value *Val = nullptr;
7946 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7949 LocTy ExplicitTypeLoc = Lex.getLoc();
7950 if (parseType(Ty) ||
7951 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7952 parseTypeAndValue(Ptr, Loc, PFS))
7955 Type *BaseType = Ptr->getType();
7956 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7957 if (!BasePointerType)
7958 return error(Loc, "base of getelementptr must be a pointer");
7960 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
7963 typeComparisonErrorMessage(
7964 "explicit pointee type doesn't match operand's pointee type", Ty,
7965 BasePointerType->getNonOpaquePointerElementType()));
7968 SmallVector<Value*, 16> Indices;
7969 bool AteExtraComma = false;
7970 // GEP returns a vector of pointers if at least one of parameters is a vector.
7971 // All vector parameters should have the same vector width.
7972 ElementCount GEPWidth = BaseType->isVectorTy()
7973 ? cast<VectorType>(BaseType)->getElementCount()
7974 : ElementCount::getFixed(0);
7976 while (EatIfPresent(lltok::comma)) {
7977 if (Lex.getKind() == lltok::MetadataVar) {
7978 AteExtraComma = true;
7981 if (parseTypeAndValue(Val, EltLoc, PFS))
7983 if (!Val->getType()->isIntOrIntVectorTy())
7984 return error(EltLoc, "getelementptr index must be an integer");
7986 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7987 ElementCount ValNumEl = ValVTy->getElementCount();
7988 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7991 "getelementptr vector index has a wrong number of elements");
7992 GEPWidth = ValNumEl;
7994 Indices.push_back(Val);
7997 SmallPtrSet<Type*, 4> Visited;
7998 if (!Indices.empty() && !Ty->isSized(&Visited))
7999 return error(Loc, "base element of getelementptr must be sized");
8001 auto *STy = dyn_cast<StructType>(Ty);
8002 if (STy && STy->containsScalableVectorType())
8003 return error(Loc, "getelementptr cannot target structure that contains "
8004 "scalable vector type");
8006 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8007 return error(Loc, "invalid getelementptr indices");
8008 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
8010 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
8011 return AteExtraComma ? InstExtraComma : InstNormal;
8014 /// parseExtractValue
8015 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
8016 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8017 Value *Val; LocTy Loc;
8018 SmallVector<unsigned, 4> Indices;
8020 if (parseTypeAndValue(Val, Loc, PFS) ||
8021 parseIndexList(Indices, AteExtraComma))
8024 if (!Val->getType()->isAggregateType())
8025 return error(Loc, "extractvalue operand must be aggregate type");
8027 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8028 return error(Loc, "invalid indices for extractvalue");
8029 Inst = ExtractValueInst::Create(Val, Indices);
8030 return AteExtraComma ? InstExtraComma : InstNormal;
8033 /// parseInsertValue
8034 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8035 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8036 Value *Val0, *Val1; LocTy Loc0, Loc1;
8037 SmallVector<unsigned, 4> Indices;
8039 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8040 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8041 parseTypeAndValue(Val1, Loc1, PFS) ||
8042 parseIndexList(Indices, AteExtraComma))
8045 if (!Val0->getType()->isAggregateType())
8046 return error(Loc0, "insertvalue operand must be aggregate type");
8048 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8050 return error(Loc0, "invalid indices for insertvalue");
8051 if (IndexedType != Val1->getType())
8052 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8053 getTypeString(Val1->getType()) + "' instead of '" +
8054 getTypeString(IndexedType) + "'");
8055 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8056 return AteExtraComma ? InstExtraComma : InstNormal;
8059 //===----------------------------------------------------------------------===//
8060 // Embedded metadata.
8061 //===----------------------------------------------------------------------===//
8063 /// parseMDNodeVector
8064 /// ::= { Element (',' Element)* }
8066 /// ::= 'null' | TypeAndValue
8067 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8068 if (parseToken(lltok::lbrace, "expected '{' here"))
8071 // Check for an empty list.
8072 if (EatIfPresent(lltok::rbrace))
8076 // Null is a special case since it is typeless.
8077 if (EatIfPresent(lltok::kw_null)) {
8078 Elts.push_back(nullptr);
8083 if (parseMetadata(MD, nullptr))
8086 } while (EatIfPresent(lltok::comma));
8088 return parseToken(lltok::rbrace, "expected end of metadata node");
8091 //===----------------------------------------------------------------------===//
8092 // Use-list order directives.
8093 //===----------------------------------------------------------------------===//
8094 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
8097 return error(Loc, "value has no uses");
8099 unsigned NumUses = 0;
8100 SmallDenseMap<const Use *, unsigned, 16> Order;
8101 for (const Use &U : V->uses()) {
8102 if (++NumUses > Indexes.size())
8104 Order[&U] = Indexes[NumUses - 1];
8107 return error(Loc, "value only has one use");
8108 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
8110 "wrong number of indexes, expected " + Twine(V->getNumUses()));
8112 V->sortUseList([&](const Use &L, const Use &R) {
8113 return Order.lookup(&L) < Order.lookup(&R);
8118 /// parseUseListOrderIndexes
8119 /// ::= '{' uint32 (',' uint32)+ '}'
8120 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8121 SMLoc Loc = Lex.getLoc();
8122 if (parseToken(lltok::lbrace, "expected '{' here"))
8124 if (Lex.getKind() == lltok::rbrace)
8125 return Lex.Error("expected non-empty list of uselistorder indexes");
8127 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8128 // indexes should be distinct numbers in the range [0, size-1], and should
8130 unsigned Offset = 0;
8132 bool IsOrdered = true;
8133 assert(Indexes.empty() && "Expected empty order vector");
8136 if (parseUInt32(Index))
8139 // Update consistency checks.
8140 Offset += Index - Indexes.size();
8141 Max = std::max(Max, Index);
8142 IsOrdered &= Index == Indexes.size();
8144 Indexes.push_back(Index);
8145 } while (EatIfPresent(lltok::comma));
8147 if (parseToken(lltok::rbrace, "expected '}' here"))
8150 if (Indexes.size() < 2)
8151 return error(Loc, "expected >= 2 uselistorder indexes");
8152 if (Offset != 0 || Max >= Indexes.size())
8154 "expected distinct uselistorder indexes in range [0, size)");
8156 return error(Loc, "expected uselistorder indexes to change the order");
8161 /// parseUseListOrder
8162 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8163 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8164 SMLoc Loc = Lex.getLoc();
8165 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
8169 SmallVector<unsigned, 16> Indexes;
8170 if (parseTypeAndValue(V, PFS) ||
8171 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
8172 parseUseListOrderIndexes(Indexes))
8175 return sortUseListOrder(V, Indexes, Loc);
8178 /// parseUseListOrderBB
8179 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8180 bool LLParser::parseUseListOrderBB() {
8181 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
8182 SMLoc Loc = Lex.getLoc();
8186 SmallVector<unsigned, 16> Indexes;
8187 if (parseValID(Fn, /*PFS=*/nullptr) ||
8188 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8189 parseValID(Label, /*PFS=*/nullptr) ||
8190 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8191 parseUseListOrderIndexes(Indexes))
8194 // Check the function.
8196 if (Fn.Kind == ValID::t_GlobalName)
8197 GV = M->getNamedValue(Fn.StrVal);
8198 else if (Fn.Kind == ValID::t_GlobalID)
8199 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
8201 return error(Fn.Loc, "expected function name in uselistorder_bb");
8203 return error(Fn.Loc,
8204 "invalid function forward reference in uselistorder_bb");
8205 auto *F = dyn_cast<Function>(GV);
8207 return error(Fn.Loc, "expected function name in uselistorder_bb");
8208 if (F->isDeclaration())
8209 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
8211 // Check the basic block.
8212 if (Label.Kind == ValID::t_LocalID)
8213 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
8214 if (Label.Kind != ValID::t_LocalName)
8215 return error(Label.Loc, "expected basic block name in uselistorder_bb");
8216 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
8218 return error(Label.Loc, "invalid basic block in uselistorder_bb");
8219 if (!isa<BasicBlock>(V))
8220 return error(Label.Loc, "expected basic block in uselistorder_bb");
8222 return sortUseListOrder(V, Indexes, Loc);
8226 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8227 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8228 bool LLParser::parseModuleEntry(unsigned ID) {
8229 assert(Lex.getKind() == lltok::kw_module);
8233 if (parseToken(lltok::colon, "expected ':' here") ||
8234 parseToken(lltok::lparen, "expected '(' here") ||
8235 parseToken(lltok::kw_path, "expected 'path' here") ||
8236 parseToken(lltok::colon, "expected ':' here") ||
8237 parseStringConstant(Path) ||
8238 parseToken(lltok::comma, "expected ',' here") ||
8239 parseToken(lltok::kw_hash, "expected 'hash' here") ||
8240 parseToken(lltok::colon, "expected ':' here") ||
8241 parseToken(lltok::lparen, "expected '(' here"))
8245 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8246 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8247 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8248 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8249 parseUInt32(Hash[4]))
8252 if (parseToken(lltok::rparen, "expected ')' here") ||
8253 parseToken(lltok::rparen, "expected ')' here"))
8256 auto ModuleEntry = Index->addModule(Path, ID, Hash);
8257 ModuleIdMap[ID] = ModuleEntry->first();
8263 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8264 bool LLParser::parseTypeIdEntry(unsigned ID) {
8265 assert(Lex.getKind() == lltok::kw_typeid);
8269 if (parseToken(lltok::colon, "expected ':' here") ||
8270 parseToken(lltok::lparen, "expected '(' here") ||
8271 parseToken(lltok::kw_name, "expected 'name' here") ||
8272 parseToken(lltok::colon, "expected ':' here") ||
8273 parseStringConstant(Name))
8276 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8277 if (parseToken(lltok::comma, "expected ',' here") ||
8278 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8281 // Check if this ID was forward referenced, and if so, update the
8282 // corresponding GUIDs.
8283 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8284 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8285 for (auto TIDRef : FwdRefTIDs->second) {
8286 assert(!*TIDRef.first &&
8287 "Forward referenced type id GUID expected to be 0");
8288 *TIDRef.first = GlobalValue::getGUID(Name);
8290 ForwardRefTypeIds.erase(FwdRefTIDs);
8297 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8298 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8299 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8300 parseToken(lltok::colon, "expected ':' here") ||
8301 parseToken(lltok::lparen, "expected '(' here") ||
8302 parseTypeTestResolution(TIS.TTRes))
8305 if (EatIfPresent(lltok::comma)) {
8306 // Expect optional wpdResolutions field
8307 if (parseOptionalWpdResolutions(TIS.WPDRes))
8311 if (parseToken(lltok::rparen, "expected ')' here"))
8317 static ValueInfo EmptyVI =
8318 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8320 /// TypeIdCompatibleVtableEntry
8321 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8322 /// TypeIdCompatibleVtableInfo
8324 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8325 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
8329 if (parseToken(lltok::colon, "expected ':' here") ||
8330 parseToken(lltok::lparen, "expected '(' here") ||
8331 parseToken(lltok::kw_name, "expected 'name' here") ||
8332 parseToken(lltok::colon, "expected ':' here") ||
8333 parseStringConstant(Name))
8336 TypeIdCompatibleVtableInfo &TI =
8337 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8338 if (parseToken(lltok::comma, "expected ',' here") ||
8339 parseToken(lltok::kw_summary, "expected 'summary' here") ||
8340 parseToken(lltok::colon, "expected ':' here") ||
8341 parseToken(lltok::lparen, "expected '(' here"))
8344 IdToIndexMapType IdToIndexMap;
8345 // parse each call edge
8348 if (parseToken(lltok::lparen, "expected '(' here") ||
8349 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8350 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8351 parseToken(lltok::comma, "expected ',' here"))
8354 LocTy Loc = Lex.getLoc();
8357 if (parseGVReference(VI, GVId))
8360 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8361 // forward reference. We will save the location of the ValueInfo needing an
8362 // update, but can only do so once the std::vector is finalized.
8364 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8365 TI.push_back({Offset, VI});
8367 if (parseToken(lltok::rparen, "expected ')' in call"))
8369 } while (EatIfPresent(lltok::comma));
8371 // Now that the TI vector is finalized, it is safe to save the locations
8372 // of any forward GV references that need updating later.
8373 for (auto I : IdToIndexMap) {
8374 auto &Infos = ForwardRefValueInfos[I.first];
8375 for (auto P : I.second) {
8376 assert(TI[P.first].VTableVI == EmptyVI &&
8377 "Forward referenced ValueInfo expected to be empty");
8378 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8382 if (parseToken(lltok::rparen, "expected ')' here") ||
8383 parseToken(lltok::rparen, "expected ')' here"))
8386 // Check if this ID was forward referenced, and if so, update the
8387 // corresponding GUIDs.
8388 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8389 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8390 for (auto TIDRef : FwdRefTIDs->second) {
8391 assert(!*TIDRef.first &&
8392 "Forward referenced type id GUID expected to be 0");
8393 *TIDRef.first = GlobalValue::getGUID(Name);
8395 ForwardRefTypeIds.erase(FwdRefTIDs);
8401 /// TypeTestResolution
8402 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
8403 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8404 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8405 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8406 /// [',' 'inlinesBits' ':' UInt64]? ')'
8407 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8408 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8409 parseToken(lltok::colon, "expected ':' here") ||
8410 parseToken(lltok::lparen, "expected '(' here") ||
8411 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8412 parseToken(lltok::colon, "expected ':' here"))
8415 switch (Lex.getKind()) {
8416 case lltok::kw_unknown:
8417 TTRes.TheKind = TypeTestResolution::Unknown;
8419 case lltok::kw_unsat:
8420 TTRes.TheKind = TypeTestResolution::Unsat;
8422 case lltok::kw_byteArray:
8423 TTRes.TheKind = TypeTestResolution::ByteArray;
8425 case lltok::kw_inline:
8426 TTRes.TheKind = TypeTestResolution::Inline;
8428 case lltok::kw_single:
8429 TTRes.TheKind = TypeTestResolution::Single;
8431 case lltok::kw_allOnes:
8432 TTRes.TheKind = TypeTestResolution::AllOnes;
8435 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8439 if (parseToken(lltok::comma, "expected ',' here") ||
8440 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8441 parseToken(lltok::colon, "expected ':' here") ||
8442 parseUInt32(TTRes.SizeM1BitWidth))
8445 // parse optional fields
8446 while (EatIfPresent(lltok::comma)) {
8447 switch (Lex.getKind()) {
8448 case lltok::kw_alignLog2:
8450 if (parseToken(lltok::colon, "expected ':'") ||
8451 parseUInt64(TTRes.AlignLog2))
8454 case lltok::kw_sizeM1:
8456 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8459 case lltok::kw_bitMask: {
8462 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8464 assert(Val <= 0xff);
8465 TTRes.BitMask = (uint8_t)Val;
8468 case lltok::kw_inlineBits:
8470 if (parseToken(lltok::colon, "expected ':'") ||
8471 parseUInt64(TTRes.InlineBits))
8475 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8479 if (parseToken(lltok::rparen, "expected ')' here"))
8485 /// OptionalWpdResolutions
8486 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8487 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8488 bool LLParser::parseOptionalWpdResolutions(
8489 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8490 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8491 parseToken(lltok::colon, "expected ':' here") ||
8492 parseToken(lltok::lparen, "expected '(' here"))
8497 WholeProgramDevirtResolution WPDRes;
8498 if (parseToken(lltok::lparen, "expected '(' here") ||
8499 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8500 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8501 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8502 parseToken(lltok::rparen, "expected ')' here"))
8504 WPDResMap[Offset] = WPDRes;
8505 } while (EatIfPresent(lltok::comma));
8507 if (parseToken(lltok::rparen, "expected ')' here"))
8514 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8515 /// [',' OptionalResByArg]? ')'
8516 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8517 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
8518 /// [',' OptionalResByArg]? ')'
8519 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8520 /// [',' OptionalResByArg]? ')'
8521 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8522 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8523 parseToken(lltok::colon, "expected ':' here") ||
8524 parseToken(lltok::lparen, "expected '(' here") ||
8525 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8526 parseToken(lltok::colon, "expected ':' here"))
8529 switch (Lex.getKind()) {
8530 case lltok::kw_indir:
8531 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8533 case lltok::kw_singleImpl:
8534 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8536 case lltok::kw_branchFunnel:
8537 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8540 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8544 // parse optional fields
8545 while (EatIfPresent(lltok::comma)) {
8546 switch (Lex.getKind()) {
8547 case lltok::kw_singleImplName:
8549 if (parseToken(lltok::colon, "expected ':' here") ||
8550 parseStringConstant(WPDRes.SingleImplName))
8553 case lltok::kw_resByArg:
8554 if (parseOptionalResByArg(WPDRes.ResByArg))
8558 return error(Lex.getLoc(),
8559 "expected optional WholeProgramDevirtResolution field");
8563 if (parseToken(lltok::rparen, "expected ')' here"))
8569 /// OptionalResByArg
8570 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8571 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8572 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8573 /// 'virtualConstProp' )
8574 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8575 /// [',' 'bit' ':' UInt32]? ')'
8576 bool LLParser::parseOptionalResByArg(
8577 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8579 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8580 parseToken(lltok::colon, "expected ':' here") ||
8581 parseToken(lltok::lparen, "expected '(' here"))
8585 std::vector<uint64_t> Args;
8586 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8587 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8588 parseToken(lltok::colon, "expected ':' here") ||
8589 parseToken(lltok::lparen, "expected '(' here") ||
8590 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8591 parseToken(lltok::colon, "expected ':' here"))
8594 WholeProgramDevirtResolution::ByArg ByArg;
8595 switch (Lex.getKind()) {
8596 case lltok::kw_indir:
8597 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8599 case lltok::kw_uniformRetVal:
8600 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8602 case lltok::kw_uniqueRetVal:
8603 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8605 case lltok::kw_virtualConstProp:
8606 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8609 return error(Lex.getLoc(),
8610 "unexpected WholeProgramDevirtResolution::ByArg kind");
8614 // parse optional fields
8615 while (EatIfPresent(lltok::comma)) {
8616 switch (Lex.getKind()) {
8617 case lltok::kw_info:
8619 if (parseToken(lltok::colon, "expected ':' here") ||
8620 parseUInt64(ByArg.Info))
8623 case lltok::kw_byte:
8625 if (parseToken(lltok::colon, "expected ':' here") ||
8626 parseUInt32(ByArg.Byte))
8631 if (parseToken(lltok::colon, "expected ':' here") ||
8632 parseUInt32(ByArg.Bit))
8636 return error(Lex.getLoc(),
8637 "expected optional whole program devirt field");
8641 if (parseToken(lltok::rparen, "expected ')' here"))
8644 ResByArg[Args] = ByArg;
8645 } while (EatIfPresent(lltok::comma));
8647 if (parseToken(lltok::rparen, "expected ')' here"))
8653 /// OptionalResByArg
8654 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8655 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8656 if (parseToken(lltok::kw_args, "expected 'args' here") ||
8657 parseToken(lltok::colon, "expected ':' here") ||
8658 parseToken(lltok::lparen, "expected '(' here"))
8663 if (parseUInt64(Val))
8665 Args.push_back(Val);
8666 } while (EatIfPresent(lltok::comma));
8668 if (parseToken(lltok::rparen, "expected ')' here"))
8674 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8676 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8677 bool ReadOnly = Fwd->isReadOnly();
8678 bool WriteOnly = Fwd->isWriteOnly();
8679 assert(!(ReadOnly && WriteOnly));
8684 Fwd->setWriteOnly();
8687 /// Stores the given Name/GUID and associated summary into the Index.
8688 /// Also updates any forward references to the associated entry ID.
8689 void LLParser::addGlobalValueToIndex(
8690 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8691 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8692 // First create the ValueInfo utilizing the Name or GUID.
8695 assert(Name.empty());
8696 VI = Index->getOrInsertValueInfo(GUID);
8698 assert(!Name.empty());
8700 auto *GV = M->getNamedValue(Name);
8702 VI = Index->getOrInsertValueInfo(GV);
8705 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8706 "Need a source_filename to compute GUID for local");
8707 GUID = GlobalValue::getGUID(
8708 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8709 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8713 // Resolve forward references from calls/refs
8714 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8715 if (FwdRefVIs != ForwardRefValueInfos.end()) {
8716 for (auto VIRef : FwdRefVIs->second) {
8717 assert(VIRef.first->getRef() == FwdVIRef &&
8718 "Forward referenced ValueInfo expected to be empty");
8719 resolveFwdRef(VIRef.first, VI);
8721 ForwardRefValueInfos.erase(FwdRefVIs);
8724 // Resolve forward references from aliases
8725 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8726 if (FwdRefAliasees != ForwardRefAliasees.end()) {
8727 for (auto AliaseeRef : FwdRefAliasees->second) {
8728 assert(!AliaseeRef.first->hasAliasee() &&
8729 "Forward referencing alias already has aliasee");
8730 assert(Summary && "Aliasee must be a definition");
8731 AliaseeRef.first->setAliasee(VI, Summary.get());
8733 ForwardRefAliasees.erase(FwdRefAliasees);
8736 // Add the summary if one was provided.
8738 Index->addGlobalValueSummary(VI, std::move(Summary));
8740 // Save the associated ValueInfo for use in later references by ID.
8741 if (ID == NumberedValueInfos.size())
8742 NumberedValueInfos.push_back(VI);
8744 // Handle non-continuous numbers (to make test simplification easier).
8745 if (ID > NumberedValueInfos.size())
8746 NumberedValueInfos.resize(ID + 1);
8747 NumberedValueInfos[ID] = VI;
8751 /// parseSummaryIndexFlags
8752 /// ::= 'flags' ':' UInt64
8753 bool LLParser::parseSummaryIndexFlags() {
8754 assert(Lex.getKind() == lltok::kw_flags);
8757 if (parseToken(lltok::colon, "expected ':' here"))
8760 if (parseUInt64(Flags))
8763 Index->setFlags(Flags);
8768 /// ::= 'blockcount' ':' UInt64
8769 bool LLParser::parseBlockCount() {
8770 assert(Lex.getKind() == lltok::kw_blockcount);
8773 if (parseToken(lltok::colon, "expected ':' here"))
8775 uint64_t BlockCount;
8776 if (parseUInt64(BlockCount))
8779 Index->setBlockCount(BlockCount);
8784 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8785 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8786 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8787 bool LLParser::parseGVEntry(unsigned ID) {
8788 assert(Lex.getKind() == lltok::kw_gv);
8791 if (parseToken(lltok::colon, "expected ':' here") ||
8792 parseToken(lltok::lparen, "expected '(' here"))
8796 GlobalValue::GUID GUID = 0;
8797 switch (Lex.getKind()) {
8798 case lltok::kw_name:
8800 if (parseToken(lltok::colon, "expected ':' here") ||
8801 parseStringConstant(Name))
8803 // Can't create GUID/ValueInfo until we have the linkage.
8805 case lltok::kw_guid:
8807 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8811 return error(Lex.getLoc(), "expected name or guid tag");
8814 if (!EatIfPresent(lltok::comma)) {
8815 // No summaries. Wrap up.
8816 if (parseToken(lltok::rparen, "expected ')' here"))
8818 // This was created for a call to an external or indirect target.
8819 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8820 // created for indirect calls with VP. A Name with no GUID came from
8821 // an external definition. We pass ExternalLinkage since that is only
8822 // used when the GUID must be computed from Name, and in that case
8823 // the symbol must have external linkage.
8824 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8829 // Have a list of summaries
8830 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8831 parseToken(lltok::colon, "expected ':' here") ||
8832 parseToken(lltok::lparen, "expected '(' here"))
8835 switch (Lex.getKind()) {
8836 case lltok::kw_function:
8837 if (parseFunctionSummary(Name, GUID, ID))
8840 case lltok::kw_variable:
8841 if (parseVariableSummary(Name, GUID, ID))
8844 case lltok::kw_alias:
8845 if (parseAliasSummary(Name, GUID, ID))
8849 return error(Lex.getLoc(), "expected summary type");
8851 } while (EatIfPresent(lltok::comma));
8853 if (parseToken(lltok::rparen, "expected ')' here") ||
8854 parseToken(lltok::rparen, "expected ')' here"))
8861 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8862 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8863 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8864 /// [',' OptionalRefs]? ')'
8865 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8867 assert(Lex.getKind() == lltok::kw_function);
8870 StringRef ModulePath;
8871 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8872 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8873 /*NotEligibleToImport=*/false,
8874 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8876 std::vector<FunctionSummary::EdgeTy> Calls;
8877 FunctionSummary::TypeIdInfo TypeIdInfo;
8878 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8879 std::vector<ValueInfo> Refs;
8880 std::vector<CallsiteInfo> Callsites;
8881 std::vector<AllocInfo> Allocs;
8882 // Default is all-zeros (conservative values).
8883 FunctionSummary::FFlags FFlags = {};
8884 if (parseToken(lltok::colon, "expected ':' here") ||
8885 parseToken(lltok::lparen, "expected '(' here") ||
8886 parseModuleReference(ModulePath) ||
8887 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8888 parseToken(lltok::comma, "expected ',' here") ||
8889 parseToken(lltok::kw_insts, "expected 'insts' here") ||
8890 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8893 // parse optional fields
8894 while (EatIfPresent(lltok::comma)) {
8895 switch (Lex.getKind()) {
8896 case lltok::kw_funcFlags:
8897 if (parseOptionalFFlags(FFlags))
8900 case lltok::kw_calls:
8901 if (parseOptionalCalls(Calls))
8904 case lltok::kw_typeIdInfo:
8905 if (parseOptionalTypeIdInfo(TypeIdInfo))
8908 case lltok::kw_refs:
8909 if (parseOptionalRefs(Refs))
8912 case lltok::kw_params:
8913 if (parseOptionalParamAccesses(ParamAccesses))
8916 case lltok::kw_allocs:
8917 if (parseOptionalAllocs(Allocs))
8920 case lltok::kw_callsites:
8921 if (parseOptionalCallsites(Callsites))
8925 return error(Lex.getLoc(), "expected optional function summary field");
8929 if (parseToken(lltok::rparen, "expected ')' here"))
8932 auto FS = std::make_unique<FunctionSummary>(
8933 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8934 std::move(Calls), std::move(TypeIdInfo.TypeTests),
8935 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8936 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8937 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8938 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8939 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
8941 FS->setModulePath(ModulePath);
8943 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8950 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8951 /// [',' OptionalRefs]? ')'
8952 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8954 assert(Lex.getKind() == lltok::kw_variable);
8957 StringRef ModulePath;
8958 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8959 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8960 /*NotEligibleToImport=*/false,
8961 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8962 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8963 /* WriteOnly */ false,
8964 /* Constant */ false,
8965 GlobalObject::VCallVisibilityPublic);
8966 std::vector<ValueInfo> Refs;
8967 VTableFuncList VTableFuncs;
8968 if (parseToken(lltok::colon, "expected ':' here") ||
8969 parseToken(lltok::lparen, "expected '(' here") ||
8970 parseModuleReference(ModulePath) ||
8971 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8972 parseToken(lltok::comma, "expected ',' here") ||
8973 parseGVarFlags(GVarFlags))
8976 // parse optional fields
8977 while (EatIfPresent(lltok::comma)) {
8978 switch (Lex.getKind()) {
8979 case lltok::kw_vTableFuncs:
8980 if (parseOptionalVTableFuncs(VTableFuncs))
8983 case lltok::kw_refs:
8984 if (parseOptionalRefs(Refs))
8988 return error(Lex.getLoc(), "expected optional variable summary field");
8992 if (parseToken(lltok::rparen, "expected ')' here"))
8996 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8998 GS->setModulePath(ModulePath);
8999 GS->setVTableFuncs(std::move(VTableFuncs));
9001 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
9008 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9009 /// 'aliasee' ':' GVReference ')'
9010 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9012 assert(Lex.getKind() == lltok::kw_alias);
9013 LocTy Loc = Lex.getLoc();
9016 StringRef ModulePath;
9017 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9018 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
9019 /*NotEligibleToImport=*/false,
9020 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
9021 if (parseToken(lltok::colon, "expected ':' here") ||
9022 parseToken(lltok::lparen, "expected '(' here") ||
9023 parseModuleReference(ModulePath) ||
9024 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9025 parseToken(lltok::comma, "expected ',' here") ||
9026 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9027 parseToken(lltok::colon, "expected ':' here"))
9030 ValueInfo AliaseeVI;
9032 if (parseGVReference(AliaseeVI, GVId))
9035 if (parseToken(lltok::rparen, "expected ')' here"))
9038 auto AS = std::make_unique<AliasSummary>(GVFlags);
9040 AS->setModulePath(ModulePath);
9042 // Record forward reference if the aliasee is not parsed yet.
9043 if (AliaseeVI.getRef() == FwdVIRef) {
9044 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9046 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9047 assert(Summary && "Aliasee must be a definition");
9048 AS->setAliasee(AliaseeVI, Summary);
9051 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
9059 bool LLParser::parseFlag(unsigned &Val) {
9060 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9061 return tokError("expected integer");
9062 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9068 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9069 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9070 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9071 /// [',' 'noInline' ':' Flag]? ')'
9072 /// [',' 'alwaysInline' ':' Flag]? ')'
9073 /// [',' 'noUnwind' ':' Flag]? ')'
9074 /// [',' 'mayThrow' ':' Flag]? ')'
9075 /// [',' 'hasUnknownCall' ':' Flag]? ')'
9076 /// [',' 'mustBeUnreachable' ':' Flag]? ')'
9078 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9079 assert(Lex.getKind() == lltok::kw_funcFlags);
9082 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
9083 parseToken(lltok::lparen, "expected '(' in funcFlags"))
9088 switch (Lex.getKind()) {
9089 case lltok::kw_readNone:
9091 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9093 FFlags.ReadNone = Val;
9095 case lltok::kw_readOnly:
9097 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9099 FFlags.ReadOnly = Val;
9101 case lltok::kw_noRecurse:
9103 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9105 FFlags.NoRecurse = Val;
9107 case lltok::kw_returnDoesNotAlias:
9109 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9111 FFlags.ReturnDoesNotAlias = Val;
9113 case lltok::kw_noInline:
9115 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9117 FFlags.NoInline = Val;
9119 case lltok::kw_alwaysInline:
9121 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9123 FFlags.AlwaysInline = Val;
9125 case lltok::kw_noUnwind:
9127 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9129 FFlags.NoUnwind = Val;
9131 case lltok::kw_mayThrow:
9133 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9135 FFlags.MayThrow = Val;
9137 case lltok::kw_hasUnknownCall:
9139 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9141 FFlags.HasUnknownCall = Val;
9143 case lltok::kw_mustBeUnreachable:
9145 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9147 FFlags.MustBeUnreachable = Val;
9150 return error(Lex.getLoc(), "expected function flag type");
9152 } while (EatIfPresent(lltok::comma));
9154 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
9161 /// := 'calls' ':' '(' Call [',' Call]* ')'
9162 /// Call ::= '(' 'callee' ':' GVReference
9163 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
9164 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9165 assert(Lex.getKind() == lltok::kw_calls);
9168 if (parseToken(lltok::colon, "expected ':' in calls") ||
9169 parseToken(lltok::lparen, "expected '(' in calls"))
9172 IdToIndexMapType IdToIndexMap;
9173 // parse each call edge
9176 if (parseToken(lltok::lparen, "expected '(' in call") ||
9177 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
9178 parseToken(lltok::colon, "expected ':'"))
9181 LocTy Loc = Lex.getLoc();
9183 if (parseGVReference(VI, GVId))
9186 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
9188 if (EatIfPresent(lltok::comma)) {
9189 // Expect either hotness or relbf
9190 if (EatIfPresent(lltok::kw_hotness)) {
9191 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
9194 if (parseToken(lltok::kw_relbf, "expected relbf") ||
9195 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
9199 // Keep track of the Call array index needing a forward reference.
9200 // We will save the location of the ValueInfo needing an update, but
9201 // can only do so once the std::vector is finalized.
9202 if (VI.getRef() == FwdVIRef)
9203 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9204 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
9206 if (parseToken(lltok::rparen, "expected ')' in call"))
9208 } while (EatIfPresent(lltok::comma));
9210 // Now that the Calls vector is finalized, it is safe to save the locations
9211 // of any forward GV references that need updating later.
9212 for (auto I : IdToIndexMap) {
9213 auto &Infos = ForwardRefValueInfos[I.first];
9214 for (auto P : I.second) {
9215 assert(Calls[P.first].first.getRef() == FwdVIRef &&
9216 "Forward referenced ValueInfo expected to be empty");
9217 Infos.emplace_back(&Calls[P.first].first, P.second);
9221 if (parseToken(lltok::rparen, "expected ')' in calls"))
9228 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
9229 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
9230 switch (Lex.getKind()) {
9231 case lltok::kw_unknown:
9232 Hotness = CalleeInfo::HotnessType::Unknown;
9234 case lltok::kw_cold:
9235 Hotness = CalleeInfo::HotnessType::Cold;
9237 case lltok::kw_none:
9238 Hotness = CalleeInfo::HotnessType::None;
9241 Hotness = CalleeInfo::HotnessType::Hot;
9243 case lltok::kw_critical:
9244 Hotness = CalleeInfo::HotnessType::Critical;
9247 return error(Lex.getLoc(), "invalid call edge hotness");
9253 /// OptionalVTableFuncs
9254 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9255 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9256 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
9257 assert(Lex.getKind() == lltok::kw_vTableFuncs);
9260 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
9261 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9264 IdToIndexMapType IdToIndexMap;
9265 // parse each virtual function pair
9268 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9269 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9270 parseToken(lltok::colon, "expected ':'"))
9273 LocTy Loc = Lex.getLoc();
9275 if (parseGVReference(VI, GVId))
9279 if (parseToken(lltok::comma, "expected comma") ||
9280 parseToken(lltok::kw_offset, "expected offset") ||
9281 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9284 // Keep track of the VTableFuncs array index needing a forward reference.
9285 // We will save the location of the ValueInfo needing an update, but
9286 // can only do so once the std::vector is finalized.
9288 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9289 VTableFuncs.push_back({VI, Offset});
9291 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9293 } while (EatIfPresent(lltok::comma));
9295 // Now that the VTableFuncs vector is finalized, it is safe to save the
9296 // locations of any forward GV references that need updating later.
9297 for (auto I : IdToIndexMap) {
9298 auto &Infos = ForwardRefValueInfos[I.first];
9299 for (auto P : I.second) {
9300 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9301 "Forward referenced ValueInfo expected to be empty");
9302 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9306 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9312 /// ParamNo := 'param' ':' UInt64
9313 bool LLParser::parseParamNo(uint64_t &ParamNo) {
9314 if (parseToken(lltok::kw_param, "expected 'param' here") ||
9315 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9320 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9321 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9324 auto ParseAPSInt = [&](APSInt &Val) {
9325 if (Lex.getKind() != lltok::APSInt)
9326 return tokError("expected integer");
9327 Val = Lex.getAPSIntVal();
9328 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9329 Val.setIsSigned(true);
9333 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9334 parseToken(lltok::colon, "expected ':' here") ||
9335 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9336 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9337 parseToken(lltok::rsquare, "expected ']' here"))
9342 (Lower == Upper && !Lower.isMaxValue())
9343 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9344 : ConstantRange(Lower, Upper);
9350 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9351 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9352 IdLocListType &IdLocList) {
9353 if (parseToken(lltok::lparen, "expected '(' here") ||
9354 parseToken(lltok::kw_callee, "expected 'callee' here") ||
9355 parseToken(lltok::colon, "expected ':' here"))
9360 LocTy Loc = Lex.getLoc();
9361 if (parseGVReference(VI, GVId))
9365 IdLocList.emplace_back(GVId, Loc);
9367 if (parseToken(lltok::comma, "expected ',' here") ||
9368 parseParamNo(Call.ParamNo) ||
9369 parseToken(lltok::comma, "expected ',' here") ||
9370 parseParamAccessOffset(Call.Offsets))
9373 if (parseToken(lltok::rparen, "expected ')' here"))
9380 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9381 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9382 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
9383 IdLocListType &IdLocList) {
9384 if (parseToken(lltok::lparen, "expected '(' here") ||
9385 parseParamNo(Param.ParamNo) ||
9386 parseToken(lltok::comma, "expected ',' here") ||
9387 parseParamAccessOffset(Param.Use))
9390 if (EatIfPresent(lltok::comma)) {
9391 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
9392 parseToken(lltok::colon, "expected ':' here") ||
9393 parseToken(lltok::lparen, "expected '(' here"))
9396 FunctionSummary::ParamAccess::Call Call;
9397 if (parseParamAccessCall(Call, IdLocList))
9399 Param.Calls.push_back(Call);
9400 } while (EatIfPresent(lltok::comma));
9402 if (parseToken(lltok::rparen, "expected ')' here"))
9406 if (parseToken(lltok::rparen, "expected ')' here"))
9412 /// OptionalParamAccesses
9413 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9414 bool LLParser::parseOptionalParamAccesses(
9415 std::vector<FunctionSummary::ParamAccess> &Params) {
9416 assert(Lex.getKind() == lltok::kw_params);
9419 if (parseToken(lltok::colon, "expected ':' here") ||
9420 parseToken(lltok::lparen, "expected '(' here"))
9423 IdLocListType VContexts;
9424 size_t CallsNum = 0;
9426 FunctionSummary::ParamAccess ParamAccess;
9427 if (parseParamAccess(ParamAccess, VContexts))
9429 CallsNum += ParamAccess.Calls.size();
9430 assert(VContexts.size() == CallsNum);
9432 Params.emplace_back(std::move(ParamAccess));
9433 } while (EatIfPresent(lltok::comma));
9435 if (parseToken(lltok::rparen, "expected ')' here"))
9438 // Now that the Params is finalized, it is safe to save the locations
9439 // of any forward GV references that need updating later.
9440 IdLocListType::const_iterator ItContext = VContexts.begin();
9441 for (auto &PA : Params) {
9442 for (auto &C : PA.Calls) {
9443 if (C.Callee.getRef() == FwdVIRef)
9444 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9449 assert(ItContext == VContexts.end());
9455 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9456 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9457 assert(Lex.getKind() == lltok::kw_refs);
9460 if (parseToken(lltok::colon, "expected ':' in refs") ||
9461 parseToken(lltok::lparen, "expected '(' in refs"))
9464 struct ValueContext {
9469 std::vector<ValueContext> VContexts;
9470 // parse each ref edge
9473 VC.Loc = Lex.getLoc();
9474 if (parseGVReference(VC.VI, VC.GVId))
9476 VContexts.push_back(VC);
9477 } while (EatIfPresent(lltok::comma));
9479 // Sort value contexts so that ones with writeonly
9480 // and readonly ValueInfo are at the end of VContexts vector.
9481 // See FunctionSummary::specialRefCounts()
9482 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9483 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9486 IdToIndexMapType IdToIndexMap;
9487 for (auto &VC : VContexts) {
9488 // Keep track of the Refs array index needing a forward reference.
9489 // We will save the location of the ValueInfo needing an update, but
9490 // can only do so once the std::vector is finalized.
9491 if (VC.VI.getRef() == FwdVIRef)
9492 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9493 Refs.push_back(VC.VI);
9496 // Now that the Refs vector is finalized, it is safe to save the locations
9497 // of any forward GV references that need updating later.
9498 for (auto I : IdToIndexMap) {
9499 auto &Infos = ForwardRefValueInfos[I.first];
9500 for (auto P : I.second) {
9501 assert(Refs[P.first].getRef() == FwdVIRef &&
9502 "Forward referenced ValueInfo expected to be empty");
9503 Infos.emplace_back(&Refs[P.first], P.second);
9507 if (parseToken(lltok::rparen, "expected ')' in refs"))
9513 /// OptionalTypeIdInfo
9514 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9515 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
9516 /// [',' TypeCheckedLoadConstVCalls]? ')'
9517 bool LLParser::parseOptionalTypeIdInfo(
9518 FunctionSummary::TypeIdInfo &TypeIdInfo) {
9519 assert(Lex.getKind() == lltok::kw_typeIdInfo);
9522 if (parseToken(lltok::colon, "expected ':' here") ||
9523 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9527 switch (Lex.getKind()) {
9528 case lltok::kw_typeTests:
9529 if (parseTypeTests(TypeIdInfo.TypeTests))
9532 case lltok::kw_typeTestAssumeVCalls:
9533 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9534 TypeIdInfo.TypeTestAssumeVCalls))
9537 case lltok::kw_typeCheckedLoadVCalls:
9538 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9539 TypeIdInfo.TypeCheckedLoadVCalls))
9542 case lltok::kw_typeTestAssumeConstVCalls:
9543 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9544 TypeIdInfo.TypeTestAssumeConstVCalls))
9547 case lltok::kw_typeCheckedLoadConstVCalls:
9548 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9549 TypeIdInfo.TypeCheckedLoadConstVCalls))
9553 return error(Lex.getLoc(), "invalid typeIdInfo list type");
9555 } while (EatIfPresent(lltok::comma));
9557 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9564 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9565 /// [',' (SummaryID | UInt64)]* ')'
9566 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9567 assert(Lex.getKind() == lltok::kw_typeTests);
9570 if (parseToken(lltok::colon, "expected ':' here") ||
9571 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9574 IdToIndexMapType IdToIndexMap;
9576 GlobalValue::GUID GUID = 0;
9577 if (Lex.getKind() == lltok::SummaryID) {
9578 unsigned ID = Lex.getUIntVal();
9579 LocTy Loc = Lex.getLoc();
9580 // Keep track of the TypeTests array index needing a forward reference.
9581 // We will save the location of the GUID needing an update, but
9582 // can only do so once the std::vector is finalized.
9583 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9585 } else if (parseUInt64(GUID))
9587 TypeTests.push_back(GUID);
9588 } while (EatIfPresent(lltok::comma));
9590 // Now that the TypeTests vector is finalized, it is safe to save the
9591 // locations of any forward GV references that need updating later.
9592 for (auto I : IdToIndexMap) {
9593 auto &Ids = ForwardRefTypeIds[I.first];
9594 for (auto P : I.second) {
9595 assert(TypeTests[P.first] == 0 &&
9596 "Forward referenced type id GUID expected to be 0");
9597 Ids.emplace_back(&TypeTests[P.first], P.second);
9601 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9608 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9609 bool LLParser::parseVFuncIdList(
9610 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9611 assert(Lex.getKind() == Kind);
9614 if (parseToken(lltok::colon, "expected ':' here") ||
9615 parseToken(lltok::lparen, "expected '(' here"))
9618 IdToIndexMapType IdToIndexMap;
9620 FunctionSummary::VFuncId VFuncId;
9621 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9623 VFuncIdList.push_back(VFuncId);
9624 } while (EatIfPresent(lltok::comma));
9626 if (parseToken(lltok::rparen, "expected ')' here"))
9629 // Now that the VFuncIdList vector is finalized, it is safe to save the
9630 // locations of any forward GV references that need updating later.
9631 for (auto I : IdToIndexMap) {
9632 auto &Ids = ForwardRefTypeIds[I.first];
9633 for (auto P : I.second) {
9634 assert(VFuncIdList[P.first].GUID == 0 &&
9635 "Forward referenced type id GUID expected to be 0");
9636 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9644 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9645 bool LLParser::parseConstVCallList(
9647 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9648 assert(Lex.getKind() == Kind);
9651 if (parseToken(lltok::colon, "expected ':' here") ||
9652 parseToken(lltok::lparen, "expected '(' here"))
9655 IdToIndexMapType IdToIndexMap;
9657 FunctionSummary::ConstVCall ConstVCall;
9658 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9660 ConstVCallList.push_back(ConstVCall);
9661 } while (EatIfPresent(lltok::comma));
9663 if (parseToken(lltok::rparen, "expected ')' here"))
9666 // Now that the ConstVCallList vector is finalized, it is safe to save the
9667 // locations of any forward GV references that need updating later.
9668 for (auto I : IdToIndexMap) {
9669 auto &Ids = ForwardRefTypeIds[I.first];
9670 for (auto P : I.second) {
9671 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9672 "Forward referenced type id GUID expected to be 0");
9673 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9681 /// ::= '(' VFuncId ',' Args ')'
9682 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9683 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9684 if (parseToken(lltok::lparen, "expected '(' here") ||
9685 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9688 if (EatIfPresent(lltok::comma))
9689 if (parseArgs(ConstVCall.Args))
9692 if (parseToken(lltok::rparen, "expected ')' here"))
9699 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9700 /// 'offset' ':' UInt64 ')'
9701 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9702 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9703 assert(Lex.getKind() == lltok::kw_vFuncId);
9706 if (parseToken(lltok::colon, "expected ':' here") ||
9707 parseToken(lltok::lparen, "expected '(' here"))
9710 if (Lex.getKind() == lltok::SummaryID) {
9712 unsigned ID = Lex.getUIntVal();
9713 LocTy Loc = Lex.getLoc();
9714 // Keep track of the array index needing a forward reference.
9715 // We will save the location of the GUID needing an update, but
9716 // can only do so once the caller's std::vector is finalized.
9717 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9719 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9720 parseToken(lltok::colon, "expected ':' here") ||
9721 parseUInt64(VFuncId.GUID))
9724 if (parseToken(lltok::comma, "expected ',' here") ||
9725 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9726 parseToken(lltok::colon, "expected ':' here") ||
9727 parseUInt64(VFuncId.Offset) ||
9728 parseToken(lltok::rparen, "expected ')' here"))
9735 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9736 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9737 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9738 /// 'canAutoHide' ':' Flag ',' ')'
9739 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9740 assert(Lex.getKind() == lltok::kw_flags);
9743 if (parseToken(lltok::colon, "expected ':' here") ||
9744 parseToken(lltok::lparen, "expected '(' here"))
9749 switch (Lex.getKind()) {
9750 case lltok::kw_linkage:
9752 if (parseToken(lltok::colon, "expected ':'"))
9755 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9756 assert(HasLinkage && "Linkage not optional in summary entry");
9759 case lltok::kw_visibility:
9761 if (parseToken(lltok::colon, "expected ':'"))
9763 parseOptionalVisibility(Flag);
9764 GVFlags.Visibility = Flag;
9766 case lltok::kw_notEligibleToImport:
9768 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9770 GVFlags.NotEligibleToImport = Flag;
9772 case lltok::kw_live:
9774 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9776 GVFlags.Live = Flag;
9778 case lltok::kw_dsoLocal:
9780 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9782 GVFlags.DSOLocal = Flag;
9784 case lltok::kw_canAutoHide:
9786 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9788 GVFlags.CanAutoHide = Flag;
9791 return error(Lex.getLoc(), "expected gv flag type");
9793 } while (EatIfPresent(lltok::comma));
9795 if (parseToken(lltok::rparen, "expected ')' here"))
9802 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9803 /// ',' 'writeonly' ':' Flag
9804 /// ',' 'constant' ':' Flag ')'
9805 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9806 assert(Lex.getKind() == lltok::kw_varFlags);
9809 if (parseToken(lltok::colon, "expected ':' here") ||
9810 parseToken(lltok::lparen, "expected '(' here"))
9813 auto ParseRest = [this](unsigned int &Val) {
9815 if (parseToken(lltok::colon, "expected ':'"))
9817 return parseFlag(Val);
9822 switch (Lex.getKind()) {
9823 case lltok::kw_readonly:
9824 if (ParseRest(Flag))
9826 GVarFlags.MaybeReadOnly = Flag;
9828 case lltok::kw_writeonly:
9829 if (ParseRest(Flag))
9831 GVarFlags.MaybeWriteOnly = Flag;
9833 case lltok::kw_constant:
9834 if (ParseRest(Flag))
9836 GVarFlags.Constant = Flag;
9838 case lltok::kw_vcall_visibility:
9839 if (ParseRest(Flag))
9841 GVarFlags.VCallVisibility = Flag;
9844 return error(Lex.getLoc(), "expected gvar flag type");
9846 } while (EatIfPresent(lltok::comma));
9847 return parseToken(lltok::rparen, "expected ')' here");
9851 /// ::= 'module' ':' UInt
9852 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9854 if (parseToken(lltok::kw_module, "expected 'module' here") ||
9855 parseToken(lltok::colon, "expected ':' here") ||
9856 parseToken(lltok::SummaryID, "expected module ID"))
9859 unsigned ModuleID = Lex.getUIntVal();
9860 auto I = ModuleIdMap.find(ModuleID);
9861 // We should have already parsed all module IDs
9862 assert(I != ModuleIdMap.end());
9863 ModulePath = I->second;
9869 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9870 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9872 WriteOnly = EatIfPresent(lltok::kw_writeonly);
9873 if (parseToken(lltok::SummaryID, "expected GV ID"))
9876 GVId = Lex.getUIntVal();
9877 // Check if we already have a VI for this GV
9878 if (GVId < NumberedValueInfos.size()) {
9879 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9880 VI = NumberedValueInfos[GVId];
9882 // We will create a forward reference to the stored location.
9883 VI = ValueInfo(false, FwdVIRef);
9893 /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
9894 /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
9895 /// ',' MemProfs ')'
9896 /// Version ::= UInt32
9897 bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
9898 assert(Lex.getKind() == lltok::kw_allocs);
9901 if (parseToken(lltok::colon, "expected ':' in allocs") ||
9902 parseToken(lltok::lparen, "expected '(' in allocs"))
9907 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
9908 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
9909 parseToken(lltok::colon, "expected ':'") ||
9910 parseToken(lltok::lparen, "expected '(' in versions"))
9913 SmallVector<uint8_t> Versions;
9916 if (parseAllocType(V))
9918 Versions.push_back(V);
9919 } while (EatIfPresent(lltok::comma));
9921 if (parseToken(lltok::rparen, "expected ')' in versions") ||
9922 parseToken(lltok::comma, "expected ',' in alloc"))
9925 std::vector<MIBInfo> MIBs;
9926 if (parseMemProfs(MIBs))
9929 Allocs.push_back({Versions, MIBs});
9931 if (parseToken(lltok::rparen, "expected ')' in alloc"))
9933 } while (EatIfPresent(lltok::comma));
9935 if (parseToken(lltok::rparen, "expected ')' in allocs"))
9942 /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
9943 /// MemProf ::= '(' 'type' ':' AllocType
9944 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
9945 /// StackId ::= UInt64
9946 bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
9947 assert(Lex.getKind() == lltok::kw_memProf);
9950 if (parseToken(lltok::colon, "expected ':' in memprof") ||
9951 parseToken(lltok::lparen, "expected '(' in memprof"))
9956 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
9957 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
9958 parseToken(lltok::colon, "expected ':'"))
9962 if (parseAllocType(AllocType))
9965 if (parseToken(lltok::comma, "expected ',' in memprof") ||
9966 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
9967 parseToken(lltok::colon, "expected ':'") ||
9968 parseToken(lltok::lparen, "expected '(' in stackIds"))
9971 SmallVector<unsigned> StackIdIndices;
9973 uint64_t StackId = 0;
9974 if (parseUInt64(StackId))
9976 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
9977 } while (EatIfPresent(lltok::comma));
9979 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
9982 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
9984 if (parseToken(lltok::rparen, "expected ')' in memprof"))
9986 } while (EatIfPresent(lltok::comma));
9988 if (parseToken(lltok::rparen, "expected ')' in memprof"))
9995 /// := ('none'|'notcold'|'cold'|'hot')
9996 bool LLParser::parseAllocType(uint8_t &AllocType) {
9997 switch (Lex.getKind()) {
9998 case lltok::kw_none:
9999 AllocType = (uint8_t)AllocationType::None;
10001 case lltok::kw_notcold:
10002 AllocType = (uint8_t)AllocationType::NotCold;
10004 case lltok::kw_cold:
10005 AllocType = (uint8_t)AllocationType::Cold;
10007 case lltok::kw_hot:
10008 AllocType = (uint8_t)AllocationType::Hot;
10011 return error(Lex.getLoc(), "invalid alloc type");
10017 /// OptionalCallsites
10018 /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10019 /// Callsite ::= '(' 'callee' ':' GVReference
10020 /// ',' 'clones' ':' '(' Version [',' Version]* ')'
10021 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10022 /// Version ::= UInt32
10023 /// StackId ::= UInt64
10024 bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10025 assert(Lex.getKind() == lltok::kw_callsites);
10028 if (parseToken(lltok::colon, "expected ':' in callsites") ||
10029 parseToken(lltok::lparen, "expected '(' in callsites"))
10032 IdToIndexMapType IdToIndexMap;
10033 // parse each callsite
10035 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10036 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10037 parseToken(lltok::colon, "expected ':'"))
10042 LocTy Loc = Lex.getLoc();
10043 if (!EatIfPresent(lltok::kw_null)) {
10044 if (parseGVReference(VI, GVId))
10048 if (parseToken(lltok::comma, "expected ',' in callsite") ||
10049 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10050 parseToken(lltok::colon, "expected ':'") ||
10051 parseToken(lltok::lparen, "expected '(' in clones"))
10054 SmallVector<unsigned> Clones;
10057 if (parseUInt32(V))
10059 Clones.push_back(V);
10060 } while (EatIfPresent(lltok::comma));
10062 if (parseToken(lltok::rparen, "expected ')' in clones") ||
10063 parseToken(lltok::comma, "expected ',' in callsite") ||
10064 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
10065 parseToken(lltok::colon, "expected ':'") ||
10066 parseToken(lltok::lparen, "expected '(' in stackIds"))
10069 SmallVector<unsigned> StackIdIndices;
10071 uint64_t StackId = 0;
10072 if (parseUInt64(StackId))
10074 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10075 } while (EatIfPresent(lltok::comma));
10077 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10080 // Keep track of the Callsites array index needing a forward reference.
10081 // We will save the location of the ValueInfo needing an update, but
10082 // can only do so once the SmallVector is finalized.
10083 if (VI.getRef() == FwdVIRef)
10084 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10085 Callsites.push_back({VI, Clones, StackIdIndices});
10087 if (parseToken(lltok::rparen, "expected ')' in callsite"))
10089 } while (EatIfPresent(lltok::comma));
10091 // Now that the Callsites vector is finalized, it is safe to save the
10092 // locations of any forward GV references that need updating later.
10093 for (auto I : IdToIndexMap) {
10094 auto &Infos = ForwardRefValueInfos[I.first];
10095 for (auto P : I.second) {
10096 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
10097 "Forward referenced ValueInfo expected to be empty");
10098 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
10102 if (parseToken(lltok::rparen, "expected ')' in callsites"))