1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.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/Constants.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalObject.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instruction.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/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/IR/ValueSymbolTable.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.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() {
69 if (Context.shouldDiscardValueNames())
72 "Can't read textual IR with a Context that discards named Values");
74 return ParseTopLevelEntities() || ValidateEndOfModule() ||
78 bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
93 restoreParsingState(Slots);
97 SMLoc Start = Lex.getLoc();
101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
107 void LLParser::restoreParsingState(const SlotMapping *Slots) {
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
122 bool LLParser::ValidateEndOfModule() {
125 // Handle any function attribute group forward references.
126 for (const auto &RAG : ForwardRefAttrGroups) {
127 Value *V = RAG.first;
128 const std::vector<unsigned> &Attrs = RAG.second;
131 for (const auto &Attr : Attrs)
132 B.merge(NumberedAttrBuilders[Attr]);
134 if (Function *Fn = dyn_cast<Function>(V)) {
135 AttributeList AS = Fn->getAttributes();
136 AttrBuilder FnAttrs(AS.getFnAttributes());
137 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
141 // If the alignment was parsed as an attribute, move to the alignment
143 if (FnAttrs.hasAlignmentAttr()) {
144 Fn->setAlignment(FnAttrs.getAlignment());
145 FnAttrs.removeAttribute(Attribute::Alignment);
148 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
149 AttributeSet::get(Context, FnAttrs));
150 Fn->setAttributes(AS);
151 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
152 AttributeList AS = CI->getAttributes();
153 AttrBuilder FnAttrs(AS.getFnAttributes());
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
156 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
157 AttributeSet::get(Context, FnAttrs));
158 CI->setAttributes(AS);
159 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
160 AttributeList AS = II->getAttributes();
161 AttrBuilder FnAttrs(AS.getFnAttributes());
162 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
164 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
165 AttributeSet::get(Context, FnAttrs));
166 II->setAttributes(AS);
167 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
168 AttrBuilder Attrs(GV->getAttributes());
170 GV->setAttributes(AttributeSet::get(Context,Attrs));
172 llvm_unreachable("invalid object with forward attribute group reference");
176 // If there are entries in ForwardRefBlockAddresses at this point, the
177 // function was never defined.
178 if (!ForwardRefBlockAddresses.empty())
179 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
180 "expected function name in blockaddress");
182 for (const auto &NT : NumberedTypes)
183 if (NT.second.second.isValid())
184 return Error(NT.second.second,
185 "use of undefined type '%" + Twine(NT.first) + "'");
187 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
188 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
189 if (I->second.second.isValid())
190 return Error(I->second.second,
191 "use of undefined type named '" + I->getKey() + "'");
193 if (!ForwardRefComdats.empty())
194 return Error(ForwardRefComdats.begin()->second,
195 "use of undefined comdat '$" +
196 ForwardRefComdats.begin()->first + "'");
198 if (!ForwardRefVals.empty())
199 return Error(ForwardRefVals.begin()->second.second,
200 "use of undefined value '@" + ForwardRefVals.begin()->first +
203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
206 Twine(ForwardRefValIDs.begin()->first) + "'");
208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
211 Twine(ForwardRefMDNodes.begin()->first) + "'");
213 // Resolve metadata cycles.
214 for (auto &N : NumberedMetadata) {
215 if (N.second && !N.second->isResolved())
216 N.second->resolveCycles();
219 for (auto *Inst : InstsWithTBAATag) {
220 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
221 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
222 auto *UpgradedMD = UpgradeTBAANode(*MD);
223 if (MD != UpgradedMD)
224 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
227 // Look for intrinsic functions and CallInst that need to be upgraded
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
229 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
231 // Some types could be renamed during loading if several modules are
232 // loaded in the same LLVMContext (LTO scenario). In this case we should
233 // remangle intrinsics names as well.
234 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
235 Function *F = &*FI++;
236 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
237 F->replaceAllUsesWith(Remangled.getValue());
238 F->eraseFromParent();
242 if (UpgradeDebugInfo)
243 llvm::UpgradeDebugInfo(*M);
245 UpgradeModuleFlags(*M);
246 UpgradeSectionAttributes(*M);
250 // Initialize the slot mapping.
251 // Because by this point we've parsed and validated everything, we can "steal"
252 // the mapping from LLParser as it doesn't need it anymore.
253 Slots->GlobalValues = std::move(NumberedVals);
254 Slots->MetadataNodes = std::move(NumberedMetadata);
255 for (const auto &I : NamedTypes)
256 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
257 for (const auto &I : NumberedTypes)
258 Slots->Types.insert(std::make_pair(I.first, I.second.first));
263 /// Do final validity and sanity checks at the end of the index.
264 bool LLParser::ValidateEndOfIndex() {
268 if (!ForwardRefValueInfos.empty())
269 return Error(ForwardRefValueInfos.begin()->second.front().second,
270 "use of undefined summary '^" +
271 Twine(ForwardRefValueInfos.begin()->first) + "'");
273 if (!ForwardRefAliasees.empty())
274 return Error(ForwardRefAliasees.begin()->second.front().second,
275 "use of undefined summary '^" +
276 Twine(ForwardRefAliasees.begin()->first) + "'");
278 if (!ForwardRefTypeIds.empty())
279 return Error(ForwardRefTypeIds.begin()->second.front().second,
280 "use of undefined type id summary '^" +
281 Twine(ForwardRefTypeIds.begin()->first) + "'");
286 //===----------------------------------------------------------------------===//
287 // Top-Level Entities
288 //===----------------------------------------------------------------------===//
290 bool LLParser::ParseTopLevelEntities() {
291 // If there is no Module, then parse just the summary index entries.
294 switch (Lex.getKind()) {
297 case lltok::SummaryID:
298 if (ParseSummaryEntry())
301 case lltok::kw_source_filename:
302 if (ParseSourceFileName())
306 // Skip everything else
312 switch (Lex.getKind()) {
313 default: return TokError("expected top-level entity");
314 case lltok::Eof: return false;
315 case lltok::kw_declare: if (ParseDeclare()) return true; break;
316 case lltok::kw_define: if (ParseDefine()) return true; break;
317 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
318 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
319 case lltok::kw_source_filename:
320 if (ParseSourceFileName())
323 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
324 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
325 case lltok::LocalVar: if (ParseNamedType()) return true; break;
326 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
327 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
328 case lltok::ComdatVar: if (parseComdat()) return true; break;
329 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
330 case lltok::SummaryID:
331 if (ParseSummaryEntry())
334 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
335 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
336 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
337 case lltok::kw_uselistorder_bb:
338 if (ParseUseListOrderBB())
346 /// ::= 'module' 'asm' STRINGCONSTANT
347 bool LLParser::ParseModuleAsm() {
348 assert(Lex.getKind() == lltok::kw_module);
352 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
353 ParseStringConstant(AsmStr)) return true;
355 M->appendModuleInlineAsm(AsmStr);
360 /// ::= 'target' 'triple' '=' STRINGCONSTANT
361 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
362 bool LLParser::ParseTargetDefinition() {
363 assert(Lex.getKind() == lltok::kw_target);
366 default: return TokError("unknown target property");
367 case lltok::kw_triple:
369 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
370 ParseStringConstant(Str))
372 M->setTargetTriple(Str);
374 case lltok::kw_datalayout:
376 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
377 ParseStringConstant(Str))
379 if (DataLayoutStr.empty())
380 M->setDataLayout(Str);
386 /// ::= 'source_filename' '=' STRINGCONSTANT
387 bool LLParser::ParseSourceFileName() {
388 assert(Lex.getKind() == lltok::kw_source_filename);
390 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
391 ParseStringConstant(SourceFileName))
394 M->setSourceFileName(SourceFileName);
399 /// ::= 'deplibs' '=' '[' ']'
400 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
401 /// FIXME: Remove in 4.0. Currently parse, but ignore.
402 bool LLParser::ParseDepLibs() {
403 assert(Lex.getKind() == lltok::kw_deplibs);
405 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
406 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
409 if (EatIfPresent(lltok::rsquare))
414 if (ParseStringConstant(Str)) return true;
415 } while (EatIfPresent(lltok::comma));
417 return ParseToken(lltok::rsquare, "expected ']' at end of list");
420 /// ParseUnnamedType:
421 /// ::= LocalVarID '=' 'type' type
422 bool LLParser::ParseUnnamedType() {
423 LocTy TypeLoc = Lex.getLoc();
424 unsigned TypeID = Lex.getUIntVal();
425 Lex.Lex(); // eat LocalVarID;
427 if (ParseToken(lltok::equal, "expected '=' after name") ||
428 ParseToken(lltok::kw_type, "expected 'type' after '='"))
431 Type *Result = nullptr;
432 if (ParseStructDefinition(TypeLoc, "",
433 NumberedTypes[TypeID], Result)) return true;
435 if (!isa<StructType>(Result)) {
436 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
438 return Error(TypeLoc, "non-struct types may not be recursive");
439 Entry.first = Result;
440 Entry.second = SMLoc();
447 /// ::= LocalVar '=' 'type' type
448 bool LLParser::ParseNamedType() {
449 std::string Name = Lex.getStrVal();
450 LocTy NameLoc = Lex.getLoc();
451 Lex.Lex(); // eat LocalVar.
453 if (ParseToken(lltok::equal, "expected '=' after name") ||
454 ParseToken(lltok::kw_type, "expected 'type' after name"))
457 Type *Result = nullptr;
458 if (ParseStructDefinition(NameLoc, Name,
459 NamedTypes[Name], Result)) return true;
461 if (!isa<StructType>(Result)) {
462 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
464 return Error(NameLoc, "non-struct types may not be recursive");
465 Entry.first = Result;
466 Entry.second = SMLoc();
473 /// ::= 'declare' FunctionHeader
474 bool LLParser::ParseDeclare() {
475 assert(Lex.getKind() == lltok::kw_declare);
478 std::vector<std::pair<unsigned, MDNode *>> MDs;
479 while (Lex.getKind() == lltok::MetadataVar) {
482 if (ParseMetadataAttachment(MDK, N))
484 MDs.push_back({MDK, N});
488 if (ParseFunctionHeader(F, false))
491 F->addMetadata(MD.first, *MD.second);
496 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
497 bool LLParser::ParseDefine() {
498 assert(Lex.getKind() == lltok::kw_define);
502 return ParseFunctionHeader(F, true) ||
503 ParseOptionalFunctionMetadata(*F) ||
504 ParseFunctionBody(*F);
510 bool LLParser::ParseGlobalType(bool &IsConstant) {
511 if (Lex.getKind() == lltok::kw_constant)
513 else if (Lex.getKind() == lltok::kw_global)
517 return TokError("expected 'global' or 'constant'");
523 bool LLParser::ParseOptionalUnnamedAddr(
524 GlobalVariable::UnnamedAddr &UnnamedAddr) {
525 if (EatIfPresent(lltok::kw_unnamed_addr))
526 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
527 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
528 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
530 UnnamedAddr = GlobalValue::UnnamedAddr::None;
534 /// ParseUnnamedGlobal:
535 /// OptionalVisibility (ALIAS | IFUNC) ...
536 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
537 /// OptionalDLLStorageClass
538 /// ... -> global variable
539 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
540 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
541 /// OptionalDLLStorageClass
542 /// ... -> global variable
543 bool LLParser::ParseUnnamedGlobal() {
544 unsigned VarID = NumberedVals.size();
546 LocTy NameLoc = Lex.getLoc();
548 // Handle the GlobalID form.
549 if (Lex.getKind() == lltok::GlobalID) {
550 if (Lex.getUIntVal() != VarID)
551 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
553 Lex.Lex(); // eat GlobalID;
555 if (ParseToken(lltok::equal, "expected '=' after name"))
560 unsigned Linkage, Visibility, DLLStorageClass;
562 GlobalVariable::ThreadLocalMode TLM;
563 GlobalVariable::UnnamedAddr UnnamedAddr;
564 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
566 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
569 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
570 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
571 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
573 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
574 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
577 /// ParseNamedGlobal:
578 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
579 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
580 /// OptionalVisibility OptionalDLLStorageClass
581 /// ... -> global variable
582 bool LLParser::ParseNamedGlobal() {
583 assert(Lex.getKind() == lltok::GlobalVar);
584 LocTy NameLoc = Lex.getLoc();
585 std::string Name = Lex.getStrVal();
589 unsigned Linkage, Visibility, DLLStorageClass;
591 GlobalVariable::ThreadLocalMode TLM;
592 GlobalVariable::UnnamedAddr UnnamedAddr;
593 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
594 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
596 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
599 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
600 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
601 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
603 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
604 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
607 bool LLParser::parseComdat() {
608 assert(Lex.getKind() == lltok::ComdatVar);
609 std::string Name = Lex.getStrVal();
610 LocTy NameLoc = Lex.getLoc();
613 if (ParseToken(lltok::equal, "expected '=' here"))
616 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
617 return TokError("expected comdat type");
619 Comdat::SelectionKind SK;
620 switch (Lex.getKind()) {
622 return TokError("unknown selection kind");
626 case lltok::kw_exactmatch:
627 SK = Comdat::ExactMatch;
629 case lltok::kw_largest:
630 SK = Comdat::Largest;
632 case lltok::kw_noduplicates:
633 SK = Comdat::NoDuplicates;
635 case lltok::kw_samesize:
636 SK = Comdat::SameSize;
641 // See if the comdat was forward referenced, if so, use the comdat.
642 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
643 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
644 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
645 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
648 if (I != ComdatSymTab.end())
651 C = M->getOrInsertComdat(Name);
652 C->setSelectionKind(SK);
658 // ::= '!' STRINGCONSTANT
659 bool LLParser::ParseMDString(MDString *&Result) {
661 if (ParseStringConstant(Str)) return true;
662 Result = MDString::get(Context, Str);
667 // ::= '!' MDNodeNumber
668 bool LLParser::ParseMDNodeID(MDNode *&Result) {
669 // !{ ..., !42, ... }
670 LocTy IDLoc = Lex.getLoc();
672 if (ParseUInt32(MID))
675 // If not a forward reference, just return it now.
676 if (NumberedMetadata.count(MID)) {
677 Result = NumberedMetadata[MID];
681 // Otherwise, create MDNode forward reference.
682 auto &FwdRef = ForwardRefMDNodes[MID];
683 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
685 Result = FwdRef.first.get();
686 NumberedMetadata[MID].reset(Result);
690 /// ParseNamedMetadata:
691 /// !foo = !{ !1, !2 }
692 bool LLParser::ParseNamedMetadata() {
693 assert(Lex.getKind() == lltok::MetadataVar);
694 std::string Name = Lex.getStrVal();
697 if (ParseToken(lltok::equal, "expected '=' here") ||
698 ParseToken(lltok::exclaim, "Expected '!' here") ||
699 ParseToken(lltok::lbrace, "Expected '{' here"))
702 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
703 if (Lex.getKind() != lltok::rbrace)
706 // Parse DIExpressions inline as a special case. They are still MDNodes,
707 // so they can still appear in named metadata. Remove this logic if they
708 // become plain Metadata.
709 if (Lex.getKind() == lltok::MetadataVar &&
710 Lex.getStrVal() == "DIExpression") {
711 if (ParseDIExpression(N, /*IsDistinct=*/false))
713 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
718 } while (EatIfPresent(lltok::comma));
720 return ParseToken(lltok::rbrace, "expected end of metadata node");
723 /// ParseStandaloneMetadata:
725 bool LLParser::ParseStandaloneMetadata() {
726 assert(Lex.getKind() == lltok::exclaim);
728 unsigned MetadataID = 0;
731 if (ParseUInt32(MetadataID) ||
732 ParseToken(lltok::equal, "expected '=' here"))
735 // Detect common error, from old metadata syntax.
736 if (Lex.getKind() == lltok::Type)
737 return TokError("unexpected type in metadata definition");
739 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
740 if (Lex.getKind() == lltok::MetadataVar) {
741 if (ParseSpecializedMDNode(Init, IsDistinct))
743 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
744 ParseMDTuple(Init, IsDistinct))
747 // See if this was forward referenced, if so, handle it.
748 auto FI = ForwardRefMDNodes.find(MetadataID);
749 if (FI != ForwardRefMDNodes.end()) {
750 FI->second.first->replaceAllUsesWith(Init);
751 ForwardRefMDNodes.erase(FI);
753 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
755 if (NumberedMetadata.count(MetadataID))
756 return TokError("Metadata id is already used");
757 NumberedMetadata[MetadataID].reset(Init);
763 // Skips a single module summary entry.
764 bool LLParser::SkipModuleSummaryEntry() {
765 // Each module summary entry consists of a tag for the entry
766 // type, followed by a colon, then the fields surrounded by nested sets of
767 // parentheses. The "tag:" looks like a Label. Once parsing support is
768 // in place we will look for the tokens corresponding to the expected tags.
769 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
770 Lex.getKind() != lltok::kw_typeid)
772 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
774 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
775 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
777 // Now walk through the parenthesized entry, until the number of open
778 // parentheses goes back down to 0 (the first '(' was parsed above).
779 unsigned NumOpenParen = 1;
781 switch (Lex.getKind()) {
789 return TokError("found end of file while parsing summary entry");
791 // Skip everything in between parentheses.
795 } while (NumOpenParen > 0);
800 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
801 bool LLParser::ParseSummaryEntry() {
802 assert(Lex.getKind() == lltok::SummaryID);
803 unsigned SummaryID = Lex.getUIntVal();
805 // For summary entries, colons should be treated as distinct tokens,
806 // not an indication of the end of a label token.
807 Lex.setIgnoreColonInIdentifiers(true);
810 if (ParseToken(lltok::equal, "expected '=' here"))
813 // If we don't have an index object, skip the summary entry.
815 return SkipModuleSummaryEntry();
817 switch (Lex.getKind()) {
819 return ParseGVEntry(SummaryID);
820 case lltok::kw_module:
821 return ParseModuleEntry(SummaryID);
822 case lltok::kw_typeid:
823 return ParseTypeIdEntry(SummaryID);
826 return Error(Lex.getLoc(), "unexpected summary kind");
828 Lex.setIgnoreColonInIdentifiers(false);
832 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
833 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
834 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
837 // If there was an explicit dso_local, update GV. In the absence of an explicit
838 // dso_local we keep the default value.
839 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
841 GV.setDSOLocal(true);
844 /// parseIndirectSymbol:
845 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
846 /// OptionalVisibility OptionalDLLStorageClass
847 /// OptionalThreadLocal OptionalUnnamedAddr
848 // 'alias|ifunc' IndirectSymbol
853 /// Everything through OptionalUnnamedAddr has already been parsed.
855 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
856 unsigned L, unsigned Visibility,
857 unsigned DLLStorageClass, bool DSOLocal,
858 GlobalVariable::ThreadLocalMode TLM,
859 GlobalVariable::UnnamedAddr UnnamedAddr) {
861 if (Lex.getKind() == lltok::kw_alias)
863 else if (Lex.getKind() == lltok::kw_ifunc)
866 llvm_unreachable("Not an alias or ifunc!");
869 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
871 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
872 return Error(NameLoc, "invalid linkage type for alias");
874 if (!isValidVisibilityForLinkage(Visibility, L))
875 return Error(NameLoc,
876 "symbol with local linkage must have default visibility");
879 LocTy ExplicitTypeLoc = Lex.getLoc();
881 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
885 LocTy AliaseeLoc = Lex.getLoc();
886 if (Lex.getKind() != lltok::kw_bitcast &&
887 Lex.getKind() != lltok::kw_getelementptr &&
888 Lex.getKind() != lltok::kw_addrspacecast &&
889 Lex.getKind() != lltok::kw_inttoptr) {
890 if (ParseGlobalTypeAndValue(Aliasee))
893 // The bitcast dest type is not present, it is implied by the dest type.
897 if (ID.Kind != ValID::t_Constant)
898 return Error(AliaseeLoc, "invalid aliasee");
899 Aliasee = ID.ConstantVal;
902 Type *AliaseeType = Aliasee->getType();
903 auto *PTy = dyn_cast<PointerType>(AliaseeType);
905 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
906 unsigned AddrSpace = PTy->getAddressSpace();
908 if (IsAlias && Ty != PTy->getElementType())
911 "explicit pointee type doesn't match operand's pointee type");
913 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
916 "explicit pointee type should be a function type");
918 GlobalValue *GVal = nullptr;
920 // See if the alias was forward referenced, if so, prepare to replace the
921 // forward reference.
923 GVal = M->getNamedValue(Name);
925 if (!ForwardRefVals.erase(Name))
926 return Error(NameLoc, "redefinition of global '@" + Name + "'");
929 auto I = ForwardRefValIDs.find(NumberedVals.size());
930 if (I != ForwardRefValIDs.end()) {
931 GVal = I->second.first;
932 ForwardRefValIDs.erase(I);
936 // Okay, create the alias but do not insert it into the module yet.
937 std::unique_ptr<GlobalIndirectSymbol> GA;
939 GA.reset(GlobalAlias::create(Ty, AddrSpace,
940 (GlobalValue::LinkageTypes)Linkage, Name,
941 Aliasee, /*Parent*/ nullptr));
943 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
944 (GlobalValue::LinkageTypes)Linkage, Name,
945 Aliasee, /*Parent*/ nullptr));
946 GA->setThreadLocalMode(TLM);
947 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
948 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
949 GA->setUnnamedAddr(UnnamedAddr);
950 maybeSetDSOLocal(DSOLocal, *GA);
953 NumberedVals.push_back(GA.get());
956 // Verify that types agree.
957 if (GVal->getType() != GA->getType())
960 "forward reference and definition of alias have different types");
962 // If they agree, just RAUW the old value with the alias and remove the
964 GVal->replaceAllUsesWith(GA.get());
965 GVal->eraseFromParent();
968 // Insert into the module, we know its name won't collide now.
970 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
972 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
973 assert(GA->getName() == Name && "Should not be a name conflict!");
975 // The module owns this now
982 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
983 /// OptionalVisibility OptionalDLLStorageClass
984 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
985 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
986 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
987 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
988 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
989 /// Const OptionalAttrs
991 /// Everything up to and including OptionalUnnamedAddr has been parsed
994 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
995 unsigned Linkage, bool HasLinkage,
996 unsigned Visibility, unsigned DLLStorageClass,
997 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
998 GlobalVariable::UnnamedAddr UnnamedAddr) {
999 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1000 return Error(NameLoc,
1001 "symbol with local linkage must have default visibility");
1004 bool IsConstant, IsExternallyInitialized;
1005 LocTy IsExternallyInitializedLoc;
1009 if (ParseOptionalAddrSpace(AddrSpace) ||
1010 ParseOptionalToken(lltok::kw_externally_initialized,
1011 IsExternallyInitialized,
1012 &IsExternallyInitializedLoc) ||
1013 ParseGlobalType(IsConstant) ||
1014 ParseType(Ty, TyLoc))
1017 // If the linkage is specified and is external, then no initializer is
1019 Constant *Init = nullptr;
1021 !GlobalValue::isValidDeclarationLinkage(
1022 (GlobalValue::LinkageTypes)Linkage)) {
1023 if (ParseGlobalValue(Ty, Init))
1027 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1028 return Error(TyLoc, "invalid type for global variable");
1030 GlobalValue *GVal = nullptr;
1032 // See if the global was forward referenced, if so, use the global.
1033 if (!Name.empty()) {
1034 GVal = M->getNamedValue(Name);
1036 if (!ForwardRefVals.erase(Name))
1037 return Error(NameLoc, "redefinition of global '@" + Name + "'");
1040 auto I = ForwardRefValIDs.find(NumberedVals.size());
1041 if (I != ForwardRefValIDs.end()) {
1042 GVal = I->second.first;
1043 ForwardRefValIDs.erase(I);
1049 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1050 Name, nullptr, GlobalVariable::NotThreadLocal,
1053 if (GVal->getValueType() != Ty)
1055 "forward reference and definition of global have different types");
1057 GV = cast<GlobalVariable>(GVal);
1059 // Move the forward-reference to the correct spot in the module.
1060 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1064 NumberedVals.push_back(GV);
1066 // Set the parsed properties on the global.
1068 GV->setInitializer(Init);
1069 GV->setConstant(IsConstant);
1070 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1071 maybeSetDSOLocal(DSOLocal, *GV);
1072 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1073 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1074 GV->setExternallyInitialized(IsExternallyInitialized);
1075 GV->setThreadLocalMode(TLM);
1076 GV->setUnnamedAddr(UnnamedAddr);
1078 // Parse attributes on the global.
1079 while (Lex.getKind() == lltok::comma) {
1082 if (Lex.getKind() == lltok::kw_section) {
1084 GV->setSection(Lex.getStrVal());
1085 if (ParseToken(lltok::StringConstant, "expected global section string"))
1087 } else if (Lex.getKind() == lltok::kw_align) {
1089 if (ParseOptionalAlignment(Alignment)) return true;
1090 GV->setAlignment(Alignment);
1091 } else if (Lex.getKind() == lltok::MetadataVar) {
1092 if (ParseGlobalObjectMetadataAttachment(*GV))
1096 if (parseOptionalComdat(Name, C))
1101 return TokError("unknown global variable property!");
1107 std::vector<unsigned> FwdRefAttrGrps;
1108 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1110 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1111 GV->setAttributes(AttributeSet::get(Context, Attrs));
1112 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1118 /// ParseUnnamedAttrGrp
1119 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1120 bool LLParser::ParseUnnamedAttrGrp() {
1121 assert(Lex.getKind() == lltok::kw_attributes);
1122 LocTy AttrGrpLoc = Lex.getLoc();
1125 if (Lex.getKind() != lltok::AttrGrpID)
1126 return TokError("expected attribute group id");
1128 unsigned VarID = Lex.getUIntVal();
1129 std::vector<unsigned> unused;
1133 if (ParseToken(lltok::equal, "expected '=' here") ||
1134 ParseToken(lltok::lbrace, "expected '{' here") ||
1135 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1137 ParseToken(lltok::rbrace, "expected end of attribute group"))
1140 if (!NumberedAttrBuilders[VarID].hasAttributes())
1141 return Error(AttrGrpLoc, "attribute group has no attributes");
1146 /// ParseFnAttributeValuePairs
1147 /// ::= <attr> | <attr> '=' <value>
1148 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1149 std::vector<unsigned> &FwdRefAttrGrps,
1150 bool inAttrGrp, LocTy &BuiltinLoc) {
1151 bool HaveError = false;
1156 lltok::Kind Token = Lex.getKind();
1157 if (Token == lltok::kw_builtin)
1158 BuiltinLoc = Lex.getLoc();
1161 if (!inAttrGrp) return HaveError;
1162 return Error(Lex.getLoc(), "unterminated attribute group");
1167 case lltok::AttrGrpID: {
1168 // Allow a function to reference an attribute group:
1170 // define void @foo() #1 { ... }
1174 "cannot have an attribute group reference in an attribute group");
1176 unsigned AttrGrpNum = Lex.getUIntVal();
1177 if (inAttrGrp) break;
1179 // Save the reference to the attribute group. We'll fill it in later.
1180 FwdRefAttrGrps.push_back(AttrGrpNum);
1183 // Target-dependent attributes:
1184 case lltok::StringConstant: {
1185 if (ParseStringAttribute(B))
1190 // Target-independent attributes:
1191 case lltok::kw_align: {
1192 // As a hack, we allow function alignment to be initially parsed as an
1193 // attribute on a function declaration/definition or added to an attribute
1194 // group and later moved to the alignment field.
1198 if (ParseToken(lltok::equal, "expected '=' here") ||
1199 ParseUInt32(Alignment))
1202 if (ParseOptionalAlignment(Alignment))
1205 B.addAlignmentAttr(Alignment);
1208 case lltok::kw_alignstack: {
1212 if (ParseToken(lltok::equal, "expected '=' here") ||
1213 ParseUInt32(Alignment))
1216 if (ParseOptionalStackAlignment(Alignment))
1219 B.addStackAlignmentAttr(Alignment);
1222 case lltok::kw_allocsize: {
1223 unsigned ElemSizeArg;
1224 Optional<unsigned> NumElemsArg;
1225 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1226 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1228 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1231 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1232 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1233 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1234 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1235 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1236 case lltok::kw_inaccessiblememonly:
1237 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1238 case lltok::kw_inaccessiblemem_or_argmemonly:
1239 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1240 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1241 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1242 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1243 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1244 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1245 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1246 case lltok::kw_noimplicitfloat:
1247 B.addAttribute(Attribute::NoImplicitFloat); break;
1248 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1249 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1250 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1251 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1252 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1253 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1254 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1255 case lltok::kw_optforfuzzing:
1256 B.addAttribute(Attribute::OptForFuzzing); break;
1257 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1258 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1259 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1260 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1261 case lltok::kw_returns_twice:
1262 B.addAttribute(Attribute::ReturnsTwice); break;
1263 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1264 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1265 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1266 case lltok::kw_sspstrong:
1267 B.addAttribute(Attribute::StackProtectStrong); break;
1268 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1269 case lltok::kw_shadowcallstack:
1270 B.addAttribute(Attribute::ShadowCallStack); break;
1271 case lltok::kw_sanitize_address:
1272 B.addAttribute(Attribute::SanitizeAddress); break;
1273 case lltok::kw_sanitize_hwaddress:
1274 B.addAttribute(Attribute::SanitizeHWAddress); break;
1275 case lltok::kw_sanitize_thread:
1276 B.addAttribute(Attribute::SanitizeThread); break;
1277 case lltok::kw_sanitize_memory:
1278 B.addAttribute(Attribute::SanitizeMemory); break;
1279 case lltok::kw_speculative_load_hardening:
1280 B.addAttribute(Attribute::SpeculativeLoadHardening);
1282 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1283 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1284 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1287 case lltok::kw_inreg:
1288 case lltok::kw_signext:
1289 case lltok::kw_zeroext:
1292 "invalid use of attribute on a function");
1294 case lltok::kw_byval:
1295 case lltok::kw_dereferenceable:
1296 case lltok::kw_dereferenceable_or_null:
1297 case lltok::kw_inalloca:
1298 case lltok::kw_nest:
1299 case lltok::kw_noalias:
1300 case lltok::kw_nocapture:
1301 case lltok::kw_nonnull:
1302 case lltok::kw_returned:
1303 case lltok::kw_sret:
1304 case lltok::kw_swifterror:
1305 case lltok::kw_swiftself:
1308 "invalid use of parameter-only attribute on a function");
1316 //===----------------------------------------------------------------------===//
1317 // GlobalValue Reference/Resolution Routines.
1318 //===----------------------------------------------------------------------===//
1320 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1321 const std::string &Name) {
1322 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1323 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1324 PTy->getAddressSpace(), Name, M);
1326 return new GlobalVariable(*M, PTy->getElementType(), false,
1327 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1328 nullptr, GlobalVariable::NotThreadLocal,
1329 PTy->getAddressSpace());
1332 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1333 Value *Val, bool IsCall) {
1334 if (Val->getType() == Ty)
1336 // For calls we also accept variables in the program address space.
1337 Type *SuggestedTy = Ty;
1338 if (IsCall && isa<PointerType>(Ty)) {
1339 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1340 M->getDataLayout().getProgramAddressSpace());
1341 SuggestedTy = TyInProgAS;
1342 if (Val->getType() == TyInProgAS)
1345 if (Ty->isLabelTy())
1346 Error(Loc, "'" + Name + "' is not a basic block");
1348 Error(Loc, "'" + Name + "' defined with type '" +
1349 getTypeString(Val->getType()) + "' but expected '" +
1350 getTypeString(SuggestedTy) + "'");
1354 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1355 /// forward reference record if needed. This can return null if the value
1356 /// exists but does not have the right type.
1357 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1358 LocTy Loc, bool IsCall) {
1359 PointerType *PTy = dyn_cast<PointerType>(Ty);
1361 Error(Loc, "global variable reference must have pointer type");
1365 // Look this name up in the normal function symbol table.
1367 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1369 // If this is a forward reference for the value, see if we already created a
1370 // forward ref record.
1372 auto I = ForwardRefVals.find(Name);
1373 if (I != ForwardRefVals.end())
1374 Val = I->second.first;
1377 // If we have the value in the symbol table or fwd-ref table, return it.
1379 return cast_or_null<GlobalValue>(
1380 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1382 // Otherwise, create a new forward reference for this value and remember it.
1383 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1384 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1388 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1390 PointerType *PTy = dyn_cast<PointerType>(Ty);
1392 Error(Loc, "global variable reference must have pointer type");
1396 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1398 // If this is a forward reference for the value, see if we already created a
1399 // forward ref record.
1401 auto I = ForwardRefValIDs.find(ID);
1402 if (I != ForwardRefValIDs.end())
1403 Val = I->second.first;
1406 // If we have the value in the symbol table or fwd-ref table, return it.
1408 return cast_or_null<GlobalValue>(
1409 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1411 // Otherwise, create a new forward reference for this value and remember it.
1412 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1413 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1417 //===----------------------------------------------------------------------===//
1418 // Comdat Reference/Resolution Routines.
1419 //===----------------------------------------------------------------------===//
1421 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1422 // Look this name up in the comdat symbol table.
1423 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1424 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1425 if (I != ComdatSymTab.end())
1428 // Otherwise, create a new forward reference for this value and remember it.
1429 Comdat *C = M->getOrInsertComdat(Name);
1430 ForwardRefComdats[Name] = Loc;
1434 //===----------------------------------------------------------------------===//
1436 //===----------------------------------------------------------------------===//
1438 /// ParseToken - If the current token has the specified kind, eat it and return
1439 /// success. Otherwise, emit the specified error and return failure.
1440 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1441 if (Lex.getKind() != T)
1442 return TokError(ErrMsg);
1447 /// ParseStringConstant
1448 /// ::= StringConstant
1449 bool LLParser::ParseStringConstant(std::string &Result) {
1450 if (Lex.getKind() != lltok::StringConstant)
1451 return TokError("expected string constant");
1452 Result = Lex.getStrVal();
1459 bool LLParser::ParseUInt32(uint32_t &Val) {
1460 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1461 return TokError("expected integer");
1462 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1463 if (Val64 != unsigned(Val64))
1464 return TokError("expected 32-bit integer (too large)");
1472 bool LLParser::ParseUInt64(uint64_t &Val) {
1473 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1474 return TokError("expected integer");
1475 Val = Lex.getAPSIntVal().getLimitedValue();
1481 /// := 'localdynamic'
1482 /// := 'initialexec'
1484 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1485 switch (Lex.getKind()) {
1487 return TokError("expected localdynamic, initialexec or localexec");
1488 case lltok::kw_localdynamic:
1489 TLM = GlobalVariable::LocalDynamicTLSModel;
1491 case lltok::kw_initialexec:
1492 TLM = GlobalVariable::InitialExecTLSModel;
1494 case lltok::kw_localexec:
1495 TLM = GlobalVariable::LocalExecTLSModel;
1503 /// ParseOptionalThreadLocal
1505 /// := 'thread_local'
1506 /// := 'thread_local' '(' tlsmodel ')'
1507 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1508 TLM = GlobalVariable::NotThreadLocal;
1509 if (!EatIfPresent(lltok::kw_thread_local))
1512 TLM = GlobalVariable::GeneralDynamicTLSModel;
1513 if (Lex.getKind() == lltok::lparen) {
1515 return ParseTLSModel(TLM) ||
1516 ParseToken(lltok::rparen, "expected ')' after thread local model");
1521 /// ParseOptionalAddrSpace
1523 /// := 'addrspace' '(' uint32 ')'
1524 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1525 AddrSpace = DefaultAS;
1526 if (!EatIfPresent(lltok::kw_addrspace))
1528 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1529 ParseUInt32(AddrSpace) ||
1530 ParseToken(lltok::rparen, "expected ')' in address space");
1533 /// ParseStringAttribute
1534 /// := StringConstant
1535 /// := StringConstant '=' StringConstant
1536 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1537 std::string Attr = Lex.getStrVal();
1540 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1542 B.addAttribute(Attr, Val);
1546 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1547 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1548 bool HaveError = false;
1553 lltok::Kind Token = Lex.getKind();
1555 default: // End of attributes.
1557 case lltok::StringConstant: {
1558 if (ParseStringAttribute(B))
1562 case lltok::kw_align: {
1564 if (ParseOptionalAlignment(Alignment))
1566 B.addAlignmentAttr(Alignment);
1569 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1570 case lltok::kw_dereferenceable: {
1572 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1574 B.addDereferenceableAttr(Bytes);
1577 case lltok::kw_dereferenceable_or_null: {
1579 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1581 B.addDereferenceableOrNullAttr(Bytes);
1584 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1585 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1586 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1587 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1588 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1589 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1590 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1591 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1592 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1593 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1594 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1595 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1596 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1597 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1598 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1600 case lltok::kw_alignstack:
1601 case lltok::kw_alwaysinline:
1602 case lltok::kw_argmemonly:
1603 case lltok::kw_builtin:
1604 case lltok::kw_inlinehint:
1605 case lltok::kw_jumptable:
1606 case lltok::kw_minsize:
1607 case lltok::kw_naked:
1608 case lltok::kw_nobuiltin:
1609 case lltok::kw_noduplicate:
1610 case lltok::kw_noimplicitfloat:
1611 case lltok::kw_noinline:
1612 case lltok::kw_nonlazybind:
1613 case lltok::kw_noredzone:
1614 case lltok::kw_noreturn:
1615 case lltok::kw_nocf_check:
1616 case lltok::kw_nounwind:
1617 case lltok::kw_optforfuzzing:
1618 case lltok::kw_optnone:
1619 case lltok::kw_optsize:
1620 case lltok::kw_returns_twice:
1621 case lltok::kw_sanitize_address:
1622 case lltok::kw_sanitize_hwaddress:
1623 case lltok::kw_sanitize_memory:
1624 case lltok::kw_sanitize_thread:
1625 case lltok::kw_speculative_load_hardening:
1627 case lltok::kw_sspreq:
1628 case lltok::kw_sspstrong:
1629 case lltok::kw_safestack:
1630 case lltok::kw_shadowcallstack:
1631 case lltok::kw_strictfp:
1632 case lltok::kw_uwtable:
1633 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1641 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1642 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1643 bool HaveError = false;
1648 lltok::Kind Token = Lex.getKind();
1650 default: // End of attributes.
1652 case lltok::StringConstant: {
1653 if (ParseStringAttribute(B))
1657 case lltok::kw_dereferenceable: {
1659 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1661 B.addDereferenceableAttr(Bytes);
1664 case lltok::kw_dereferenceable_or_null: {
1666 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1668 B.addDereferenceableOrNullAttr(Bytes);
1671 case lltok::kw_align: {
1673 if (ParseOptionalAlignment(Alignment))
1675 B.addAlignmentAttr(Alignment);
1678 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1679 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1680 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1681 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1682 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1685 case lltok::kw_byval:
1686 case lltok::kw_inalloca:
1687 case lltok::kw_nest:
1688 case lltok::kw_nocapture:
1689 case lltok::kw_returned:
1690 case lltok::kw_sret:
1691 case lltok::kw_swifterror:
1692 case lltok::kw_swiftself:
1693 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1696 case lltok::kw_alignstack:
1697 case lltok::kw_alwaysinline:
1698 case lltok::kw_argmemonly:
1699 case lltok::kw_builtin:
1700 case lltok::kw_cold:
1701 case lltok::kw_inlinehint:
1702 case lltok::kw_jumptable:
1703 case lltok::kw_minsize:
1704 case lltok::kw_naked:
1705 case lltok::kw_nobuiltin:
1706 case lltok::kw_noduplicate:
1707 case lltok::kw_noimplicitfloat:
1708 case lltok::kw_noinline:
1709 case lltok::kw_nonlazybind:
1710 case lltok::kw_noredzone:
1711 case lltok::kw_noreturn:
1712 case lltok::kw_nocf_check:
1713 case lltok::kw_nounwind:
1714 case lltok::kw_optforfuzzing:
1715 case lltok::kw_optnone:
1716 case lltok::kw_optsize:
1717 case lltok::kw_returns_twice:
1718 case lltok::kw_sanitize_address:
1719 case lltok::kw_sanitize_hwaddress:
1720 case lltok::kw_sanitize_memory:
1721 case lltok::kw_sanitize_thread:
1722 case lltok::kw_speculative_load_hardening:
1724 case lltok::kw_sspreq:
1725 case lltok::kw_sspstrong:
1726 case lltok::kw_safestack:
1727 case lltok::kw_shadowcallstack:
1728 case lltok::kw_strictfp:
1729 case lltok::kw_uwtable:
1730 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1733 case lltok::kw_readnone:
1734 case lltok::kw_readonly:
1735 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1742 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1747 return GlobalValue::ExternalLinkage;
1748 case lltok::kw_private:
1749 return GlobalValue::PrivateLinkage;
1750 case lltok::kw_internal:
1751 return GlobalValue::InternalLinkage;
1752 case lltok::kw_weak:
1753 return GlobalValue::WeakAnyLinkage;
1754 case lltok::kw_weak_odr:
1755 return GlobalValue::WeakODRLinkage;
1756 case lltok::kw_linkonce:
1757 return GlobalValue::LinkOnceAnyLinkage;
1758 case lltok::kw_linkonce_odr:
1759 return GlobalValue::LinkOnceODRLinkage;
1760 case lltok::kw_available_externally:
1761 return GlobalValue::AvailableExternallyLinkage;
1762 case lltok::kw_appending:
1763 return GlobalValue::AppendingLinkage;
1764 case lltok::kw_common:
1765 return GlobalValue::CommonLinkage;
1766 case lltok::kw_extern_weak:
1767 return GlobalValue::ExternalWeakLinkage;
1768 case lltok::kw_external:
1769 return GlobalValue::ExternalLinkage;
1773 /// ParseOptionalLinkage
1780 /// ::= 'linkonce_odr'
1781 /// ::= 'available_externally'
1784 /// ::= 'extern_weak'
1786 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1787 unsigned &Visibility,
1788 unsigned &DLLStorageClass,
1790 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1793 ParseOptionalDSOLocal(DSOLocal);
1794 ParseOptionalVisibility(Visibility);
1795 ParseOptionalDLLStorageClass(DLLStorageClass);
1797 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1798 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1804 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1805 switch (Lex.getKind()) {
1809 case lltok::kw_dso_local:
1813 case lltok::kw_dso_preemptable:
1820 /// ParseOptionalVisibility
1826 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1827 switch (Lex.getKind()) {
1829 Res = GlobalValue::DefaultVisibility;
1831 case lltok::kw_default:
1832 Res = GlobalValue::DefaultVisibility;
1834 case lltok::kw_hidden:
1835 Res = GlobalValue::HiddenVisibility;
1837 case lltok::kw_protected:
1838 Res = GlobalValue::ProtectedVisibility;
1844 /// ParseOptionalDLLStorageClass
1849 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1850 switch (Lex.getKind()) {
1852 Res = GlobalValue::DefaultStorageClass;
1854 case lltok::kw_dllimport:
1855 Res = GlobalValue::DLLImportStorageClass;
1857 case lltok::kw_dllexport:
1858 Res = GlobalValue::DLLExportStorageClass;
1864 /// ParseOptionalCallingConv
1868 /// ::= 'intel_ocl_bicc'
1870 /// ::= 'x86_stdcallcc'
1871 /// ::= 'x86_fastcallcc'
1872 /// ::= 'x86_thiscallcc'
1873 /// ::= 'x86_vectorcallcc'
1874 /// ::= 'arm_apcscc'
1875 /// ::= 'arm_aapcscc'
1876 /// ::= 'arm_aapcs_vfpcc'
1877 /// ::= 'aarch64_vector_pcs'
1878 /// ::= 'msp430_intrcc'
1879 /// ::= 'avr_intrcc'
1880 /// ::= 'avr_signalcc'
1881 /// ::= 'ptx_kernel'
1882 /// ::= 'ptx_device'
1884 /// ::= 'spir_kernel'
1885 /// ::= 'x86_64_sysvcc'
1887 /// ::= 'webkit_jscc'
1889 /// ::= 'preserve_mostcc'
1890 /// ::= 'preserve_allcc'
1893 /// ::= 'x86_intrcc'
1896 /// ::= 'cxx_fast_tlscc'
1904 /// ::= 'amdgpu_kernel'
1907 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1908 switch (Lex.getKind()) {
1909 default: CC = CallingConv::C; return false;
1910 case lltok::kw_ccc: CC = CallingConv::C; break;
1911 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1912 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1913 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1914 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1915 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1916 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1917 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1918 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1919 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1920 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1921 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1922 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1923 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1924 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1925 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1926 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1927 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1928 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1929 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1930 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1931 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1932 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1933 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1934 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1935 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1936 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1937 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1938 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1939 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1940 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1941 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1942 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1943 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1944 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1945 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1946 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1947 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1948 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1949 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1950 case lltok::kw_cc: {
1952 return ParseUInt32(CC);
1960 /// ParseMetadataAttachment
1962 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1963 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1965 std::string Name = Lex.getStrVal();
1966 Kind = M->getMDKindID(Name);
1969 return ParseMDNode(MD);
1972 /// ParseInstructionMetadata
1973 /// ::= !dbg !42 (',' !dbg !57)*
1974 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1976 if (Lex.getKind() != lltok::MetadataVar)
1977 return TokError("expected metadata after comma");
1981 if (ParseMetadataAttachment(MDK, N))
1984 Inst.setMetadata(MDK, N);
1985 if (MDK == LLVMContext::MD_tbaa)
1986 InstsWithTBAATag.push_back(&Inst);
1988 // If this is the end of the list, we're done.
1989 } while (EatIfPresent(lltok::comma));
1993 /// ParseGlobalObjectMetadataAttachment
1995 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1998 if (ParseMetadataAttachment(MDK, N))
2001 GO.addMetadata(MDK, *N);
2005 /// ParseOptionalFunctionMetadata
2007 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
2008 while (Lex.getKind() == lltok::MetadataVar)
2009 if (ParseGlobalObjectMetadataAttachment(F))
2014 /// ParseOptionalAlignment
2017 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2019 if (!EatIfPresent(lltok::kw_align))
2021 LocTy AlignLoc = Lex.getLoc();
2022 if (ParseUInt32(Alignment)) return true;
2023 if (!isPowerOf2_32(Alignment))
2024 return Error(AlignLoc, "alignment is not a power of two");
2025 if (Alignment > Value::MaximumAlignment)
2026 return Error(AlignLoc, "huge alignments are not supported yet");
2030 /// ParseOptionalDerefAttrBytes
2032 /// ::= AttrKind '(' 4 ')'
2034 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2035 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2037 assert((AttrKind == lltok::kw_dereferenceable ||
2038 AttrKind == lltok::kw_dereferenceable_or_null) &&
2042 if (!EatIfPresent(AttrKind))
2044 LocTy ParenLoc = Lex.getLoc();
2045 if (!EatIfPresent(lltok::lparen))
2046 return Error(ParenLoc, "expected '('");
2047 LocTy DerefLoc = Lex.getLoc();
2048 if (ParseUInt64(Bytes)) return true;
2049 ParenLoc = Lex.getLoc();
2050 if (!EatIfPresent(lltok::rparen))
2051 return Error(ParenLoc, "expected ')'");
2053 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2057 /// ParseOptionalCommaAlign
2061 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2063 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2064 bool &AteExtraComma) {
2065 AteExtraComma = false;
2066 while (EatIfPresent(lltok::comma)) {
2067 // Metadata at the end is an early exit.
2068 if (Lex.getKind() == lltok::MetadataVar) {
2069 AteExtraComma = true;
2073 if (Lex.getKind() != lltok::kw_align)
2074 return Error(Lex.getLoc(), "expected metadata or 'align'");
2076 if (ParseOptionalAlignment(Alignment)) return true;
2082 /// ParseOptionalCommaAddrSpace
2084 /// ::= ',' addrspace(1)
2086 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2088 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2090 bool &AteExtraComma) {
2091 AteExtraComma = false;
2092 while (EatIfPresent(lltok::comma)) {
2093 // Metadata at the end is an early exit.
2094 if (Lex.getKind() == lltok::MetadataVar) {
2095 AteExtraComma = true;
2100 if (Lex.getKind() != lltok::kw_addrspace)
2101 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2103 if (ParseOptionalAddrSpace(AddrSpace))
2110 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2111 Optional<unsigned> &HowManyArg) {
2114 auto StartParen = Lex.getLoc();
2115 if (!EatIfPresent(lltok::lparen))
2116 return Error(StartParen, "expected '('");
2118 if (ParseUInt32(BaseSizeArg))
2121 if (EatIfPresent(lltok::comma)) {
2122 auto HowManyAt = Lex.getLoc();
2124 if (ParseUInt32(HowMany))
2126 if (HowMany == BaseSizeArg)
2127 return Error(HowManyAt,
2128 "'allocsize' indices can't refer to the same parameter");
2129 HowManyArg = HowMany;
2133 auto EndParen = Lex.getLoc();
2134 if (!EatIfPresent(lltok::rparen))
2135 return Error(EndParen, "expected ')'");
2139 /// ParseScopeAndOrdering
2140 /// if isAtomic: ::= SyncScope? AtomicOrdering
2143 /// This sets Scope and Ordering to the parsed values.
2144 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
2145 AtomicOrdering &Ordering) {
2149 return ParseScope(SSID) || ParseOrdering(Ordering);
2153 /// ::= syncscope("singlethread" | "<target scope>")?
2155 /// This sets synchronization scope ID to the ID of the parsed value.
2156 bool LLParser::ParseScope(SyncScope::ID &SSID) {
2157 SSID = SyncScope::System;
2158 if (EatIfPresent(lltok::kw_syncscope)) {
2159 auto StartParenAt = Lex.getLoc();
2160 if (!EatIfPresent(lltok::lparen))
2161 return Error(StartParenAt, "Expected '(' in syncscope");
2164 auto SSNAt = Lex.getLoc();
2165 if (ParseStringConstant(SSN))
2166 return Error(SSNAt, "Expected synchronization scope name");
2168 auto EndParenAt = Lex.getLoc();
2169 if (!EatIfPresent(lltok::rparen))
2170 return Error(EndParenAt, "Expected ')' in syncscope");
2172 SSID = Context.getOrInsertSyncScopeID(SSN);
2179 /// ::= AtomicOrdering
2181 /// This sets Ordering to the parsed value.
2182 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2183 switch (Lex.getKind()) {
2184 default: return TokError("Expected ordering on atomic instruction");
2185 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2186 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2187 // Not specified yet:
2188 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2189 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2190 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2191 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2192 case lltok::kw_seq_cst:
2193 Ordering = AtomicOrdering::SequentiallyConsistent;
2200 /// ParseOptionalStackAlignment
2202 /// ::= 'alignstack' '(' 4 ')'
2203 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2205 if (!EatIfPresent(lltok::kw_alignstack))
2207 LocTy ParenLoc = Lex.getLoc();
2208 if (!EatIfPresent(lltok::lparen))
2209 return Error(ParenLoc, "expected '('");
2210 LocTy AlignLoc = Lex.getLoc();
2211 if (ParseUInt32(Alignment)) return true;
2212 ParenLoc = Lex.getLoc();
2213 if (!EatIfPresent(lltok::rparen))
2214 return Error(ParenLoc, "expected ')'");
2215 if (!isPowerOf2_32(Alignment))
2216 return Error(AlignLoc, "stack alignment is not a power of two");
2220 /// ParseIndexList - This parses the index list for an insert/extractvalue
2221 /// instruction. This sets AteExtraComma in the case where we eat an extra
2222 /// comma at the end of the line and find that it is followed by metadata.
2223 /// Clients that don't allow metadata can call the version of this function that
2224 /// only takes one argument.
2227 /// ::= (',' uint32)+
2229 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2230 bool &AteExtraComma) {
2231 AteExtraComma = false;
2233 if (Lex.getKind() != lltok::comma)
2234 return TokError("expected ',' as start of index list");
2236 while (EatIfPresent(lltok::comma)) {
2237 if (Lex.getKind() == lltok::MetadataVar) {
2238 if (Indices.empty()) return TokError("expected index");
2239 AteExtraComma = true;
2243 if (ParseUInt32(Idx)) return true;
2244 Indices.push_back(Idx);
2250 //===----------------------------------------------------------------------===//
2252 //===----------------------------------------------------------------------===//
2254 /// ParseType - Parse a type.
2255 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2256 SMLoc TypeLoc = Lex.getLoc();
2257 switch (Lex.getKind()) {
2259 return TokError(Msg);
2261 // Type ::= 'float' | 'void' (etc)
2262 Result = Lex.getTyVal();
2266 // Type ::= StructType
2267 if (ParseAnonStructType(Result, false))
2270 case lltok::lsquare:
2271 // Type ::= '[' ... ']'
2272 Lex.Lex(); // eat the lsquare.
2273 if (ParseArrayVectorType(Result, false))
2276 case lltok::less: // Either vector or packed struct.
2277 // Type ::= '<' ... '>'
2279 if (Lex.getKind() == lltok::lbrace) {
2280 if (ParseAnonStructType(Result, true) ||
2281 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2283 } else if (ParseArrayVectorType(Result, true))
2286 case lltok::LocalVar: {
2288 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2290 // If the type hasn't been defined yet, create a forward definition and
2291 // remember where that forward def'n was seen (in case it never is defined).
2293 Entry.first = StructType::create(Context, Lex.getStrVal());
2294 Entry.second = Lex.getLoc();
2296 Result = Entry.first;
2301 case lltok::LocalVarID: {
2303 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2305 // If the type hasn't been defined yet, create a forward definition and
2306 // remember where that forward def'n was seen (in case it never is defined).
2308 Entry.first = StructType::create(Context);
2309 Entry.second = Lex.getLoc();
2311 Result = Entry.first;
2317 // Parse the type suffixes.
2319 switch (Lex.getKind()) {
2322 if (!AllowVoid && Result->isVoidTy())
2323 return Error(TypeLoc, "void type only allowed for function results");
2326 // Type ::= Type '*'
2328 if (Result->isLabelTy())
2329 return TokError("basic block pointers are invalid");
2330 if (Result->isVoidTy())
2331 return TokError("pointers to void are invalid - use i8* instead");
2332 if (!PointerType::isValidElementType(Result))
2333 return TokError("pointer to this type is invalid");
2334 Result = PointerType::getUnqual(Result);
2338 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2339 case lltok::kw_addrspace: {
2340 if (Result->isLabelTy())
2341 return TokError("basic block pointers are invalid");
2342 if (Result->isVoidTy())
2343 return TokError("pointers to void are invalid; use i8* instead");
2344 if (!PointerType::isValidElementType(Result))
2345 return TokError("pointer to this type is invalid");
2347 if (ParseOptionalAddrSpace(AddrSpace) ||
2348 ParseToken(lltok::star, "expected '*' in address space"))
2351 Result = PointerType::get(Result, AddrSpace);
2355 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2357 if (ParseFunctionType(Result))
2364 /// ParseParameterList
2366 /// ::= '(' Arg (',' Arg)* ')'
2368 /// ::= Type OptionalAttributes Value OptionalAttributes
2369 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2370 PerFunctionState &PFS, bool IsMustTailCall,
2371 bool InVarArgsFunc) {
2372 if (ParseToken(lltok::lparen, "expected '(' in call"))
2375 while (Lex.getKind() != lltok::rparen) {
2376 // If this isn't the first argument, we need a comma.
2377 if (!ArgList.empty() &&
2378 ParseToken(lltok::comma, "expected ',' in argument list"))
2381 // Parse an ellipsis if this is a musttail call in a variadic function.
2382 if (Lex.getKind() == lltok::dotdotdot) {
2383 const char *Msg = "unexpected ellipsis in argument list for ";
2384 if (!IsMustTailCall)
2385 return TokError(Twine(Msg) + "non-musttail call");
2387 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2388 Lex.Lex(); // Lex the '...', it is purely for readability.
2389 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2392 // Parse the argument.
2394 Type *ArgTy = nullptr;
2395 AttrBuilder ArgAttrs;
2397 if (ParseType(ArgTy, ArgLoc))
2400 if (ArgTy->isMetadataTy()) {
2401 if (ParseMetadataAsValue(V, PFS))
2404 // Otherwise, handle normal operands.
2405 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2408 ArgList.push_back(ParamInfo(
2409 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2412 if (IsMustTailCall && InVarArgsFunc)
2413 return TokError("expected '...' at end of argument list for musttail call "
2414 "in varargs function");
2416 Lex.Lex(); // Lex the ')'.
2420 /// ParseOptionalOperandBundles
2422 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2425 /// ::= bundle-tag '(' ')'
2426 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2428 /// bundle-tag ::= String Constant
2429 bool LLParser::ParseOptionalOperandBundles(
2430 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2431 LocTy BeginLoc = Lex.getLoc();
2432 if (!EatIfPresent(lltok::lsquare))
2435 while (Lex.getKind() != lltok::rsquare) {
2436 // If this isn't the first operand bundle, we need a comma.
2437 if (!BundleList.empty() &&
2438 ParseToken(lltok::comma, "expected ',' in input list"))
2442 if (ParseStringConstant(Tag))
2445 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2448 std::vector<Value *> Inputs;
2449 while (Lex.getKind() != lltok::rparen) {
2450 // If this isn't the first input, we need a comma.
2451 if (!Inputs.empty() &&
2452 ParseToken(lltok::comma, "expected ',' in input list"))
2456 Value *Input = nullptr;
2457 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2459 Inputs.push_back(Input);
2462 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2464 Lex.Lex(); // Lex the ')'.
2467 if (BundleList.empty())
2468 return Error(BeginLoc, "operand bundle set must not be empty");
2470 Lex.Lex(); // Lex the ']'.
2474 /// ParseArgumentList - Parse the argument list for a function type or function
2476 /// ::= '(' ArgTypeListI ')'
2480 /// ::= ArgTypeList ',' '...'
2481 /// ::= ArgType (',' ArgType)*
2483 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2486 assert(Lex.getKind() == lltok::lparen);
2487 Lex.Lex(); // eat the (.
2489 if (Lex.getKind() == lltok::rparen) {
2491 } else if (Lex.getKind() == lltok::dotdotdot) {
2495 LocTy TypeLoc = Lex.getLoc();
2496 Type *ArgTy = nullptr;
2500 if (ParseType(ArgTy) ||
2501 ParseOptionalParamAttrs(Attrs)) return true;
2503 if (ArgTy->isVoidTy())
2504 return Error(TypeLoc, "argument can not have void type");
2506 if (Lex.getKind() == lltok::LocalVar) {
2507 Name = Lex.getStrVal();
2511 if (!FunctionType::isValidArgumentType(ArgTy))
2512 return Error(TypeLoc, "invalid type for function argument");
2514 ArgList.emplace_back(TypeLoc, ArgTy,
2515 AttributeSet::get(ArgTy->getContext(), Attrs),
2518 while (EatIfPresent(lltok::comma)) {
2519 // Handle ... at end of arg list.
2520 if (EatIfPresent(lltok::dotdotdot)) {
2525 // Otherwise must be an argument type.
2526 TypeLoc = Lex.getLoc();
2527 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2529 if (ArgTy->isVoidTy())
2530 return Error(TypeLoc, "argument can not have void type");
2532 if (Lex.getKind() == lltok::LocalVar) {
2533 Name = Lex.getStrVal();
2539 if (!ArgTy->isFirstClassType())
2540 return Error(TypeLoc, "invalid type for function argument");
2542 ArgList.emplace_back(TypeLoc, ArgTy,
2543 AttributeSet::get(ArgTy->getContext(), Attrs),
2548 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2551 /// ParseFunctionType
2552 /// ::= Type ArgumentList OptionalAttrs
2553 bool LLParser::ParseFunctionType(Type *&Result) {
2554 assert(Lex.getKind() == lltok::lparen);
2556 if (!FunctionType::isValidReturnType(Result))
2557 return TokError("invalid function return type");
2559 SmallVector<ArgInfo, 8> ArgList;
2561 if (ParseArgumentList(ArgList, isVarArg))
2564 // Reject names on the arguments lists.
2565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2566 if (!ArgList[i].Name.empty())
2567 return Error(ArgList[i].Loc, "argument name invalid in function type");
2568 if (ArgList[i].Attrs.hasAttributes())
2569 return Error(ArgList[i].Loc,
2570 "argument attributes invalid in function type");
2573 SmallVector<Type*, 16> ArgListTy;
2574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2575 ArgListTy.push_back(ArgList[i].Ty);
2577 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2581 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2583 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2584 SmallVector<Type*, 8> Elts;
2585 if (ParseStructBody(Elts)) return true;
2587 Result = StructType::get(Context, Elts, Packed);
2591 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2592 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2593 std::pair<Type*, LocTy> &Entry,
2595 // If the type was already defined, diagnose the redefinition.
2596 if (Entry.first && !Entry.second.isValid())
2597 return Error(TypeLoc, "redefinition of type");
2599 // If we have opaque, just return without filling in the definition for the
2600 // struct. This counts as a definition as far as the .ll file goes.
2601 if (EatIfPresent(lltok::kw_opaque)) {
2602 // This type is being defined, so clear the location to indicate this.
2603 Entry.second = SMLoc();
2605 // If this type number has never been uttered, create it.
2607 Entry.first = StructType::create(Context, Name);
2608 ResultTy = Entry.first;
2612 // If the type starts with '<', then it is either a packed struct or a vector.
2613 bool isPacked = EatIfPresent(lltok::less);
2615 // If we don't have a struct, then we have a random type alias, which we
2616 // accept for compatibility with old files. These types are not allowed to be
2617 // forward referenced and not allowed to be recursive.
2618 if (Lex.getKind() != lltok::lbrace) {
2620 return Error(TypeLoc, "forward references to non-struct type");
2624 return ParseArrayVectorType(ResultTy, true);
2625 return ParseType(ResultTy);
2628 // This type is being defined, so clear the location to indicate this.
2629 Entry.second = SMLoc();
2631 // If this type number has never been uttered, create it.
2633 Entry.first = StructType::create(Context, Name);
2635 StructType *STy = cast<StructType>(Entry.first);
2637 SmallVector<Type*, 8> Body;
2638 if (ParseStructBody(Body) ||
2639 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2642 STy->setBody(Body, isPacked);
2647 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2650 /// ::= '{' Type (',' Type)* '}'
2651 /// ::= '<' '{' '}' '>'
2652 /// ::= '<' '{' Type (',' Type)* '}' '>'
2653 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2654 assert(Lex.getKind() == lltok::lbrace);
2655 Lex.Lex(); // Consume the '{'
2657 // Handle the empty struct.
2658 if (EatIfPresent(lltok::rbrace))
2661 LocTy EltTyLoc = Lex.getLoc();
2663 if (ParseType(Ty)) return true;
2666 if (!StructType::isValidElementType(Ty))
2667 return Error(EltTyLoc, "invalid element type for struct");
2669 while (EatIfPresent(lltok::comma)) {
2670 EltTyLoc = Lex.getLoc();
2671 if (ParseType(Ty)) return true;
2673 if (!StructType::isValidElementType(Ty))
2674 return Error(EltTyLoc, "invalid element type for struct");
2679 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2682 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2683 /// token has already been consumed.
2685 /// ::= '[' APSINTVAL 'x' Types ']'
2686 /// ::= '<' APSINTVAL 'x' Types '>'
2687 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2688 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2689 Lex.getAPSIntVal().getBitWidth() > 64)
2690 return TokError("expected number in address space");
2692 LocTy SizeLoc = Lex.getLoc();
2693 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2696 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2699 LocTy TypeLoc = Lex.getLoc();
2700 Type *EltTy = nullptr;
2701 if (ParseType(EltTy)) return true;
2703 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2704 "expected end of sequential type"))
2709 return Error(SizeLoc, "zero element vector is illegal");
2710 if ((unsigned)Size != Size)
2711 return Error(SizeLoc, "size too large for vector");
2712 if (!VectorType::isValidElementType(EltTy))
2713 return Error(TypeLoc, "invalid vector element type");
2714 Result = VectorType::get(EltTy, unsigned(Size));
2716 if (!ArrayType::isValidElementType(EltTy))
2717 return Error(TypeLoc, "invalid array element type");
2718 Result = ArrayType::get(EltTy, Size);
2723 //===----------------------------------------------------------------------===//
2724 // Function Semantic Analysis.
2725 //===----------------------------------------------------------------------===//
2727 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2729 : P(p), F(f), FunctionNumber(functionNumber) {
2731 // Insert unnamed arguments into the NumberedVals list.
2732 for (Argument &A : F.args())
2734 NumberedVals.push_back(&A);
2737 LLParser::PerFunctionState::~PerFunctionState() {
2738 // If there were any forward referenced non-basicblock values, delete them.
2740 for (const auto &P : ForwardRefVals) {
2741 if (isa<BasicBlock>(P.second.first))
2743 P.second.first->replaceAllUsesWith(
2744 UndefValue::get(P.second.first->getType()));
2745 P.second.first->deleteValue();
2748 for (const auto &P : ForwardRefValIDs) {
2749 if (isa<BasicBlock>(P.second.first))
2751 P.second.first->replaceAllUsesWith(
2752 UndefValue::get(P.second.first->getType()));
2753 P.second.first->deleteValue();
2757 bool LLParser::PerFunctionState::FinishFunction() {
2758 if (!ForwardRefVals.empty())
2759 return P.Error(ForwardRefVals.begin()->second.second,
2760 "use of undefined value '%" + ForwardRefVals.begin()->first +
2762 if (!ForwardRefValIDs.empty())
2763 return P.Error(ForwardRefValIDs.begin()->second.second,
2764 "use of undefined value '%" +
2765 Twine(ForwardRefValIDs.begin()->first) + "'");
2769 /// GetVal - Get a value with the specified name or ID, creating a
2770 /// forward reference record if needed. This can return null if the value
2771 /// exists but does not have the right type.
2772 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2773 LocTy Loc, bool IsCall) {
2774 // Look this name up in the normal function symbol table.
2775 Value *Val = F.getValueSymbolTable()->lookup(Name);
2777 // If this is a forward reference for the value, see if we already created a
2778 // forward ref record.
2780 auto I = ForwardRefVals.find(Name);
2781 if (I != ForwardRefVals.end())
2782 Val = I->second.first;
2785 // If we have the value in the symbol table or fwd-ref table, return it.
2787 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2789 // Don't make placeholders with invalid type.
2790 if (!Ty->isFirstClassType()) {
2791 P.Error(Loc, "invalid use of a non-first-class type");
2795 // Otherwise, create a new forward reference for this value and remember it.
2797 if (Ty->isLabelTy()) {
2798 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2800 FwdVal = new Argument(Ty, Name);
2803 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2807 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2809 // Look this name up in the normal function symbol table.
2810 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2812 // If this is a forward reference for the value, see if we already created a
2813 // forward ref record.
2815 auto I = ForwardRefValIDs.find(ID);
2816 if (I != ForwardRefValIDs.end())
2817 Val = I->second.first;
2820 // If we have the value in the symbol table or fwd-ref table, return it.
2822 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2824 if (!Ty->isFirstClassType()) {
2825 P.Error(Loc, "invalid use of a non-first-class type");
2829 // Otherwise, create a new forward reference for this value and remember it.
2831 if (Ty->isLabelTy()) {
2832 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2834 FwdVal = new Argument(Ty);
2837 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2841 /// SetInstName - After an instruction is parsed and inserted into its
2842 /// basic block, this installs its name.
2843 bool LLParser::PerFunctionState::SetInstName(int NameID,
2844 const std::string &NameStr,
2845 LocTy NameLoc, Instruction *Inst) {
2846 // If this instruction has void type, it cannot have a name or ID specified.
2847 if (Inst->getType()->isVoidTy()) {
2848 if (NameID != -1 || !NameStr.empty())
2849 return P.Error(NameLoc, "instructions returning void cannot have a name");
2853 // If this was a numbered instruction, verify that the instruction is the
2854 // expected value and resolve any forward references.
2855 if (NameStr.empty()) {
2856 // If neither a name nor an ID was specified, just use the next ID.
2858 NameID = NumberedVals.size();
2860 if (unsigned(NameID) != NumberedVals.size())
2861 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2862 Twine(NumberedVals.size()) + "'");
2864 auto FI = ForwardRefValIDs.find(NameID);
2865 if (FI != ForwardRefValIDs.end()) {
2866 Value *Sentinel = FI->second.first;
2867 if (Sentinel->getType() != Inst->getType())
2868 return P.Error(NameLoc, "instruction forward referenced with type '" +
2869 getTypeString(FI->second.first->getType()) + "'");
2871 Sentinel->replaceAllUsesWith(Inst);
2872 Sentinel->deleteValue();
2873 ForwardRefValIDs.erase(FI);
2876 NumberedVals.push_back(Inst);
2880 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2881 auto FI = ForwardRefVals.find(NameStr);
2882 if (FI != ForwardRefVals.end()) {
2883 Value *Sentinel = FI->second.first;
2884 if (Sentinel->getType() != Inst->getType())
2885 return P.Error(NameLoc, "instruction forward referenced with type '" +
2886 getTypeString(FI->second.first->getType()) + "'");
2888 Sentinel->replaceAllUsesWith(Inst);
2889 Sentinel->deleteValue();
2890 ForwardRefVals.erase(FI);
2893 // Set the name on the instruction.
2894 Inst->setName(NameStr);
2896 if (Inst->getName() != NameStr)
2897 return P.Error(NameLoc, "multiple definition of local value named '" +
2902 /// GetBB - Get a basic block with the specified name or ID, creating a
2903 /// forward reference record if needed.
2904 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2906 return dyn_cast_or_null<BasicBlock>(
2907 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2910 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2911 return dyn_cast_or_null<BasicBlock>(
2912 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2915 /// DefineBB - Define the specified basic block, which is either named or
2916 /// unnamed. If there is an error, this returns null otherwise it returns
2917 /// the block being defined.
2918 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2922 BB = GetBB(NumberedVals.size(), Loc);
2924 BB = GetBB(Name, Loc);
2925 if (!BB) return nullptr; // Already diagnosed error.
2927 // Move the block to the end of the function. Forward ref'd blocks are
2928 // inserted wherever they happen to be referenced.
2929 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2931 // Remove the block from forward ref sets.
2933 ForwardRefValIDs.erase(NumberedVals.size());
2934 NumberedVals.push_back(BB);
2936 // BB forward references are already in the function symbol table.
2937 ForwardRefVals.erase(Name);
2943 //===----------------------------------------------------------------------===//
2945 //===----------------------------------------------------------------------===//
2947 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2948 /// type implied. For example, if we parse "4" we don't know what integer type
2949 /// it has. The value will later be combined with its type and checked for
2950 /// sanity. PFS is used to convert function-local operands of metadata (since
2951 /// metadata operands are not just parsed here but also converted to values).
2952 /// PFS can be null when we are not parsing metadata values inside a function.
2953 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2954 ID.Loc = Lex.getLoc();
2955 switch (Lex.getKind()) {
2956 default: return TokError("expected value token");
2957 case lltok::GlobalID: // @42
2958 ID.UIntVal = Lex.getUIntVal();
2959 ID.Kind = ValID::t_GlobalID;
2961 case lltok::GlobalVar: // @foo
2962 ID.StrVal = Lex.getStrVal();
2963 ID.Kind = ValID::t_GlobalName;
2965 case lltok::LocalVarID: // %42
2966 ID.UIntVal = Lex.getUIntVal();
2967 ID.Kind = ValID::t_LocalID;
2969 case lltok::LocalVar: // %foo
2970 ID.StrVal = Lex.getStrVal();
2971 ID.Kind = ValID::t_LocalName;
2974 ID.APSIntVal = Lex.getAPSIntVal();
2975 ID.Kind = ValID::t_APSInt;
2977 case lltok::APFloat:
2978 ID.APFloatVal = Lex.getAPFloatVal();
2979 ID.Kind = ValID::t_APFloat;
2981 case lltok::kw_true:
2982 ID.ConstantVal = ConstantInt::getTrue(Context);
2983 ID.Kind = ValID::t_Constant;
2985 case lltok::kw_false:
2986 ID.ConstantVal = ConstantInt::getFalse(Context);
2987 ID.Kind = ValID::t_Constant;
2989 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2990 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2991 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2992 case lltok::kw_none: ID.Kind = ValID::t_None; break;
2994 case lltok::lbrace: {
2995 // ValID ::= '{' ConstVector '}'
2997 SmallVector<Constant*, 16> Elts;
2998 if (ParseGlobalValueVector(Elts) ||
2999 ParseToken(lltok::rbrace, "expected end of struct constant"))
3002 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3003 ID.UIntVal = Elts.size();
3004 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3005 Elts.size() * sizeof(Elts[0]));
3006 ID.Kind = ValID::t_ConstantStruct;
3010 // ValID ::= '<' ConstVector '>' --> Vector.
3011 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3013 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3015 SmallVector<Constant*, 16> Elts;
3016 LocTy FirstEltLoc = Lex.getLoc();
3017 if (ParseGlobalValueVector(Elts) ||
3019 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3020 ParseToken(lltok::greater, "expected end of constant"))
3023 if (isPackedStruct) {
3024 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3025 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3026 Elts.size() * sizeof(Elts[0]));
3027 ID.UIntVal = Elts.size();
3028 ID.Kind = ValID::t_PackedConstantStruct;
3033 return Error(ID.Loc, "constant vector must not be empty");
3035 if (!Elts[0]->getType()->isIntegerTy() &&
3036 !Elts[0]->getType()->isFloatingPointTy() &&
3037 !Elts[0]->getType()->isPointerTy())
3038 return Error(FirstEltLoc,
3039 "vector elements must have integer, pointer or floating point type");
3041 // Verify that all the vector elements have the same type.
3042 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3043 if (Elts[i]->getType() != Elts[0]->getType())
3044 return Error(FirstEltLoc,
3045 "vector element #" + Twine(i) +
3046 " is not of type '" + getTypeString(Elts[0]->getType()));
3048 ID.ConstantVal = ConstantVector::get(Elts);
3049 ID.Kind = ValID::t_Constant;
3052 case lltok::lsquare: { // Array Constant
3054 SmallVector<Constant*, 16> Elts;
3055 LocTy FirstEltLoc = Lex.getLoc();
3056 if (ParseGlobalValueVector(Elts) ||
3057 ParseToken(lltok::rsquare, "expected end of array constant"))
3060 // Handle empty element.
3062 // Use undef instead of an array because it's inconvenient to determine
3063 // the element type at this point, there being no elements to examine.
3064 ID.Kind = ValID::t_EmptyArray;
3068 if (!Elts[0]->getType()->isFirstClassType())
3069 return Error(FirstEltLoc, "invalid array element type: " +
3070 getTypeString(Elts[0]->getType()));
3072 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3074 // Verify all elements are correct type!
3075 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3076 if (Elts[i]->getType() != Elts[0]->getType())
3077 return Error(FirstEltLoc,
3078 "array element #" + Twine(i) +
3079 " is not of type '" + getTypeString(Elts[0]->getType()));
3082 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3083 ID.Kind = ValID::t_Constant;
3086 case lltok::kw_c: // c "foo"
3088 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3090 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3091 ID.Kind = ValID::t_Constant;
3094 case lltok::kw_asm: {
3095 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3097 bool HasSideEffect, AlignStack, AsmDialect;
3099 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3100 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3101 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3102 ParseStringConstant(ID.StrVal) ||
3103 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
3104 ParseToken(lltok::StringConstant, "expected constraint string"))
3106 ID.StrVal2 = Lex.getStrVal();
3107 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3108 (unsigned(AsmDialect)<<2);
3109 ID.Kind = ValID::t_InlineAsm;
3113 case lltok::kw_blockaddress: {
3114 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3119 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3121 ParseToken(lltok::comma, "expected comma in block address expression")||
3122 ParseValID(Label) ||
3123 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3126 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3127 return Error(Fn.Loc, "expected function name in blockaddress");
3128 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3129 return Error(Label.Loc, "expected basic block name in blockaddress");
3131 // Try to find the function (but skip it if it's forward-referenced).
3132 GlobalValue *GV = nullptr;
3133 if (Fn.Kind == ValID::t_GlobalID) {
3134 if (Fn.UIntVal < NumberedVals.size())
3135 GV = NumberedVals[Fn.UIntVal];
3136 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3137 GV = M->getNamedValue(Fn.StrVal);
3139 Function *F = nullptr;
3141 // Confirm that it's actually a function with a definition.
3142 if (!isa<Function>(GV))
3143 return Error(Fn.Loc, "expected function name in blockaddress");
3144 F = cast<Function>(GV);
3145 if (F->isDeclaration())
3146 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3150 // Make a global variable as a placeholder for this reference.
3151 GlobalValue *&FwdRef =
3152 ForwardRefBlockAddresses.insert(std::make_pair(
3154 std::map<ValID, GlobalValue *>()))
3155 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3158 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3159 GlobalValue::InternalLinkage, nullptr, "");
3160 ID.ConstantVal = FwdRef;
3161 ID.Kind = ValID::t_Constant;
3165 // We found the function; now find the basic block. Don't use PFS, since we
3166 // might be inside a constant expression.
3168 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3169 if (Label.Kind == ValID::t_LocalID)
3170 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3172 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3174 return Error(Label.Loc, "referenced value is not a basic block");
3176 if (Label.Kind == ValID::t_LocalID)
3177 return Error(Label.Loc, "cannot take address of numeric label after "
3178 "the function is defined");
3179 BB = dyn_cast_or_null<BasicBlock>(
3180 F->getValueSymbolTable()->lookup(Label.StrVal));
3182 return Error(Label.Loc, "referenced value is not a basic block");
3185 ID.ConstantVal = BlockAddress::get(F, BB);
3186 ID.Kind = ValID::t_Constant;
3190 case lltok::kw_trunc:
3191 case lltok::kw_zext:
3192 case lltok::kw_sext:
3193 case lltok::kw_fptrunc:
3194 case lltok::kw_fpext:
3195 case lltok::kw_bitcast:
3196 case lltok::kw_addrspacecast:
3197 case lltok::kw_uitofp:
3198 case lltok::kw_sitofp:
3199 case lltok::kw_fptoui:
3200 case lltok::kw_fptosi:
3201 case lltok::kw_inttoptr:
3202 case lltok::kw_ptrtoint: {
3203 unsigned Opc = Lex.getUIntVal();
3204 Type *DestTy = nullptr;
3207 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3208 ParseGlobalTypeAndValue(SrcVal) ||
3209 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3210 ParseType(DestTy) ||
3211 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3213 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3214 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3215 getTypeString(SrcVal->getType()) + "' to '" +
3216 getTypeString(DestTy) + "'");
3217 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3219 ID.Kind = ValID::t_Constant;
3222 case lltok::kw_extractvalue: {
3225 SmallVector<unsigned, 4> Indices;
3226 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3227 ParseGlobalTypeAndValue(Val) ||
3228 ParseIndexList(Indices) ||
3229 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3232 if (!Val->getType()->isAggregateType())
3233 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3234 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3235 return Error(ID.Loc, "invalid indices for extractvalue");
3236 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3237 ID.Kind = ValID::t_Constant;
3240 case lltok::kw_insertvalue: {
3242 Constant *Val0, *Val1;
3243 SmallVector<unsigned, 4> Indices;
3244 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3245 ParseGlobalTypeAndValue(Val0) ||
3246 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3247 ParseGlobalTypeAndValue(Val1) ||
3248 ParseIndexList(Indices) ||
3249 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3251 if (!Val0->getType()->isAggregateType())
3252 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3254 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3256 return Error(ID.Loc, "invalid indices for insertvalue");
3257 if (IndexedType != Val1->getType())
3258 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3259 getTypeString(Val1->getType()) +
3260 "' instead of '" + getTypeString(IndexedType) +
3262 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3263 ID.Kind = ValID::t_Constant;
3266 case lltok::kw_icmp:
3267 case lltok::kw_fcmp: {
3268 unsigned PredVal, Opc = Lex.getUIntVal();
3269 Constant *Val0, *Val1;
3271 if (ParseCmpPredicate(PredVal, Opc) ||
3272 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3273 ParseGlobalTypeAndValue(Val0) ||
3274 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3275 ParseGlobalTypeAndValue(Val1) ||
3276 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3279 if (Val0->getType() != Val1->getType())
3280 return Error(ID.Loc, "compare operands must have the same type");
3282 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3284 if (Opc == Instruction::FCmp) {
3285 if (!Val0->getType()->isFPOrFPVectorTy())
3286 return Error(ID.Loc, "fcmp requires floating point operands");
3287 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3289 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3290 if (!Val0->getType()->isIntOrIntVectorTy() &&
3291 !Val0->getType()->isPtrOrPtrVectorTy())
3292 return Error(ID.Loc, "icmp requires pointer or integer operands");
3293 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3295 ID.Kind = ValID::t_Constant;
3300 case lltok::kw_fneg: {
3301 unsigned Opc = Lex.getUIntVal();
3304 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3305 ParseGlobalTypeAndValue(Val) ||
3306 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3309 // Check that the type is valid for the operator.
3311 case Instruction::FNeg:
3312 if (!Val->getType()->isFPOrFPVectorTy())
3313 return Error(ID.Loc, "constexpr requires fp operands");
3315 default: llvm_unreachable("Unknown unary operator!");
3318 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3320 ID.Kind = ValID::t_Constant;
3323 // Binary Operators.
3325 case lltok::kw_fadd:
3327 case lltok::kw_fsub:
3329 case lltok::kw_fmul:
3330 case lltok::kw_udiv:
3331 case lltok::kw_sdiv:
3332 case lltok::kw_fdiv:
3333 case lltok::kw_urem:
3334 case lltok::kw_srem:
3335 case lltok::kw_frem:
3337 case lltok::kw_lshr:
3338 case lltok::kw_ashr: {
3342 unsigned Opc = Lex.getUIntVal();
3343 Constant *Val0, *Val1;
3345 LocTy ModifierLoc = Lex.getLoc();
3346 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3347 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3348 if (EatIfPresent(lltok::kw_nuw))
3350 if (EatIfPresent(lltok::kw_nsw)) {
3352 if (EatIfPresent(lltok::kw_nuw))
3355 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3356 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3357 if (EatIfPresent(lltok::kw_exact))
3360 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3361 ParseGlobalTypeAndValue(Val0) ||
3362 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3363 ParseGlobalTypeAndValue(Val1) ||
3364 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3366 if (Val0->getType() != Val1->getType())
3367 return Error(ID.Loc, "operands of constexpr must have same type");
3368 if (!Val0->getType()->isIntOrIntVectorTy()) {
3370 return Error(ModifierLoc, "nuw only applies to integer operations");
3372 return Error(ModifierLoc, "nsw only applies to integer operations");
3374 // Check that the type is valid for the operator.
3376 case Instruction::Add:
3377 case Instruction::Sub:
3378 case Instruction::Mul:
3379 case Instruction::UDiv:
3380 case Instruction::SDiv:
3381 case Instruction::URem:
3382 case Instruction::SRem:
3383 case Instruction::Shl:
3384 case Instruction::AShr:
3385 case Instruction::LShr:
3386 if (!Val0->getType()->isIntOrIntVectorTy())
3387 return Error(ID.Loc, "constexpr requires integer operands");
3389 case Instruction::FAdd:
3390 case Instruction::FSub:
3391 case Instruction::FMul:
3392 case Instruction::FDiv:
3393 case Instruction::FRem:
3394 if (!Val0->getType()->isFPOrFPVectorTy())
3395 return Error(ID.Loc, "constexpr requires fp operands");
3397 default: llvm_unreachable("Unknown binary operator!");
3400 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3401 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3402 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3403 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3405 ID.Kind = ValID::t_Constant;
3409 // Logical Operations
3412 case lltok::kw_xor: {
3413 unsigned Opc = Lex.getUIntVal();
3414 Constant *Val0, *Val1;
3416 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3417 ParseGlobalTypeAndValue(Val0) ||
3418 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3419 ParseGlobalTypeAndValue(Val1) ||
3420 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3422 if (Val0->getType() != Val1->getType())
3423 return Error(ID.Loc, "operands of constexpr must have same type");
3424 if (!Val0->getType()->isIntOrIntVectorTy())
3425 return Error(ID.Loc,
3426 "constexpr requires integer or integer vector operands");
3427 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3428 ID.Kind = ValID::t_Constant;
3432 case lltok::kw_getelementptr:
3433 case lltok::kw_shufflevector:
3434 case lltok::kw_insertelement:
3435 case lltok::kw_extractelement:
3436 case lltok::kw_select: {
3437 unsigned Opc = Lex.getUIntVal();
3438 SmallVector<Constant*, 16> Elts;
3439 bool InBounds = false;
3443 if (Opc == Instruction::GetElementPtr)
3444 InBounds = EatIfPresent(lltok::kw_inbounds);
3446 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3449 LocTy ExplicitTypeLoc = Lex.getLoc();
3450 if (Opc == Instruction::GetElementPtr) {
3451 if (ParseType(Ty) ||
3452 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3456 Optional<unsigned> InRangeOp;
3457 if (ParseGlobalValueVector(
3458 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3459 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3462 if (Opc == Instruction::GetElementPtr) {
3463 if (Elts.size() == 0 ||
3464 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3465 return Error(ID.Loc, "base of getelementptr must be a pointer");
3467 Type *BaseType = Elts[0]->getType();
3468 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3469 if (Ty != BasePointerType->getElementType())
3472 "explicit pointee type doesn't match operand's pointee type");
3475 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3477 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3478 for (Constant *Val : Indices) {
3479 Type *ValTy = Val->getType();
3480 if (!ValTy->isIntOrIntVectorTy())
3481 return Error(ID.Loc, "getelementptr index must be an integer");
3482 if (ValTy->isVectorTy()) {
3483 unsigned ValNumEl = ValTy->getVectorNumElements();
3484 if (GEPWidth && (ValNumEl != GEPWidth))
3487 "getelementptr vector index has a wrong number of elements");
3488 // GEPWidth may have been unknown because the base is a scalar,
3489 // but it is known now.
3490 GEPWidth = ValNumEl;
3494 SmallPtrSet<Type*, 4> Visited;
3495 if (!Indices.empty() && !Ty->isSized(&Visited))
3496 return Error(ID.Loc, "base element of getelementptr must be sized");
3498 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3499 return Error(ID.Loc, "invalid getelementptr indices");
3502 if (*InRangeOp == 0)
3503 return Error(ID.Loc,
3504 "inrange keyword may not appear on pointer operand");
3508 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3509 InBounds, InRangeOp);
3510 } else if (Opc == Instruction::Select) {
3511 if (Elts.size() != 3)
3512 return Error(ID.Loc, "expected three operands to select");
3513 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3515 return Error(ID.Loc, Reason);
3516 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3517 } else if (Opc == Instruction::ShuffleVector) {
3518 if (Elts.size() != 3)
3519 return Error(ID.Loc, "expected three operands to shufflevector");
3520 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3521 return Error(ID.Loc, "invalid operands to shufflevector");
3523 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3524 } else if (Opc == Instruction::ExtractElement) {
3525 if (Elts.size() != 2)
3526 return Error(ID.Loc, "expected two operands to extractelement");
3527 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3528 return Error(ID.Loc, "invalid extractelement operands");
3529 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3531 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3532 if (Elts.size() != 3)
3533 return Error(ID.Loc, "expected three operands to insertelement");
3534 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3535 return Error(ID.Loc, "invalid insertelement operands");
3537 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3540 ID.Kind = ValID::t_Constant;
3549 /// ParseGlobalValue - Parse a global value with the specified type.
3550 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3554 bool Parsed = ParseValID(ID) ||
3555 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3556 if (V && !(C = dyn_cast<Constant>(V)))
3557 return Error(ID.Loc, "global values must be constants");
3561 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3563 return ParseType(Ty) ||
3564 ParseGlobalValue(Ty, V);
3567 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3570 LocTy KwLoc = Lex.getLoc();
3571 if (!EatIfPresent(lltok::kw_comdat))
3574 if (EatIfPresent(lltok::lparen)) {
3575 if (Lex.getKind() != lltok::ComdatVar)
3576 return TokError("expected comdat variable");
3577 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3579 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3582 if (GlobalName.empty())
3583 return TokError("comdat cannot be unnamed");
3584 C = getComdat(GlobalName, KwLoc);
3590 /// ParseGlobalValueVector
3592 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3593 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3594 Optional<unsigned> *InRangeOp) {
3596 if (Lex.getKind() == lltok::rbrace ||
3597 Lex.getKind() == lltok::rsquare ||
3598 Lex.getKind() == lltok::greater ||
3599 Lex.getKind() == lltok::rparen)
3603 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3604 *InRangeOp = Elts.size();
3607 if (ParseGlobalTypeAndValue(C)) return true;
3609 } while (EatIfPresent(lltok::comma));
3614 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3615 SmallVector<Metadata *, 16> Elts;
3616 if (ParseMDNodeVector(Elts))
3619 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3626 /// ::= !DILocation(...)
3627 bool LLParser::ParseMDNode(MDNode *&N) {
3628 if (Lex.getKind() == lltok::MetadataVar)
3629 return ParseSpecializedMDNode(N);
3631 return ParseToken(lltok::exclaim, "expected '!' here") ||
3635 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3637 if (Lex.getKind() == lltok::lbrace)
3638 return ParseMDTuple(N);
3641 return ParseMDNodeID(N);
3646 /// Structure to represent an optional metadata field.
3647 template <class FieldTy> struct MDFieldImpl {
3648 typedef MDFieldImpl ImplTy;
3652 void assign(FieldTy Val) {
3654 this->Val = std::move(Val);
3657 explicit MDFieldImpl(FieldTy Default)
3658 : Val(std::move(Default)), Seen(false) {}
3661 /// Structure to represent an optional metadata field that
3662 /// can be of either type (A or B) and encapsulates the
3663 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3664 /// to reimplement the specifics for representing each Field.
3665 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3666 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3677 void assign(FieldTypeA A) {
3679 this->A = std::move(A);
3683 void assign(FieldTypeB B) {
3685 this->B = std::move(B);
3689 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3690 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3691 WhatIs(IsInvalid) {}
3694 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3697 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3698 : ImplTy(Default), Max(Max) {}
3701 struct LineField : public MDUnsignedField {
3702 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3705 struct ColumnField : public MDUnsignedField {
3706 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3709 struct DwarfTagField : public MDUnsignedField {
3710 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3711 DwarfTagField(dwarf::Tag DefaultTag)
3712 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3715 struct DwarfMacinfoTypeField : public MDUnsignedField {
3716 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3717 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3718 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3721 struct DwarfAttEncodingField : public MDUnsignedField {
3722 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3725 struct DwarfVirtualityField : public MDUnsignedField {
3726 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3729 struct DwarfLangField : public MDUnsignedField {
3730 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3733 struct DwarfCCField : public MDUnsignedField {
3734 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3737 struct EmissionKindField : public MDUnsignedField {
3738 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3741 struct NameTableKindField : public MDUnsignedField {
3742 NameTableKindField()
3745 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3748 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3749 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3752 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3753 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3756 struct MDSignedField : public MDFieldImpl<int64_t> {
3760 MDSignedField(int64_t Default = 0)
3761 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3762 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3763 : ImplTy(Default), Min(Min), Max(Max) {}
3766 struct MDBoolField : public MDFieldImpl<bool> {
3767 MDBoolField(bool Default = false) : ImplTy(Default) {}
3770 struct MDField : public MDFieldImpl<Metadata *> {
3773 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3776 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3777 MDConstant() : ImplTy(nullptr) {}
3780 struct MDStringField : public MDFieldImpl<MDString *> {
3782 MDStringField(bool AllowEmpty = true)
3783 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3786 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3787 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3790 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3791 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3794 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3795 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3796 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3798 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3799 bool AllowNull = true)
3800 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3802 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3803 bool isMDField() const { return WhatIs == IsTypeB; }
3804 int64_t getMDSignedValue() const {
3805 assert(isMDSignedField() && "Wrong field type");
3808 Metadata *getMDFieldValue() const {
3809 assert(isMDField() && "Wrong field type");
3814 struct MDSignedOrUnsignedField
3815 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3816 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3818 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3819 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3820 int64_t getMDSignedValue() const {
3821 assert(isMDSignedField() && "Wrong field type");
3824 uint64_t getMDUnsignedValue() const {
3825 assert(isMDUnsignedField() && "Wrong field type");
3830 } // end anonymous namespace
3835 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3836 MDUnsignedField &Result) {
3837 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3838 return TokError("expected unsigned integer");
3840 auto &U = Lex.getAPSIntVal();
3841 if (U.ugt(Result.Max))
3842 return TokError("value for '" + Name + "' too large, limit is " +
3844 Result.assign(U.getZExtValue());
3845 assert(Result.Val <= Result.Max && "Expected value in range");
3851 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3852 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3855 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3856 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3860 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3861 if (Lex.getKind() == lltok::APSInt)
3862 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3864 if (Lex.getKind() != lltok::DwarfTag)
3865 return TokError("expected DWARF tag");
3867 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3868 if (Tag == dwarf::DW_TAG_invalid)
3869 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3870 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3878 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3879 DwarfMacinfoTypeField &Result) {
3880 if (Lex.getKind() == lltok::APSInt)
3881 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3883 if (Lex.getKind() != lltok::DwarfMacinfo)
3884 return TokError("expected DWARF macinfo type");
3886 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3887 if (Macinfo == dwarf::DW_MACINFO_invalid)
3889 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3890 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3892 Result.assign(Macinfo);
3898 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3899 DwarfVirtualityField &Result) {
3900 if (Lex.getKind() == lltok::APSInt)
3901 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3903 if (Lex.getKind() != lltok::DwarfVirtuality)
3904 return TokError("expected DWARF virtuality code");
3906 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3907 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3908 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3909 Lex.getStrVal() + "'");
3910 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3911 Result.assign(Virtuality);
3917 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3918 if (Lex.getKind() == lltok::APSInt)
3919 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3921 if (Lex.getKind() != lltok::DwarfLang)
3922 return TokError("expected DWARF language");
3924 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3926 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3928 assert(Lang <= Result.Max && "Expected valid DWARF language");
3929 Result.assign(Lang);
3935 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3936 if (Lex.getKind() == lltok::APSInt)
3937 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3939 if (Lex.getKind() != lltok::DwarfCC)
3940 return TokError("expected DWARF calling convention");
3942 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3944 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3946 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3953 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3954 if (Lex.getKind() == lltok::APSInt)
3955 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3957 if (Lex.getKind() != lltok::EmissionKind)
3958 return TokError("expected emission kind");
3960 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3962 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3964 assert(*Kind <= Result.Max && "Expected valid emission kind");
3965 Result.assign(*Kind);
3971 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3972 NameTableKindField &Result) {
3973 if (Lex.getKind() == lltok::APSInt)
3974 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3976 if (Lex.getKind() != lltok::NameTableKind)
3977 return TokError("expected nameTable kind");
3979 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3981 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3983 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3984 Result.assign((unsigned)*Kind);
3990 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3991 DwarfAttEncodingField &Result) {
3992 if (Lex.getKind() == lltok::APSInt)
3993 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3995 if (Lex.getKind() != lltok::DwarfAttEncoding)
3996 return TokError("expected DWARF type attribute encoding");
3998 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4000 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4001 Lex.getStrVal() + "'");
4002 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4003 Result.assign(Encoding);
4010 /// ::= DIFlagVector
4011 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4013 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4015 // Parser for a single flag.
4016 auto parseFlag = [&](DINode::DIFlags &Val) {
4017 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4018 uint32_t TempVal = static_cast<uint32_t>(Val);
4019 bool Res = ParseUInt32(TempVal);
4020 Val = static_cast<DINode::DIFlags>(TempVal);
4024 if (Lex.getKind() != lltok::DIFlag)
4025 return TokError("expected debug info flag");
4027 Val = DINode::getFlag(Lex.getStrVal());
4029 return TokError(Twine("invalid debug info flag flag '") +
4030 Lex.getStrVal() + "'");
4035 // Parse the flags and combine them together.
4036 DINode::DIFlags Combined = DINode::FlagZero;
4038 DINode::DIFlags Val;
4042 } while (EatIfPresent(lltok::bar));
4044 Result.assign(Combined);
4050 /// ::= DISPFlagVector
4051 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4053 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4055 // Parser for a single flag.
4056 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4057 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4058 uint32_t TempVal = static_cast<uint32_t>(Val);
4059 bool Res = ParseUInt32(TempVal);
4060 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4064 if (Lex.getKind() != lltok::DISPFlag)
4065 return TokError("expected debug info flag");
4067 Val = DISubprogram::getFlag(Lex.getStrVal());
4069 return TokError(Twine("invalid subprogram debug info flag '") +
4070 Lex.getStrVal() + "'");
4075 // Parse the flags and combine them together.
4076 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4078 DISubprogram::DISPFlags Val;
4082 } while (EatIfPresent(lltok::bar));
4084 Result.assign(Combined);
4089 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4090 MDSignedField &Result) {
4091 if (Lex.getKind() != lltok::APSInt)
4092 return TokError("expected signed integer");
4094 auto &S = Lex.getAPSIntVal();
4096 return TokError("value for '" + Name + "' too small, limit is " +
4099 return TokError("value for '" + Name + "' too large, limit is " +
4101 Result.assign(S.getExtValue());
4102 assert(Result.Val >= Result.Min && "Expected value in range");
4103 assert(Result.Val <= Result.Max && "Expected value in range");
4109 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4110 switch (Lex.getKind()) {
4112 return TokError("expected 'true' or 'false'");
4113 case lltok::kw_true:
4114 Result.assign(true);
4116 case lltok::kw_false:
4117 Result.assign(false);
4125 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4126 if (Lex.getKind() == lltok::kw_null) {
4127 if (!Result.AllowNull)
4128 return TokError("'" + Name + "' cannot be null");
4130 Result.assign(nullptr);
4135 if (ParseMetadata(MD, nullptr))
4143 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4144 MDSignedOrMDField &Result) {
4145 // Try to parse a signed int.
4146 if (Lex.getKind() == lltok::APSInt) {
4147 MDSignedField Res = Result.A;
4148 if (!ParseMDField(Loc, Name, Res)) {
4155 // Otherwise, try to parse as an MDField.
4156 MDField Res = Result.B;
4157 if (!ParseMDField(Loc, Name, Res)) {
4166 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4167 MDSignedOrUnsignedField &Result) {
4168 if (Lex.getKind() != lltok::APSInt)
4171 if (Lex.getAPSIntVal().isSigned()) {
4172 MDSignedField Res = Result.A;
4173 if (ParseMDField(Loc, Name, Res))
4179 MDUnsignedField Res = Result.B;
4180 if (ParseMDField(Loc, Name, Res))
4187 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4188 LocTy ValueLoc = Lex.getLoc();
4190 if (ParseStringConstant(S))
4193 if (!Result.AllowEmpty && S.empty())
4194 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4196 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4201 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4202 SmallVector<Metadata *, 4> MDs;
4203 if (ParseMDNodeVector(MDs))
4206 Result.assign(std::move(MDs));
4211 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4212 ChecksumKindField &Result) {
4213 Optional<DIFile::ChecksumKind> CSKind =
4214 DIFile::getChecksumKind(Lex.getStrVal());
4216 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4218 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4220 Result.assign(*CSKind);
4225 } // end namespace llvm
4227 template <class ParserTy>
4228 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
4230 if (Lex.getKind() != lltok::LabelStr)
4231 return TokError("expected field label here");
4235 } while (EatIfPresent(lltok::comma));
4240 template <class ParserTy>
4241 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4242 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4245 if (ParseToken(lltok::lparen, "expected '(' here"))
4247 if (Lex.getKind() != lltok::rparen)
4248 if (ParseMDFieldsImplBody(parseField))
4251 ClosingLoc = Lex.getLoc();
4252 return ParseToken(lltok::rparen, "expected ')' here");
4255 template <class FieldTy>
4256 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4258 return TokError("field '" + Name + "' cannot be specified more than once");
4260 LocTy Loc = Lex.getLoc();
4262 return ParseMDField(Loc, Name, Result);
4265 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4266 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4268 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4269 if (Lex.getStrVal() == #CLASS) \
4270 return Parse##CLASS(N, IsDistinct);
4271 #include "llvm/IR/Metadata.def"
4273 return TokError("expected metadata type");
4276 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4277 #define NOP_FIELD(NAME, TYPE, INIT)
4278 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4280 return Error(ClosingLoc, "missing required field '" #NAME "'");
4281 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4282 if (Lex.getStrVal() == #NAME) \
4283 return ParseMDField(#NAME, NAME);
4284 #define PARSE_MD_FIELDS() \
4285 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4288 if (ParseMDFieldsImpl([&]() -> bool { \
4289 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4290 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4293 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4295 #define GET_OR_DISTINCT(CLASS, ARGS) \
4296 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4298 /// ParseDILocationFields:
4299 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4300 /// isImplicitCode: true)
4301 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4302 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4303 OPTIONAL(line, LineField, ); \
4304 OPTIONAL(column, ColumnField, ); \
4305 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4306 OPTIONAL(inlinedAt, MDField, ); \
4307 OPTIONAL(isImplicitCode, MDBoolField, (false));
4309 #undef VISIT_MD_FIELDS
4312 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4313 inlinedAt.Val, isImplicitCode.Val));
4317 /// ParseGenericDINode:
4318 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4319 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4320 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4321 REQUIRED(tag, DwarfTagField, ); \
4322 OPTIONAL(header, MDStringField, ); \
4323 OPTIONAL(operands, MDFieldList, );
4325 #undef VISIT_MD_FIELDS
4327 Result = GET_OR_DISTINCT(GenericDINode,
4328 (Context, tag.Val, header.Val, operands.Val));
4332 /// ParseDISubrange:
4333 /// ::= !DISubrange(count: 30, lowerBound: 2)
4334 /// ::= !DISubrange(count: !node, lowerBound: 2)
4335 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4336 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4337 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4338 OPTIONAL(lowerBound, MDSignedField, );
4340 #undef VISIT_MD_FIELDS
4342 if (count.isMDSignedField())
4343 Result = GET_OR_DISTINCT(
4344 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4345 else if (count.isMDField())
4346 Result = GET_OR_DISTINCT(
4347 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4354 /// ParseDIEnumerator:
4355 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4356 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4357 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4358 REQUIRED(name, MDStringField, ); \
4359 REQUIRED(value, MDSignedOrUnsignedField, ); \
4360 OPTIONAL(isUnsigned, MDBoolField, (false));
4362 #undef VISIT_MD_FIELDS
4364 if (isUnsigned.Val && value.isMDSignedField())
4365 return TokError("unsigned enumerator with negative value");
4367 int64_t Value = value.isMDSignedField()
4368 ? value.getMDSignedValue()
4369 : static_cast<int64_t>(value.getMDUnsignedValue());
4371 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4376 /// ParseDIBasicType:
4377 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4378 /// encoding: DW_ATE_encoding, flags: 0)
4379 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4380 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4381 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4382 OPTIONAL(name, MDStringField, ); \
4383 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4384 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4385 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4386 OPTIONAL(flags, DIFlagField, );
4388 #undef VISIT_MD_FIELDS
4390 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4391 align.Val, encoding.Val, flags.Val));
4395 /// ParseDIDerivedType:
4396 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4397 /// line: 7, scope: !1, baseType: !2, size: 32,
4398 /// align: 32, offset: 0, flags: 0, extraData: !3,
4399 /// dwarfAddressSpace: 3)
4400 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4401 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4402 REQUIRED(tag, DwarfTagField, ); \
4403 OPTIONAL(name, MDStringField, ); \
4404 OPTIONAL(file, MDField, ); \
4405 OPTIONAL(line, LineField, ); \
4406 OPTIONAL(scope, MDField, ); \
4407 REQUIRED(baseType, MDField, ); \
4408 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4409 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4410 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4411 OPTIONAL(flags, DIFlagField, ); \
4412 OPTIONAL(extraData, MDField, ); \
4413 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4415 #undef VISIT_MD_FIELDS
4417 Optional<unsigned> DWARFAddressSpace;
4418 if (dwarfAddressSpace.Val != UINT32_MAX)
4419 DWARFAddressSpace = dwarfAddressSpace.Val;
4421 Result = GET_OR_DISTINCT(DIDerivedType,
4422 (Context, tag.Val, name.Val, file.Val, line.Val,
4423 scope.Val, baseType.Val, size.Val, align.Val,
4424 offset.Val, DWARFAddressSpace, flags.Val,
4429 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4430 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4431 REQUIRED(tag, DwarfTagField, ); \
4432 OPTIONAL(name, MDStringField, ); \
4433 OPTIONAL(file, MDField, ); \
4434 OPTIONAL(line, LineField, ); \
4435 OPTIONAL(scope, MDField, ); \
4436 OPTIONAL(baseType, MDField, ); \
4437 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4438 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4439 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4440 OPTIONAL(flags, DIFlagField, ); \
4441 OPTIONAL(elements, MDField, ); \
4442 OPTIONAL(runtimeLang, DwarfLangField, ); \
4443 OPTIONAL(vtableHolder, MDField, ); \
4444 OPTIONAL(templateParams, MDField, ); \
4445 OPTIONAL(identifier, MDStringField, ); \
4446 OPTIONAL(discriminator, MDField, );
4448 #undef VISIT_MD_FIELDS
4450 // If this has an identifier try to build an ODR type.
4452 if (auto *CT = DICompositeType::buildODRType(
4453 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4454 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4455 elements.Val, runtimeLang.Val, vtableHolder.Val,
4456 templateParams.Val, discriminator.Val)) {
4461 // Create a new node, and save it in the context if it belongs in the type
4463 Result = GET_OR_DISTINCT(
4465 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4466 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4467 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4468 discriminator.Val));
4472 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4473 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4474 OPTIONAL(flags, DIFlagField, ); \
4475 OPTIONAL(cc, DwarfCCField, ); \
4476 REQUIRED(types, MDField, );
4478 #undef VISIT_MD_FIELDS
4480 Result = GET_OR_DISTINCT(DISubroutineType,
4481 (Context, flags.Val, cc.Val, types.Val));
4485 /// ParseDIFileType:
4486 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4487 /// checksumkind: CSK_MD5,
4488 /// checksum: "000102030405060708090a0b0c0d0e0f",
4489 /// source: "source file contents")
4490 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4491 // The default constructed value for checksumkind is required, but will never
4492 // be used, as the parser checks if the field was actually Seen before using
4494 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4495 REQUIRED(filename, MDStringField, ); \
4496 REQUIRED(directory, MDStringField, ); \
4497 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4498 OPTIONAL(checksum, MDStringField, ); \
4499 OPTIONAL(source, MDStringField, );
4501 #undef VISIT_MD_FIELDS
4503 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4504 if (checksumkind.Seen && checksum.Seen)
4505 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4506 else if (checksumkind.Seen || checksum.Seen)
4507 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4509 Optional<MDString *> OptSource;
4511 OptSource = source.Val;
4512 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4513 OptChecksum, OptSource));
4517 /// ParseDICompileUnit:
4518 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4519 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4520 /// splitDebugFilename: "abc.debug",
4521 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4522 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4523 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4525 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4527 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4528 REQUIRED(language, DwarfLangField, ); \
4529 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4530 OPTIONAL(producer, MDStringField, ); \
4531 OPTIONAL(isOptimized, MDBoolField, ); \
4532 OPTIONAL(flags, MDStringField, ); \
4533 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4534 OPTIONAL(splitDebugFilename, MDStringField, ); \
4535 OPTIONAL(emissionKind, EmissionKindField, ); \
4536 OPTIONAL(enums, MDField, ); \
4537 OPTIONAL(retainedTypes, MDField, ); \
4538 OPTIONAL(globals, MDField, ); \
4539 OPTIONAL(imports, MDField, ); \
4540 OPTIONAL(macros, MDField, ); \
4541 OPTIONAL(dwoId, MDUnsignedField, ); \
4542 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4543 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4544 OPTIONAL(nameTableKind, NameTableKindField, ); \
4545 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4547 #undef VISIT_MD_FIELDS
4549 Result = DICompileUnit::getDistinct(
4550 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4551 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4552 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4553 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4554 debugBaseAddress.Val);
4558 /// ParseDISubprogram:
4559 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4560 /// file: !1, line: 7, type: !2, isLocal: false,
4561 /// isDefinition: true, scopeLine: 8, containingType: !3,
4562 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4563 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4564 /// spFlags: 10, isOptimized: false, templateParams: !4,
4565 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4566 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4567 auto Loc = Lex.getLoc();
4568 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4569 OPTIONAL(scope, MDField, ); \
4570 OPTIONAL(name, MDStringField, ); \
4571 OPTIONAL(linkageName, MDStringField, ); \
4572 OPTIONAL(file, MDField, ); \
4573 OPTIONAL(line, LineField, ); \
4574 OPTIONAL(type, MDField, ); \
4575 OPTIONAL(isLocal, MDBoolField, ); \
4576 OPTIONAL(isDefinition, MDBoolField, (true)); \
4577 OPTIONAL(scopeLine, LineField, ); \
4578 OPTIONAL(containingType, MDField, ); \
4579 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4580 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4581 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4582 OPTIONAL(flags, DIFlagField, ); \
4583 OPTIONAL(spFlags, DISPFlagField, ); \
4584 OPTIONAL(isOptimized, MDBoolField, ); \
4585 OPTIONAL(unit, MDField, ); \
4586 OPTIONAL(templateParams, MDField, ); \
4587 OPTIONAL(declaration, MDField, ); \
4588 OPTIONAL(retainedNodes, MDField, ); \
4589 OPTIONAL(thrownTypes, MDField, );
4591 #undef VISIT_MD_FIELDS
4593 // An explicit spFlags field takes precedence over individual fields in
4594 // older IR versions.
4595 DISubprogram::DISPFlags SPFlags =
4596 spFlags.Seen ? spFlags.Val
4597 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4598 isOptimized.Val, virtuality.Val);
4599 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4602 "missing 'distinct', required for !DISubprogram that is a Definition");
4603 Result = GET_OR_DISTINCT(
4605 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4606 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4607 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4608 declaration.Val, retainedNodes.Val, thrownTypes.Val));
4612 /// ParseDILexicalBlock:
4613 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4614 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4615 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4616 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4617 OPTIONAL(file, MDField, ); \
4618 OPTIONAL(line, LineField, ); \
4619 OPTIONAL(column, ColumnField, );
4621 #undef VISIT_MD_FIELDS
4623 Result = GET_OR_DISTINCT(
4624 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4628 /// ParseDILexicalBlockFile:
4629 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4630 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4631 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4632 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4633 OPTIONAL(file, MDField, ); \
4634 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4636 #undef VISIT_MD_FIELDS
4638 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4639 (Context, scope.Val, file.Val, discriminator.Val));
4643 /// ParseDINamespace:
4644 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4645 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4646 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4647 REQUIRED(scope, MDField, ); \
4648 OPTIONAL(name, MDStringField, ); \
4649 OPTIONAL(exportSymbols, MDBoolField, );
4651 #undef VISIT_MD_FIELDS
4653 Result = GET_OR_DISTINCT(DINamespace,
4654 (Context, scope.Val, name.Val, exportSymbols.Val));
4659 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4660 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4661 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4662 REQUIRED(type, DwarfMacinfoTypeField, ); \
4663 OPTIONAL(line, LineField, ); \
4664 REQUIRED(name, MDStringField, ); \
4665 OPTIONAL(value, MDStringField, );
4667 #undef VISIT_MD_FIELDS
4669 Result = GET_OR_DISTINCT(DIMacro,
4670 (Context, type.Val, line.Val, name.Val, value.Val));
4674 /// ParseDIMacroFile:
4675 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4676 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4677 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4678 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4679 OPTIONAL(line, LineField, ); \
4680 REQUIRED(file, MDField, ); \
4681 OPTIONAL(nodes, MDField, );
4683 #undef VISIT_MD_FIELDS
4685 Result = GET_OR_DISTINCT(DIMacroFile,
4686 (Context, type.Val, line.Val, file.Val, nodes.Val));
4691 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4692 /// includePath: "/usr/include", isysroot: "/")
4693 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4694 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4695 REQUIRED(scope, MDField, ); \
4696 REQUIRED(name, MDStringField, ); \
4697 OPTIONAL(configMacros, MDStringField, ); \
4698 OPTIONAL(includePath, MDStringField, ); \
4699 OPTIONAL(isysroot, MDStringField, );
4701 #undef VISIT_MD_FIELDS
4703 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4704 configMacros.Val, includePath.Val, isysroot.Val));
4708 /// ParseDITemplateTypeParameter:
4709 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4710 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4711 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4712 OPTIONAL(name, MDStringField, ); \
4713 REQUIRED(type, MDField, );
4715 #undef VISIT_MD_FIELDS
4718 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4722 /// ParseDITemplateValueParameter:
4723 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4724 /// name: "V", type: !1, value: i32 7)
4725 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4726 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4727 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4728 OPTIONAL(name, MDStringField, ); \
4729 OPTIONAL(type, MDField, ); \
4730 REQUIRED(value, MDField, );
4732 #undef VISIT_MD_FIELDS
4734 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4735 (Context, tag.Val, name.Val, type.Val, value.Val));
4739 /// ParseDIGlobalVariable:
4740 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4741 /// file: !1, line: 7, type: !2, isLocal: false,
4742 /// isDefinition: true, templateParams: !3,
4743 /// declaration: !4, align: 8)
4744 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4745 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4746 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4747 OPTIONAL(scope, MDField, ); \
4748 OPTIONAL(linkageName, MDStringField, ); \
4749 OPTIONAL(file, MDField, ); \
4750 OPTIONAL(line, LineField, ); \
4751 OPTIONAL(type, MDField, ); \
4752 OPTIONAL(isLocal, MDBoolField, ); \
4753 OPTIONAL(isDefinition, MDBoolField, (true)); \
4754 OPTIONAL(templateParams, MDField, ); \
4755 OPTIONAL(declaration, MDField, ); \
4756 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4758 #undef VISIT_MD_FIELDS
4761 GET_OR_DISTINCT(DIGlobalVariable,
4762 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4763 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4764 declaration.Val, templateParams.Val, align.Val));
4768 /// ParseDILocalVariable:
4769 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4770 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4772 /// ::= !DILocalVariable(scope: !0, name: "foo",
4773 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4775 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4776 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4777 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4778 OPTIONAL(name, MDStringField, ); \
4779 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4780 OPTIONAL(file, MDField, ); \
4781 OPTIONAL(line, LineField, ); \
4782 OPTIONAL(type, MDField, ); \
4783 OPTIONAL(flags, DIFlagField, ); \
4784 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4786 #undef VISIT_MD_FIELDS
4788 Result = GET_OR_DISTINCT(DILocalVariable,
4789 (Context, scope.Val, name.Val, file.Val, line.Val,
4790 type.Val, arg.Val, flags.Val, align.Val));
4795 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4796 bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4797 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4798 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4799 REQUIRED(name, MDStringField, ); \
4800 REQUIRED(file, MDField, ); \
4801 REQUIRED(line, LineField, );
4803 #undef VISIT_MD_FIELDS
4805 Result = GET_OR_DISTINCT(DILabel,
4806 (Context, scope.Val, name.Val, file.Val, line.Val));
4810 /// ParseDIExpression:
4811 /// ::= !DIExpression(0, 7, -1)
4812 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4813 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4816 if (ParseToken(lltok::lparen, "expected '(' here"))
4819 SmallVector<uint64_t, 8> Elements;
4820 if (Lex.getKind() != lltok::rparen)
4822 if (Lex.getKind() == lltok::DwarfOp) {
4823 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4825 Elements.push_back(Op);
4828 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4831 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4832 return TokError("expected unsigned integer");
4834 auto &U = Lex.getAPSIntVal();
4835 if (U.ugt(UINT64_MAX))
4836 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4837 Elements.push_back(U.getZExtValue());
4839 } while (EatIfPresent(lltok::comma));
4841 if (ParseToken(lltok::rparen, "expected ')' here"))
4844 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4848 /// ParseDIGlobalVariableExpression:
4849 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4850 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4852 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4853 REQUIRED(var, MDField, ); \
4854 REQUIRED(expr, MDField, );
4856 #undef VISIT_MD_FIELDS
4859 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4863 /// ParseDIObjCProperty:
4864 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4865 /// getter: "getFoo", attributes: 7, type: !2)
4866 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4867 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4868 OPTIONAL(name, MDStringField, ); \
4869 OPTIONAL(file, MDField, ); \
4870 OPTIONAL(line, LineField, ); \
4871 OPTIONAL(setter, MDStringField, ); \
4872 OPTIONAL(getter, MDStringField, ); \
4873 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4874 OPTIONAL(type, MDField, );
4876 #undef VISIT_MD_FIELDS
4878 Result = GET_OR_DISTINCT(DIObjCProperty,
4879 (Context, name.Val, file.Val, line.Val, setter.Val,
4880 getter.Val, attributes.Val, type.Val));
4884 /// ParseDIImportedEntity:
4885 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4886 /// line: 7, name: "foo")
4887 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4888 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4889 REQUIRED(tag, DwarfTagField, ); \
4890 REQUIRED(scope, MDField, ); \
4891 OPTIONAL(entity, MDField, ); \
4892 OPTIONAL(file, MDField, ); \
4893 OPTIONAL(line, LineField, ); \
4894 OPTIONAL(name, MDStringField, );
4896 #undef VISIT_MD_FIELDS
4898 Result = GET_OR_DISTINCT(
4900 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
4904 #undef PARSE_MD_FIELD
4906 #undef REQUIRE_FIELD
4907 #undef DECLARE_FIELD
4909 /// ParseMetadataAsValue
4910 /// ::= metadata i32 %local
4911 /// ::= metadata i32 @global
4912 /// ::= metadata i32 7
4914 /// ::= metadata !{...}
4915 /// ::= metadata !"string"
4916 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4917 // Note: the type 'metadata' has already been parsed.
4919 if (ParseMetadata(MD, &PFS))
4922 V = MetadataAsValue::get(Context, MD);
4926 /// ParseValueAsMetadata
4930 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4931 PerFunctionState *PFS) {
4934 if (ParseType(Ty, TypeMsg, Loc))
4936 if (Ty->isMetadataTy())
4937 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4940 if (ParseValue(Ty, V, PFS))
4943 MD = ValueAsMetadata::get(V);
4954 /// ::= !DILocation(...)
4955 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4956 if (Lex.getKind() == lltok::MetadataVar) {
4958 if (ParseSpecializedMDNode(N))
4966 if (Lex.getKind() != lltok::exclaim)
4967 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4970 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4974 // ::= '!' STRINGCONSTANT
4975 if (Lex.getKind() == lltok::StringConstant) {
4977 if (ParseMDString(S))
4987 if (ParseMDNodeTail(N))
4993 //===----------------------------------------------------------------------===//
4994 // Function Parsing.
4995 //===----------------------------------------------------------------------===//
4997 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4998 PerFunctionState *PFS, bool IsCall) {
4999 if (Ty->isFunctionTy())
5000 return Error(ID.Loc, "functions are not values, refer to them as pointers");
5003 case ValID::t_LocalID:
5004 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5005 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5006 return V == nullptr;
5007 case ValID::t_LocalName:
5008 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5009 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
5010 return V == nullptr;
5011 case ValID::t_InlineAsm: {
5012 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5013 return Error(ID.Loc, "invalid type for inline asm constraint string");
5014 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5015 (ID.UIntVal >> 1) & 1,
5016 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5019 case ValID::t_GlobalName:
5020 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5021 return V == nullptr;
5022 case ValID::t_GlobalID:
5023 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5024 return V == nullptr;
5025 case ValID::t_APSInt:
5026 if (!Ty->isIntegerTy())
5027 return Error(ID.Loc, "integer constant must have integer type");
5028 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5029 V = ConstantInt::get(Context, ID.APSIntVal);
5031 case ValID::t_APFloat:
5032 if (!Ty->isFloatingPointTy() ||
5033 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5034 return Error(ID.Loc, "floating point constant invalid for type");
5036 // The lexer has no type info, so builds all half, float, and double FP
5037 // constants as double. Fix this here. Long double does not need this.
5038 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5041 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5043 else if (Ty->isFloatTy())
5044 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5047 V = ConstantFP::get(Context, ID.APFloatVal);
5049 if (V->getType() != Ty)
5050 return Error(ID.Loc, "floating point constant does not have type '" +
5051 getTypeString(Ty) + "'");
5055 if (!Ty->isPointerTy())
5056 return Error(ID.Loc, "null must be a pointer type");
5057 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5059 case ValID::t_Undef:
5060 // FIXME: LabelTy should not be a first-class type.
5061 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5062 return Error(ID.Loc, "invalid type for undef constant");
5063 V = UndefValue::get(Ty);
5065 case ValID::t_EmptyArray:
5066 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5067 return Error(ID.Loc, "invalid empty array initializer");
5068 V = UndefValue::get(Ty);
5071 // FIXME: LabelTy should not be a first-class type.
5072 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5073 return Error(ID.Loc, "invalid type for null constant");
5074 V = Constant::getNullValue(Ty);
5077 if (!Ty->isTokenTy())
5078 return Error(ID.Loc, "invalid type for none constant");
5079 V = Constant::getNullValue(Ty);
5081 case ValID::t_Constant:
5082 if (ID.ConstantVal->getType() != Ty)
5083 return Error(ID.Loc, "constant expression type mismatch");
5087 case ValID::t_ConstantStruct:
5088 case ValID::t_PackedConstantStruct:
5089 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5090 if (ST->getNumElements() != ID.UIntVal)
5091 return Error(ID.Loc,
5092 "initializer with struct type has wrong # elements");
5093 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5094 return Error(ID.Loc, "packed'ness of initializer and type don't match");
5096 // Verify that the elements are compatible with the structtype.
5097 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5098 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5099 return Error(ID.Loc, "element " + Twine(i) +
5100 " of struct initializer doesn't match struct element type");
5102 V = ConstantStruct::get(
5103 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5105 return Error(ID.Loc, "constant expression type mismatch");
5108 llvm_unreachable("Invalid ValID");
5111 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5114 auto Loc = Lex.getLoc();
5115 if (ParseValID(ID, /*PFS=*/nullptr))
5118 case ValID::t_APSInt:
5119 case ValID::t_APFloat:
5120 case ValID::t_Undef:
5121 case ValID::t_Constant:
5122 case ValID::t_ConstantStruct:
5123 case ValID::t_PackedConstantStruct: {
5125 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5127 assert(isa<Constant>(V) && "Expected a constant value");
5128 C = cast<Constant>(V);
5132 C = Constant::getNullValue(Ty);
5135 return Error(Loc, "expected a constant value");
5139 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5142 return ParseValID(ID, PFS) ||
5143 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5146 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5148 return ParseType(Ty) ||
5149 ParseValue(Ty, V, PFS);
5152 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5153 PerFunctionState &PFS) {
5156 if (ParseTypeAndValue(V, PFS)) return true;
5157 if (!isa<BasicBlock>(V))
5158 return Error(Loc, "expected a basic block");
5159 BB = cast<BasicBlock>(V);
5164 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5165 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5166 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5167 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5168 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5169 // Parse the linkage.
5170 LocTy LinkageLoc = Lex.getLoc();
5172 unsigned Visibility;
5173 unsigned DLLStorageClass;
5175 AttrBuilder RetAttrs;
5178 Type *RetType = nullptr;
5179 LocTy RetTypeLoc = Lex.getLoc();
5180 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5182 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5183 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
5186 // Verify that the linkage is ok.
5187 switch ((GlobalValue::LinkageTypes)Linkage) {
5188 case GlobalValue::ExternalLinkage:
5189 break; // always ok.
5190 case GlobalValue::ExternalWeakLinkage:
5192 return Error(LinkageLoc, "invalid linkage for function definition");
5194 case GlobalValue::PrivateLinkage:
5195 case GlobalValue::InternalLinkage:
5196 case GlobalValue::AvailableExternallyLinkage:
5197 case GlobalValue::LinkOnceAnyLinkage:
5198 case GlobalValue::LinkOnceODRLinkage:
5199 case GlobalValue::WeakAnyLinkage:
5200 case GlobalValue::WeakODRLinkage:
5202 return Error(LinkageLoc, "invalid linkage for function declaration");
5204 case GlobalValue::AppendingLinkage:
5205 case GlobalValue::CommonLinkage:
5206 return Error(LinkageLoc, "invalid function linkage type");
5209 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5210 return Error(LinkageLoc,
5211 "symbol with local linkage must have default visibility");
5213 if (!FunctionType::isValidReturnType(RetType))
5214 return Error(RetTypeLoc, "invalid function return type");
5216 LocTy NameLoc = Lex.getLoc();
5218 std::string FunctionName;
5219 if (Lex.getKind() == lltok::GlobalVar) {
5220 FunctionName = Lex.getStrVal();
5221 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5222 unsigned NameID = Lex.getUIntVal();
5224 if (NameID != NumberedVals.size())
5225 return TokError("function expected to be numbered '%" +
5226 Twine(NumberedVals.size()) + "'");
5228 return TokError("expected function name");
5233 if (Lex.getKind() != lltok::lparen)
5234 return TokError("expected '(' in function argument list");
5236 SmallVector<ArgInfo, 8> ArgList;
5238 AttrBuilder FuncAttrs;
5239 std::vector<unsigned> FwdRefAttrGrps;
5241 std::string Section;
5244 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5245 unsigned AddrSpace = 0;
5246 Constant *Prefix = nullptr;
5247 Constant *Prologue = nullptr;
5248 Constant *PersonalityFn = nullptr;
5251 if (ParseArgumentList(ArgList, isVarArg) ||
5252 ParseOptionalUnnamedAddr(UnnamedAddr) ||
5253 ParseOptionalProgramAddrSpace(AddrSpace) ||
5254 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5256 (EatIfPresent(lltok::kw_section) &&
5257 ParseStringConstant(Section)) ||
5258 parseOptionalComdat(FunctionName, C) ||
5259 ParseOptionalAlignment(Alignment) ||
5260 (EatIfPresent(lltok::kw_gc) &&
5261 ParseStringConstant(GC)) ||
5262 (EatIfPresent(lltok::kw_prefix) &&
5263 ParseGlobalTypeAndValue(Prefix)) ||
5264 (EatIfPresent(lltok::kw_prologue) &&
5265 ParseGlobalTypeAndValue(Prologue)) ||
5266 (EatIfPresent(lltok::kw_personality) &&
5267 ParseGlobalTypeAndValue(PersonalityFn)))
5270 if (FuncAttrs.contains(Attribute::Builtin))
5271 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
5273 // If the alignment was parsed as an attribute, move to the alignment field.
5274 if (FuncAttrs.hasAlignmentAttr()) {
5275 Alignment = FuncAttrs.getAlignment();
5276 FuncAttrs.removeAttribute(Attribute::Alignment);
5279 // Okay, if we got here, the function is syntactically valid. Convert types
5280 // and do semantic checks.
5281 std::vector<Type*> ParamTypeList;
5282 SmallVector<AttributeSet, 8> Attrs;
5284 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5285 ParamTypeList.push_back(ArgList[i].Ty);
5286 Attrs.push_back(ArgList[i].Attrs);
5290 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5291 AttributeSet::get(Context, RetAttrs), Attrs);
5293 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5294 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5297 FunctionType::get(RetType, ParamTypeList, isVarArg);
5298 PointerType *PFT = PointerType::get(FT, AddrSpace);
5301 if (!FunctionName.empty()) {
5302 // If this was a definition of a forward reference, remove the definition
5303 // from the forward reference table and fill in the forward ref.
5304 auto FRVI = ForwardRefVals.find(FunctionName);
5305 if (FRVI != ForwardRefVals.end()) {
5306 Fn = M->getFunction(FunctionName);
5308 return Error(FRVI->second.second, "invalid forward reference to "
5309 "function as global value!");
5310 if (Fn->getType() != PFT)
5311 return Error(FRVI->second.second, "invalid forward reference to "
5312 "function '" + FunctionName + "' with wrong type: "
5313 "expected '" + getTypeString(PFT) + "' but was '" +
5314 getTypeString(Fn->getType()) + "'");
5315 ForwardRefVals.erase(FRVI);
5316 } else if ((Fn = M->getFunction(FunctionName))) {
5317 // Reject redefinitions.
5318 return Error(NameLoc, "invalid redefinition of function '" +
5319 FunctionName + "'");
5320 } else if (M->getNamedValue(FunctionName)) {
5321 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5325 // If this is a definition of a forward referenced function, make sure the
5327 auto I = ForwardRefValIDs.find(NumberedVals.size());
5328 if (I != ForwardRefValIDs.end()) {
5329 Fn = cast<Function>(I->second.first);
5330 if (Fn->getType() != PFT)
5331 return Error(NameLoc, "type of definition and forward reference of '@" +
5332 Twine(NumberedVals.size()) + "' disagree: "
5333 "expected '" + getTypeString(PFT) + "' but was '" +
5334 getTypeString(Fn->getType()) + "'");
5335 ForwardRefValIDs.erase(I);
5340 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5342 else // Move the forward-reference to the correct spot in the module.
5343 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5345 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5347 if (FunctionName.empty())
5348 NumberedVals.push_back(Fn);
5350 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5351 maybeSetDSOLocal(DSOLocal, *Fn);
5352 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5353 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5354 Fn->setCallingConv(CC);
5355 Fn->setAttributes(PAL);
5356 Fn->setUnnamedAddr(UnnamedAddr);
5357 Fn->setAlignment(Alignment);
5358 Fn->setSection(Section);
5360 Fn->setPersonalityFn(PersonalityFn);
5361 if (!GC.empty()) Fn->setGC(GC);
5362 Fn->setPrefixData(Prefix);
5363 Fn->setPrologueData(Prologue);
5364 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5366 // Add all of the arguments we parsed to the function.
5367 Function::arg_iterator ArgIt = Fn->arg_begin();
5368 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5369 // If the argument has a name, insert it into the argument symbol table.
5370 if (ArgList[i].Name.empty()) continue;
5372 // Set the name, if it conflicted, it will be auto-renamed.
5373 ArgIt->setName(ArgList[i].Name);
5375 if (ArgIt->getName() != ArgList[i].Name)
5376 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5377 ArgList[i].Name + "'");
5383 // Check the declaration has no block address forward references.
5385 if (FunctionName.empty()) {
5386 ID.Kind = ValID::t_GlobalID;
5387 ID.UIntVal = NumberedVals.size() - 1;
5389 ID.Kind = ValID::t_GlobalName;
5390 ID.StrVal = FunctionName;
5392 auto Blocks = ForwardRefBlockAddresses.find(ID);
5393 if (Blocks != ForwardRefBlockAddresses.end())
5394 return Error(Blocks->first.Loc,
5395 "cannot take blockaddress inside a declaration");
5399 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5401 if (FunctionNumber == -1) {
5402 ID.Kind = ValID::t_GlobalName;
5403 ID.StrVal = F.getName();
5405 ID.Kind = ValID::t_GlobalID;
5406 ID.UIntVal = FunctionNumber;
5409 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5410 if (Blocks == P.ForwardRefBlockAddresses.end())
5413 for (const auto &I : Blocks->second) {
5414 const ValID &BBID = I.first;
5415 GlobalValue *GV = I.second;
5417 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5418 "Expected local id or name");
5420 if (BBID.Kind == ValID::t_LocalName)
5421 BB = GetBB(BBID.StrVal, BBID.Loc);
5423 BB = GetBB(BBID.UIntVal, BBID.Loc);
5425 return P.Error(BBID.Loc, "referenced value is not a basic block");
5427 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5428 GV->eraseFromParent();
5431 P.ForwardRefBlockAddresses.erase(Blocks);
5435 /// ParseFunctionBody
5436 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5437 bool LLParser::ParseFunctionBody(Function &Fn) {
5438 if (Lex.getKind() != lltok::lbrace)
5439 return TokError("expected '{' in function body");
5440 Lex.Lex(); // eat the {.
5442 int FunctionNumber = -1;
5443 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5445 PerFunctionState PFS(*this, Fn, FunctionNumber);
5447 // Resolve block addresses and allow basic blocks to be forward-declared
5448 // within this function.
5449 if (PFS.resolveForwardRefBlockAddresses())
5451 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5453 // We need at least one basic block.
5454 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5455 return TokError("function body requires at least one basic block");
5457 while (Lex.getKind() != lltok::rbrace &&
5458 Lex.getKind() != lltok::kw_uselistorder)
5459 if (ParseBasicBlock(PFS)) return true;
5461 while (Lex.getKind() != lltok::rbrace)
5462 if (ParseUseListOrder(&PFS))
5468 // Verify function is ok.
5469 return PFS.FinishFunction();
5473 /// ::= LabelStr? Instruction*
5474 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5475 // If this basic block starts out with a name, remember it.
5477 LocTy NameLoc = Lex.getLoc();
5478 if (Lex.getKind() == lltok::LabelStr) {
5479 Name = Lex.getStrVal();
5483 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
5485 return Error(NameLoc,
5486 "unable to create block named '" + Name + "'");
5488 std::string NameStr;
5490 // Parse the instructions in this block until we get a terminator.
5493 // This instruction may have three possibilities for a name: a) none
5494 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5495 LocTy NameLoc = Lex.getLoc();
5499 if (Lex.getKind() == lltok::LocalVarID) {
5500 NameID = Lex.getUIntVal();
5502 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5504 } else if (Lex.getKind() == lltok::LocalVar) {
5505 NameStr = Lex.getStrVal();
5507 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5511 switch (ParseInstruction(Inst, BB, PFS)) {
5512 default: llvm_unreachable("Unknown ParseInstruction result!");
5513 case InstError: return true;
5515 BB->getInstList().push_back(Inst);
5517 // With a normal result, we check to see if the instruction is followed by
5518 // a comma and metadata.
5519 if (EatIfPresent(lltok::comma))
5520 if (ParseInstructionMetadata(*Inst))
5523 case InstExtraComma:
5524 BB->getInstList().push_back(Inst);
5526 // If the instruction parser ate an extra comma at the end of it, it
5527 // *must* be followed by metadata.
5528 if (ParseInstructionMetadata(*Inst))
5533 // Set the name on the instruction.
5534 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5535 } while (!Inst->isTerminator());
5540 //===----------------------------------------------------------------------===//
5541 // Instruction Parsing.
5542 //===----------------------------------------------------------------------===//
5544 /// ParseInstruction - Parse one of the many different instructions.
5546 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5547 PerFunctionState &PFS) {
5548 lltok::Kind Token = Lex.getKind();
5549 if (Token == lltok::Eof)
5550 return TokError("found end of file when expecting more instructions");
5551 LocTy Loc = Lex.getLoc();
5552 unsigned KeywordVal = Lex.getUIntVal();
5553 Lex.Lex(); // Eat the keyword.
5556 default: return Error(Loc, "expected instruction opcode");
5557 // Terminator Instructions.
5558 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5559 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5560 case lltok::kw_br: return ParseBr(Inst, PFS);
5561 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5562 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5563 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5564 case lltok::kw_resume: return ParseResume(Inst, PFS);
5565 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5566 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5567 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5568 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5569 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5571 case lltok::kw_fneg: {
5572 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5573 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, 2);
5577 Inst->setFastMathFlags(FMF);
5580 // Binary Operators.
5584 case lltok::kw_shl: {
5585 bool NUW = EatIfPresent(lltok::kw_nuw);
5586 bool NSW = EatIfPresent(lltok::kw_nsw);
5587 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5589 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5591 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5592 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5595 case lltok::kw_fadd:
5596 case lltok::kw_fsub:
5597 case lltok::kw_fmul:
5598 case lltok::kw_fdiv:
5599 case lltok::kw_frem: {
5600 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5601 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5605 Inst->setFastMathFlags(FMF);
5609 case lltok::kw_sdiv:
5610 case lltok::kw_udiv:
5611 case lltok::kw_lshr:
5612 case lltok::kw_ashr: {
5613 bool Exact = EatIfPresent(lltok::kw_exact);
5615 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5616 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5620 case lltok::kw_urem:
5621 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5624 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5625 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5626 case lltok::kw_fcmp: {
5627 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5628 int Res = ParseCompare(Inst, PFS, KeywordVal);
5632 Inst->setFastMathFlags(FMF);
5637 case lltok::kw_trunc:
5638 case lltok::kw_zext:
5639 case lltok::kw_sext:
5640 case lltok::kw_fptrunc:
5641 case lltok::kw_fpext:
5642 case lltok::kw_bitcast:
5643 case lltok::kw_addrspacecast:
5644 case lltok::kw_uitofp:
5645 case lltok::kw_sitofp:
5646 case lltok::kw_fptoui:
5647 case lltok::kw_fptosi:
5648 case lltok::kw_inttoptr:
5649 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5651 case lltok::kw_select: return ParseSelect(Inst, PFS);
5652 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5653 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5654 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5655 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5656 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5657 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5659 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5660 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5661 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5662 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5664 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5665 case lltok::kw_load: return ParseLoad(Inst, PFS);
5666 case lltok::kw_store: return ParseStore(Inst, PFS);
5667 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5668 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5669 case lltok::kw_fence: return ParseFence(Inst, PFS);
5670 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5671 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5672 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5676 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5677 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5678 if (Opc == Instruction::FCmp) {
5679 switch (Lex.getKind()) {
5680 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5681 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5682 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5683 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5684 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5685 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5686 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5687 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5688 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5689 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5690 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5691 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5692 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5693 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5694 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5695 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5696 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5699 switch (Lex.getKind()) {
5700 default: return TokError("expected icmp predicate (e.g. 'eq')");
5701 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5702 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5703 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5704 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5705 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5706 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5707 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5708 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5709 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5710 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5717 //===----------------------------------------------------------------------===//
5718 // Terminator Instructions.
5719 //===----------------------------------------------------------------------===//
5721 /// ParseRet - Parse a return instruction.
5722 /// ::= 'ret' void (',' !dbg, !1)*
5723 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5724 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5725 PerFunctionState &PFS) {
5726 SMLoc TypeLoc = Lex.getLoc();
5728 if (ParseType(Ty, true /*void allowed*/)) return true;
5730 Type *ResType = PFS.getFunction().getReturnType();
5732 if (Ty->isVoidTy()) {
5733 if (!ResType->isVoidTy())
5734 return Error(TypeLoc, "value doesn't match function result type '" +
5735 getTypeString(ResType) + "'");
5737 Inst = ReturnInst::Create(Context);
5742 if (ParseValue(Ty, RV, PFS)) return true;
5744 if (ResType != RV->getType())
5745 return Error(TypeLoc, "value doesn't match function result type '" +
5746 getTypeString(ResType) + "'");
5748 Inst = ReturnInst::Create(Context, RV);
5753 /// ::= 'br' TypeAndValue
5754 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5755 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5758 BasicBlock *Op1, *Op2;
5759 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5761 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5762 Inst = BranchInst::Create(BB);
5766 if (Op0->getType() != Type::getInt1Ty(Context))
5767 return Error(Loc, "branch condition must have 'i1' type");
5769 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5770 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5771 ParseToken(lltok::comma, "expected ',' after true destination") ||
5772 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5775 Inst = BranchInst::Create(Op1, Op2, Op0);
5781 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5783 /// ::= (TypeAndValue ',' TypeAndValue)*
5784 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5785 LocTy CondLoc, BBLoc;
5787 BasicBlock *DefaultBB;
5788 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5789 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5790 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5791 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5794 if (!Cond->getType()->isIntegerTy())
5795 return Error(CondLoc, "switch condition must have integer type");
5797 // Parse the jump table pairs.
5798 SmallPtrSet<Value*, 32> SeenCases;
5799 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5800 while (Lex.getKind() != lltok::rsquare) {
5804 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5805 ParseToken(lltok::comma, "expected ',' after case value") ||
5806 ParseTypeAndBasicBlock(DestBB, PFS))
5809 if (!SeenCases.insert(Constant).second)
5810 return Error(CondLoc, "duplicate case value in switch");
5811 if (!isa<ConstantInt>(Constant))
5812 return Error(CondLoc, "case value is not a constant integer");
5814 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5817 Lex.Lex(); // Eat the ']'.
5819 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5820 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5821 SI->addCase(Table[i].first, Table[i].second);
5828 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5829 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5832 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5833 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5834 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5837 if (!Address->getType()->isPointerTy())
5838 return Error(AddrLoc, "indirectbr address must have pointer type");
5840 // Parse the destination list.
5841 SmallVector<BasicBlock*, 16> DestList;
5843 if (Lex.getKind() != lltok::rsquare) {
5845 if (ParseTypeAndBasicBlock(DestBB, PFS))
5847 DestList.push_back(DestBB);
5849 while (EatIfPresent(lltok::comma)) {
5850 if (ParseTypeAndBasicBlock(DestBB, PFS))
5852 DestList.push_back(DestBB);
5856 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5859 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5860 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5861 IBI->addDestination(DestList[i]);
5867 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5868 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5869 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5870 LocTy CallLoc = Lex.getLoc();
5871 AttrBuilder RetAttrs, FnAttrs;
5872 std::vector<unsigned> FwdRefAttrGrps;
5875 unsigned InvokeAddrSpace;
5876 Type *RetType = nullptr;
5879 SmallVector<ParamInfo, 16> ArgList;
5880 SmallVector<OperandBundleDef, 2> BundleList;
5882 BasicBlock *NormalBB, *UnwindBB;
5883 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5884 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
5885 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5886 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5887 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5889 ParseOptionalOperandBundles(BundleList, PFS) ||
5890 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5891 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5892 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5893 ParseTypeAndBasicBlock(UnwindBB, PFS))
5896 // If RetType is a non-function pointer type, then this is the short syntax
5897 // for the call, which means that RetType is just the return type. Infer the
5898 // rest of the function argument types from the arguments that are present.
5899 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5901 // Pull out the types of all of the arguments...
5902 std::vector<Type*> ParamTypes;
5903 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5904 ParamTypes.push_back(ArgList[i].V->getType());
5906 if (!FunctionType::isValidReturnType(RetType))
5907 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5909 Ty = FunctionType::get(RetType, ParamTypes, false);
5914 // Look up the callee.
5916 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
5917 Callee, &PFS, /*IsCall=*/true))
5920 // Set up the Attribute for the function.
5921 SmallVector<Value *, 8> Args;
5922 SmallVector<AttributeSet, 8> ArgAttrs;
5924 // Loop through FunctionType's arguments and ensure they are specified
5925 // correctly. Also, gather any parameter attributes.
5926 FunctionType::param_iterator I = Ty->param_begin();
5927 FunctionType::param_iterator E = Ty->param_end();
5928 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5929 Type *ExpectedTy = nullptr;
5932 } else if (!Ty->isVarArg()) {
5933 return Error(ArgList[i].Loc, "too many arguments specified");
5936 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5937 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5938 getTypeString(ExpectedTy) + "'");
5939 Args.push_back(ArgList[i].V);
5940 ArgAttrs.push_back(ArgList[i].Attrs);
5944 return Error(CallLoc, "not enough parameters specified for call");
5946 if (FnAttrs.hasAlignmentAttr())
5947 return Error(CallLoc, "invoke instructions may not have an alignment");
5949 // Finish off the Attribute and check them
5951 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5952 AttributeSet::get(Context, RetAttrs), ArgAttrs);
5955 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5956 II->setCallingConv(CC);
5957 II->setAttributes(PAL);
5958 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5964 /// ::= 'resume' TypeAndValue
5965 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5966 Value *Exn; LocTy ExnLoc;
5967 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5970 ResumeInst *RI = ResumeInst::Create(Exn);
5975 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5976 PerFunctionState &PFS) {
5977 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5980 while (Lex.getKind() != lltok::rsquare) {
5981 // If this isn't the first argument, we need a comma.
5982 if (!Args.empty() &&
5983 ParseToken(lltok::comma, "expected ',' in argument list"))
5986 // Parse the argument.
5988 Type *ArgTy = nullptr;
5989 if (ParseType(ArgTy, ArgLoc))
5993 if (ArgTy->isMetadataTy()) {
5994 if (ParseMetadataAsValue(V, PFS))
5997 if (ParseValue(ArgTy, V, PFS))
6003 Lex.Lex(); // Lex the ']'.
6008 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6009 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6010 Value *CleanupPad = nullptr;
6012 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6015 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6018 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6021 BasicBlock *UnwindBB = nullptr;
6022 if (Lex.getKind() == lltok::kw_to) {
6024 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6027 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6032 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6037 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6038 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6039 Value *CatchPad = nullptr;
6041 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6044 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
6048 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6049 ParseTypeAndBasicBlock(BB, PFS))
6052 Inst = CatchReturnInst::Create(CatchPad, BB);
6056 /// ParseCatchSwitch
6057 /// ::= 'catchswitch' within Parent
6058 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6061 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6064 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6065 Lex.getKind() != lltok::LocalVarID)
6066 return TokError("expected scope value for catchswitch");
6068 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6071 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6074 SmallVector<BasicBlock *, 32> Table;
6077 if (ParseTypeAndBasicBlock(DestBB, PFS))
6079 Table.push_back(DestBB);
6080 } while (EatIfPresent(lltok::comma));
6082 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6085 if (ParseToken(lltok::kw_unwind,
6086 "expected 'unwind' after catchswitch scope"))
6089 BasicBlock *UnwindBB = nullptr;
6090 if (EatIfPresent(lltok::kw_to)) {
6091 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6094 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6099 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6100 for (BasicBlock *DestBB : Table)
6101 CatchSwitch->addHandler(DestBB);
6107 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6108 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6109 Value *CatchSwitch = nullptr;
6111 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6114 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6115 return TokError("expected scope value for catchpad");
6117 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6120 SmallVector<Value *, 8> Args;
6121 if (ParseExceptionArgs(Args, PFS))
6124 Inst = CatchPadInst::Create(CatchSwitch, Args);
6129 /// ::= 'cleanuppad' within Parent ParamList
6130 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6131 Value *ParentPad = nullptr;
6133 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6136 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6137 Lex.getKind() != lltok::LocalVarID)
6138 return TokError("expected scope value for cleanuppad");
6140 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6143 SmallVector<Value *, 8> Args;
6144 if (ParseExceptionArgs(Args, PFS))
6147 Inst = CleanupPadInst::Create(ParentPad, Args);
6151 //===----------------------------------------------------------------------===//
6153 //===----------------------------------------------------------------------===//
6156 /// ::= UnaryOp TypeAndValue ',' Value
6158 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6159 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6160 bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6161 unsigned Opc, unsigned OperandType) {
6162 LocTy Loc; Value *LHS;
6163 if (ParseTypeAndValue(LHS, Loc, PFS))
6167 switch (OperandType) {
6168 default: llvm_unreachable("Unknown operand type!");
6169 case 0: // int or FP.
6170 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6171 LHS->getType()->isFPOrFPVectorTy();
6174 Valid = LHS->getType()->isIntOrIntVectorTy();
6177 Valid = LHS->getType()->isFPOrFPVectorTy();
6182 return Error(Loc, "invalid operand type for instruction");
6184 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6188 //===----------------------------------------------------------------------===//
6189 // Binary Operators.
6190 //===----------------------------------------------------------------------===//
6193 /// ::= ArithmeticOps TypeAndValue ',' Value
6195 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6196 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6197 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6198 unsigned Opc, unsigned OperandType) {
6199 LocTy Loc; Value *LHS, *RHS;
6200 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6201 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6202 ParseValue(LHS->getType(), RHS, PFS))
6206 switch (OperandType) {
6207 default: llvm_unreachable("Unknown operand type!");
6208 case 0: // int or FP.
6209 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6210 LHS->getType()->isFPOrFPVectorTy();
6212 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6213 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
6217 return Error(Loc, "invalid operand type for instruction");
6219 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6224 /// ::= ArithmeticOps TypeAndValue ',' Value {
6225 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6227 LocTy Loc; Value *LHS, *RHS;
6228 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6229 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6230 ParseValue(LHS->getType(), RHS, PFS))
6233 if (!LHS->getType()->isIntOrIntVectorTy())
6234 return Error(Loc,"instruction requires integer or integer vector operands");
6236 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6241 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6242 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6243 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6245 // Parse the integer/fp comparison predicate.
6249 if (ParseCmpPredicate(Pred, Opc) ||
6250 ParseTypeAndValue(LHS, Loc, PFS) ||
6251 ParseToken(lltok::comma, "expected ',' after compare value") ||
6252 ParseValue(LHS->getType(), RHS, PFS))
6255 if (Opc == Instruction::FCmp) {
6256 if (!LHS->getType()->isFPOrFPVectorTy())
6257 return Error(Loc, "fcmp requires floating point operands");
6258 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6260 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6261 if (!LHS->getType()->isIntOrIntVectorTy() &&
6262 !LHS->getType()->isPtrOrPtrVectorTy())
6263 return Error(Loc, "icmp requires integer operands");
6264 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6269 //===----------------------------------------------------------------------===//
6270 // Other Instructions.
6271 //===----------------------------------------------------------------------===//
6275 /// ::= CastOpc TypeAndValue 'to' Type
6276 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6280 Type *DestTy = nullptr;
6281 if (ParseTypeAndValue(Op, Loc, PFS) ||
6282 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6286 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6287 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6288 return Error(Loc, "invalid cast opcode for cast from '" +
6289 getTypeString(Op->getType()) + "' to '" +
6290 getTypeString(DestTy) + "'");
6292 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6297 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6298 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6300 Value *Op0, *Op1, *Op2;
6301 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6302 ParseToken(lltok::comma, "expected ',' after select condition") ||
6303 ParseTypeAndValue(Op1, PFS) ||
6304 ParseToken(lltok::comma, "expected ',' after select value") ||
6305 ParseTypeAndValue(Op2, PFS))
6308 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6309 return Error(Loc, Reason);
6311 Inst = SelectInst::Create(Op0, Op1, Op2);
6316 /// ::= 'va_arg' TypeAndValue ',' Type
6317 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
6319 Type *EltTy = nullptr;
6321 if (ParseTypeAndValue(Op, PFS) ||
6322 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
6323 ParseType(EltTy, TypeLoc))
6326 if (!EltTy->isFirstClassType())
6327 return Error(TypeLoc, "va_arg requires operand with first class type");
6329 Inst = new VAArgInst(Op, EltTy);
6333 /// ParseExtractElement
6334 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6335 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6338 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6339 ParseToken(lltok::comma, "expected ',' after extract value") ||
6340 ParseTypeAndValue(Op1, PFS))
6343 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6344 return Error(Loc, "invalid extractelement operands");
6346 Inst = ExtractElementInst::Create(Op0, Op1);
6350 /// ParseInsertElement
6351 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6352 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6354 Value *Op0, *Op1, *Op2;
6355 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6356 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6357 ParseTypeAndValue(Op1, PFS) ||
6358 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6359 ParseTypeAndValue(Op2, PFS))
6362 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6363 return Error(Loc, "invalid insertelement operands");
6365 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6369 /// ParseShuffleVector
6370 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6371 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6373 Value *Op0, *Op1, *Op2;
6374 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6375 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6376 ParseTypeAndValue(Op1, PFS) ||
6377 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6378 ParseTypeAndValue(Op2, PFS))
6381 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6382 return Error(Loc, "invalid shufflevector operands");
6384 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6389 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6390 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6391 Type *Ty = nullptr; LocTy TypeLoc;
6394 if (ParseType(Ty, TypeLoc) ||
6395 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6396 ParseValue(Ty, Op0, PFS) ||
6397 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6398 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6399 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6402 bool AteExtraComma = false;
6403 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6406 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6408 if (!EatIfPresent(lltok::comma))
6411 if (Lex.getKind() == lltok::MetadataVar) {
6412 AteExtraComma = true;
6416 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6417 ParseValue(Ty, Op0, PFS) ||
6418 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6419 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6420 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6424 if (!Ty->isFirstClassType())
6425 return Error(TypeLoc, "phi node must have first class type");
6427 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6428 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6429 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6431 return AteExtraComma ? InstExtraComma : InstNormal;
6435 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6437 /// ::= 'catch' TypeAndValue
6439 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6440 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6441 Type *Ty = nullptr; LocTy TyLoc;
6443 if (ParseType(Ty, TyLoc))
6446 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6447 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6449 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6450 LandingPadInst::ClauseType CT;
6451 if (EatIfPresent(lltok::kw_catch))
6452 CT = LandingPadInst::Catch;
6453 else if (EatIfPresent(lltok::kw_filter))
6454 CT = LandingPadInst::Filter;
6456 return TokError("expected 'catch' or 'filter' clause type");
6460 if (ParseTypeAndValue(V, VLoc, PFS))
6463 // A 'catch' type expects a non-array constant. A filter clause expects an
6465 if (CT == LandingPadInst::Catch) {
6466 if (isa<ArrayType>(V->getType()))
6467 Error(VLoc, "'catch' clause has an invalid type");
6469 if (!isa<ArrayType>(V->getType()))
6470 Error(VLoc, "'filter' clause has an invalid type");
6473 Constant *CV = dyn_cast<Constant>(V);
6475 return Error(VLoc, "clause argument must be a constant");
6479 Inst = LP.release();
6484 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6485 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6486 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6487 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6488 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6489 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6490 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6491 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6492 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
6493 CallInst::TailCallKind TCK) {
6494 AttrBuilder RetAttrs, FnAttrs;
6495 std::vector<unsigned> FwdRefAttrGrps;
6497 unsigned CallAddrSpace;
6499 Type *RetType = nullptr;
6502 SmallVector<ParamInfo, 16> ArgList;
6503 SmallVector<OperandBundleDef, 2> BundleList;
6504 LocTy CallLoc = Lex.getLoc();
6506 if (TCK != CallInst::TCK_None &&
6507 ParseToken(lltok::kw_call,
6508 "expected 'tail call', 'musttail call', or 'notail call'"))
6511 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6513 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6514 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
6515 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6516 ParseValID(CalleeID) ||
6517 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6518 PFS.getFunction().isVarArg()) ||
6519 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6520 ParseOptionalOperandBundles(BundleList, PFS))
6523 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6524 return Error(CallLoc, "fast-math-flags specified for call without "
6525 "floating-point scalar or vector return type");
6527 // If RetType is a non-function pointer type, then this is the short syntax
6528 // for the call, which means that RetType is just the return type. Infer the
6529 // rest of the function argument types from the arguments that are present.
6530 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6532 // Pull out the types of all of the arguments...
6533 std::vector<Type*> ParamTypes;
6534 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6535 ParamTypes.push_back(ArgList[i].V->getType());
6537 if (!FunctionType::isValidReturnType(RetType))
6538 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6540 Ty = FunctionType::get(RetType, ParamTypes, false);
6545 // Look up the callee.
6547 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6548 &PFS, /*IsCall=*/true))
6551 // Set up the Attribute for the function.
6552 SmallVector<AttributeSet, 8> Attrs;
6554 SmallVector<Value*, 8> Args;
6556 // Loop through FunctionType's arguments and ensure they are specified
6557 // correctly. Also, gather any parameter attributes.
6558 FunctionType::param_iterator I = Ty->param_begin();
6559 FunctionType::param_iterator E = Ty->param_end();
6560 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6561 Type *ExpectedTy = nullptr;
6564 } else if (!Ty->isVarArg()) {
6565 return Error(ArgList[i].Loc, "too many arguments specified");
6568 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6569 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6570 getTypeString(ExpectedTy) + "'");
6571 Args.push_back(ArgList[i].V);
6572 Attrs.push_back(ArgList[i].Attrs);
6576 return Error(CallLoc, "not enough parameters specified for call");
6578 if (FnAttrs.hasAlignmentAttr())
6579 return Error(CallLoc, "call instructions may not have an alignment");
6581 // Finish off the Attribute and check them
6583 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6584 AttributeSet::get(Context, RetAttrs), Attrs);
6586 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6587 CI->setTailCallKind(TCK);
6588 CI->setCallingConv(CC);
6590 CI->setFastMathFlags(FMF);
6591 CI->setAttributes(PAL);
6592 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6597 //===----------------------------------------------------------------------===//
6598 // Memory Instructions.
6599 //===----------------------------------------------------------------------===//
6602 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6603 /// (',' 'align' i32)? (',', 'addrspace(n))?
6604 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6605 Value *Size = nullptr;
6606 LocTy SizeLoc, TyLoc, ASLoc;
6607 unsigned Alignment = 0;
6608 unsigned AddrSpace = 0;
6611 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6612 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6614 if (ParseType(Ty, TyLoc)) return true;
6616 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6617 return Error(TyLoc, "invalid type for alloca");
6619 bool AteExtraComma = false;
6620 if (EatIfPresent(lltok::comma)) {
6621 if (Lex.getKind() == lltok::kw_align) {
6622 if (ParseOptionalAlignment(Alignment))
6624 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6626 } else if (Lex.getKind() == lltok::kw_addrspace) {
6627 ASLoc = Lex.getLoc();
6628 if (ParseOptionalAddrSpace(AddrSpace))
6630 } else if (Lex.getKind() == lltok::MetadataVar) {
6631 AteExtraComma = true;
6633 if (ParseTypeAndValue(Size, SizeLoc, PFS))
6635 if (EatIfPresent(lltok::comma)) {
6636 if (Lex.getKind() == lltok::kw_align) {
6637 if (ParseOptionalAlignment(Alignment))
6639 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6641 } else if (Lex.getKind() == lltok::kw_addrspace) {
6642 ASLoc = Lex.getLoc();
6643 if (ParseOptionalAddrSpace(AddrSpace))
6645 } else if (Lex.getKind() == lltok::MetadataVar) {
6646 AteExtraComma = true;
6652 if (Size && !Size->getType()->isIntegerTy())
6653 return Error(SizeLoc, "element count must have integer type");
6655 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
6656 AI->setUsedWithInAlloca(IsInAlloca);
6657 AI->setSwiftError(IsSwiftError);
6659 return AteExtraComma ? InstExtraComma : InstNormal;
6663 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6664 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6665 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6666 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6667 Value *Val; LocTy Loc;
6668 unsigned Alignment = 0;
6669 bool AteExtraComma = false;
6670 bool isAtomic = false;
6671 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6672 SyncScope::ID SSID = SyncScope::System;
6674 if (Lex.getKind() == lltok::kw_atomic) {
6679 bool isVolatile = false;
6680 if (Lex.getKind() == lltok::kw_volatile) {
6686 LocTy ExplicitTypeLoc = Lex.getLoc();
6687 if (ParseType(Ty) ||
6688 ParseToken(lltok::comma, "expected comma after load's type") ||
6689 ParseTypeAndValue(Val, Loc, PFS) ||
6690 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6691 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6694 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6695 return Error(Loc, "load operand must be a pointer to a first class type");
6696 if (isAtomic && !Alignment)
6697 return Error(Loc, "atomic load must have explicit non-zero alignment");
6698 if (Ordering == AtomicOrdering::Release ||
6699 Ordering == AtomicOrdering::AcquireRelease)
6700 return Error(Loc, "atomic load cannot use Release ordering");
6702 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6703 return Error(ExplicitTypeLoc,
6704 "explicit pointee type doesn't match operand's pointee type");
6706 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6707 return AteExtraComma ? InstExtraComma : InstNormal;
6712 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6713 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6714 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6715 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6716 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6717 unsigned Alignment = 0;
6718 bool AteExtraComma = false;
6719 bool isAtomic = false;
6720 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6721 SyncScope::ID SSID = SyncScope::System;
6723 if (Lex.getKind() == lltok::kw_atomic) {
6728 bool isVolatile = false;
6729 if (Lex.getKind() == lltok::kw_volatile) {
6734 if (ParseTypeAndValue(Val, Loc, PFS) ||
6735 ParseToken(lltok::comma, "expected ',' after store operand") ||
6736 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6737 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6738 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6741 if (!Ptr->getType()->isPointerTy())
6742 return Error(PtrLoc, "store operand must be a pointer");
6743 if (!Val->getType()->isFirstClassType())
6744 return Error(Loc, "store operand must be a first class value");
6745 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6746 return Error(Loc, "stored value and pointer type do not match");
6747 if (isAtomic && !Alignment)
6748 return Error(Loc, "atomic store must have explicit non-zero alignment");
6749 if (Ordering == AtomicOrdering::Acquire ||
6750 Ordering == AtomicOrdering::AcquireRelease)
6751 return Error(Loc, "atomic store cannot use Acquire ordering");
6753 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
6754 return AteExtraComma ? InstExtraComma : InstNormal;
6758 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6759 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6760 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6761 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6762 bool AteExtraComma = false;
6763 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6764 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6765 SyncScope::ID SSID = SyncScope::System;
6766 bool isVolatile = false;
6767 bool isWeak = false;
6769 if (EatIfPresent(lltok::kw_weak))
6772 if (EatIfPresent(lltok::kw_volatile))
6775 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6776 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6777 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6778 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6779 ParseTypeAndValue(New, NewLoc, PFS) ||
6780 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
6781 ParseOrdering(FailureOrdering))
6784 if (SuccessOrdering == AtomicOrdering::Unordered ||
6785 FailureOrdering == AtomicOrdering::Unordered)
6786 return TokError("cmpxchg cannot be unordered");
6787 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6788 return TokError("cmpxchg failure argument shall be no stronger than the "
6789 "success argument");
6790 if (FailureOrdering == AtomicOrdering::Release ||
6791 FailureOrdering == AtomicOrdering::AcquireRelease)
6793 "cmpxchg failure ordering cannot include release semantics");
6794 if (!Ptr->getType()->isPointerTy())
6795 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6796 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6797 return Error(CmpLoc, "compare value and pointer type do not match");
6798 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6799 return Error(NewLoc, "new value and pointer type do not match");
6800 if (!New->getType()->isFirstClassType())
6801 return Error(NewLoc, "cmpxchg operand must be a first class value");
6802 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6803 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
6804 CXI->setVolatile(isVolatile);
6805 CXI->setWeak(isWeak);
6807 return AteExtraComma ? InstExtraComma : InstNormal;
6811 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6812 /// 'singlethread'? AtomicOrdering
6813 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6814 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6815 bool AteExtraComma = false;
6816 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6817 SyncScope::ID SSID = SyncScope::System;
6818 bool isVolatile = false;
6819 AtomicRMWInst::BinOp Operation;
6821 if (EatIfPresent(lltok::kw_volatile))
6824 switch (Lex.getKind()) {
6825 default: return TokError("expected binary operation in atomicrmw");
6826 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6827 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6828 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6829 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6830 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6831 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6832 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6833 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6834 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6835 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6836 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6838 Lex.Lex(); // Eat the operation.
6840 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6841 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6842 ParseTypeAndValue(Val, ValLoc, PFS) ||
6843 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6846 if (Ordering == AtomicOrdering::Unordered)
6847 return TokError("atomicrmw cannot be unordered");
6848 if (!Ptr->getType()->isPointerTy())
6849 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6850 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6851 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6853 if (!Val->getType()->isIntegerTy()) {
6854 return Error(ValLoc, "atomicrmw " +
6855 AtomicRMWInst::getOperationName(Operation) +
6856 " operand must be an integer");
6859 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6860 if (Size < 8 || (Size & (Size - 1)))
6861 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6864 AtomicRMWInst *RMWI =
6865 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
6866 RMWI->setVolatile(isVolatile);
6868 return AteExtraComma ? InstExtraComma : InstNormal;
6872 /// ::= 'fence' 'singlethread'? AtomicOrdering
6873 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6874 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6875 SyncScope::ID SSID = SyncScope::System;
6876 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6879 if (Ordering == AtomicOrdering::Unordered)
6880 return TokError("fence cannot be unordered");
6881 if (Ordering == AtomicOrdering::Monotonic)
6882 return TokError("fence cannot be monotonic");
6884 Inst = new FenceInst(Context, Ordering, SSID);
6888 /// ParseGetElementPtr
6889 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6890 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6891 Value *Ptr = nullptr;
6892 Value *Val = nullptr;
6895 bool InBounds = EatIfPresent(lltok::kw_inbounds);
6898 LocTy ExplicitTypeLoc = Lex.getLoc();
6899 if (ParseType(Ty) ||
6900 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6901 ParseTypeAndValue(Ptr, Loc, PFS))
6904 Type *BaseType = Ptr->getType();
6905 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6906 if (!BasePointerType)
6907 return Error(Loc, "base of getelementptr must be a pointer");
6909 if (Ty != BasePointerType->getElementType())
6910 return Error(ExplicitTypeLoc,
6911 "explicit pointee type doesn't match operand's pointee type");
6913 SmallVector<Value*, 16> Indices;
6914 bool AteExtraComma = false;
6915 // GEP returns a vector of pointers if at least one of parameters is a vector.
6916 // All vector parameters should have the same vector width.
6917 unsigned GEPWidth = BaseType->isVectorTy() ?
6918 BaseType->getVectorNumElements() : 0;
6920 while (EatIfPresent(lltok::comma)) {
6921 if (Lex.getKind() == lltok::MetadataVar) {
6922 AteExtraComma = true;
6925 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6926 if (!Val->getType()->isIntOrIntVectorTy())
6927 return Error(EltLoc, "getelementptr index must be an integer");
6929 if (Val->getType()->isVectorTy()) {
6930 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6931 if (GEPWidth && GEPWidth != ValNumEl)
6932 return Error(EltLoc,
6933 "getelementptr vector index has a wrong number of elements");
6934 GEPWidth = ValNumEl;
6936 Indices.push_back(Val);
6939 SmallPtrSet<Type*, 4> Visited;
6940 if (!Indices.empty() && !Ty->isSized(&Visited))
6941 return Error(Loc, "base element of getelementptr must be sized");
6943 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6944 return Error(Loc, "invalid getelementptr indices");
6945 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6947 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6948 return AteExtraComma ? InstExtraComma : InstNormal;
6951 /// ParseExtractValue
6952 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6953 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6954 Value *Val; LocTy Loc;
6955 SmallVector<unsigned, 4> Indices;
6957 if (ParseTypeAndValue(Val, Loc, PFS) ||
6958 ParseIndexList(Indices, AteExtraComma))
6961 if (!Val->getType()->isAggregateType())
6962 return Error(Loc, "extractvalue operand must be aggregate type");
6964 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6965 return Error(Loc, "invalid indices for extractvalue");
6966 Inst = ExtractValueInst::Create(Val, Indices);
6967 return AteExtraComma ? InstExtraComma : InstNormal;
6970 /// ParseInsertValue
6971 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6972 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6973 Value *Val0, *Val1; LocTy Loc0, Loc1;
6974 SmallVector<unsigned, 4> Indices;
6976 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6977 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6978 ParseTypeAndValue(Val1, Loc1, PFS) ||
6979 ParseIndexList(Indices, AteExtraComma))
6982 if (!Val0->getType()->isAggregateType())
6983 return Error(Loc0, "insertvalue operand must be aggregate type");
6985 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6987 return Error(Loc0, "invalid indices for insertvalue");
6988 if (IndexedType != Val1->getType())
6989 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6990 getTypeString(Val1->getType()) + "' instead of '" +
6991 getTypeString(IndexedType) + "'");
6992 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6993 return AteExtraComma ? InstExtraComma : InstNormal;
6996 //===----------------------------------------------------------------------===//
6997 // Embedded metadata.
6998 //===----------------------------------------------------------------------===//
7000 /// ParseMDNodeVector
7001 /// ::= { Element (',' Element)* }
7003 /// ::= 'null' | TypeAndValue
7004 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7005 if (ParseToken(lltok::lbrace, "expected '{' here"))
7008 // Check for an empty list.
7009 if (EatIfPresent(lltok::rbrace))
7013 // Null is a special case since it is typeless.
7014 if (EatIfPresent(lltok::kw_null)) {
7015 Elts.push_back(nullptr);
7020 if (ParseMetadata(MD, nullptr))
7023 } while (EatIfPresent(lltok::comma));
7025 return ParseToken(lltok::rbrace, "expected end of metadata node");
7028 //===----------------------------------------------------------------------===//
7029 // Use-list order directives.
7030 //===----------------------------------------------------------------------===//
7031 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7034 return Error(Loc, "value has no uses");
7036 unsigned NumUses = 0;
7037 SmallDenseMap<const Use *, unsigned, 16> Order;
7038 for (const Use &U : V->uses()) {
7039 if (++NumUses > Indexes.size())
7041 Order[&U] = Indexes[NumUses - 1];
7044 return Error(Loc, "value only has one use");
7045 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7047 "wrong number of indexes, expected " + Twine(V->getNumUses()));
7049 V->sortUseList([&](const Use &L, const Use &R) {
7050 return Order.lookup(&L) < Order.lookup(&R);
7055 /// ParseUseListOrderIndexes
7056 /// ::= '{' uint32 (',' uint32)+ '}'
7057 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7058 SMLoc Loc = Lex.getLoc();
7059 if (ParseToken(lltok::lbrace, "expected '{' here"))
7061 if (Lex.getKind() == lltok::rbrace)
7062 return Lex.Error("expected non-empty list of uselistorder indexes");
7064 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7065 // indexes should be distinct numbers in the range [0, size-1], and should
7067 unsigned Offset = 0;
7069 bool IsOrdered = true;
7070 assert(Indexes.empty() && "Expected empty order vector");
7073 if (ParseUInt32(Index))
7076 // Update consistency checks.
7077 Offset += Index - Indexes.size();
7078 Max = std::max(Max, Index);
7079 IsOrdered &= Index == Indexes.size();
7081 Indexes.push_back(Index);
7082 } while (EatIfPresent(lltok::comma));
7084 if (ParseToken(lltok::rbrace, "expected '}' here"))
7087 if (Indexes.size() < 2)
7088 return Error(Loc, "expected >= 2 uselistorder indexes");
7089 if (Offset != 0 || Max >= Indexes.size())
7090 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7092 return Error(Loc, "expected uselistorder indexes to change the order");
7097 /// ParseUseListOrder
7098 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7099 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7100 SMLoc Loc = Lex.getLoc();
7101 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7105 SmallVector<unsigned, 16> Indexes;
7106 if (ParseTypeAndValue(V, PFS) ||
7107 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7108 ParseUseListOrderIndexes(Indexes))
7111 return sortUseListOrder(V, Indexes, Loc);
7114 /// ParseUseListOrderBB
7115 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7116 bool LLParser::ParseUseListOrderBB() {
7117 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7118 SMLoc Loc = Lex.getLoc();
7122 SmallVector<unsigned, 16> Indexes;
7123 if (ParseValID(Fn) ||
7124 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7125 ParseValID(Label) ||
7126 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7127 ParseUseListOrderIndexes(Indexes))
7130 // Check the function.
7132 if (Fn.Kind == ValID::t_GlobalName)
7133 GV = M->getNamedValue(Fn.StrVal);
7134 else if (Fn.Kind == ValID::t_GlobalID)
7135 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7137 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7139 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7140 auto *F = dyn_cast<Function>(GV);
7142 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7143 if (F->isDeclaration())
7144 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7146 // Check the basic block.
7147 if (Label.Kind == ValID::t_LocalID)
7148 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7149 if (Label.Kind != ValID::t_LocalName)
7150 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
7151 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7153 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7154 if (!isa<BasicBlock>(V))
7155 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7157 return sortUseListOrder(V, Indexes, Loc);
7161 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7162 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7163 bool LLParser::ParseModuleEntry(unsigned ID) {
7164 assert(Lex.getKind() == lltok::kw_module);
7168 if (ParseToken(lltok::colon, "expected ':' here") ||
7169 ParseToken(lltok::lparen, "expected '(' here") ||
7170 ParseToken(lltok::kw_path, "expected 'path' here") ||
7171 ParseToken(lltok::colon, "expected ':' here") ||
7172 ParseStringConstant(Path) ||
7173 ParseToken(lltok::comma, "expected ',' here") ||
7174 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7175 ParseToken(lltok::colon, "expected ':' here") ||
7176 ParseToken(lltok::lparen, "expected '(' here"))
7180 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7181 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7182 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7183 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7184 ParseUInt32(Hash[4]))
7187 if (ParseToken(lltok::rparen, "expected ')' here") ||
7188 ParseToken(lltok::rparen, "expected ')' here"))
7191 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7192 ModuleIdMap[ID] = ModuleEntry->first();
7198 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7199 bool LLParser::ParseTypeIdEntry(unsigned ID) {
7200 assert(Lex.getKind() == lltok::kw_typeid);
7204 if (ParseToken(lltok::colon, "expected ':' here") ||
7205 ParseToken(lltok::lparen, "expected '(' here") ||
7206 ParseToken(lltok::kw_name, "expected 'name' here") ||
7207 ParseToken(lltok::colon, "expected ':' here") ||
7208 ParseStringConstant(Name))
7211 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7212 if (ParseToken(lltok::comma, "expected ',' here") ||
7213 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7216 // Check if this ID was forward referenced, and if so, update the
7217 // corresponding GUIDs.
7218 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7219 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7220 for (auto TIDRef : FwdRefTIDs->second) {
7221 assert(!*TIDRef.first &&
7222 "Forward referenced type id GUID expected to be 0");
7223 *TIDRef.first = GlobalValue::getGUID(Name);
7225 ForwardRefTypeIds.erase(FwdRefTIDs);
7232 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7233 bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7234 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7235 ParseToken(lltok::colon, "expected ':' here") ||
7236 ParseToken(lltok::lparen, "expected '(' here") ||
7237 ParseTypeTestResolution(TIS.TTRes))
7240 if (EatIfPresent(lltok::comma)) {
7241 // Expect optional wpdResolutions field
7242 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7246 if (ParseToken(lltok::rparen, "expected ')' here"))
7252 /// TypeTestResolution
7253 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7254 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7255 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7256 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7257 /// [',' 'inlinesBits' ':' UInt64]? ')'
7258 bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7259 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7260 ParseToken(lltok::colon, "expected ':' here") ||
7261 ParseToken(lltok::lparen, "expected '(' here") ||
7262 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7263 ParseToken(lltok::colon, "expected ':' here"))
7266 switch (Lex.getKind()) {
7267 case lltok::kw_unsat:
7268 TTRes.TheKind = TypeTestResolution::Unsat;
7270 case lltok::kw_byteArray:
7271 TTRes.TheKind = TypeTestResolution::ByteArray;
7273 case lltok::kw_inline:
7274 TTRes.TheKind = TypeTestResolution::Inline;
7276 case lltok::kw_single:
7277 TTRes.TheKind = TypeTestResolution::Single;
7279 case lltok::kw_allOnes:
7280 TTRes.TheKind = TypeTestResolution::AllOnes;
7283 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7287 if (ParseToken(lltok::comma, "expected ',' here") ||
7288 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7289 ParseToken(lltok::colon, "expected ':' here") ||
7290 ParseUInt32(TTRes.SizeM1BitWidth))
7293 // Parse optional fields
7294 while (EatIfPresent(lltok::comma)) {
7295 switch (Lex.getKind()) {
7296 case lltok::kw_alignLog2:
7298 if (ParseToken(lltok::colon, "expected ':'") ||
7299 ParseUInt64(TTRes.AlignLog2))
7302 case lltok::kw_sizeM1:
7304 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7307 case lltok::kw_bitMask: {
7310 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7312 assert(Val <= 0xff);
7313 TTRes.BitMask = (uint8_t)Val;
7316 case lltok::kw_inlineBits:
7318 if (ParseToken(lltok::colon, "expected ':'") ||
7319 ParseUInt64(TTRes.InlineBits))
7323 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7327 if (ParseToken(lltok::rparen, "expected ')' here"))
7333 /// OptionalWpdResolutions
7334 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7335 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7336 bool LLParser::ParseOptionalWpdResolutions(
7337 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7338 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7339 ParseToken(lltok::colon, "expected ':' here") ||
7340 ParseToken(lltok::lparen, "expected '(' here"))
7345 WholeProgramDevirtResolution WPDRes;
7346 if (ParseToken(lltok::lparen, "expected '(' here") ||
7347 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7348 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7349 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7350 ParseToken(lltok::rparen, "expected ')' here"))
7352 WPDResMap[Offset] = WPDRes;
7353 } while (EatIfPresent(lltok::comma));
7355 if (ParseToken(lltok::rparen, "expected ')' here"))
7362 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7363 /// [',' OptionalResByArg]? ')'
7364 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7365 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7366 /// [',' OptionalResByArg]? ')'
7367 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7368 /// [',' OptionalResByArg]? ')'
7369 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7370 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7371 ParseToken(lltok::colon, "expected ':' here") ||
7372 ParseToken(lltok::lparen, "expected '(' here") ||
7373 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7374 ParseToken(lltok::colon, "expected ':' here"))
7377 switch (Lex.getKind()) {
7378 case lltok::kw_indir:
7379 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7381 case lltok::kw_singleImpl:
7382 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7384 case lltok::kw_branchFunnel:
7385 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7388 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7392 // Parse optional fields
7393 while (EatIfPresent(lltok::comma)) {
7394 switch (Lex.getKind()) {
7395 case lltok::kw_singleImplName:
7397 if (ParseToken(lltok::colon, "expected ':' here") ||
7398 ParseStringConstant(WPDRes.SingleImplName))
7401 case lltok::kw_resByArg:
7402 if (ParseOptionalResByArg(WPDRes.ResByArg))
7406 return Error(Lex.getLoc(),
7407 "expected optional WholeProgramDevirtResolution field");
7411 if (ParseToken(lltok::rparen, "expected ')' here"))
7417 /// OptionalResByArg
7418 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7419 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7420 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7421 /// 'virtualConstProp' )
7422 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7423 /// [',' 'bit' ':' UInt32]? ')'
7424 bool LLParser::ParseOptionalResByArg(
7425 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7427 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7428 ParseToken(lltok::colon, "expected ':' here") ||
7429 ParseToken(lltok::lparen, "expected '(' here"))
7433 std::vector<uint64_t> Args;
7434 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7435 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7436 ParseToken(lltok::colon, "expected ':' here") ||
7437 ParseToken(lltok::lparen, "expected '(' here") ||
7438 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7439 ParseToken(lltok::colon, "expected ':' here"))
7442 WholeProgramDevirtResolution::ByArg ByArg;
7443 switch (Lex.getKind()) {
7444 case lltok::kw_indir:
7445 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7447 case lltok::kw_uniformRetVal:
7448 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7450 case lltok::kw_uniqueRetVal:
7451 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7453 case lltok::kw_virtualConstProp:
7454 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7457 return Error(Lex.getLoc(),
7458 "unexpected WholeProgramDevirtResolution::ByArg kind");
7462 // Parse optional fields
7463 while (EatIfPresent(lltok::comma)) {
7464 switch (Lex.getKind()) {
7465 case lltok::kw_info:
7467 if (ParseToken(lltok::colon, "expected ':' here") ||
7468 ParseUInt64(ByArg.Info))
7471 case lltok::kw_byte:
7473 if (ParseToken(lltok::colon, "expected ':' here") ||
7474 ParseUInt32(ByArg.Byte))
7479 if (ParseToken(lltok::colon, "expected ':' here") ||
7480 ParseUInt32(ByArg.Bit))
7484 return Error(Lex.getLoc(),
7485 "expected optional whole program devirt field");
7489 if (ParseToken(lltok::rparen, "expected ')' here"))
7492 ResByArg[Args] = ByArg;
7493 } while (EatIfPresent(lltok::comma));
7495 if (ParseToken(lltok::rparen, "expected ')' here"))
7501 /// OptionalResByArg
7502 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7503 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7504 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7505 ParseToken(lltok::colon, "expected ':' here") ||
7506 ParseToken(lltok::lparen, "expected '(' here"))
7511 if (ParseUInt64(Val))
7513 Args.push_back(Val);
7514 } while (EatIfPresent(lltok::comma));
7516 if (ParseToken(lltok::rparen, "expected ')' here"))
7522 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
7524 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7525 bool ReadOnly = Fwd->isReadOnly();
7531 /// Stores the given Name/GUID and associated summary into the Index.
7532 /// Also updates any forward references to the associated entry ID.
7533 void LLParser::AddGlobalValueToIndex(
7534 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7535 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7536 // First create the ValueInfo utilizing the Name or GUID.
7539 assert(Name.empty());
7540 VI = Index->getOrInsertValueInfo(GUID);
7542 assert(!Name.empty());
7544 auto *GV = M->getNamedValue(Name);
7546 VI = Index->getOrInsertValueInfo(GV);
7549 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7550 "Need a source_filename to compute GUID for local");
7551 GUID = GlobalValue::getGUID(
7552 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7553 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7557 // Add the summary if one was provided.
7559 Index->addGlobalValueSummary(VI, std::move(Summary));
7561 // Resolve forward references from calls/refs
7562 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7563 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7564 for (auto VIRef : FwdRefVIs->second) {
7565 assert(VIRef.first->getRef() == FwdVIRef &&
7566 "Forward referenced ValueInfo expected to be empty");
7567 resolveFwdRef(VIRef.first, VI);
7569 ForwardRefValueInfos.erase(FwdRefVIs);
7572 // Resolve forward references from aliases
7573 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7574 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7575 for (auto AliaseeRef : FwdRefAliasees->second) {
7576 assert(!AliaseeRef.first->hasAliasee() &&
7577 "Forward referencing alias already has aliasee");
7578 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7580 ForwardRefAliasees.erase(FwdRefAliasees);
7583 // Save the associated ValueInfo for use in later references by ID.
7584 if (ID == NumberedValueInfos.size())
7585 NumberedValueInfos.push_back(VI);
7587 // Handle non-continuous numbers (to make test simplification easier).
7588 if (ID > NumberedValueInfos.size())
7589 NumberedValueInfos.resize(ID + 1);
7590 NumberedValueInfos[ID] = VI;
7595 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7596 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7597 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7598 bool LLParser::ParseGVEntry(unsigned ID) {
7599 assert(Lex.getKind() == lltok::kw_gv);
7602 if (ParseToken(lltok::colon, "expected ':' here") ||
7603 ParseToken(lltok::lparen, "expected '(' here"))
7607 GlobalValue::GUID GUID = 0;
7608 switch (Lex.getKind()) {
7609 case lltok::kw_name:
7611 if (ParseToken(lltok::colon, "expected ':' here") ||
7612 ParseStringConstant(Name))
7614 // Can't create GUID/ValueInfo until we have the linkage.
7616 case lltok::kw_guid:
7618 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7622 return Error(Lex.getLoc(), "expected name or guid tag");
7625 if (!EatIfPresent(lltok::comma)) {
7626 // No summaries. Wrap up.
7627 if (ParseToken(lltok::rparen, "expected ')' here"))
7629 // This was created for a call to an external or indirect target.
7630 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7631 // created for indirect calls with VP. A Name with no GUID came from
7632 // an external definition. We pass ExternalLinkage since that is only
7633 // used when the GUID must be computed from Name, and in that case
7634 // the symbol must have external linkage.
7635 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7640 // Have a list of summaries
7641 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7642 ParseToken(lltok::colon, "expected ':' here"))
7646 if (ParseToken(lltok::lparen, "expected '(' here"))
7648 switch (Lex.getKind()) {
7649 case lltok::kw_function:
7650 if (ParseFunctionSummary(Name, GUID, ID))
7653 case lltok::kw_variable:
7654 if (ParseVariableSummary(Name, GUID, ID))
7657 case lltok::kw_alias:
7658 if (ParseAliasSummary(Name, GUID, ID))
7662 return Error(Lex.getLoc(), "expected summary type");
7664 if (ParseToken(lltok::rparen, "expected ')' here"))
7666 } while (EatIfPresent(lltok::comma));
7668 if (ParseToken(lltok::rparen, "expected ')' here"))
7675 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7676 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7677 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7678 bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7680 assert(Lex.getKind() == lltok::kw_function);
7683 StringRef ModulePath;
7684 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7685 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7686 /*Live=*/false, /*IsLocal=*/false);
7688 std::vector<FunctionSummary::EdgeTy> Calls;
7689 FunctionSummary::TypeIdInfo TypeIdInfo;
7690 std::vector<ValueInfo> Refs;
7691 // Default is all-zeros (conservative values).
7692 FunctionSummary::FFlags FFlags = {};
7693 if (ParseToken(lltok::colon, "expected ':' here") ||
7694 ParseToken(lltok::lparen, "expected '(' here") ||
7695 ParseModuleReference(ModulePath) ||
7696 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7697 ParseToken(lltok::comma, "expected ',' here") ||
7698 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7699 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7702 // Parse optional fields
7703 while (EatIfPresent(lltok::comma)) {
7704 switch (Lex.getKind()) {
7705 case lltok::kw_funcFlags:
7706 if (ParseOptionalFFlags(FFlags))
7709 case lltok::kw_calls:
7710 if (ParseOptionalCalls(Calls))
7713 case lltok::kw_typeIdInfo:
7714 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7717 case lltok::kw_refs:
7718 if (ParseOptionalRefs(Refs))
7722 return Error(Lex.getLoc(), "expected optional function summary field");
7726 if (ParseToken(lltok::rparen, "expected ')' here"))
7729 auto FS = llvm::make_unique<FunctionSummary>(
7730 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
7731 std::move(Calls), std::move(TypeIdInfo.TypeTests),
7732 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7733 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7734 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7735 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7737 FS->setModulePath(ModulePath);
7739 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7746 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7747 /// [',' OptionalRefs]? ')'
7748 bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7750 assert(Lex.getKind() == lltok::kw_variable);
7753 StringRef ModulePath;
7754 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7755 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7756 /*Live=*/false, /*IsLocal=*/false);
7757 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false);
7758 std::vector<ValueInfo> Refs;
7759 if (ParseToken(lltok::colon, "expected ':' here") ||
7760 ParseToken(lltok::lparen, "expected '(' here") ||
7761 ParseModuleReference(ModulePath) ||
7762 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7763 ParseToken(lltok::comma, "expected ',' here") ||
7764 ParseGVarFlags(GVarFlags))
7767 // Parse optional refs field
7768 if (EatIfPresent(lltok::comma)) {
7769 if (ParseOptionalRefs(Refs))
7773 if (ParseToken(lltok::rparen, "expected ')' here"))
7777 llvm::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
7779 GS->setModulePath(ModulePath);
7781 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7788 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7789 /// 'aliasee' ':' GVReference ')'
7790 bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7792 assert(Lex.getKind() == lltok::kw_alias);
7793 LocTy Loc = Lex.getLoc();
7796 StringRef ModulePath;
7797 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7798 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7799 /*Live=*/false, /*IsLocal=*/false);
7800 if (ParseToken(lltok::colon, "expected ':' here") ||
7801 ParseToken(lltok::lparen, "expected '(' here") ||
7802 ParseModuleReference(ModulePath) ||
7803 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7804 ParseToken(lltok::comma, "expected ',' here") ||
7805 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7806 ParseToken(lltok::colon, "expected ':' here"))
7809 ValueInfo AliaseeVI;
7811 if (ParseGVReference(AliaseeVI, GVId))
7814 if (ParseToken(lltok::rparen, "expected ')' here"))
7817 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7819 AS->setModulePath(ModulePath);
7821 // Record forward reference if the aliasee is not parsed yet.
7822 if (AliaseeVI.getRef() == FwdVIRef) {
7823 auto FwdRef = ForwardRefAliasees.insert(
7824 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7825 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7827 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7829 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7837 bool LLParser::ParseFlag(unsigned &Val) {
7838 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7839 return TokError("expected integer");
7840 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7846 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7847 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7848 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
7849 /// [',' 'noInline' ':' Flag]? ')'
7850 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
7851 assert(Lex.getKind() == lltok::kw_funcFlags);
7854 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
7855 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
7860 switch (Lex.getKind()) {
7861 case lltok::kw_readNone:
7863 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7865 FFlags.ReadNone = Val;
7867 case lltok::kw_readOnly:
7869 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7871 FFlags.ReadOnly = Val;
7873 case lltok::kw_noRecurse:
7875 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7877 FFlags.NoRecurse = Val;
7879 case lltok::kw_returnDoesNotAlias:
7881 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7883 FFlags.ReturnDoesNotAlias = Val;
7885 case lltok::kw_noInline:
7887 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7889 FFlags.NoInline = Val;
7892 return Error(Lex.getLoc(), "expected function flag type");
7894 } while (EatIfPresent(lltok::comma));
7896 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
7903 /// := 'calls' ':' '(' Call [',' Call]* ')'
7904 /// Call ::= '(' 'callee' ':' GVReference
7905 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
7906 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
7907 assert(Lex.getKind() == lltok::kw_calls);
7910 if (ParseToken(lltok::colon, "expected ':' in calls") |
7911 ParseToken(lltok::lparen, "expected '(' in calls"))
7914 IdToIndexMapType IdToIndexMap;
7915 // Parse each call edge
7918 if (ParseToken(lltok::lparen, "expected '(' in call") ||
7919 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
7920 ParseToken(lltok::colon, "expected ':'"))
7923 LocTy Loc = Lex.getLoc();
7925 if (ParseGVReference(VI, GVId))
7928 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7930 if (EatIfPresent(lltok::comma)) {
7931 // Expect either hotness or relbf
7932 if (EatIfPresent(lltok::kw_hotness)) {
7933 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
7936 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
7937 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
7941 // Keep track of the Call array index needing a forward reference.
7942 // We will save the location of the ValueInfo needing an update, but
7943 // can only do so once the std::vector is finalized.
7944 if (VI.getRef() == FwdVIRef)
7945 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
7946 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
7948 if (ParseToken(lltok::rparen, "expected ')' in call"))
7950 } while (EatIfPresent(lltok::comma));
7952 // Now that the Calls vector is finalized, it is safe to save the locations
7953 // of any forward GV references that need updating later.
7954 for (auto I : IdToIndexMap) {
7955 for (auto P : I.second) {
7956 assert(Calls[P.first].first.getRef() == FwdVIRef &&
7957 "Forward referenced ValueInfo expected to be empty");
7958 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7959 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7960 FwdRef.first->second.push_back(
7961 std::make_pair(&Calls[P.first].first, P.second));
7965 if (ParseToken(lltok::rparen, "expected ')' in calls"))
7972 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
7973 bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
7974 switch (Lex.getKind()) {
7975 case lltok::kw_unknown:
7976 Hotness = CalleeInfo::HotnessType::Unknown;
7978 case lltok::kw_cold:
7979 Hotness = CalleeInfo::HotnessType::Cold;
7981 case lltok::kw_none:
7982 Hotness = CalleeInfo::HotnessType::None;
7985 Hotness = CalleeInfo::HotnessType::Hot;
7987 case lltok::kw_critical:
7988 Hotness = CalleeInfo::HotnessType::Critical;
7991 return Error(Lex.getLoc(), "invalid call edge hotness");
7998 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
7999 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8000 assert(Lex.getKind() == lltok::kw_refs);
8003 if (ParseToken(lltok::colon, "expected ':' in refs") |
8004 ParseToken(lltok::lparen, "expected '(' in refs"))
8007 struct ValueContext {
8012 std::vector<ValueContext> VContexts;
8013 // Parse each ref edge
8016 VC.Loc = Lex.getLoc();
8017 if (ParseGVReference(VC.VI, VC.GVId))
8019 VContexts.push_back(VC);
8020 } while (EatIfPresent(lltok::comma));
8022 // Sort value contexts so that ones with readonly ValueInfo are at the end
8023 // of VContexts vector. This is needed to match immutableRefCount() behavior.
8024 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
8025 return VC1.VI.isReadOnly() < VC2.VI.isReadOnly();
8028 IdToIndexMapType IdToIndexMap;
8029 for (auto &VC : VContexts) {
8030 // Keep track of the Refs array index needing a forward reference.
8031 // We will save the location of the ValueInfo needing an update, but
8032 // can only do so once the std::vector is finalized.
8033 if (VC.VI.getRef() == FwdVIRef)
8034 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8035 Refs.push_back(VC.VI);
8038 // Now that the Refs vector is finalized, it is safe to save the locations
8039 // of any forward GV references that need updating later.
8040 for (auto I : IdToIndexMap) {
8041 for (auto P : I.second) {
8042 assert(Refs[P.first].getRef() == FwdVIRef &&
8043 "Forward referenced ValueInfo expected to be empty");
8044 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8045 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8046 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8050 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8056 /// OptionalTypeIdInfo
8057 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8058 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8059 /// [',' TypeCheckedLoadConstVCalls]? ')'
8060 bool LLParser::ParseOptionalTypeIdInfo(
8061 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8062 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8065 if (ParseToken(lltok::colon, "expected ':' here") ||
8066 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8070 switch (Lex.getKind()) {
8071 case lltok::kw_typeTests:
8072 if (ParseTypeTests(TypeIdInfo.TypeTests))
8075 case lltok::kw_typeTestAssumeVCalls:
8076 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8077 TypeIdInfo.TypeTestAssumeVCalls))
8080 case lltok::kw_typeCheckedLoadVCalls:
8081 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8082 TypeIdInfo.TypeCheckedLoadVCalls))
8085 case lltok::kw_typeTestAssumeConstVCalls:
8086 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8087 TypeIdInfo.TypeTestAssumeConstVCalls))
8090 case lltok::kw_typeCheckedLoadConstVCalls:
8091 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8092 TypeIdInfo.TypeCheckedLoadConstVCalls))
8096 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8098 } while (EatIfPresent(lltok::comma));
8100 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8107 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8108 /// [',' (SummaryID | UInt64)]* ')'
8109 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8110 assert(Lex.getKind() == lltok::kw_typeTests);
8113 if (ParseToken(lltok::colon, "expected ':' here") ||
8114 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8117 IdToIndexMapType IdToIndexMap;
8119 GlobalValue::GUID GUID = 0;
8120 if (Lex.getKind() == lltok::SummaryID) {
8121 unsigned ID = Lex.getUIntVal();
8122 LocTy Loc = Lex.getLoc();
8123 // Keep track of the TypeTests array index needing a forward reference.
8124 // We will save the location of the GUID needing an update, but
8125 // can only do so once the std::vector is finalized.
8126 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8128 } else if (ParseUInt64(GUID))
8130 TypeTests.push_back(GUID);
8131 } while (EatIfPresent(lltok::comma));
8133 // Now that the TypeTests vector is finalized, it is safe to save the
8134 // locations of any forward GV references that need updating later.
8135 for (auto I : IdToIndexMap) {
8136 for (auto P : I.second) {
8137 assert(TypeTests[P.first] == 0 &&
8138 "Forward referenced type id GUID expected to be 0");
8139 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8140 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8141 FwdRef.first->second.push_back(
8142 std::make_pair(&TypeTests[P.first], P.second));
8146 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8153 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8154 bool LLParser::ParseVFuncIdList(
8155 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8156 assert(Lex.getKind() == Kind);
8159 if (ParseToken(lltok::colon, "expected ':' here") ||
8160 ParseToken(lltok::lparen, "expected '(' here"))
8163 IdToIndexMapType IdToIndexMap;
8165 FunctionSummary::VFuncId VFuncId;
8166 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8168 VFuncIdList.push_back(VFuncId);
8169 } while (EatIfPresent(lltok::comma));
8171 if (ParseToken(lltok::rparen, "expected ')' here"))
8174 // Now that the VFuncIdList vector is finalized, it is safe to save the
8175 // locations of any forward GV references that need updating later.
8176 for (auto I : IdToIndexMap) {
8177 for (auto P : I.second) {
8178 assert(VFuncIdList[P.first].GUID == 0 &&
8179 "Forward referenced type id GUID expected to be 0");
8180 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8181 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8182 FwdRef.first->second.push_back(
8183 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8191 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8192 bool LLParser::ParseConstVCallList(
8194 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8195 assert(Lex.getKind() == Kind);
8198 if (ParseToken(lltok::colon, "expected ':' here") ||
8199 ParseToken(lltok::lparen, "expected '(' here"))
8202 IdToIndexMapType IdToIndexMap;
8204 FunctionSummary::ConstVCall ConstVCall;
8205 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8207 ConstVCallList.push_back(ConstVCall);
8208 } while (EatIfPresent(lltok::comma));
8210 if (ParseToken(lltok::rparen, "expected ')' here"))
8213 // Now that the ConstVCallList vector is finalized, it is safe to save the
8214 // locations of any forward GV references that need updating later.
8215 for (auto I : IdToIndexMap) {
8216 for (auto P : I.second) {
8217 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8218 "Forward referenced type id GUID expected to be 0");
8219 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8220 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8221 FwdRef.first->second.push_back(
8222 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8230 /// ::= '(' VFuncId ',' Args ')'
8231 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8232 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8233 if (ParseToken(lltok::lparen, "expected '(' here") ||
8234 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8237 if (EatIfPresent(lltok::comma))
8238 if (ParseArgs(ConstVCall.Args))
8241 if (ParseToken(lltok::rparen, "expected ')' here"))
8248 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8249 /// 'offset' ':' UInt64 ')'
8250 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8251 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8252 assert(Lex.getKind() == lltok::kw_vFuncId);
8255 if (ParseToken(lltok::colon, "expected ':' here") ||
8256 ParseToken(lltok::lparen, "expected '(' here"))
8259 if (Lex.getKind() == lltok::SummaryID) {
8261 unsigned ID = Lex.getUIntVal();
8262 LocTy Loc = Lex.getLoc();
8263 // Keep track of the array index needing a forward reference.
8264 // We will save the location of the GUID needing an update, but
8265 // can only do so once the caller's std::vector is finalized.
8266 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8268 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8269 ParseToken(lltok::colon, "expected ':' here") ||
8270 ParseUInt64(VFuncId.GUID))
8273 if (ParseToken(lltok::comma, "expected ',' here") ||
8274 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8275 ParseToken(lltok::colon, "expected ':' here") ||
8276 ParseUInt64(VFuncId.Offset) ||
8277 ParseToken(lltok::rparen, "expected ')' here"))
8284 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8285 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8286 /// 'dsoLocal' ':' Flag ')'
8287 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8288 assert(Lex.getKind() == lltok::kw_flags);
8292 if (ParseToken(lltok::colon, "expected ':' here") ||
8293 ParseToken(lltok::lparen, "expected '(' here") ||
8294 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8295 ParseToken(lltok::colon, "expected ':' here"))
8298 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8299 assert(HasLinkage && "Linkage not optional in summary entry");
8303 if (ParseToken(lltok::comma, "expected ',' here") ||
8304 ParseToken(lltok::kw_notEligibleToImport,
8305 "expected 'notEligibleToImport' here") ||
8306 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8308 GVFlags.NotEligibleToImport = Flag;
8310 if (ParseToken(lltok::comma, "expected ',' here") ||
8311 ParseToken(lltok::kw_live, "expected 'live' here") ||
8312 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8314 GVFlags.Live = Flag;
8316 if (ParseToken(lltok::comma, "expected ',' here") ||
8317 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8318 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8320 GVFlags.DSOLocal = Flag;
8322 if (ParseToken(lltok::rparen, "expected ')' here"))
8329 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag ')'
8330 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8331 assert(Lex.getKind() == lltok::kw_varFlags);
8335 if (ParseToken(lltok::colon, "expected ':' here") ||
8336 ParseToken(lltok::lparen, "expected '(' here") ||
8337 ParseToken(lltok::kw_readonly, "expected 'readonly' here") ||
8338 ParseToken(lltok::colon, "expected ':' here"))
8342 GVarFlags.ReadOnly = Flag;
8344 if (ParseToken(lltok::rparen, "expected ')' here"))
8350 /// ::= 'module' ':' UInt
8351 bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8353 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8354 ParseToken(lltok::colon, "expected ':' here") ||
8355 ParseToken(lltok::SummaryID, "expected module ID"))
8358 unsigned ModuleID = Lex.getUIntVal();
8359 auto I = ModuleIdMap.find(ModuleID);
8360 // We should have already parsed all module IDs
8361 assert(I != ModuleIdMap.end());
8362 ModulePath = I->second;
8368 bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8369 bool ReadOnly = EatIfPresent(lltok::kw_readonly);
8370 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8373 GVId = Lex.getUIntVal();
8374 // Check if we already have a VI for this GV
8375 if (GVId < NumberedValueInfos.size()) {
8376 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
8377 VI = NumberedValueInfos[GVId];
8379 // We will create a forward reference to the stored location.
8380 VI = ValueInfo(false, FwdVIRef);